@chatpanel/gateway 0.121.5 → 0.136.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/model-pull.js CHANGED
@@ -1 +1 @@
1
- import{createWriteStream as F,mkdirSync as $,renameSync as L,existsSync as g,writeFileSync as E,statSync as A,readFileSync as T,readdirSync as R}from"node:fs";import{Readable as G}from"node:stream";import{pipeline as H}from"node:stream/promises";import c from"node:path";const b="https://huggingface.co",I=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,M=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function y(t){const r=/^([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(t||"").trim());return r?{repo:r[1],quant:r[2]||null}:null}const x=(t,r)=>c.join(t,"hub",`models--${r.replace("/","--")}`);async function z(t,{fetchImpl:r=globalThis.fetch,token:n=null}={}){const o=await r(`${b}/api/models/${t}?blobs=true`,{headers:n?{authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(2e4)});if(o.status===401||o.status===403)throw new Error(`${t}: gated or private on Hugging Face — accept its licence there and add a token`);if(o.status===404)throw new Error(`${t}: no such model on Hugging Face`);if(!o.ok)throw new Error(`${t}: Hugging Face answered ${o.status}`);const l=await o.json(),i=(l.siblings||[]).map(e=>({path:e.rfilename,size:Number(e.lfs?.size??e.size??0)})).filter(e=>e.path);return{commit:String(l.sha||"main"),siblings:i}}function Q(t){const r=t.some(o=>/\.safetensors$/i.test(o.path)),n=t.filter(o=>!(M.test(o.path)||r&&I.test(o.path)||!r&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(o.path)));return{files:n,total:n.reduce((o,l)=>o+l.size,0)}}function Z(t,r=null){const n=t.filter(e=>/\.gguf$/i.test(e.path)&&!/mmproj/i.test(e.path));if(!n.length)throw new Error("no GGUF file in this repo");const o=(r||"Q4_K_M").toLowerCase();let i=(e=>n.filter(s=>s.path.toLowerCase().includes(`-${e}.`)||s.path.toLowerCase().includes(`-${e}-0`)||s.path.toLowerCase().includes(`.${e}.`)||s.path.toLowerCase().includes(`/${e}/`)||s.path.toLowerCase().includes(`_${e}.`)))(o);if(!i.length&&!r&&(i=n.length===1?n:[]),!i.length)throw new Error(`no ${r||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(n.map(e=>B(e.path)))].slice(0,12).join(", ")}`);return i=i.slice().sort((e,s)=>e.path.localeCompare(s.path)),{files:i,total:i.reduce((e,s)=>e+s.size,0),main:i[0].path}}function B(t){const r=c.basename(t).replace(/\.gguf$/i,"").replace(/-\d{5}-of-\d{5}$/,""),n=/-((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(r);return n?n[1]:r}const m=(t,r,n)=>c.join(t,"gguf",r.replace("/","--"),c.basename(n));async function S({repo:t,commit:r,files:n,destOf:o,fetchImpl:l=globalThis.fetch,token:i=null,onProgress:e=()=>{},total:s=0}){let u=0;for(const a of n){const p=o(a.path);if(g(p)&&a.size&&A(p).size===a.size){u+=a.size,e({file:a.path,bytes:u,total:s,fileBytes:a.size,fileTotal:a.size,skipped:!0});continue}$(c.dirname(p),{recursive:!0,mode:448});const h=await l(`${b}/${t}/resolve/${encodeURIComponent(r)}/${a.path.split("/").map(encodeURIComponent).join("/")}`,{headers:i?{authorization:`Bearer ${i}`}:{},redirect:"follow"});if(!h.ok||!h.body)throw new Error(`${a.path}: Hugging Face answered ${h.status}`);let f=0;const C=new TransformStream({transform(d,_){f+=d.byteLength,u+=d.byteLength,e({file:a.path,bytes:u,total:s,fileBytes:f,fileTotal:a.size}),_.enqueue(d)}}),w=`${p}.part`;await H(G.fromWeb(h.body.pipeThrough(C)),F(w,{mode:384})),L(w,p)}return u}async function O(t,{root:r,fetchImpl:n=globalThis.fetch,token:o=null,onProgress:l=()=>{}}={}){const{commit:i,siblings:e}=await z(t,{fetchImpl:n,token:o}),{files:s,total:u}=Q(e);if(!s.length)throw new Error(`${t}: nothing to download (no weights or config listed)`);const a=x(r,t),p=c.join(a,"snapshots",i),h=await S({repo:t,commit:i,files:s,total:u,destOf:f=>c.join(p,f),fetchImpl:n,token:o,onProgress:l});return $(c.join(a,"refs"),{recursive:!0,mode:448}),E(c.join(a,"refs","main"),i,{mode:384}),{dir:p,commit:i,files:s.map(f=>f.path),bytes:h,total:u}}async function k(t,{root:r,fetchImpl:n=globalThis.fetch,token:o=null,onProgress:l=()=>{}}={}){const i=y(t);if(!i)throw new Error(`not a model id: ${t}`);const{commit:e,siblings:s}=await z(i.repo,{fetchImpl:n,token:o}),{files:u,total:a,main:p}=Z(s,i.quant),h=await S({repo:i.repo,commit:e,files:u,total:a,destOf:f=>m(r,i.repo,f),fetchImpl:n,token:o,onProgress:l});return{main:m(r,i.repo,p),files:u.map(f=>m(r,i.repo,f.path)),bytes:h,total:a}}function D(t,r){const n=x(t,r);try{const o=T(c.join(n,"refs","main"),"utf8").trim();return!!o&&g(c.join(n,"snapshots",o))&&g(c.join(n,"snapshots",o,"config.json"))}catch{return!1}}function P(t,r){const n=y(r);if(!n)return null;const o=c.join(t,"gguf",n.repo.replace("/","--"));if(!g(o))return null;const l=(n.quant||"Q4_K_M").toLowerCase(),i=j(o).filter(e=>/\.gguf$/i.test(e)&&!e.endsWith(".part")&&(e.toLowerCase().includes(`-${l}.`)||e.toLowerCase().includes(`-${l}-0`)||e.toLowerCase().includes(`.${l}.`)||e.toLowerCase().includes(`_${l}.`)||!n.quant&&j(o).filter(s=>/\.gguf$/i.test(s)).length===1)).sort();return i.length?c.join(o,i[0]):null}function j(t){try{return R(t)}catch{return[]}}export{b as HF_API,z as describeRepo,S as downloadFiles,P as ggufInstalled,m as ggufPath,y as parseModelRef,Z as planGgufFiles,Q as planRepoFiles,k as pullGguf,O as pullRepo,B as quantOf,x as repoCacheDir,D as repoInstalled};
1
+ import{createWriteStream as W,mkdirSync as k,renameSync as D,existsSync as z,writeFileSync as U,statSync as x,readFileSync as E,readdirSync as Z}from"node:fs";import{ggufRecommended as K}from"./gguf-meta.js";import{Readable as P}from"node:stream";import{pipeline as J}from"node:stream/promises";import f from"node:path";const R="https://huggingface.co",X=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,Y=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function F(r){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(r||"").trim());return t?{repo:t[1],quant:t[2]||null}:null}const O=(r,t)=>f.join(r,"hub",`models--${t.replace("/","--")}`);async function C(r,{fetchImpl:t=globalThis.fetch,token:n=null}={}){const e=await t(`${R}/api/models/${r}?blobs=true`,{headers:n?{authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(2e4)});if(e.status===401||e.status===403)throw new Error(`${r}: gated or private on Hugging Face — accept its licence there and add a token`);if(e.status===404)throw new Error(`${r}: no such model on Hugging Face`);if(!e.ok)throw new Error(`${r}: Hugging Face answered ${e.status}`);const a=await e.json(),s=(a.siblings||[]).map(c=>({path:c.rfilename,size:Number(c.lfs?.size??c.size??0)})).filter(c=>c.path);return{commit:String(a.sha||"main"),siblings:s}}function V(r){const t=r.some(e=>/\.safetensors$/i.test(e.path)),n=r.filter(e=>!(Y.test(e.path)||t&&X.test(e.path)||!t&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(e.path)));return{files:n,total:n.reduce((e,a)=>e+a.size,0)}}const L=/(^|\/)mmproj[^/]*\.gguf$/i,B=/(^|\/)(?:dspark|dflash|eagle3?)[-_][^/]*\.gguf$|[-_.]mtp(?:[-_.][^/]*)?\.gguf$|(^|\/)[^/]*draft[^/]*\.gguf$/i,tt=/(^|\/)imatrix[^/]*\.gguf$/i,I=(r,t)=>t.test(r)&&!L.test(r)&&!B.test(r)&&!tt.test(r);function G(r){const t=f.basename(String(r||"")).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 T(r){return{mains:r.filter(t=>I(t.path,/\.gguf$/i)),alts:r.filter(t=>/\.gguf_file$/i.test(t.path)&&I(t.path.replace(/_file$/i,""),/\.gguf$/i)),projectors:r.filter(t=>L.test(t.path)),drafts:r.filter(t=>B.test(t.path))}}const M=(r,t)=>(r.path.includes("/")?1:0)-(t.path.includes("/")?1:0);function et(r){const t=n=>{const e=["f16","bf16","q8_0","f32"].findIndex(a=>new RegExp(`[-_.]${a}\\.gguf$`,"i").test(n));return e<0?9:e};return r.slice().sort((n,e)=>M(n,e)||t(n.path)-t(e.path))[0]||null}function rt(r){return r.slice().sort((t,n)=>M(t,n)||(t.size||0)-(n.size||0))[0]||null}const v=(r,t)=>{const n=r.toLowerCase().replace(/_file$/,"");return n.includes(`-${t}.`)||n.includes(`-${t}-0`)||n.includes(`.${t}.`)||n.includes(`/${t}/`)||n.includes(`_${t}.`)};function nt(r,t=null,{layout:n="main"}={}){const e=T(r),a=n==="alt"?e.alts:e.mains;if(!a.length)throw new Error("no GGUF file in this repo");const s=(t||"Q4_K_M").toLowerCase();let c=a.filter(i=>v(i.path,s));if(!c.length&&!t){const i=N(a);c=a.filter(l=>j(l.path)===i)}if(!c.length)throw new Error(`no ${t||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(a.map(i=>j(i.path)))].slice(0,12).join(", ")}`);return c=c.slice().sort((i,l)=>i.path.localeCompare(l.path)),{files:c,total:c.reduce((i,l)=>i+l.size,0),main:c[0].path}}function N(r){const t=e=>r.filter(a=>j(a.path)===e).reduce((a,s)=>a+(s.size||0),0),n=[...new Set(r.map(e=>j(e.path)))].sort((e,a)=>t(e)-t(a));return n.find(e=>/(^|-)I?Q4/i.test(e))||n[0]}function ot(r){const t=new Map;for(const n of T(r).mains){const e=j(n.path);t.set(e,(t.get(e)||0)+(n.size||0))}return[...t].map(([n,e])=>({quant:n,size:e})).sort((n,e)=>n.size-e.size)}function j(r){const t=f.basename(r).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 b=(r,t,n)=>f.join(r,"gguf",t.replace("/","--"),f.basename(n).replace(/\.gguf_file$/i,".gguf")),_={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8};function at(r){try{if(r.length<24||r.toString("latin1",0,4)!=="GGUF")return null;let t=16;const n=Number(r.readBigUInt64LE(t));t+=8;const e=()=>{const a=Number(r.readBigUInt64LE(t));t+=8;const s=r.toString("utf8",t,t+a);return t+=a,s};for(let a=0;a<n&&t<r.length;a++){const s=e(),c=r.readUInt32LE(t);if(t+=4,c===8){const i=e();if(s==="general.architecture")return i||null;continue}if(c===9){const i=r.readUInt32LE(t);t+=4;const l=Number(r.readBigUInt64LE(t));if(t+=8,i===8)for(let o=0;o<l;o++)e();else if(_[i])t+=_[i]*l;else return null;continue}if(!_[c])return null;t+=_[c]}}catch{}return null}async function it(r,t,n,{fetchImpl:e=globalThis.fetch,token:a=null}={}){try{const s=await e(`${R}/${r}/resolve/${encodeURIComponent(t)}/${n.split("/").map(encodeURIComponent).join("/")}`,{headers:{range:"bytes=0-65535",...a?{authorization:`Bearer ${a}`}:{}},redirect:"follow",signal:AbortSignal.timeout(2e4)});return!s.ok||typeof s.arrayBuffer!="function"?null:at(Buffer.from(await s.arrayBuffer()))}catch{return null}}async function q({repo:r,commit:t,files:n,destOf:e,fetchImpl:a=globalThis.fetch,token:s=null,onProgress:c=()=>{},total:i=0}){let l=0;for(const o of n){const u=e(o.path);if(z(u)&&o.size&&x(u).size===o.size){l+=o.size,c({file:o.path,bytes:l,total:i,fileBytes:o.size,fileTotal:o.size,skipped:!0});continue}k(f.dirname(u),{recursive:!0,mode:448});const g=`${u}.part`,h=z(g)?x(g).size:0,w=h>0&&(!o.size||h<o.size),m={...s?{authorization:`Bearer ${s}`}:{},...w?{range:`bytes=${h}-`}:{}},p=await a(`${R}/${r}/resolve/${encodeURIComponent(t)}/${o.path.split("/").map(encodeURIComponent).join("/")}`,{headers:m,redirect:"follow"});if(!p.ok||!p.body)throw new Error(`${o.path}: Hugging Face answered ${p.status}`);const $=w&&p.status===206;let y=$?h:0;$&&(l+=h,c({file:o.path,bytes:l,total:i,fileBytes:y,fileTotal:o.size,skipped:!0}));const d=new TransformStream({transform(S,Q){y+=S.byteLength,l+=S.byteLength,c({file:o.path,bytes:l,total:i,fileBytes:y,fileTotal:o.size}),Q.enqueue(S)}});if(await J(P.fromWeb(p.body.pipeThrough(d)),W(g,{mode:384,flags:$?"a":"w"})),o.size&&x(g).size!==o.size)throw new Error(`${o.path}: ${x(g).size} of ${o.size} bytes arrived — Start continues the download`);D(g,u)}return l}async function dt(r,{root:t,fetchImpl:n=globalThis.fetch,token:e=null,onProgress:a=()=>{}}={}){const{commit:s,siblings:c}=await C(r,{fetchImpl:n,token:e}),{files:i,total:l}=V(c);if(!i.length)throw new Error(`${r}: nothing to download (no weights or config listed)`);const o=O(t,r),u=f.join(o,"snapshots",s),g=await q({repo:r,commit:s,files:i,total:l,destOf:h=>f.join(u,h),fetchImpl:n,token:e,onProgress:a});return k(f.join(o,"refs"),{recursive:!0,mode:448}),U(f.join(o,"refs","main"),s,{mode:384}),{dir:u,commit:s,files:i.map(h=>h.path),bytes:g,total:l}}async function st(r,{fetchImpl:t=globalThis.fetch,token:n=null,knows:e=null,engineVersion:a=null}={}){const s=F(r);if(!s)throw new Error(`not a model id: ${r}`);const{commit:c,siblings:i}=await C(s.repo,{fetchImpl:t,token:n}),l=T(i),o=l.alts.length?["main","alt"]:["main"];let u=null;const g=[];for(const m of o){let p;try{p=nt(i,s.quant,{layout:m})}catch(d){if(m==="main")throw d;continue}const $=e?await it(s.repo,c,p.main,{fetchImpl:t,token:n}):null;if(($&&e?e($):null)===!1){g.push($);continue}u={layout:m,arch:$,...p};break}if(!u){const m=[...new Set(g)].join(" or "),p=new Error(`${s.repo}: llama.cpp${a?` ${a}`:""} on this machine cannot run ${m} models. Update it on its row in Settings › Runtime — and if that says it is up to date, support for ${m} is not in a llama.cpp release yet: the model has to wait for the next one.`);throw p.code="unsupported_arch",p.arch=g[0],p}const h=et(l.projectors),w=rt(l.drafts);return{repo:s.repo,commit:c,quant:s.quant||j(u.main),layout:u.layout,arch:u.arch,weights:u.files,total:u.total,main:u.main,projector:h?{path:h.path,size:h.size}:null,draft:w?{path:w.path,size:w.size,spec:G(w.path)}:null,quants:ot(i)}}function mt(r,t){const n=F(t);if(!n)return{};try{const e=JSON.parse(E(f.join(r,"gguf",n.repo.replace("/","--"),"recipe.json"),"utf8"));return{...e.projector&&z(e.projector)?{projector:e.projector}:{},...e.draft?.path&&z(e.draft.path)?{draft:{path:e.draft.path,spec:e.draft.spec||G(e.draft.path)}}:{},...H(r,t)}}catch{return H(r,t)}}const A=new Map;function H(r,t){const n=ct(r,t);if(!n)return{};let e;try{e=`${n}:${x(n).mtimeMs}`}catch{return{}}A.has(e)||A.set(e,K(n));const a=A.get(e);return a?{recommended:a}:{}}async function $t(r,{root:t,fetchImpl:n=globalThis.fetch,token:e=null,onProgress:a=()=>{},knows:s=null,engineVersion:c=null,vision:i=!0,draft:l=!0}={}){const o=await st(r,{fetchImpl:n,token:e,knows:s,engineVersion:c}),u=[...i&&o.projector?[o.projector]:[],...l&&o.draft?[o.draft]:[]],g=[...o.weights,...u],h=g.reduce((d,S)=>d+(S.size||0),0),w=await q({repo:o.repo,commit:o.commit,files:g,total:h,destOf:d=>b(t,o.repo,d),fetchImpl:n,token:e,onProgress:a}),m=d=>d?b(t,o.repo,d.path):null,p={projector:i?m(o.projector):null,draft:l&&o.draft?{path:m(o.draft),spec:o.draft.spec}:null,arch:o.arch,layout:o.layout},$=f.join(t,"gguf",o.repo.replace("/","--"),"recipe.json");let y={};try{y=JSON.parse(E($,"utf8"))}catch{}return U($,JSON.stringify({...y,...Object.fromEntries(Object.entries(p).filter(([,d])=>d))},null,2),{mode:384}),{main:b(t,o.repo,o.main),files:o.weights.map(d=>b(t,o.repo,d.path)),bytes:w,total:h,projector:p.projector,draft:p.draft}}function wt(r,t){const n=O(r,t);try{const e=E(f.join(n,"refs","main"),"utf8").trim();return!!e&&z(f.join(n,"snapshots",e))&&z(f.join(n,"snapshots",e,"config.json"))}catch{return!1}}function ct(r,t){const n=F(t);if(!n)return null;const e=f.join(r,"gguf",n.repo.replace("/","--"));if(!z(e))return null;const a=(n.quant||"Q4_K_M").toLowerCase(),s=lt(e).filter(i=>I(i,/\.gguf$/i)&&!i.endsWith(".part"));let c=s.filter(i=>v(i,a)).sort();if(!c.length&&!n.quant&&s.length){const i=s.map(o=>({path:o,size:(()=>{try{return x(f.join(e,o)).size}catch{return 0}})()})),l=N(i);c=s.filter(o=>j(o)===l).sort()}return c.length?f.join(e,c[0]):null}function lt(r){try{return Z(r)}catch{return[]}}export{R as HF_API,C as describeRepo,q as downloadFiles,G as draftSpecOf,it as ggufArchitecture,at as ggufHeaderArch,ct as ggufInstalled,T as ggufKinds,b as ggufPath,ot as ggufQuants,mt as ggufRecipe,F as parseModelRef,rt as pickDraft,et as pickProjector,nt as planGgufFiles,st as planGgufRecipe,V as planRepoFiles,$t as pullGguf,dt as pullRepo,j as quantOf,O as repoCacheDir,wt as repoInstalled};
package/src/providers.js CHANGED
@@ -1 +1 @@
1
- import{CAPABILITIES as m,CAPABILITY_ROUTES as b,PROVIDER_KINDS as k}from"./capability-endpoints.js";import{listDestinations as h}from"./router.js";import{defaultEmbeddedModel as c}from"./embedded-models.js";const g=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,v=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function l(t){if(!t)return"none";let r="";try{r=new URL(t).hostname}catch{return"internet"}return g.test(r)?"loopback":v.test(r)?"lan":"internet"}const d=t=>typeof t=="string"&&t.trim()?t.trim():null;function f(t,r){const e=t?.capabilities?.[r];if(!e||typeof e!="object")return null;const a=d(e.url);let n=k.includes(e.provider)?e.provider:null;return n||(n=e.service?"container":a?"remote":"embedded"),n==="remote"&&!/^https?:\/\//.test(a||"")?null:{kind:n,...a?{url:a}:{},...d(e.adapter)?{adapter:d(e.adapter)}:{},...d(e.model)?{model:d(e.model)}:n==="embedded"&&c(r)?{model:c(r)}:{},...d(e.service)?{service:d(e.service)}:{},...d(e.token)?{token:d(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},egress:n==="embedded"?"none":n==="container"?"loopback":l(a)}}function y(t,r,e={}){if(!m.includes(r))throw new Error(`providerOf: unknown capability ${r}`);const a=f(t,r);if(a)return o(r,a,e);switch(r){case"chat":{const n=h(t),s=n.filter(u=>u.type==="agent").length,i=n.filter(u=>u.type!=="agent");if(!n.length)return o(r,{kind:"none",egress:"none"},e);if(!i.length)return o(r,{kind:"harness",egress:"internet",destinations:n.length,harnesses:s},e);const p=i.some(u=>l(u.baseUrl)==="internet")?"internet":i.some(u=>l(u.baseUrl)==="lan")?"lan":"loopback";return o(r,{kind:"router",egress:p,destinations:n.length,harnesses:s,apis:i.length},e)}case"detect":{const n=t?.redaction?.detection;return n?.backend==="endpoint"&&d(n.url)?o(r,{kind:"remote",url:n.url,adapter:"detect",egress:l(n.url)},e):n?.backend&&n.backend!=="off"&&n.backend!=="endpoint"?o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e):o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e)}case"stt":return t?.stt?.enabled===!1?o(r,{kind:"none",egress:"none"},e):o(r,{kind:"embedded",egress:"none",model:e.sttModel||t?.stt?.model},e);case"tts":{const n=t?.tts?.provider;if(t?.tts?.enabled===!1)return o(r,{kind:"none",egress:"none"},e);if(n&&n!=="local"){const s=t?.tts?.remote||{},i=d(s.baseUrl)||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(r,{kind:"remote",url:i,adapter:n,model:d(s.model)||void 0,egress:l(i),redact:s.redact!==!1},e)}return o(r,{kind:"embedded",egress:"none",model:e.ttsModel||t?.tts?.model},e)}case"search":{const n=t?.search?.provider||"auto",s=d(t?.search?.searxng?.url);return n==="searxng"||n==="auto"&&s?o(r,{kind:l(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:l(s)},e):o(r,{kind:"embedded",adapter:"serp",egress:"internet"},e)}case"read":{const n=t?.read?.provider||"defuddle",s=d(t?.read?.remote?.url);return n==="remote"&&s?o(r,{kind:"remote",url:s,adapter:"remote",egress:l(s)},e):o(r,{kind:"embedded",adapter:n,egress:"internet"},e)}case"extract":return o(r,{kind:"embedded",egress:"none"},e);case"rerank":case"decide":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);case"embed":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);default:return o(r,{kind:"none",egress:"none"},e)}}const w={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(t,r,e){const a=r.kind==="remote"?(()=>{try{return new URL(r.url).host}catch{return r.url}})():w[r.kind],n=r.model||r.adapter||r.service||"";return{...r,label:n?`${n} — ${a}`:a,route:b[t]}}function x(t,r={}){return Object.fromEntries(m.map(e=>[e,y(t,e,r)]))}function E(t,r={}){const e=[];for(const[a,n]of Object.entries(x(t,r))){if(n.kind!=="remote"||!n.url)continue;let s=n.url;try{s=new URL(n.url).host}catch{}e.push({id:a,host:s,adapter:n.adapter||"",token:!!n.token,egress:n.egress,route:n.route})}return e}export{E as declaredProviderHosts,l as egressOf,y as providerOf,x as providerTable};
1
+ import{CAPABILITIES as m,CAPABILITY_ROUTES as v,PROVIDER_KINDS as g}from"./capability-endpoints.js";import{listDestinations as f}from"./router.js";import{defaultEmbeddedModel as p}from"./embedded-models.js";import{capabilityList as c}from"./capability-config.js";const y=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,w=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function a(n){if(!n)return"none";let e="";try{e=new URL(n).hostname}catch{return"internet"}return y.test(e)?"loopback":w.test(e)?"lan":"internet"}const i=n=>typeof n=="string"&&n.trim()?n.trim():null;function x(n,e){if(!e||typeof e!="object")return null;const r=i(e.url);let d=g.includes(e.provider)?e.provider:null;return d||(d=e.service?"container":r?"remote":"embedded"),d==="remote"&&!/^https?:\/\//.test(r||"")?null:{kind:d,...r?{url:r}:{},...i(e.adapter)?{adapter:i(e.adapter)}:{},...i(e.model)?{model:i(e.model)}:d==="embedded"&&p(n)?{model:p(n)}:{},...i(e.service)?{service:i(e.service)}:{},...i(e.token)?{token:i(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},...typeof e.id=="string"&&e.id?{id:e.id}:{},egress:d==="embedded"?"none":d==="container"?"loopback":a(r)}}const b=(n,e)=>c(n?.capabilities?.[e],e,{destinations:n?.destinations||[]}).providers.map(r=>x(e,r)).filter(Boolean),O=(n,e)=>b(n,e)[0]||null;function k(n,e,r={}){if(!m.includes(e))throw new Error(`providerOf: unknown capability ${e}`);const d=O(n,e);if(d)return o(e,d,r);switch(e){case"chat":{const t=f(n),s=t.filter(u=>u.type==="agent").length,l=t.filter(u=>u.type!=="agent");if(!t.length)return o(e,{kind:"none",egress:"none"},r);if(!l.length)return o(e,{kind:"harness",egress:"internet",destinations:t.length,harnesses:s},r);const h=l.some(u=>a(u.baseUrl)==="internet")?"internet":l.some(u=>a(u.baseUrl)==="lan")?"lan":"loopback";return o(e,{kind:"router",egress:h,destinations:t.length,harnesses:s,apis:l.length},r)}case"detect":{const t=n?.redaction?.detection;return t?.backend==="endpoint"&&i(t.url)?o(e,{kind:"remote",url:t.url,adapter:"detect",egress:a(t.url)},r):t?.backend&&t.backend!=="off"&&t.backend!=="endpoint"?o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r):o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r)}case"stt":return n?.stt?.enabled===!1?o(e,{kind:"none",egress:"none"},r):o(e,{kind:"embedded",egress:"none",model:r.sttModel||n?.stt?.model},r);case"tts":{const t=n?.tts?.provider;if(n?.tts?.enabled===!1)return o(e,{kind:"none",egress:"none"},r);if(t&&t!=="local"){const s=n?.tts?.remote||{},l=i(s.baseUrl)||(t==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(e,{kind:"remote",url:l,adapter:t,model:i(s.model)||void 0,egress:a(l),redact:s.redact!==!1},r)}return o(e,{kind:"embedded",egress:"none",model:r.ttsModel||n?.tts?.model},r)}case"search":{const t=n?.search?.provider||"auto",s=i(n?.search?.searxng?.url);return t==="searxng"||t==="auto"&&s?o(e,{kind:a(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:a(s)},r):o(e,{kind:"embedded",adapter:"serp",egress:"internet"},r)}case"read":{const t=n?.read?.provider||"defuddle",s=i(n?.read?.remote?.url);return t==="remote"&&s?o(e,{kind:"remote",url:s,adapter:"remote",egress:a(s)},r):o(e,{kind:"embedded",adapter:t,egress:"internet"},r)}case"extract":return o(e,{kind:"embedded",egress:"none"},r);case"rerank":case"decide":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);case"embed":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);default:return o(e,{kind:"none",egress:"none"},r)}}const L={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(n,e,r){const d=e.kind==="remote"?(()=>{try{return new URL(e.url).host}catch{return e.url}})():L[e.kind],t=e.model||e.adapter||e.service||"";return{...e,label:t?`${t} — ${d}`:d,route:v[n]}}function E(n,e,r={}){if(!m.includes(e))throw new Error(`providersOf: unknown capability ${e}`);const{mode:d}=c(n?.capabilities?.[e],e),t=b(n,e);return{mode:d,providers:t.length?t.map(s=>o(e,s,r)):[k(n,e,r)]}}function R(n,e={}){return Object.fromEntries(m.map(r=>[r,k(n,r,e)]))}function S(n,e={}){const r=[];for(const d of m)for(const t of E(n,d,e).providers){if(t.kind!=="remote"||!t.url)continue;let s=t.url;try{s=new URL(t.url).host}catch{}r.push({id:d,host:s,adapter:t.adapter||"",token:!!t.token,egress:t.egress,route:t.route})}return r}export{S as declaredProviderHosts,a as egressOf,k as providerOf,R as providerTable,E as providersOf};
package/src/router.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as T}from"./secure-fetch.js";import{readBridgeToken as O,resolveBridgeUrl as x}from"./bridge.js";import{reachOfGatewayModel as B,agentModelReach as K}from"@chatpanel/events/model-candidates.js";import{localModelCard as N,reachByCard as D}from"@chatpanel/events/local-engine.js";import{loopbackRoot as k}from"./local-engine-probe.js";const E=["codex","claude","opencode","pi","kiro","antigravity"];function w(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),i=new Set(a.map(t=>t.id)),l=[...a.filter(t=>t.type==="agent"),...E.filter(t=>!i.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...a.filter(t=>t.type!=="agent")];if(e.backend==="api"&&!a.some(t=>t.type==="api")){const t=r=>({...r?.redact===!0?{redact:!0}:{},...r?.local===!0?{local:!0}:{}});l.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[],...t(e.upstreams?.openai)}),l.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[],...t(e.upstreams?.anthropic)})}return l}function Y(e,a,i,{destination:l="",down:t=()=>!1}={}){const r=w(a),c=i==="anthropic",s=o=>(c?o.protocol==="anthropic":o.protocol!=="anthropic")&&!t(o);return l?r.find(o=>o.id===l)||null:e&&r.find(o=>Array.isArray(o.models)&&o.models.includes(e))||e&&r.find(o=>o.id===e||o.agent===e)||e&&e.includes("/")&&r.find(o=>o.type==="agent"&&(o.agent===e.slice(0,e.indexOf("/"))||o.id===e.slice(0,e.indexOf("/"))))||e&&F(e,r,s)||r.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||r.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!t(o))||r.find(o=>!t(o))||null}function U(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const L=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function j(e){if(!e||e.type==="agent")return"";const a=String(e.baseUrl||"");return a?L.test(a)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function _(e,a,i,l){const t=B({id:e,owned_by:a,provider_type:i.type==="agent"?"agent":"openai"},i);if(i.type==="agent")return{reach:t};const r=!!k(i.baseUrl),c=D({dest:i,loopback:r,card:N(l,e),otherwise:t});return{reach:c.reach,...r?{reach_why:c.why,...c.engine?{engine:c.engine}:{}}:{}}}function P(e){const a=[],i=new Set,l=(t,r,c)=>{if(!t||i.has(t))return;i.add(t);const s=U(c),o=j(c);a.push({id:t,object:"model",owned_by:r,...o?{configured:!1,reason:o}:{},provider:c.id,provider_type:c.type==="agent"?"agent":c.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints,..._(t,r,c,null)})};for(const t of w(e))if(t.type==="agent")for(const r of t.models?.length?t.models:[t.id])l(r,"chatpanel-bridge",t);else for(const r of t.models||[])l(r,t.id,t);return{object:"list",data:a}}async function R(e,a,i){const l=await x(e);if(!l||!a)return new Map;const t=O(e.bridge?.token),r=[...a.entries()].filter(([,s])=>s).map(([s])=>s),c=new Map;return await Promise.all(r.map(async s=>{try{const o=await fetch(`${l}/list-models`,{method:"POST",headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(i)});if(!o.ok)return;const g=await o.json(),f=(Array.isArray(g?.models)?g.models:[]).map(b=>typeof b=="string"?b:b?.id||b?.name||"").map(b=>String(b).trim()).filter(Boolean);f.length&&c.set(s,f.slice(0,40))}catch{}})),c}async function z(e,a){const i=await x(e);if(!i)return null;try{const l=O(e.bridge?.token),t=await fetch(`${i}/health`,{headers:{Accept:"application/json",...l?{Authorization:`Bearer ${l}`}:{}},signal:AbortSignal.timeout(a)});if(!t.ok)return null;const r=await t.json();if(!Array.isArray(r?.agents))return null;const c=new Map(r.agents.map(s=>[s.id,!!s.available]));return c.noTools=new Set(r.agents.filter(s=>s.tools===!1).map(s=>s.id)),c}catch{return null}}const H=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function I(e){try{return JSON.stringify([w(e).map(a=>[a.id,a.type,a.baseUrl,a.models,a.service||"",a.local===!0,a.redact===!0]),e.bridge?.url||""])}catch{return String(Date.now())}}function Z(){d={at:0,key:"",value:null,inflight:null}}function ee(e,a){const i=String(a||"");if(!e||e.type!=="agent"||!i)return!1;const l=i.includes("/")?i.slice(0,i.indexOf("/")):i;return Array.isArray(e.models)&&e.models.includes(i)||e.id===i||e.agent===i||e.id===l||e.agent===l}function F(e,a,i){const l=(d.value?.data||[]).find(t=>t?.id===e&&t.owned_by!=="chatpanel-bridge");return l&&a.find(t=>t.id===l.owned_by&&t.type==="api"&&i(t))||null}async function te(e,a){if(!d.value)try{await G(e,a)}catch{}}async function G(e,{timeoutMs:a=4e3,fresh:i=!1,now:l=Date.now,serviceHealth:t=null,engineAt:r=null}={}){const c=I(e),s=d.value&&d.key===c,o=!s||l()-d.at>H;if(s&&!i&&!o)return d.value;const g=()=>(d.inflight||(d.inflight=J(e,{timeoutMs:a,serviceHealth:t,engineAt:r}).then(f=>(d={at:l(),key:c,value:f,inflight:null},f)).catch(f=>{throw d.inflight=null,f})),d.inflight);return s&&!i?(g().catch(()=>{}),d.value):g()}async function J(e,{timeoutMs:a=4e3,serviceHealth:i=null,engineAt:l=null}={}){const t=P(e),r=new Set(t.data.map(n=>n.id)),c=new Map;if(l){await Promise.all(w(e).filter(p=>p.type==="api"&&!p.service&&p.local!==!0&&p.redact!==!0&&k(p.baseUrl)).map(async p=>{const u=await l(k(p.baseUrl)).catch(()=>null);u&&c.set(p.id,u)}));const n=new Map(w(e).map(p=>[p.id,p]));for(const p of t.data){const u=n.get(p.provider);u&&c.has(u.id)&&Object.assign(p,_(p.id,p.owned_by,u,c.get(u.id)))}}const s=i?await i():null,o=new Map(w(e).filter(n=>n.service).map(n=>[n.id,n.service])),g=n=>{if(o.get(n.owned_by)&&s){const u=s(n.owned_by);u!=="unknown"&&(n.available=u==="up");const y=typeof s.window=="function"?s.window(n.owned_by):null;y&&(n.context_window=y);const h=typeof s.card=="function"?s.card(n.owned_by):null;h&&(n.card=h)}return n};for(const n of t.data)g(n);const f=await z(e,a);if(f){t.data=t.data.filter(n=>n.owned_by!=="chatpanel-bridge"||f.get(n.id)!==!1);for(const n of t.data)n.owned_by==="chatpanel-bridge"&&(n.available=f.get(n.id)??!1,f.noTools?.has(n.id)&&(n.tools=!1))}const b=await R(e,f,a);for(const[n,p]of b){const u=t.data.find(y=>y.id===n);if(u)for(const y of p){const h=`${n}/${y}`;r.has(h)||(r.add(h),t.data.push({...u,id:h,model:y,available:!0,reach:K(y)}))}}const C=w(e).filter(n=>n.type==="api"&&n.baseUrl);return await Promise.all(C.map(async n=>{const p=new AbortController,u=setTimeout(()=>p.abort(),a);try{const y={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(y["x-api-key"]=n.apiKey,y["anthropic-version"]="2023-06-01"):y.authorization=`Bearer ${n.apiKey}`);const h=await T(`${n.baseUrl.replace(/\/$/,"")}/models`,{headers:y,signal:p.signal});if(!h.ok)return;const v=await h.json(),$=Array.isArray(v?.data)?v.data:Array.isArray(v?.models)?v.models:[];for(const A of $){const m=typeof A=="string"?A:A?.id;if(m&&!r.has(m)){r.add(m);const S=U(n),M=j(n);t.data.push(g({id:m,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:S.api,endpoints:S.endpoints,...M?{configured:!1,reason:M}:{},..._(m,n.id,n,c.get(n.id)||null)}))}}}catch{}finally{clearTimeout(u)}})),t}export{ee as agentOwnsModel,P as aggregateModels,G as aggregateModelsAsync,te as ensureModelCatalog,w as listDestinations,Z as resetModelsCache,Y as resolveDestination};
1
+ import{secureFetch as $}from"./secure-fetch.js";import{readBridgeToken as M,resolveBridgeUrl as O}from"./bridge.js";import{reachOfGatewayModel as j,agentModelReach as x}from"@chatpanel/events/model-candidates.js";import{localModelCard as E,reachByCard as T}from"@chatpanel/events/local-engine.js";import{loopbackRoot as k}from"./local-engine-probe.js";import{SERVICES as B}from"./runtime.js";const P=["codex","claude","opencode","pi","kiro","antigravity"];function R(){return new Map(B.filter(e=>(e.provides||[]).includes("chat")&&e.port).map(e=>[String(e.port),e.id]))}function K(e){try{const o=new URL(e);return/^(localhost|127\.0\.0\.1|\[::1\])$/i.test(o.hostname)?o.port||(o.protocol==="https:"?"443":"80"):null}catch{return null}}function m(e){const o=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),s=new Set(o.map(t=>t.id)),l=[...o.filter(t=>t.type==="agent"),...P.filter(t=>!s.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...o.filter(t=>t.type!=="agent")],n=R(),c=new Set(o.filter(t=>t.service).map(t=>t.service));for(let t=l.length-1;t>=0;t--){const r=l[t];if(r.type!=="api"||r.service)continue;const i=n.get(K(r.baseUrl));if(i){if(c.has(i)){l.splice(t,1);continue}l[t]={...r,id:i,service:i,aliasOf:r.id},c.add(i)}}if(e.backend==="api"&&!o.some(t=>t.type==="api")){const t=r=>({...r?.redact===!0?{redact:!0}:{},...r?.local===!0?{local:!0}:{}});l.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[],...t(e.upstreams?.openai)}),l.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[],...t(e.upstreams?.anthropic)})}return l}function Z(e,o,s,{destination:l="",down:n=()=>!1}={}){const c=m(o),t=s==="anthropic",r=i=>(t?i.protocol==="anthropic":i.protocol!=="anthropic")&&!n(i);return l?c.find(i=>i.id===l)||null:e&&c.find(i=>Array.isArray(i.models)&&i.models.includes(e))||e&&c.find(i=>i.id===e||i.agent===e)||e&&e.includes("/")&&c.find(i=>i.type==="agent"&&(i.agent===e.slice(0,e.indexOf("/"))||i.id===e.slice(0,e.indexOf("/"))))||e&&F(e,c,r)||c.find(i=>o.backend==="bridge"?i.type==="agent":i.type==="api"&&r(i))||c.find(i=>(o.backend==="bridge"?i.type==="agent":i.type==="api")&&!n(i))||c.find(i=>!n(i))||null}function U(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const L=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function C(e){if(!e||e.type==="agent")return"";const o=String(e.baseUrl||"");return o?L.test(o)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function S(e,o,s,l){const n=j({id:e,owned_by:o,provider_type:s.type==="agent"?"agent":"openai"},s);if(s.type==="agent")return{reach:n};const c=!!k(s.baseUrl),t=T({dest:s,loopback:c,card:E(l,e),otherwise:n});return{reach:t.reach,...c?{reach_why:t.why,...t.engine?{engine:t.engine}:{}}:{}}}function N(e){const o=[],s=new Set,l=(n,c,t)=>{if(!n||s.has(n))return;s.add(n);const r=U(t),i=C(t);o.push({id:n,object:"model",owned_by:c,...i?{configured:!1,reason:i}:{},provider:t.id,provider_type:t.type==="agent"?"agent":t.protocol==="anthropic"?"anthropic":"openai",api:r.api,endpoints:r.endpoints,...S(n,c,t,null)})};for(const n of m(e))if(n.type==="agent")for(const c of n.models?.length?n.models:[n.id])l(c,"chatpanel-bridge",n);else for(const c of n.models||[])l(c,n.id,n);return{object:"list",data:o}}async function D(e,o,s){const l=await O(e);if(!l||!o)return new Map;const n=M(e.bridge?.token),c=[...o.entries()].filter(([,r])=>r).map(([r])=>r),t=new Map;return await Promise.all(c.map(async r=>{try{const i=await fetch(`${l}/list-models`,{method:"POST",headers:{"content-type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({agent:r}),signal:AbortSignal.timeout(s)});if(!i.ok)return;const g=await i.json(),y=(Array.isArray(g?.models)?g.models:[]).map(b=>typeof b=="string"?b:b?.id||b?.name||"").map(b=>String(b).trim()).filter(Boolean);y.length&&t.set(r,y.slice(0,40))}catch{}})),t}async function I(e,o){const s=await O(e);if(!s)return null;try{const l=M(e.bridge?.token),n=await fetch(`${s}/health`,{headers:{Accept:"application/json",...l?{Authorization:`Bearer ${l}`}:{}},signal:AbortSignal.timeout(o)});if(!n.ok)return null;const c=await n.json();if(!Array.isArray(c?.agents))return null;const t=new Map(c.agents.map(r=>[r.id,!!r.available]));return t.noTools=new Set(c.agents.filter(r=>r.tools===!1).map(r=>r.id)),t}catch{return null}}const z=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let h={at:0,key:"",value:null,inflight:null};function H(e){try{return JSON.stringify([m(e).map(o=>[o.id,o.type,o.baseUrl,o.models,o.service||"",o.local===!0,o.redact===!0]),e.bridge?.url||""])}catch{return String(Date.now())}}function ee(){h={at:0,key:"",value:null,inflight:null}}function te(e,o){const s=String(o||"");if(!e||e.type!=="agent"||!s)return!1;const l=s.includes("/")?s.slice(0,s.indexOf("/")):s;return Array.isArray(e.models)&&e.models.includes(s)||e.id===s||e.agent===s||e.id===l||e.agent===l}function F(e,o,s){const l=(h.value?.data||[]).find(n=>n?.id===e&&n.owned_by!=="chatpanel-bridge");return l&&o.find(n=>n.id===l.owned_by&&n.type==="api"&&s(n))||null}async function ne(e,o){if(!h.value)try{await G(e,o)}catch{}}async function G(e,{timeoutMs:o=4e3,fresh:s=!1,now:l=Date.now,serviceHealth:n=null,engineAt:c=null}={}){const t=H(e),r=h.value&&h.key===t,i=!r||l()-h.at>z;if(r&&!s&&!i)return h.value;const g=()=>(h.inflight||(h.inflight=J(e,{timeoutMs:o,serviceHealth:n,engineAt:c}).then(y=>(h={at:l(),key:t,value:y,inflight:null},y)).catch(y=>{throw h.inflight=null,y})),h.inflight);return r&&!s?(g().catch(()=>{}),h.value):g()}async function J(e,{timeoutMs:o=4e3,serviceHealth:s=null,engineAt:l=null}={}){const n=N(e),c=new Set(n.data.map(a=>a.id)),t=new Map;if(l){await Promise.all(m(e).filter(p=>p.type==="api"&&!p.service&&p.local!==!0&&p.redact!==!0&&k(p.baseUrl)).map(async p=>{const u=await l(k(p.baseUrl)).catch(()=>null);u&&t.set(p.id,u)}));const a=new Map(m(e).map(p=>[p.id,p]));for(const p of n.data){const u=a.get(p.provider);u&&t.has(u.id)&&Object.assign(p,S(p.id,p.owned_by,u,t.get(u.id)))}}const r=s?await s():null,i=new Map(m(e).filter(a=>a.service).map(a=>[a.id,a.service])),g=a=>{if(i.get(a.owned_by)&&r){const u=r(a.owned_by);u!=="unknown"&&(a.available=u==="up");const f=typeof r.window=="function"?r.window(a.owned_by):null;f&&(a.context_window=f);const d=typeof r.card=="function"?r.card(a.owned_by):null;d&&(a.card=d)}return a};for(const a of n.data)g(a);const y=await I(e,o);if(y){n.data=n.data.filter(a=>a.owned_by!=="chatpanel-bridge"||y.get(a.id)!==!1);for(const a of n.data)a.owned_by==="chatpanel-bridge"&&(a.available=y.get(a.id)??!1,y.noTools?.has(a.id)&&(a.tools=!1))}const b=await D(e,y,o);for(const[a,p]of b){const u=n.data.find(f=>f.id===a);if(u)for(const f of p){const d=`${a}/${f}`;c.has(d)||(c.add(d),n.data.push({...u,id:d,model:f,available:!0,reach:x(f)}))}}const A=m(e).filter(a=>a.type==="api"&&a.baseUrl),_=new Array(A.length).fill(null);return await Promise.all(A.map(async(a,p)=>{const u=new AbortController,f=setTimeout(()=>u.abort(),o);try{const d={"content-type":"application/json"};a.apiKey&&(a.protocol==="anthropic"?(d["x-api-key"]=a.apiKey,d["anthropic-version"]="2023-06-01"):d.authorization=`Bearer ${a.apiKey}`);const w=await $(`${a.baseUrl.replace(/\/$/,"")}/models`,{headers:d,signal:u.signal});if(!w.ok)return;const v=await w.json();_[p]=Array.isArray(v?.data)?v.data:Array.isArray(v?.models)?v.models:[]}catch{}finally{clearTimeout(f)}})),A.forEach((a,p)=>{for(const u of _[p]||[]){const f=typeof u=="string"?u:u?.id;if(f&&!c.has(f)){c.add(f);const d=U(a),w=C(a);n.data.push(g({id:f,object:"model",owned_by:a.id,provider:a.id,provider_type:a.protocol==="anthropic"?"anthropic":"openai",api:d.api,endpoints:d.endpoints,...w?{configured:!1,reason:w}:{},...S(f,a.id,a,t.get(a.id)||null)}))}}}),n}export{te as agentOwnsModel,N as aggregateModels,G as aggregateModelsAsync,ne as ensureModelCatalog,m as listDestinations,ee as resetModelsCache,Z as resolveDestination};
package/src/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import{promisify as Un}from"node:util";import{execFile as Fn}from"node:child_process";import{existsSync as Pe,mkdirSync as te,writeFileSync as le,accessSync as Hn,openSync as Dn,closeSync as jn,constants as Xn}from"node:fs";import{randomBytes as Wn,createHash as Jn}from"node:crypto";import V from"node:os";import v from"node:path";import{modelsFor as nn,isValidModelId as zn,catalogFor as ue,vllmTaskOf as re}from"./runtime-models.js";import{pickInferenceEngine as tn,pickLlamaEngine as Kn,pickMlxEngine as Qn,pickAppleEngine as Vn,recommendEngine as qn,detectAccelerator as Yn,hostShape as Zn}from"./inference-engines.js";import{tuningArgs as ce,tuningRows as rn,patchTunings as et,profilesFor as an,resolveTunings as on,ENGINE_DOCS as nt}from"./engine-tunings.js";import{IMAGE_RECIPES as tt}from"./images.js";import{pullRepo as rt,pullGguf as it,repoInstalled as at,ggufInstalled as sn}from"./model-pull.js";import{liveFit as ot,kvCacheMB as st,cachedConfigPath as lt,needMB as ut}from"./host-memory.js";import{APPLE_HELPER as Oe,APPLE_MODEL_ID as ct,APPLE_MIN_DARWIN as dt,appleHelperDirs as mt,appleInstallDoor as ft,darwinMajor as ln}from"./apple-model.js";import{spawn as pt}from"node:child_process";import{readFileSync as un,unlinkSync as cn}from"node:fs";const ht=Un(Fn),de=["podman","docker"],q="hf-cache",X=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.rerank?.url||""),configure:(r,l,f)=>{r.capabilities=r.capabilities||{},r.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(r,l)=>{r.capabilities?.rerank?.url===l&&delete r.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.decide?.url||""),configure:(r,l,f)=>{r.capabilities=r.capabilities||{},r.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(r,l)=>{r.capabilities?.decide?.url===l&&delete r.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>tn({...r,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:r=>[`${v.join(r,q)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...re(r.model)==="embed"?["--task","embed"]:[],...ce("vllm",r.tunings,{task:re(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.capabilities?.embed?.service==="vllm"?r.capabilities.embed.url.replace(/\/v1$/,""):r.capabilities?.stt?.service==="vllm"?r.capabilities.stt.url.replace(/\/v1$/,""):(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const h=`${l}/v1`,P=re(f.model);dn(r),P==="chat"?(r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(r.capabilities=r.capabilities||{},r.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(r.capabilities=r.capabilities||{},r.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>dn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>tn(r),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ce("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Kn(r),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ce("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Qn(r),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ce("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Oe,engineOf:r=>Vn(r),only:{platform:"darwin",arch:"arm64",minDarwin:dt,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:r=>[Oe,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[ct],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),ie=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function dn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),r.capabilities?.embed?.service==="vllm"&&delete r.capabilities.embed,r.capabilities?.stt?.service==="vllm"&&delete r.capabilities.stt}const _=r=>X.find(l=>l.id===r)||null,gt=({answers:r,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:H,caps:me,command:fe,engineOf:Be,alias:B,...x})=>x,kt=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),wt=Object.freeze(["brave","qwant"]);function bt(r=[]){const l=r.length?r:kt,f=wt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
2
- `)}function Ne(r=process.platform){return r==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:r==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function mn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),h=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),P=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:P,status:String(r.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}const yt=15e3;function Gt({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,D,C={})=>ht(S,D,{timeout:6e4,killSignal:"SIGKILL",...C}),platform:p=process.platform,arch:H=process.arch,osRelease:me=V.release(),spawn:fe=pt,lookup:Be=null,fetchImpl:B=globalThis.fetch,stateDir:x=v.join(V.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:pe=S=>new Promise(D=>setTimeout(D,S)),totalMem:Ce=()=>V.totalmem(),memoryProbe:fn=S=>p==="darwin"&&r?.runtime?.heatwatch!==!1?ot(S,{fetchImpl:B}):Promise.resolve(null),now:Y=()=>Date.now(),autoEnv:pn=process.env.CHATPANEL_RUNTIME_AUTO,every:Le=(S,D)=>{const C=setInterval(S,D);return C.unref?.(),C}}={}){const S=V.homedir(),D=p==="win32"?[v.join(S,"AppData","Local","Microsoft","WinGet","Links"),v.join(S,".local","bin"),v.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",v.join(S,".local","bin"),v.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?mt({home:S}):[]],C=(n=process.env)=>{const e=p==="win32"?";":":",t=String(n.PATH||n.Path||""),i=D.filter(s=>!t.split(e).includes(s));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},k=async(n,e,t={})=>{try{const i=await P(n,e,{...t,env:C(t.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},y=n=>String(r.runtime?.services?.[n.id]?.model||n.model||"");let he=null;const hn=async()=>(he===null&&(he=await Yn({exec:P,platform:p,arch:H})),he),ae={},gn=n=>{const e=p==="win32"?";":":",t=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of C().PATH.split(e).filter(Boolean))for(const s of t)try{return Hn(v.join(i,n+s),Xn.X_OK),!0}catch{}return!1},W={},L=async(n,e=["--version"])=>{if(ae[n])return!0;if(W[n]!==void 0&&Y()-W[n]<yt)return!1;const t=(Be||gn)(n)||(await k(n,e,{timeout:8e3})).ok;return t?(ae[n]=!0,delete W[n]):W[n]=Y(),t},Re=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let ge=null;const ke=async()=>(ge||(ge=await Zn({exec:P,platform:p,totalmem:Ce,cpus:()=>V.cpus()})),ge),T=async n=>({platform:p,arch:H,accelerator:await hn(),engine:n,vllmOnPath:await L("vllm"),llamaOnPath:await L("llama-server"),mlxOnPath:p==="darwin"&&H==="arm64"?await L("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?ln(me):0,appleOnPath:p==="darwin"&&H==="arm64"?await L(Oe):!1,appleInstall:p==="darwin"?ft({home:S}):null,...await ke()}),G=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===H)&&(!n.only.minDarwin||ln(me)>=n.only.minDarwin),Z=n=>v.join(x,`${n.id}.pid`),J=n=>{try{const e=Number(un(Z(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},we=n=>G(n)?J(n)?"running":"stopped":"unsupported",j={};async function oe(n){const e=ee(n);if(!G(e))return{ok:!1,error:`${e.label} runs on ${ie(e)} only`};if(J(e))return e.auto&&!e.configured(r)&&(e.configure(r,A(e),e),h()),{ok:!0,already:!0,url:A(e)};if(e.auto&&await e.answers(A(e),B)){const $=await yn(e.port);if($)return te(x,{recursive:!0,mode:448}),le(Z(e),String($),{mode:384}),j[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,A(e),e),h(),E(`[runtime] ${e.label} was already answering on ${A(e)} (pid ${$}) — adopted`),{ok:!0,adopted:!0,url:A(e),answering:!0,provides:e.provides}}const t=await T(null),i=e.engineOf(t);if(!await L(e.runner,e.runnerCheck))return{ok:!1,error:Re(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Pe(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,I(e,e.model,i,t)),a=v.join(x,q);te(a,{recursive:!0,mode:448});const d={bin:s,argv:o,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:a,LLAMA_CACHE:a,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};j[e.id]=d.record;const u=v.join(x,`${e.id}.log`);let c,m=null;try{try{m=Dn(u,"w",384)}catch{m=null}c=fe(d.bin,d.argv,{...d.opts,env:C(d.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),c.unref?.()}catch($){return{ok:!1,error:`${d.bin}: ${$.message}`,install:i.install}}finally{if(m!==null)try{jn(m)}catch{}}if(!c?.pid)return{ok:!1,error:`${d.bin} did not start`,install:i.install};le(Z(e),String(c.pid),{mode:384});const w=A(e);let g=!1;for(let $=0;$<120&&!g&&J(e);$++)g=await e.answers(w,B),g||await pe(1e3);if(!J(e)){try{cn(Z(e))}catch{}let $="";try{$=un(u,"utf8").trim().split(`
3
- `).filter(U=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(U)).slice(-3).map(U=>U.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(r,w,e),h(),E(`[runtime] ${e.label} started (pid ${c.pid}) on ${w}, sandbox ${j[e.id].layer}${g?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:w,answering:g,provides:e.provides,model:y(e),sandbox:j[e.id]}}const be=n=>r.runtime?.services?.[n.id]?.off===!0,Te=(n,e)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const t={...r.runtime.services[n.id]||{}};e?t.off=!0:delete t.off,r.runtime.services[n.id]=t},kn=()=>r.runtime?.auto!==!1&&String(pn||"").toLowerCase()!=="off",O={};async function Ge(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!kn())return{ok:!1,skipped:"automatic start is switched off"};if(!G(n))return{ok:!1,skipped:`runs on ${ie(n)} only`};if(be(n))return{ok:!1,skipped:"stopped by the person"};if(!await L(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!J(n)){const t=await k(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return O[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:O[n.id]}}}const e=await oe(n);return e.ok?(delete O[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(O[n.id]=e.error,{ok:!1,skipped:e.error})}async function wn(){const n=[];for(const e of X.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await Ge(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function bn(n){const e=_(n);return e?.auto?Ge(e):{ok:!1,skipped:"not a service that starts by itself"}}async function yn(n){if(p==="win32")return 0;const e=await k("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
4
- `)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function Ie(n){const e=J(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{cn(Z(n))}catch{}return n.unconfigure(r,A(n)),h(),{ok:!0}}const ee=n=>n.model?{...n,model:y(n),installed:Q(n,y(n)),tunings:r.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:vn(y(n))}:{}}:n,z=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function $n(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=ue(n.id).filter(d=>!d.minRamMB||t>0&&t>=d.minRamMB);if(!s.length||!t)return null;const o=s.slice().sort((d,u)=>(i[u.tier]??-1)-(i[d.tier]??-1)||d.ramMB-u.ramMB)[0],a=Math.round(o.ramMB/1024*10)/10;return{model:o.id,label:o.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${o.label} well — about ${a} GB while loaded${o.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:y(n)===o.id}}async function Ue(n,{model:e,ctx:t,needMB:i}={}){const s=_(n);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${n}`};const o=String(e||y(s)),a=ue(n).find(Ee=>Ee.id===o)||null,d=Number(i)>0?Number(i):a?.ramMB||null;if(!d)return{ok:!1,error:`${o} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):Ye(n),c=/\.gguf$/i.test(o)||s.id==="llama"?null:lt(K(),o),m=u&&c?st(c,u):null,w=ut({ramMB:d,kvMB:m||0}),g=s.kind==="native"?await fn(w):null,$=((await ke()).ramGB||0)*1024,U=g?g.fits:$>0&&w<=$,F=Ee=>`${Math.round(Ee/102.4)/10} GB`,In=g?g.fits?`${o} fits: needs about ${F(w)}, ${F(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${F(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${F(w)} and ${F(g.availableMB)} is free now — ${F(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${F(w)} of the machine's ${F($)} — ${U?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:w,weightsMB:d,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:U,live:g,advice:In}}const I=(n,e,t,i={})=>({task:n.id==="vllm"?re(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),K=()=>v.join(x,q),Q=(n,e)=>/\.gguf$/i.test(e)?Pe(e):n.id==="llama"?!!sn(K(),e):at(K(),e),vn=n=>/\.gguf$/i.test(n)?n:sn(K(),n),b={},$t=n=>b[n.id]||null;function ye(n,e,t={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},b[n.id]}function N(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const se=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(s=>{if(n.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=fe(e,t,{stdio:["ignore","pipe","pipe"],env:C()})}catch(c){return s({ok:!1,code:-1,error:c.message})}n.child=o;let a="";const d=c=>{a+=String(c);const m=a.split(/\r?\n|\r/);a=m.pop();for(const w of m)N(n,w)};o.stdout?.on("data",d),o.stderr?.on("data",d);const u=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);u.unref?.(),o.on("error",c=>{clearTimeout(u),n.child=null,s({ok:!1,code:-1,error:c.message})}),o.on("exit",c=>{clearTimeout(u),n.child=null,a&&N(n,a),s({ok:c===0&&!n.cancelled,code:c,...n.cancelled?{error:"cancelled"}:{}})})}),Fe={install:Promise.resolve(),build:Promise.resolve()},$e={install:0,build:0},He=(n,e,t)=>{$e[n]>0&&(e.waiting=!0,N(e,`waiting for the other ${n} to finish first — one at a time`)),$e[n]++;const i=Fe[n];let s;const o=new Promise(a=>{s=a});return Fe[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(N(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{$e[n]--,s()}})},De=async(n,e)=>(await k(n,["image","exists",e],{timeout:2e4})).ok;async function Sn(n,e,t,i){const s=e?.image||t.image;if(await De(n,s))return{ok:!0};const o=e?.sources?.length?e.sources:[s],a=[];for(const m of o){if(i.kind="pull-image",i.detail=m,N(i,`pulling ${m}`),(await se(i,n,["pull",m])).ok)return m!==s&&await k(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const d=e?.recipe?tt[e.recipe]:null;if(!d)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=v.join(x,"images",e.recipe);return te(u,{recursive:!0,mode:448}),le(v.join(u,"Dockerfile"),d.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=d.minutes,N(i,`no registry has ${s} for this machine — building it here (about ${d.minutes} minutes)`),E(`[runtime] building ${s} from the ${e.recipe} recipe in ${u}`),(await He("build",i,()=>se(i,n,["build","-t",s,"-f",v.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function je(n,e){const t=y(n);if(!t||Q(n,t))return{ok:!0};if(/\.gguf$/i.test(t))return{ok:!1,error:`no such file: ${t}`};e.kind="pull-model",e.detail=t;const i=s=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:s.bytes,total:s.total,file:s.file}};try{return n.id==="llama"?await it(t,{root:K(),fetchImpl:B,onProgress:i}):await rt(t,{root:K(),fetchImpl:B,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${t}: ${s.message}`}}}async function An(n,e,t){const i=[];return n.kind!=="native"&&e&&!await De(e,t?.image||n.image)&&i.push("image"),n.pull&&n.model&&!Q(n,y(n))&&i.push("model"),i}async function Xe(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const t=await k("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?i:0}if(n==="docker"&&p!=="linux"){const t=await k("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(Ce()/1048576)}async function M(){const n={};for(const t of de){const i=await k(t,["--version"],{timeout:5e3});if(!i.ok){n[t]={installed:!1};continue}const s=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let o=!1,a=null;if(t==="podman")if(p==="linux")o=(await k("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const d=await k("podman",["machine","list","--format","json"],{timeout:8e3});try{const c=JSON.parse(d.out||"[]")[0]||null;a=c?{name:c.Name,running:!!c.Running}:null,o=!!c?.Running}catch{a=null}}else o=(await k("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:s,running:o,...t==="podman"&&p!=="linux"?{machine:a}:{}}}const e=de.find(t=>n[t]?.installed&&n[t].running)||de.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:Ne(p)}}}async function ve(n="podman"){if(!de.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await M())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:Ne(p)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!e.machine){const i=await k("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await k("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function We(){const n=await M(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await k("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>mn(s,"podman"))}catch{return[]}}const t=await k("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
5
- `).filter(Boolean).map(i=>{try{return mn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Je(n,e){const t=await k(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function Se(n,e){const t=await k(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const o of e)i[o]="absent";return i}const s=new Map(t.out.split(`
6
- `).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function ze(){const n=await M(),e=n.preferred,t=await Xe(e,n),i={},s=await T(e),o=e&&n[e].running?await Se(e,X.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of X){const d=A(a);let u="no-engine";a.kind==="native"?u=we(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const c=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:t;i[a.id]={...gt(a),engine:a.kind==="native"?"host":e,state:u,url:d,configured:a.configured(r),answering:u==="running"?await a.answers(d,B):!1,...a.helper?{asleep:R.has(a.id),idleMinutes:Ze()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!G(a)?{why:`${a.label} runs on ${ie(a)} only`}:{},...a.auto&&u!=="running"&&G(a)?{auto:!0,...be(a)?{why:"Stopped here — Start turns it back on"}:O[a.id]?{why:O[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&G(a)&&O[a.id]?{why:O[a.id]}:{},...a.kind==="native"&&j[a.id]?{sandbox:j[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...z(a)?{profiles:an(a.id,r.runtime?.services?.[a.id]?.tunings,I(a,c,m,s)),docs:nt[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:$n(a,s)}:{},...a.model?{model:c,default:a.model,models:nn(a.id,{active:c,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>Q(a,g)}),machine:{engineRamMB:w}}:{},...z(a)?{tunings:rn(a.id,r.runtime?.services?.[a.id]?.tunings,I(a,c,m,s))}:{}}}return i}async function Mn(){const n=await M(),e=await T(n.preferred);return{platform:p,arch:H,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:qn(e)}}function Ke(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:s=null}={}){const o=ee(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(x):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const d=Jn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${d}`),{args:a,hash:d}}const Ae={};async function _n(n){if(Ae[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Ae[n]=Number.isFinite(t)&&t>0?t:V.cpus()?.length||2}return Math.max(1,Math.floor(Ae[n]/2))}async function Qe(n,{force:e=!1}={}){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};R.delete(t.id),xe(t.id),t.auto&&be(t)&&Te(t,!1);const i=b[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(t.kind!=="native"){const c=await M();if(s=c.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Ne(p)};if(!c[s].running){const m=await ve(s);if(!m.ok)return m}}else if(!G(t))return{ok:!1,error:`${t.label} runs on ${ie(t)} only`};const o=await T(s),a=t.engineOf?t.engineOf(o):null;if(t.kind==="native"&&!await L(t.runner,t.runnerCheck))return{ok:!1,error:Re(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(y(t))&&!Pe(y(t)))return{ok:!1,error:`no such file: ${y(t)}`};if(t.kind==="native"&&t.model&&!e){const c=await Ue(t.id);if(c.live&&!c.fits)return{ok:!1,error:c.advice,plan:c}}const d=await An(t,s,a);if(!d.length){if(delete b[t.id],t.kind!=="native")return Me(t,s);const c=await oe(t);return c.ok?delete O[t.id]:O[t.id]=c.error,c}const u=ye(t,d[0]==="image"?"pull-image":"pull-model",{detail:d[0]==="image"?a?.image||t.image:y(t)});return u.then=(async()=>{try{if(d.includes("image")){const m=await Sn(s,a,t,u);if(!m.ok)throw new Error(m.error)}if(d.includes("model")){const m=await je(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const c=t.kind==="native"?await oe(t):await Me(t,s);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,E(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,E(`[runtime] ${t.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function xn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=b[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return N(t,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function Me(n,e){let t=await Je(e,n.container);const i=n.helper?await _n(e):null,s=n.engineOf?n.engineOf(await T(e)):null,o=n.id==="searxng"?v.join(x,"searxng-settings.yml"):null,a=Ke(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(t!=="absent"){const c=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!c.ok||c.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const c=await k(e,["start",n.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${e} start: ${c.err||c.out}`}}else{te(x,{recursive:!0,mode:448});let c=null;n.id==="searxng"&&(le(o,bt(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),c=Wn(32).toString("hex")),n.volumes&&te(v.join(x,q),{recursive:!0,mode:448});const{args:m}=Ke(n,{settingsFile:o,secret:c,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const d=A(n);let u=!1;for(let c=0;c<30&&!u;c++)u=await n.answers(d,B),u||await pe(1e3);return n.configure(r,d,ee(n)),h(),{ok:!0,url:d,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function En(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(R.delete(e.id),delete _e[e.id],e.auto&&Te(e,!0),e.kind==="native")return Ie(e);const t=await M(),i=t.preferred;if(i&&t[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(r,A(e)),h(),{ok:!0}}async function Pn(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!t.model)return{ok:!1,error:`${t.label} takes no model`};const i=String(e||"").trim();if(!zn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=t.kind==="native"?((await ke()).ramGB||0)*1024:await Xe(o,s),d=nn(n,{active:i,engineRamMB:a,engine:t.kind==="native"?"host":o,platform:p,installed:m=>Q(t,m)}).find(m=>m.id===i);if(d?.unavailable)return{ok:!1,error:`${i} ${d.unavailable}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:i};const u=A(t);t.configured(r)===u&&t.configure(r,u,ee(t)),h();const c=await Ve(t,o,s);return c.ok?{ok:!0,model:i,restarted:c.restarted,...d?.ramNote?{note:d.ramNote}:{}}:c}async function Ve(n,e,t){if(n.kind==="native"){if(we(n)!=="running")return{ok:!0,restarted:!1};Ie(n);const o=await oe(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Je(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await Qe(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function On(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!z(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await M(),s=await T(i.preferred),o=t.engineOf?t.engineOf(s):null,a=an(t.id,r.runtime?.services?.[n]?.tunings,I(t,y(t),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const d=await qe(n,a.patch);return d.ok?{...d,profile:a.id}:d}async function Nn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!G(e))return{ok:!1,error:`${e.label} runs on ${ie(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(delete ae[e.runner],delete W[e.runner],await L(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await T(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=ye(e,"install",{detail:e.runner});return o.then=He("install",o,async()=>{const a=async c=>{for(const[m,...w]of c){N(o,`$ ${m} ${w.join(" ")}`);let g=await se(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(U=>/already locked|Please wait for it to finish/i.test(U));$++)N(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await pe(2e4),g=await se(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let d=await a(s.steps);!d.ok&&!o.cancelled&&s.fallback?.length&&(N(o,`${d.error} — trying the other way`),d=await a(s.fallback)),delete ae[e.runner],delete W[e.runner];const u=d.ok&&await L(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":d.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${d.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function Bn(n){const e=_(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Q(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=ye(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await je(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function qe(n,e){const t=_(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!z(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(t),a=await T(s),d=t.engineOf?t.engineOf(a):null,u=et(t.id,r.runtime?.services?.[n]?.tunings,e,I(t,o,d,a));if(u.error)return{ok:!1,error:u.error};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},tunings:u},h();const c=await Ve(t,s,i);return c.ok?{ok:!0,tunings:rn(t.id,u,I(t,o,d,a)),restarted:c.restarted}:c}async function Cn(){const n=await M(),e=n.preferred,t=e&&n[e].running?await Se(e,X.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(X.map(async o=>{const a=o.kind==="native"?we(o):e&&n[e].running?t[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),B)?"up":"down";const d=(o.provides||[]).some(u=>["embedded","none"].includes(r.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!d&&o.configured(r)!==A(o)&&(o.configure(r,A(o),ee(o)),s=!0)})),s&&h(),i}function Ye(n){const e=_(n);if(e?.window)return e.window;if(!e||!z(e))return null;const t=Number(on(e.id,r.runtime?.services?.[n]?.tunings,I(e,y(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function Ln(n){const e=_(n);if(e?.card)return e.card;if(!e||!z(e))return null;const t=y(e),i=on(e.id,r.runtime?.services?.[n]?.tunings,I(e,t,null,{})),s=ue(e.id).find(a=>a.id===t)||null,o=e.id==="vllm"?re(t):"chat";return{engine:e.id,backend:j[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Rn=10,Ze=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Rn)*6e4},Tn=Y(),_e={},R=new Set,ne={};function xe(n){_e[n]=Y()}async function Gn(n,{force:e=!1}={}){const t=_(n);if(!t||!t.helper)return{ok:!0};if(xe(t.id),!R.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await We()).find(s=>s.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};R.add(t.id)}return ne[t.id]||(ne[t.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await ve(s);if(!a.ok)return a}const o=await Me(t,s);return o.ok&&(R.delete(t.id),E(`[runtime] ${t.label}: woken for a request`)),o})().finally(()=>{delete ne[t.id]})),ne[t.id]}async function en(){const n=Ze();if(!n)return[];const e=X.filter(a=>a.helper&&a.configured(r)&&!R.has(a.id)&&!ne[a.id]&&!(b[a.id]&&!b[a.id].done)&&Y()-(_e[a.id]??Tn)>=n);if(!e.length)return[];const t=await M(),i=t.preferred;if(!i||!t[i].running){for(const a of e)R.add(a.id);return e.map(a=>a.id)}const s=await Se(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}R.add(a.id),o.push(a.id)}return o}return Le&&Le(()=>{en().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Gn,sweepIdle:en,health:Cn,contextWindow:Ye,modelCard:Ln,async status(){const[n,e,t,i,s]=await Promise.all([l().catch(()=>null),M(),ze(),We(),Mn()]);return{machine:s,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:t}},startEngine:ve,startService:Qe,stopService:En,ensureDefaults:wn,revive:bn,plan:Ue,setModel:Pn,setTunings:qe,setProfile:On,pullModel:Bn,installRunner:Nn,cancelJob:xn,services:ze,catalogFor:ue}}export{kt as SEARXNG_DEFAULT_ENGINES,X as SERVICES,mn as containerRow,Gt as createRuntime,Ne as installDoor,bt as searxngSettings};
1
+ import{promisify as xt}from"node:util";import{execFile as Pt}from"node:child_process";import{existsSync as Qe,mkdirSync as pe,writeFileSync as ye,accessSync as Nn,openSync as Et,closeSync as Ot,constants as Ln}from"node:fs";import{randomBytes as Bt,createHash as Nt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Tn,isValidModelId as Cn,catalogFor as $e,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Rn,pickLlamaEngine as Lt,pickMlxEngine as Tt,pickAppleEngine as Ct,recommendEngine as Rt,detectAccelerator as Gt,hostShape as Ut}from"./inference-engines.js";import{tuningArgs as ve,tuningRows as Gn,patchTunings as Un,profilesFor as Hn,resolveTunings as In,splitTunings as ge,ENGINE_DOCS as Ht}from"./engine-tunings.js";import{IMAGE_RECIPES as It}from"./images.js";import{pullRepo as Ft,pullGguf as jt,repoInstalled as Dt,ggufInstalled as Fn,ggufRecipe as Ye,planGgufRecipe as Xt}from"./model-pull.js";import{llamaKnows as jn,llamaFlags as zt}from"./llama-arch.js";import{installBuild as Vt,installedBuild as Wt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as Dn,DEFAULT_LLAMA_BUILD as Jt}from"./llama-builds.js";import{liveFit as qt,kvCacheMB as Kt,cachedConfigPath as Qt,needMB as Xn}from"./host-memory.js";import{APPLE_HELPER as Ze,APPLE_MODEL_ID as Yt,APPLE_MIN_DARWIN as Zt,appleHelperDirs as er,appleInstallDoor as nr,darwinMajor as zn}from"./apple-model.js";import{transferRate as tr}from"./transfer-rate.js";import{capabilityList as Se,primaryProvider as rr,withProvider as Vn,withoutProvider as Wn}from"./capability-config.js";import{isEmbeddedModel as ir}from"./embedded-models.js";import{spawn as ar}from"node:child_process";import{readFileSync as Jn,unlinkSync as qn,realpathSync as or,readdirSync as Kn}from"node:fs";const sr=xt(Pt),Me=["podman","docker"],ae="hf-cache",F=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>_e(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>xe(r,"rerank",f=>f.url===l)},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",retired:{why:"Retired — decisions are answered in the gateway with the same zero-shot models. Bring another decision model on the Models page.",instead:"Models › Decide"},model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>_e(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>xe(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Rn({...r,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...he(r.model)==="embed"?["--task","embed"]:[],...ve("vllm",r.tunings,{task:he(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||Ae(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,R=he(f.model);Qn(r),R==="chat"?(r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm"&&h?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:p,models:[f.model],service:"vllm"})):R==="embed"?_e(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):R==="transcription"&&_e(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Qn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Rn(r),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm-metal"&&p?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Lt(r),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ve("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="llama"&&p?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Tt(r),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="mlx"&&p?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Ze,engineOf:r=>Ct(r),only:{platform:"darwin",arch:"arm64",minDarwin:Zt,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:r=>[Ze,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[Yt],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),oe=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function Qn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),xe(r,"embed",l=>l.service==="vllm"),xe(r,"stt",l=>l.service==="vllm")}function Ae(r,l,f){return Se(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function en(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function _e(r,l,f){en(r,l,Vn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function xe(r,l,f){r.capabilities?.[l]&&en(r,l,Wn(r.capabilities[l],l,f))}const A=r=>F.find(l=>l.id===r)||null,lr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:R,args:h,env:z,caps:Pe,command:Ee,engineOf:tn,alias:Oe,...B})=>B,ur=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),cr=Object.freeze(["brave","qwant"]);function dr(r=[]){const l=r.length?r:ur,f=cr.filter(p=>!l.includes(p));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(p=>[` - name: ${p}`," disabled: false"]),...f.flatMap(p=>[` - name: ${p}`," disabled: true"]),""].join(`
2
+ `)}function nn(r=process.platform){return r==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:r==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function Yn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),p=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(h=>`${h.host_ip||""}:${h.host_port}->${h.container_port}/${h.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(h=>h.trim()).filter(Boolean),R=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:R,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const mr=15e3;function Tr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:R=(x,q,G={})=>sr(x,q,{timeout:6e4,killSignal:"SIGKILL",...G}),platform:h=process.platform,arch:z=process.arch,osRelease:Pe=ie.release(),spawn:Ee=ar,lookup:tn=null,archKnower:Oe=null,fetchImpl:B=globalThis.fetch,stateDir:N=$.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Be=x=>new Promise(q=>setTimeout(q,x)),totalMem:rn=()=>ie.totalmem(),memoryProbe:Zn=x=>h==="darwin"&&r?.runtime?.heatwatch!==!1?qt(x,{fetchImpl:B}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:et=process.env.CHATPANEL_RUNTIME_AUTO,every:an=(x,q)=>{const G=setInterval(x,q);return G.unref?.(),G}}={}){const x=ie.homedir(),q=h==="win32"?[$.join(x,"AppData","Local","Microsoft","WinGet","Links"),$.join(x,".local","bin"),$.join(x,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",$.join(x,".local","bin"),$.join(x,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...h==="darwin"?er({home:x}):[]],G=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=q.filter(o=>!t.split(e).includes(o));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},b=async(n,e,t={})=>{try{const i=await R(n,e,{...t,env:G(t.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},w=n=>String(r.runtime?.services?.[n.id]?.model||n.model||"");let Ne=null;const on=async()=>(Ne===null&&(Ne=await Gt({exec:R,platform:h,arch:z})),Ne),K={},nt=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t)try{return Nn($.join(i,n+o),Ln.X_OK),!0}catch{}return!1},Le=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t){const s=$.join(i,n+o);try{return Nn(s,Ln.X_OK),s}catch{}}return null},Q={},U=async(n,e=["--version"])=>{if(K[n])return!0;if(Q[n]!==void 0&&se()-Q[n]<mr)return!1;const t=(tn||nt)(n)||(await b(n,e,{timeout:8e3})).ok;return t?(K[n]=!0,delete Q[n]):Q[n]=se(),t},ne=n=>{const e=Le(n);let t;try{t=or(e)}catch{return null}const i=/[\\/]Cellar[\\/][^\\/]+[\\/]([^\\/]+)[\\/]/.exec(t);if(i)return i[1].replace(/_\d+$/,"");try{const o=$.join($.dirname(t),"..","lib");for(const s of Kn(o)){const a=$.join(o,s,"site-packages"),c=Kn(a).find(u=>/\.dist-info$/.test(u)&&u.toLowerCase().startsWith(`${$.basename($.dirname($.dirname(t))).replace(/-/g,"_").toLowerCase()}-`));if(c){const u=c.replace(/\.dist-info$/,"");return u.slice(u.lastIndexOf("-")+1)}}}catch{}return null},te=()=>r.runtime?.services?.llama?.build==="system"?"system":Jt,Y=n=>n?.id==="llama"&&te()==="unsloth",V=()=>Wt(N,h),le=()=>te()==="system"?"llama-server":V()?.bin||null,Te=()=>te()==="system"?Le("llama-server"):V()?.bin||null,sn=()=>te()==="system"?ne("llama-server"):V()?.tag||null,tt=Object.freeze({command:`downloaded from github.com/${v.repo} (${v.tag}), checked against its SHA-256`,note:`${v.label}: ${v.why}.`,url:`https://github.com/${v.repo}/releases`,update:{command:`the newest ${v.label} release, checked against its SHA-256`,steps:[["unsloth-llama"]]}});async function Ce(n,{tag:e=v.tag}={}){n.kind=n.kind==="update"?"update":"install",n.detail=v.label,O(n,`fetching ${v.label} (${e==="latest"?"the newest release":e}) from github.com/${v.repo}`);try{const t=await Vt({stateDir:N,platform:h,arch:z,accelerator:await on(),tag:e,fetchImpl:B,run:b,onProgress:gn(n)});return O(n,t.already?`${v.label} ${t.tag} — already here`:`${v.label} ${t.tag} — checked against its published SHA-256`),{ok:!0,...t}}catch(t){return{ok:!1,error:n.cancelled?"cancelled":t.message}}}const ln=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let Re=null;const ke=async()=>(Re||(Re=await Ut({exec:R,platform:h,totalmem:rn,cpus:()=>ie.cpus()})),Re),H=async n=>({platform:h,arch:z,accelerator:await on(),engine:n,vllmOnPath:await U("vllm"),llamaOnPath:await U("llama-server"),mlxOnPath:h==="darwin"&&z==="arm64"?await U("mlx_lm.server",["--help"]):!1,osMajor:h==="darwin"?zn(Pe):0,appleOnPath:h==="darwin"&&z==="arm64"?await U(Ze):!1,appleInstall:h==="darwin"?nr({home:x}):null,...await ke()}),C=n=>!n.only||(!n.only.platform||n.only.platform===h)&&(!n.only.arch||n.only.arch===z)&&(!n.only.minDarwin||zn(Pe)>=n.only.minDarwin),ue=n=>$.join(N,`${n.id}.pid`),re=n=>{try{const e=Number(Jn(ue(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ce=n=>C(n)?re(n)?"running":"stopped":"unsupported",Z={};async function Ge(n){const e=de(n);if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};if(re(e))return e.auto&&!e.configured(r)&&(e.configure(r,_(e),e),p()),{ok:!0,already:!0,url:_(e)};if(e.auto&&await e.answers(_(e),B)){const M=await st(e.port);if(M)return pe(N,{recursive:!0,mode:448}),ye(ue(e),String(M),{mode:384}),Z[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,_(e),e),p(),S(`[runtime] ${e.label} was already answering on ${_(e)} (pid ${M}) — adopted`),{ok:!0,adopted:!0,url:_(e),answering:!0,provides:e.provides}}const t=await H(null),i=e.engineOf(t);if(Y(e)?!le():!await U(e.runner,e.runnerCheck))return Y(e)?{ok:!1,error:`${v.label} is not downloaded yet — Start fetches it`}:{ok:!1,error:ln(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Qe(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[o,s]=e.command(e,D(e,e.model,i,t)),a=e.id==="llama"?le():o,c=$.join(N,ae);pe(c,{recursive:!0,mode:448});const u={bin:a,argv:s,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:c,LLAMA_CACHE:c,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};Z[e.id]=u.record;const d=$.join(N,`${e.id}.log`);let m,k=null;try{try{k=Et(d,"w",384)}catch{k=null}m=Ee(u.bin,u.argv,{...u.opts,env:G(u.opts?.env),detached:!0,stdio:["ignore",k??"ignore",k??"ignore"]}),m.unref?.()}catch(M){return{ok:!1,error:`${u.bin}: ${M.message}`,install:i.install}}finally{if(k!==null)try{Ot(k)}catch{}}if(!m?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};ye(ue(e),String(m.pid),{mode:384});const g=_(e);let E=!1;for(let M=0;M<120&&!E&&re(e);M++)E=await e.answers(g,B),E||await Be(1e3);if(!re(e)){try{qn(ue(e))}catch{}let M="";try{M=Jn(d,"utf8").trim().split(`
3
+ `).filter(T=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(T)).slice(-3).map(T=>T.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{M=""}return{ok:!1,error:`${e.label} exited on start${M?` — ${M}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:d}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Z[e.id].layer}${E?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:E,provides:e.provides,model:w(e),sandbox:Z[e.id]}}const Ue=n=>r.runtime?.services?.[n.id]?.off===!0,un=(n,e)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const t={...r.runtime.services[n.id]||{}};e?t.off=!0:delete t.off,r.runtime.services[n.id]=t},cn=()=>r.runtime?.auto!==!1&&String(et||"").toLowerCase()!=="off",L={};async function dn(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!cn())return{ok:!1,skipped:"automatic start is switched off"};if(!C(n))return{ok:!1,skipped:`runs on ${oe(n)} only`};if(Ue(n))return{ok:!1,skipped:"stopped by the person"};if(!await U(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!re(n)){const t=await b(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return L[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:L[n.id]}}}const e=await Ge(n);return e.ok?(delete L[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(L[n.id]=e.error,{ok:!1,skipped:e.error})}const mn=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{},r.runtime.services[n.id]={...r.runtime.services[n.id]||{},pulling:{model:e,start:!!t}},p()},He=n=>{const e=r.runtime?.services?.[n.id];e?.pulling&&(delete e.pulling,p())};function fn(){let n=!1;for(const e of F.filter(t=>t.retired))for(const t of e.provides||[]){const i=r.capabilities?.[t];if(!i||!Se(i,t).providers.some(c=>c.service===e.id))continue;const o=Se(i,t).providers.find(c=>c.service===e.id),s={provider:"embedded",...ir(t,o?.model)?{model:o.model}:{}},a=Se(i,t).providers.some(c=>c.provider==="embedded"&&(c.model||null)===(s.model||null));en(r,t,a?Wn(i,t,c=>c.service===e.id):Vn(i,t,s,{match:c=>c.service===e.id})),S(`[runtime] ${e.label} is retired: ${t} now answers in the gateway${s.model?` with ${s.model}`:""}`),n=!0}n&&p()}async function rt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.retired)return{ok:!1,error:`${e.label} is not retired — stop it instead`};const t=(await P()).preferred;if(!t)return{ok:!1,error:"no container engine"};const i=await b(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 b(t,["rmi",e.image],{timeout:6e4});return e.unconfigure(r,_(e)),p(),S(`[runtime] ${e.label} removed (container${o.ok?" and image":""})`),{ok:!0,removed:{container:!0,image:!!o.ok}}}async function it(){const n=[];if(!cn())return n;for(const e of F.filter(t=>t.pull)){const t=r.runtime?.services?.[e.id]?.pulling;if(t){if(t.model!==w(e)||J(e,w(e))){He(e),J(e,w(e))&&t.start&&n.push({id:e.id,...await ee(e.id).catch(i=>({ok:!1,error:i.message}))});continue}S(`[runtime] ${e.label}: resuming the download of ${t.model} a previous run left under way`),n.push({id:e.id,resumed:t.model,...await(t.start?ee(e.id):xn(e.id)).catch(i=>({ok:!1,error:i.message}))})}}return n}async function at(){try{fn()}catch(e){S(`[runtime] retiring: ${e.message}`)}try{pn()}catch(e){S(`[runtime] settings per model: ${e.message}`)}const n=[...await it().catch(()=>[])];for(const e of F.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await dn(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function ot(n){const e=A(n);return e?.auto?dn(e):{ok:!1,skipped:"not a service that starts by itself"}}async function st(n){if(h==="win32")return 0;const e=await b("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
4
+ `)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function we(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{qn(ue(n))}catch{}return n.unconfigure(r,_(n)),p(),{ok:!0}}const de=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:j(n,w(n)),...n.id==="llama"?{file:ut(w(n))}:{}}:n,W=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx",j=(n,e)=>{const t=r.runtime?.services?.[n.id]||{},{engine:i,model:o}=ge(t.tunings),s=e&&t.byModel?.[e]?t.byModel[e]:e&&e===w(n)?o:{};return{...i,...s}},Ie=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const i=r.runtime.services[n.id]||{},{engine:o,model:s}=ge(t),a={...i.byModel||{}};e&&(Object.keys(s).length?a[e]=s:delete a[e]),r.runtime.services[n.id]={...i,tunings:o,...Object.keys(a).length?{byModel:a}:{}},Object.keys(a).length||delete r.runtime.services[n.id].byModel};function pn(){let n=!1;for(const e of F.filter(W)){const t=r.runtime?.services?.[e.id];if(!t?.tunings)continue;const{model:i}=ge(t.tunings);if(!Object.keys(i).length)continue;const o=w(e);o?Ie(e,o,{...i,...(t.byModel||{})[o]||{},...ge(t.tunings).engine}):t.tunings=ge(t.tunings).engine,n=!0}n&&p()}function lt(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=$e(n.id).filter(c=>!c.minRamMB||t>0&&t>=c.minRamMB);if(!o.length||!t)return null;const s=o.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(s.ramMB/1024*10)/10;return{model:s.id,label:s.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${s.label} well — about ${a} GB while loaded${s.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:w(n)===s.id}}async function hn(n,{model:e,ctx:t,needMB:i}={}){const o=A(n);if(!o||!o.model)return{ok:!1,error:o?`${o.label} takes no model`:`unknown service ${n}`};const s=String(e||w(o)),a=$e(n).find(Ke=>Ke.id===s)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${s} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):En(n),d=/\.gguf$/i.test(s)||o.id==="llama"?null:Qt(X(),s),m=u&&d?Kt(d,u):null,k=Xn({ramMB:c,kvMB:m||0}),g=o.kind==="native"?await Zn(k):null,E=((await ke()).ramGB||0)*1024,M=g?g.fits:E>0&&k<=E,T=Ke=>`${Math.round(Ke/102.4)/10} GB`,_t=g?g.fits?`${s} fits: needs about ${T(k)}, ${T(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${T(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${s} needs about ${T(k)} and ${T(g.availableMB)} is free now — ${T(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${s} needs about ${T(k)} of the machine's ${T(E)} — ${M?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:o.id,model:s,needMB:k,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:M,live:g,advice:_t}}const D=(n,e,t,i={})=>({task:n.id==="vllm"?he(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0,...n.id==="llama"?{recipe:Ye(X(),e),flags:zt(Te())}:{}}),X=()=>$.join(N,ae),J=(n,e)=>/\.gguf$/i.test(e)?Qe(e):n.id==="llama"?!!Fn(X(),e):Dt(X(),e),ut=n=>/\.gguf$/i.test(n)?n:Fn(X(),n),y={},fr=n=>y[n.id]||null;function gn(n){const e=tr();return t=>{if(n.cancelled)throw new Error("cancelled");n.progress={bytes:t.bytes,total:t.total,file:t.file,...e(t.bytes,{skipped:!!t.skipped,total:t.total})}}}function me(n,e,t={}){return y[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},y[n.id]}function O(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 be=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(o=>{if(n.cancelled)return o({ok:!1,code:-1,error:"cancelled"});let s;try{s=Ee(e,t,{stdio:["ignore","pipe","pipe"],env:G()})}catch(d){return o({ok:!1,code:-1,error:d.message})}n.child=s;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const k of m)O(n,k)};s.stdout?.on("data",c),s.stderr?.on("data",c);const u=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}},i);u.unref?.(),s.on("error",d=>{clearTimeout(u),n.child=null,o({ok:!1,code:-1,error:d.message})}),s.on("exit",d=>{clearTimeout(u),n.child=null,a&&O(n,a),o({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),kn={install:Promise.resolve(),build:Promise.resolve()},Fe={install:0,build:0},wn=(n,e,t)=>{Fe[n]>0&&(e.waiting=!0,O(e,`waiting for the other ${n} to finish first — one at a time`)),Fe[n]++;const i=kn[n];let o;const s=new Promise(a=>{o=a});return kn[n]=i.then(()=>s),i.then(async()=>{e.waiting&&(O(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{Fe[n]--,o()}})},bn=async(n,e)=>(await b(n,["image","exists",e],{timeout:2e4})).ok;async function ct(n,e,t,i){const o=e?.image||t.image;if(await bn(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,O(i,`pulling ${m}`),(await be(i,n,["pull",m])).ok)return m!==o&&await b(n,["tag",m,o],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?It[e.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=$.join(N,"images",e.recipe);return pe(u,{recursive:!0,mode:448}),ye($.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=o,i.minutes=c.minutes,O(i,`no registry has ${o} for this machine — building it here (about ${c.minutes} minutes)`),S(`[runtime] building ${o} from the ${e.recipe} recipe in ${u}`),(await wn("build",i,()=>be(i,n,["build","-t",o,"-f",$.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function yn(n,e){const t=w(n);if(!t||J(n,t))return{ok:!0};if(/\.gguf$/i.test(t))return{ok:!1,error:`no such file: ${t}`};e.kind="pull-model",e.detail=t;const i=gn(e);try{if(n.id==="llama"){const o=j(n,t);await jt(t,{root:X(),fetchImpl:B,onProgress:i,knows:(Oe||jn)(Te()),engineVersion:sn(),vision:o.vision!=="off",draft:o.draftModel!=="off"})}else await Ft(t,{root:X(),fetchImpl:B,onProgress:i});return{ok:!0}}catch(o){return{ok:!1,error:`pull ${t}: ${o.message}`}}}async function dt(n,e,t){const i=[];return Y(n)&&!le()&&i.push("runner"),n.kind!=="native"&&e&&!await bn(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 b("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 b("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(rn()/1048576)}async function P(){const n={};for(const t of Me){const i=await b(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 b("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await b("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(c.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,s=!!d?.Running}catch{a=null}}else s=(await b("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:o,running:s,...t==="podman"&&h!=="linux"?{machine:a}:{}}}const e=Me.find(t=>n[t]?.installed&&n[t].running)||Me.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:nn(h)}}}async function je(n="podman"){if(!Me.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await P())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:nn(h)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(h!=="linux"){if(!e.machine){const i=await b("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await b("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function vn(){const n=await P(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await b("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(o=>Yn(o,"podman"))}catch{return[]}}const t=await b("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
5
+ `).filter(Boolean).map(i=>{try{return Yn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Sn(n,e){const t=await b(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function De(n,e){const t=await b(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const s of e)i[s]="absent";return i}const o=new Map(t.out.split(`
6
+ `).map(s=>s.split(" ")).filter(s=>s[0]).map(([s,a])=>[s,/running/i.test(a||"")?"running":"stopped"]));for(const s of e)i[s]=o.get(s)||"absent";return i}const _=n=>`http://127.0.0.1:${n.port}`;async function Mn(){const n=await P(),e=n.preferred,t=await $n(e,n),i={},o=await H(e),s=e&&n[e].running?await De(e,F.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of F){const c=_(a);let u="no-engine";if(a.kind==="native"?u=ce(a):e&&n[e].running?u=s[a.container]||"absent":e&&(u="engine-stopped"),a.retired&&!["running","stopped","exited","created","paused"].includes(u))continue;const d=a.model?w(a):null,m=a.engineOf?Y(a)?{...a.engineOf({...o,llamaOnPath:!0}),install:tt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...lr(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(r),answering:u==="running"?await a.answers(c,B):!1,...a.helper?{asleep:I.has(a.id),idleMinutes:On()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!C(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.id==="llama"&&C(a)?{...d&&Ye(X(),d).recommended?{recommended:Ye(X(),d).recommended}:{},build:te(),builds:[{id:"unsloth",label:v.label,why:v.why,installed:!!V(),version:V()?.tag||null,default:!0},{id:"system",label:"The system’s llama.cpp",why:"Homebrew’s, or one you built — `llama-server` on PATH",installed:!!Le("llama-server"),version:ne("llama-server")}],...te()==="unsloth"?V()?{runnerVersion:V().tag,updatable:!0}:{}:K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{}}:a.kind==="native"&&a.runner&&C(a)&&K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{},...a.auto&&u!=="running"&&C(a)?{auto:!0,...Ue(a)?{why:"Stopped here — Start turns it back on"}:L[a.id]?{why:L[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&C(a)&&L[a.id]?{why:L[a.id]}:{},...a.kind==="native"&&Z[a.id]?{sandbox:Z[a.id]}:{},...y[a.id]?{job:{kind:y[a.id].kind,since:y[a.id].since,detail:y[a.id].detail||null,step:y[a.id].step||null,minutes:y[a.id].minutes||null,progress:y[a.id].progress,lines:y[a.id].lines.slice(-4),done:y[a.id].done,error:y[a.id].error,waiting:!!y[a.id].waiting,cancelled:!!y[a.id].cancelled}}:{},...W(a)?{profiles:Hn(a.id,j(a,d),D(a,d,m,o)),docs:Ht[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:lt(a,o)}:{},...a.model?{model:d,default:a.model,models:Tn(a.id,{active:d,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g)}),machine:{engineRamMB:k}}:{},...W(a)?{tunings:Gn(a.id,j(a,d),D(a,d,m,o))}:{}}}return i}async function mt(){const n=await P(),e=await H(n.preferred);return{platform:h,arch:z,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Rt(e)}}function An(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:o=null}={}){const s=de(n),a=["run","-d","--name",s.container,"--restart","no","-p",`127.0.0.1:${s.port}:${s.containerPort}`];s.helper&&o&&a.push("--cpus",String(o));for(const u of s.volumes?s.volumes(N):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of s.env?s.env(s):[])a.push("-e",u);s.helper&&o&&a.push("-e",`THREADS=${o}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${s.port}/`),a.push("--cap-drop","ALL");for(const u of s.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||s.image,...s.args?s.args(s,i):[]);const c=Nt("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${c}`),{args:a,hash:c}}const Xe={};async function ft(n){if(Xe[n]==null){const e=await b(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Xe[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(Xe[n]/2))}async function ee(n,{force:e=!1}={}){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(t.retired)return{ok:!1,error:t.retired.why,retired:!0};I.delete(t.id),qe(t.id),t.auto&&Ue(t)&&un(t,!1);const i=y[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let o=null;if(t.kind!=="native"){const d=await P();if(o=d.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:nn(h)};if(!d[o].running){const m=await je(o);if(!m.ok)return m}}else if(!C(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await H(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await U(t.runner,t.runnerCheck))return{ok:!1,error:ln(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!Qe(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const d=await hn(t.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await dt(t,o,a);if(!c.length){if(delete y[t.id],t.kind!=="native")return ze(t,o);const d=await Ge(t);return d.ok?delete L[t.id]:L[t.id]=d.error,d}const u=me(t,c[0]==="runner"?"install":c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="runner"?v.label:c[0]==="image"?a?.image||t.image:w(t)});return c.includes("model")&&mn(t,w(t),!0),u.then=(async()=>{try{if(c.includes("runner")){const m=await Ce(u);if(!m.ok)throw new Error(m.error)}if(c.includes("image")){const m=await ct(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await yn(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const d=t.kind==="native"?await Ge(t):await ze(t,o);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,S(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,S(`[runtime] ${t.label}: ${u.error}`)}finally{c.includes("model")&&He(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function pt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=y[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return O(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function ze(n,e){let t=await Sn(e,n.container);const i=n.helper?await ft(e):null,o=n.engineOf?n.engineOf(await H(e)):null,s=n.id==="searxng"?$.join(N,"searxng-settings.yml"):null,a=An(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const d=await b(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(S(`[runtime] ${n.label}: made with older settings — re-creating it`),await b(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const d=await b(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{pe(N,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(ye(s,dr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Bt(32).toString("hex")),n.volumes&&pe($.join(N,ae),{recursive:!0,mode:448});const{args:m}=An(n,{settingsFile:s,secret:d,pick:o,cpus:i});S(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await b(e,m,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const c=_(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,B),u||await Be(1e3);return n.configure(r,c,de(n)),p(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function ht(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(I.delete(e.id),delete Je[e.id],e.auto&&un(e,!0),e.kind==="native")return we(e);const t=await P(),i=t.preferred;if(i&&t[i].running){const o=await b(i,["stop",e.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${i} stop: ${o.err||o.out}`}}return e.unconfigure(r,_(e)),p(),{ok:!0}}async function gt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!Dn.includes(e))return{ok:!1,error:`one of ${Dn.join(", ")}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{};const i={...r.runtime.services.llama||{}};e==="system"?i.build="system":delete i.build,r.runtime.services.llama=i,p();const o=await Ve(t,null,await P());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function kt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a recipe is for llama.cpp (a GGUF repo)"};const i=String(e||"").trim();if(!Cn(n,i)||/\.gguf$/i.test(i))return{ok:!1,error:`not a Hugging Face id: ${JSON.stringify(e)} — owner/name, or owner/name:QUANT`};const o=((await ke()).ramGB||0)*1024,s=a=>o?Xn({ramMB:a/2**20})<=o*.75:null;try{const a=await Xt(i,{fetchImpl:B,knows:(Oe||jn)(Te()),engineVersion:sn()}),c=(a.projector?.size||0)+(a.draft?.size||0);return{ok:!0,model:`${a.repo}:${a.quant}`,quant:a.quant,arch:a.arch,layout:a.layout,main:a.main,size:a.total,projector:a.projector,draft:a.draft,quants:a.quants.map(u=>({...u,fits:s(u.size+c)})),ramGB:o/1024,fits:s(a.total+c)}}catch(a){return{ok:!1,error:a.message,...a.code?{code:a.code,arch:a.arch}:{}}}}async function wt(n,e,{tunings:t=null}={}){const i=A(n);if(!i)return{ok:!1,error:`unknown service ${n}`};if(!i.model)return{ok:!1,error:`${i.label} takes no model`};const o=String(e||"").trim();if(!Cn(n,o))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await P(),a=s.preferred,c=i.kind==="native"?((await ke()).ramGB||0)*1024:await $n(a,s),u=Tn(n,{active:o,engineRamMB:c,engine:i.kind==="native"?"host":a,platform:h,installed:g=>J(i,g)}).find(g=>g.id===o);if(u?.unavailable)return{ok:!1,error:`${o} ${u.unavailable}`};let d=null;if(t&&W(i)){const g=await H(a);if(d=Un(i.id,j(i,o),t,D(i,o,i.engineOf?i.engineOf(g):null,g)),d.error)return{ok:!1,error:d.error}}r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:o},d&&Ie(i,o,d);const m=_(i);i.configured(r)===m&&i.configure(r,m,de(i)),p();const k=await Ve(i,a,s);return k.ok?{ok:!0,model:o,restarted:k.restarted,...k.pending?{pending:k.pending}:{},...u?.ramNote?{note:u.ramNote}:{}}:k}async function Ve(n,e,t){if(n.kind==="native"){if(ce(n)!=="running")return{ok:!0,restarted:!1};we(n);const s=await ee(n.id,{force:!0});return s.ok?{ok:!0,restarted:!0,...s.pending?{pending:s.pending}:{}}:s}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Sn(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const o=await b(e,["rm","-f",n.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${e} rm: ${o.err||o.out}`};if(i==="running"){const s=await ee(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function bt(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await P(),o=await H(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Hn(t.id,j(t,w(t)),D(t,w(t),s,o)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Pn(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function We(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(le())return{ok:!0,installed:!0};const s=me(e,"install",{detail:v.label});return s.then=(async()=>{const a=await Ce(s);s.done=!0,a.ok||(s.error=a.error),S(`[runtime] install ${v.label}: ${s.error||"ok"}`)})(),{ok:!0,pending:{kind:s.kind,since:s.since,detail:s.detail}}}if(delete K[e.runner],delete Q[e.runner],await U(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await H(null))?.install;return o?.steps?.length?_n(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function _n(n,e,t){const i=me(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=wn("install",i,async()=>{const a=async d=>{for(const[m,...k]of d){O(i,`$ ${m} ${k.join(" ")}`);let g=await be(i,m,k,{timeout:36e5});for(let E=0;!g.ok&&!i.cancelled&&E<6&&i.lines.some(M=>/already locked|Please wait for it to finish/i.test(M));E++)O(i,`another ${m} holds the lock — waiting 20 s (${E+1}/6)`),await Be(2e4),g=await be(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(E=>new RegExp(e.upToDate,"i").test(E))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(e.steps);!c.ok&&!i.cancelled&&e.fallback?.length&&(O(i,`${c.error} — trying the other way`),c=await a(e.fallback)),delete K[n.runner],delete Q[n.runner];const u=c.ok&&await U(n.runner,n.runnerCheck);if(u&&t==="update"){const d=ne(n.runner);if(O(i,d&&s&&d!==s?`${n.label} ${s} → ${d}`:`${n.label}${d?` ${d}`:""} — up to date`),o&&!i.cancelled){we(n),i.done=!0;const m=await ee(n.id,{force:!0});if(m.ok||(L[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;y[n.id]||(y[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":c.ok?u||(i.error=`${n.runner} still not found after the ${t} — open a new terminal and run \`${e.command}\` by hand`):i.error=`${t} failed: ${c.error}${i.lines.length?` (${i.lines.slice(-2).join(" | ")})`:""}`,S(`[runtime] ${t} ${n.runner}: ${i.error||"ok"}`)}),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function yt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(!le())return We(n);const o=V()?.tag,s=ce(e)==="running",a=me(e,"update",{detail:v.label});return a.then=(async()=>{const c=await Ce(a,{tag:"latest"});if(!c.ok){a.done=!0,a.error=`update failed: ${c.error}`;return}if(O(a,c.tag!==o?`${v.label} ${o} → ${c.tag}`:`${v.label} ${c.tag} — up to date`),a.done=!0,s&&c.tag!==o&&!a.cancelled){we(e);const u=await ee(e.id,{force:!0});u.ok||(L[e.id]=u.error),y[e.id]||(y[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete K[e.runner],delete Q[e.runner],!await U(e.runner,e.runnerCheck))return We(n);const i=e.engineOf(await H(null))?.install;return i?.update?.steps?.length?_n(e,i.update,"update"):{ok:!1,error:`no updater for ${e.label} on this platform${i?.url?` — newer builds are at ${i.url}`:""}`,install:i||null}}async function xn(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=y[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(J(e,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=me(e,"pull-model",{detail:w(e)});return mn(e,w(e),!1),i.then=(async()=>{const o=await yn(e,i);i.done=!0,o.ok||(i.error=o.error),He(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Pn(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await P(),o=i.preferred,s=w(t),a=await H(o),c=t.engineOf?t.engineOf(a):null,u=Un(t.id,j(t,s),e,D(t,s,c,a));if(u.error)return{ok:!1,error:u.error};Ie(t,s,u),p();const d=await Ve(t,o,i);return d.ok?{ok:!0,tunings:Gn(t.id,u,D(t,s,c,a)),restarted:d.restarted}:d}async function $t(){const n=await P(),e=n.preferred,t=e&&n[e].running?await De(e,F.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(F.map(async s=>{const a=s.kind==="native"?ce(s):e&&n[e].running?t[s.container]||"absent":"no-engine";i[s.id]=a==="running"&&await s.answers(_(s),B)?"up":"down";const c=(s.provides||[]).some(u=>["embedded","none"].includes(rr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!c&&s.configured(r)!==_(s)&&(s.configure(r,_(s),de(s)),o=!0)})),o&&p(),i}function En(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(In(e.id,j(e,w(e)),D(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function vt(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=In(e.id,j(e,t),D(e,t,null,{})),o=$e(e.id).find(a=>a.id===t)||null,s=e.id==="vllm"?he(t):"chat";return{engine:e.id,backend:Z[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:s,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:s==="chat"&&!!i.vision,tools:!!(s==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:s==="chat"&&!!i.reasoning&&i.reasoning!=="off",...o?{tier:o.tier||null,licence:o.licence||null,languages:o.lang||null,label:o.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const St=10,On=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:St)*6e4},Mt=se(),Je={},I=new Set,fe={};function qe(n){Je[n]=se()}async function At(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(qe(t.id),!I.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await vn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};I.add(t.id)}return fe[t.id]||(fe[t.id]=(async()=>{const i=await P(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await je(o);if(!a.ok)return a}const s=await ze(t,o);return s.ok&&(I.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Bn(){const n=On();if(!n)return[];const e=F.filter(a=>a.helper&&a.configured(r)&&!I.has(a.id)&&!fe[a.id]&&!(y[a.id]&&!y[a.id].done)&&se()-(Je[a.id]??Mt)>=n);if(!e.length)return[];const t=await P(),i=t.preferred;if(!i||!t[i].running){for(const a of e)I.add(a.id);return e.map(a=>a.id)}const o=await De(i,e.map(a=>a.container)),s=[];for(const a of e){if(o[a.container]==="running"){if(!(await b(i,["stop",a.container],{timeout:6e4})).ok)continue;S(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}I.add(a.id),s.push(a.id)}return s}return an&&an(()=>{Bn().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:qe,wake:At,sweepIdle:Bn,health:$t,contextWindow:En,modelCard:vt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),P(),Mn(),vn(),mt()]);return{machine:o,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:t}},startEngine:je,startService:ee,stopService:ht,ensureDefaults:at,retireServices:fn,removeService:rt,upcastTunings:pn,revive:ot,plan:hn,recipe:kt,setBuild:gt,isAsleep:n=>I.has(n),setModel:wt,setTunings:Pn,setProfile:bt,pullModel:xn,installRunner:We,updateRunner:yt,cancelJob:pt,services:Mn,catalogFor:$e}}export{ur as SEARXNG_DEFAULT_ENGINES,F as SERVICES,Yn as containerRow,Tr as createRuntime,nn as installDoor,dr as searxngSettings};