@chatpanel/gateway 0.163.2 → 0.165.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.163.2",
3
+ "version": "0.165.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.53.0",
27
- "@chatpanel/events": "^0.516.0",
27
+ "@chatpanel/events": "^0.516.1",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/model-pull.js CHANGED
@@ -1 +1 @@
1
- import{createWriteStream as Z,mkdirSync as O,renameSync as K,existsSync as b,writeFileSync as I,statSync as S,readFileSync as T,readdirSync as P}from"node:fs";import{ggufRecommended as J}from"./gguf-meta.js";import{Readable as Y}from"node:stream";import{pipeline as X}from"node:stream/promises";import g from"node:path";const R="https://huggingface.co",V=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,tt=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function k(e){const t=/^([A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95})(?::([A-Za-z0-9._-]{1,32}))?$/.exec(String(e||"").trim());return t?{repo:t[1],quant:t[2]||null}:null}const C=(e,t)=>g.join(e,"hub",`models--${t.replace("/","--")}`);async function L(e,{fetchImpl:t=globalThis.fetch,token:r=null}={}){const n=await t(`${R}/api/models/${e}?blobs=true`,{headers:r?{authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(2e4)});if(n.status===401||n.status===403)throw new Error(`${e}: gated or private on Hugging Face — accept its licence there and add a token`);if(n.status===404)throw new Error(`${e}: no such model on Hugging Face`);if(!n.ok)throw new Error(`${e}: Hugging Face answered ${n.status}`);const o=await n.json(),c=(o.siblings||[]).map(s=>({path:s.rfilename,size:Number(s.lfs?.size??s.size??0)})).filter(s=>s.path);return{commit:String(o.sha||"main"),siblings:c}}function et(e){const t=e.some(n=>/\.safetensors$/i.test(n.path)),r=e.filter(n=>!(tt.test(n.path)||t&&V.test(n.path)||!t&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(n.path)));return{files:r,total:r.reduce((n,o)=>n+o.size,0)}}const U=/(^|\/)mmproj[^/]*\.gguf$/i,B=/(^|\/)(?:dspark|dflash|eagle3?)[-_][^/]*\.gguf$|[-_.]mtp(?:[-_.][^/]*)?\.gguf$|(^|\/)[^/]*draft[^/]*\.gguf$/i,rt=/(^|\/)imatrix[^/]*\.gguf$/i,M=(e,t)=>t.test(e)&&!U.test(e)&&!B.test(e)&&!rt.test(e);function G(e){const t=g.basename(String(e||"")).toLowerCase();return t.startsWith("dspark")?"draft-dspark":t.startsWith("dflash")?"draft-dflash":/^eagle3?[-_]/.test(t)?"draft-eagle3":/[-_.]mtp([-_.]|$)/.test(t.replace(/\.gguf$/,""))?"draft-mtp":"draft-simple"}function F(e){return{mains:e.filter(t=>M(t.path,/\.gguf$/i)),alts:e.filter(t=>/\.gguf_file$/i.test(t.path)&&M(t.path.replace(/_file$/i,""),/\.gguf$/i)),projectors:e.filter(t=>U.test(t.path)),drafts:e.filter(t=>B.test(t.path))}}const N=(e,t)=>(e.path.includes("/")?1:0)-(t.path.includes("/")?1:0);function nt(e){const t=r=>{const n=["f16","bf16","q8_0","f32"].findIndex(o=>new RegExp(`[-_.]${o}\\.gguf$`,"i").test(r));return n<0?9:n};return e.slice().sort((r,n)=>N(r,n)||t(r.path)-t(n.path))[0]||null}function ot(e){return e.slice().sort((t,r)=>N(t,r)||(t.size||0)-(r.size||0))[0]||null}const at=e=>g.basename(String(e)).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,"").toLowerCase(),v=(e,t)=>{const r=e.toLowerCase().replace(/_file$/,"");return r.includes(`-${t}.`)||r.includes(`-${t}-0`)||r.includes(`.${t}.`)||r.includes(`/${t}/`)||r.includes(`_${t}.`)?!0:at(e)===t||j(e).toLowerCase()===j(`${t}.gguf`).toLowerCase()};function st(e,t=null,{layout:r="main"}={}){const n=F(e),o=r==="alt"?n.alts:n.mains;if(!o.length)throw new Error("no GGUF file in this repo");const c=(t||"Q4_K_M").toLowerCase();let s=o.filter(a=>v(a.path,c));if(!s.length&&!t){const a=D(o);s=o.filter(l=>j(l.path)===a)}if(!s.length)throw new Error(`no ${t||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(o.map(a=>j(a.path)))].slice(0,12).join(", ")}`);return s=s.slice().sort((a,l)=>a.path.localeCompare(l.path)),{files:s,total:s.reduce((a,l)=>a+l.size,0),main:s[0].path}}function D(e){const t=n=>e.filter(o=>j(o.path)===n).reduce((o,c)=>o+(c.size||0),0),r=[...new Set(e.map(n=>j(n.path)))].sort((n,o)=>t(n)-t(o));return r.find(n=>/(^|-)I?Q4/i.test(n))||r[0]}function it(e){const t=new Map;for(const r of F(e).mains){const n=j(r.path);t.set(n,(t.get(n)||0)+(r.size||0))}return[...t].map(([r,n])=>({quant:r,size:n})).sort((r,n)=>r.size-n.size)}function j(e){const t=g.basename(e).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,""),r=/[-._]((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(t);return r?r[1]:t}const x=(e,t,r)=>g.join(e,"gguf",t.replace("/","--"),g.basename(r).replace(/\.gguf_file$/i,".gguf")),E={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8};function ct(e){try{if(e.length<24||e.toString("latin1",0,4)!=="GGUF")return null;let t=16;const r=Number(e.readBigUInt64LE(t));t+=8;const n=()=>{const o=Number(e.readBigUInt64LE(t));t+=8;const c=e.toString("utf8",t,t+o);return t+=o,c};for(let o=0;o<r&&t<e.length;o++){const c=n(),s=e.readUInt32LE(t);if(t+=4,s===8){const a=n();if(c==="general.architecture")return a||null;continue}if(s===9){const a=e.readUInt32LE(t);t+=4;const l=Number(e.readBigUInt64LE(t));if(t+=8,a===8)for(let i=0;i<l;i++)n();else if(E[a])t+=E[a]*l;else return null;continue}if(!E[s])return null;t+=E[s]}}catch{}return null}async function lt(e,t,r,{fetchImpl:n=globalThis.fetch,token:o=null}={}){try{const c=await n(`${R}/${e}/resolve/${encodeURIComponent(t)}/${r.split("/").map(encodeURIComponent).join("/")}`,{headers:{range:"bytes=0-65535",...o?{authorization:`Bearer ${o}`}:{}},redirect:"follow",signal:AbortSignal.timeout(2e4)});return!c.ok||typeof c.arrayBuffer!="function"?null:ct(Buffer.from(await c.arrayBuffer()))}catch{return null}}const ut=Object.freeze({attempts:6,backoffMs:Object.freeze([1e3,3e3,8e3,15e3,3e4]),stallMs:6e4}),ft=new Set([401,403,404,410]),pt=e=>new Promise(t=>setTimeout(t,e));async function W({repo:e,commit:t,files:r,destOf:n,fetchImpl:o=globalThis.fetch,token:c=null,onProgress:s=()=>{},total:a=0,retry:l=ut,sleep:i=pt}){let u=0;for(const f of r){const d=n(f.path);if(b(d)&&f.size&&S(d).size===f.size){u+=f.size,s({file:f.path,bytes:u,total:a,fileBytes:f.size,fileTotal:f.size,skipped:!0});continue}O(g.dirname(d),{recursive:!0,mode:448});const z=u;for(let p=1;;p++){u=z;try{u=await ht({repo:e,commit:t,f,dest:d,fetchImpl:o,token:c,onProgress:s,total:a,bytes:u,stallMs:l.stallMs});break}catch(h){const y=String(h?.message||h);if(h?.permanent||y==="cancelled"||p>=l.attempts)throw h;const w=l.backoffMs[Math.min(p-1,l.backoffMs.length-1)];s({file:f.path,bytes:u,total:a,fileBytes:0,fileTotal:f.size,skipped:!0,retry:{attempt:p+1,of:l.attempts,inMs:w,error:y.slice(0,160)}}),await i(w),s({file:f.path,bytes:u,total:a,fileBytes:0,fileTotal:f.size,skipped:!0})}}}return u}async function ht({repo:e,commit:t,f:r,dest:n,fetchImpl:o,token:c,onProgress:s,total:a,bytes:l,stallMs:i}){const u=`${n}.part`,f=b(u)?S(u).size:0,d=f>0&&(!r.size||f<r.size),z={...c?{authorization:`Bearer ${c}`}:{},...d?{range:`bytes=${f}-`}:{}},p=new AbortController;let h=null;const y=()=>{clearTimeout(h),h=setTimeout(()=>p.abort(new Error(`no bytes for ${Math.round(i/1e3)} s`)),i)};y();try{let w;try{w=await o(`${R}/${e}/resolve/${encodeURIComponent(t)}/${r.path.split("/").map(encodeURIComponent).join("/")}`,{headers:z,redirect:"follow",signal:p.signal})}catch(m){throw new Error(`${r.path}: ${p.signal.aborted?p.signal.reason?.message:m?.cause?.code||m?.message||m}`)}if(!w.ok||!w.body){const m=new Error(`${r.path}: Hugging Face answered ${w.status}${w.status===401||w.status===403?" — the repo needs a sign-in or accepting its licence on huggingface.co":""}`);throw m.permanent=ft.has(w.status),m}const $=d&&w.status===206;let _=$?f:0;$&&(l+=f,s({file:r.path,bytes:l,total:a,fileBytes:_,fileTotal:r.size,skipped:!0}));const Q=new TransformStream({transform(m,q){y(),_+=m.byteLength,l+=m.byteLength,s({file:r.path,bytes:l,total:a,fileBytes:_,fileTotal:r.size}),q.enqueue(m)}});try{await X(Y.fromWeb(w.body.pipeThrough(Q)),Z(u,{mode:384,flags:$?"a":"w"}))}catch(m){throw String(m?.message)==="cancelled"?m:new Error(`${r.path}: ${p.signal.aborted?p.signal.reason?.message:m?.cause?.code||m?.code||m?.message||m} after ${_} bytes`)}if(r.size&&S(u).size!==r.size)throw new Error(`${r.path}: ${S(u).size} of ${r.size} bytes arrived`);return K(u,n),l}finally{clearTimeout(h)}}async function bt(e,{root:t,fetchImpl:r=globalThis.fetch,token:n=null,onProgress:o=()=>{}}={}){const{commit:c,siblings:s}=await L(e,{fetchImpl:r,token:n}),{files:a,total:l}=et(s);if(!a.length)throw new Error(`${e}: nothing to download (no weights or config listed)`);const i=C(t,e),u=g.join(i,"snapshots",c),f=await W({repo:e,commit:c,files:a,total:l,destOf:d=>g.join(u,d),fetchImpl:r,token:n,onProgress:o});return O(g.join(i,"refs"),{recursive:!0,mode:448}),I(g.join(i,"refs","main"),c,{mode:384}),{dir:u,commit:c,files:a.map(d=>d.path),bytes:f,total:l}}async function gt(e,{fetchImpl:t=globalThis.fetch,token:r=null,knows:n=null,engineVersion:o=null}={}){const c=k(e);if(!c)throw new Error(`not a model id: ${e}`);const{commit:s,siblings:a}=await L(c.repo,{fetchImpl:t,token:r}),l=F(a),i=l.alts.length?["main","alt"]:["main"];let u=null;const f=[];for(const p of i){let h;try{h=st(a,c.quant,{layout:p})}catch($){if(p==="main")throw $;continue}const y=n?await lt(c.repo,s,h.main,{fetchImpl:t,token:r}):null;if((y&&n?n(y):null)===!1){f.push(y);continue}u={layout:p,arch:y,...h};break}if(!u){const p=[...new Set(f)].join(" or "),h=new Error(`${c.repo}: llama.cpp${o?` ${o}`:""} on this machine cannot run ${p} models. Update it on its row in Settings › Runtime — and if that says it is up to date, support for ${p} is not in a llama.cpp release yet: the model has to wait for the next one.`);throw h.code="unsupported_arch",h.arch=f[0],h}const d=nt(l.projectors),z=ot(l.drafts);return{repo:c.repo,commit:s,quant:c.quant||j(u.main),layout:u.layout,arch:u.arch,weights:u.files,total:u.total,main:u.main,projector:d?{path:d.path,size:d.size}:null,draft:z?{path:z.path,size:z.size,spec:G(z.path)}:null,quants:it(a)}}function _t(e,t){const r=k(t);if(!r)return{};try{const n=JSON.parse(T(g.join(e,"gguf",r.repo.replace("/","--"),"recipe.json"),"utf8"));return{...n.projector&&b(n.projector)?{projector:n.projector}:{},...n.draft?.path&&b(n.draft.path)?{draft:{path:n.draft.path,spec:n.draft.spec||G(n.draft.path)}}:{},...H(e,t)}}catch{return H(e,t)}}const A=new Map;function H(e,t){const r=dt(e,t);if(!r)return{};let n;try{n=`${r}:${S(r).mtimeMs}`}catch{return{}}A.has(n)||A.set(n,J(r));const o=A.get(n);return o?{recommended:o}:{}}async function St(e,{root:t,fetchImpl:r=globalThis.fetch,token:n=null,onProgress:o=()=>{},knows:c=null,engineVersion:s=null,vision:a=!0,draft:l=!0}={}){const i=await gt(e,{fetchImpl:r,token:n,knows:c,engineVersion:s}),u=[...a&&i.projector?[i.projector]:[],...l&&i.draft?[i.draft]:[]],f=[...i.weights,...u],d=f.reduce(($,_)=>$+(_.size||0),0),z=await W({repo:i.repo,commit:i.commit,files:f,total:d,destOf:$=>x(t,i.repo,$),fetchImpl:r,token:n,onProgress:o}),p=$=>$?x(t,i.repo,$.path):null,h={projector:a?p(i.projector):null,draft:l&&i.draft?{path:p(i.draft),spec:i.draft.spec}:null,arch:i.arch,layout:i.layout},y=g.join(t,"gguf",i.repo.replace("/","--"),"recipe.json");let w={};try{w=JSON.parse(T(y,"utf8"))}catch{}return I(y,JSON.stringify({...w,...Object.fromEntries(Object.entries(h).filter(([,$])=>$))},null,2),{mode:384}),{main:x(t,i.repo,i.main),files:i.weights.map($=>x(t,i.repo,$.path)),bytes:z,total:d,projector:h.projector,draft:h.draft}}function xt(e,t){const r=C(e,t);try{const n=T(g.join(r,"refs","main"),"utf8").trim();return!!n&&b(g.join(r,"snapshots",n))&&b(g.join(r,"snapshots",n,"config.json"))}catch{return!1}}function dt(e,t){const r=k(t);if(!r)return null;const n=g.join(e,"gguf",r.repo.replace("/","--"));if(!b(n))return null;const o=(r.quant||"Q4_K_M").toLowerCase(),c=mt(n).filter(a=>M(a,/\.gguf$/i)&&!a.endsWith(".part"));let s=c.filter(a=>v(a,o)).sort();if(!s.length&&!r.quant&&c.length){const a=c.map(i=>({path:i,size:(()=>{try{return S(g.join(n,i)).size}catch{return 0}})()})),l=D(a);s=c.filter(i=>j(i)===l).sort()}return s.length?g.join(n,s[0]):null}function mt(e){try{return P(e)}catch{return[]}}export{ut as DOWNLOAD_RETRY,R as HF_API,L as describeRepo,W as downloadFiles,G as draftSpecOf,lt as ggufArchitecture,ct as ggufHeaderArch,dt as ggufInstalled,F as ggufKinds,x as ggufPath,it as ggufQuants,_t as ggufRecipe,k as parseModelRef,ot as pickDraft,nt as pickProjector,st as planGgufFiles,gt as planGgufRecipe,et as planRepoFiles,St as pullGguf,bt as pullRepo,j as quantOf,C as repoCacheDir,xt as repoInstalled};
1
+ import{createWriteStream as J,mkdirSync as C,renameSync as K,existsSync as b,writeFileSync as L,statSync as _,readFileSync as x,readdirSync as P}from"node:fs";import{ggufRecommended as Y}from"./gguf-meta.js";import{Readable as X}from"node:stream";import{pipeline as V}from"node:stream/promises";import p from"node:path";const R="https://huggingface.co",tt=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,et=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function M(e){const t=/^([A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95})(?::([A-Za-z0-9._-]{1,32}))?$/.exec(String(e||"").trim());return t?{repo:t[1],quant:t[2]||null}:null}const k=(e,t)=>p.join(e,"hub",`models--${t.replace("/","--")}`);async function U(e,{fetchImpl:t=globalThis.fetch,token:n=null}={}){const r=await t(`${R}/api/models/${e}?blobs=true`,{headers:n?{authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(2e4)});if(r.status===401||r.status===403)throw new Error(`${e}: gated or private on Hugging Face — accept its licence there and add a token`);if(r.status===404)throw new Error(`${e}: no such model on Hugging Face`);if(!r.ok)throw new Error(`${e}: Hugging Face answered ${r.status}`);const o=await r.json(),i=(o.siblings||[]).map(c=>({path:c.rfilename,size:Number(c.lfs?.size??c.size??0)})).filter(c=>c.path);return{commit:String(o.sha||"main"),siblings:i}}function nt(e){const t=e.some(r=>/\.safetensors$/i.test(r.path)),n=e.filter(r=>!(et.test(r.path)||t&&tt.test(r.path)||!t&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(r.path)));return{files:n,total:n.reduce((r,o)=>r+o.size,0)}}const B=/(^|\/)mmproj[^/]*\.gguf$/i,q=/(^|\/)(?:dspark|dflash|eagle3?)[-_][^/]*\.gguf$|[-_.]mtp(?:[-_.][^/]*)?\.gguf$|(^|\/)[^/]*draft[^/]*\.gguf$/i,rt=/(^|\/)imatrix[^/]*\.gguf$/i,A=(e,t)=>t.test(e)&&!B.test(e)&&!q.test(e)&&!rt.test(e);function N(e){const t=p.basename(String(e||"")).toLowerCase();return t.startsWith("dspark")?"draft-dspark":t.startsWith("dflash")?"draft-dflash":/^eagle3?[-_]/.test(t)?"draft-eagle3":/[-_.]mtp([-_.]|$)/.test(t.replace(/\.gguf$/,""))?"draft-mtp":"draft-simple"}function F(e){return{mains:e.filter(t=>A(t.path,/\.gguf$/i)),alts:e.filter(t=>/\.gguf_file$/i.test(t.path)&&A(t.path.replace(/_file$/i,""),/\.gguf$/i)),projectors:e.filter(t=>B.test(t.path)),drafts:e.filter(t=>q.test(t.path))}}const G=(e,t)=>(e.path.includes("/")?1:0)-(t.path.includes("/")?1:0);function ot(e){const t=n=>{const r=["f16","bf16","q8_0","f32"].findIndex(o=>new RegExp(`[-_.]${o}\\.gguf$`,"i").test(n));return r<0?9:r};return e.slice().sort((n,r)=>G(n,r)||t(n.path)-t(r.path))[0]||null}function at(e){return e.slice().sort((t,n)=>G(t,n)||(t.size||0)-(n.size||0))[0]||null}const st=e=>p.basename(String(e)).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,"").toLowerCase(),v=(e,t)=>{const n=e.toLowerCase().replace(/_file$/,"");return n.includes(`-${t}.`)||n.includes(`-${t}-0`)||n.includes(`.${t}.`)||n.includes(`/${t}/`)||n.includes(`_${t}.`)?!0:st(e)===t||j(e).toLowerCase()===j(`${t}.gguf`).toLowerCase()};function it(e,t=null,{layout:n="main"}={}){const r=F(e),o=n==="alt"?r.alts:r.mains;if(!o.length)throw new Error("no GGUF file in this repo");const i=(t||"Q4_K_M").toLowerCase();let c=o.filter(s=>v(s.path,i));if(!c.length&&!t){const s=D(o);c=o.filter(l=>j(l.path)===s)}if(!c.length)throw new Error(`no ${t||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(o.map(s=>j(s.path)))].slice(0,12).join(", ")}`);return c=c.slice().sort((s,l)=>s.path.localeCompare(l.path)),{files:c,total:c.reduce((s,l)=>s+l.size,0),main:c[0].path}}function D(e){const t=r=>e.filter(o=>j(o.path)===r).reduce((o,i)=>o+(i.size||0),0),n=[...new Set(e.map(r=>j(r.path)))].sort((r,o)=>t(r)-t(o));return n.find(r=>/(^|-)I?Q4/i.test(r))||n[0]}function ct(e){const t=new Map;for(const n of F(e).mains){const r=j(n.path);t.set(r,(t.get(r)||0)+(n.size||0))}return[...t].map(([n,r])=>({quant:n,size:r})).sort((n,r)=>n.size-r.size)}function j(e){const t=p.basename(e).replace(/\.gguf(_file)?$/i,"").replace(/-\d{5}-of-\d{5}$/,""),n=/[-._]((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(t);return n?n[1]:t}const E=(e,t,n)=>p.join(e,"gguf",t.replace("/","--"),p.basename(n).replace(/\.gguf_file$/i,".gguf")),T={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8};function lt(e){try{if(e.length<24||e.toString("latin1",0,4)!=="GGUF")return null;let t=16;const n=Number(e.readBigUInt64LE(t));t+=8;const r=()=>{const o=Number(e.readBigUInt64LE(t));t+=8;const i=e.toString("utf8",t,t+o);return t+=o,i};for(let o=0;o<n&&t<e.length;o++){const i=r(),c=e.readUInt32LE(t);if(t+=4,c===8){const s=r();if(i==="general.architecture")return s||null;continue}if(c===9){const s=e.readUInt32LE(t);t+=4;const l=Number(e.readBigUInt64LE(t));if(t+=8,s===8)for(let a=0;a<l;a++)r();else if(T[s])t+=T[s]*l;else return null;continue}if(!T[c])return null;t+=T[c]}}catch{}return null}async function ut(e,t,n,{fetchImpl:r=globalThis.fetch,token:o=null}={}){try{const i=await r(`${R}/${e}/resolve/${encodeURIComponent(t)}/${n.split("/").map(encodeURIComponent).join("/")}`,{headers:{range:"bytes=0-65535",...o?{authorization:`Bearer ${o}`}:{}},redirect:"follow",signal:AbortSignal.timeout(2e4)});return!i.ok||typeof i.arrayBuffer!="function"?null:lt(Buffer.from(await i.arrayBuffer()))}catch{return null}}const ft=Object.freeze({attempts:6,backoffMs:Object.freeze([1e3,3e3,8e3,15e3,3e4]),stallMs:6e4}),pt=new Set([401,403,404,410]),ht=e=>new Promise(t=>setTimeout(t,e));async function W({repo:e,commit:t,files:n,destOf:r,fetchImpl:o=globalThis.fetch,token:i=null,onProgress:c=()=>{},total:s=0,retry:l=ft,sleep:a=ht}){let u=0;for(const f of n){const d=r(f.path);if(b(d)&&f.size&&_(d).size===f.size){u+=f.size,c({file:f.path,bytes:u,total:s,fileBytes:f.size,fileTotal:f.size,skipped:!0});continue}C(p.dirname(d),{recursive:!0,mode:448});const z=u;for(let h=1;;h++){u=z;try{u=await gt({repo:e,commit:t,f,dest:d,fetchImpl:o,token:i,onProgress:c,total:s,bytes:u,stallMs:l.stallMs});break}catch(g){const y=String(g?.message||g);if(g?.permanent||y==="cancelled"||h>=l.attempts)throw g;const $=l.backoffMs[Math.min(h-1,l.backoffMs.length-1)];c({file:f.path,bytes:u,total:s,fileBytes:0,fileTotal:f.size,skipped:!0,retry:{attempt:h+1,of:l.attempts,inMs:$,error:y.slice(0,160)}}),await a($),c({file:f.path,bytes:u,total:s,fileBytes:0,fileTotal:f.size,skipped:!0})}}}return u}async function gt({repo:e,commit:t,f:n,dest:r,fetchImpl:o,token:i,onProgress:c,total:s,bytes:l,stallMs:a}){const u=`${r}.part`,f=b(u)?_(u).size:0,d=f>0&&(!n.size||f<n.size),z={...i?{authorization:`Bearer ${i}`}:{},...d?{range:`bytes=${f}-`}:{}},h=new AbortController;let g=null;const y=()=>{clearTimeout(g),g=setTimeout(()=>h.abort(new Error(`no bytes for ${Math.round(a/1e3)} s`)),a)};y();try{let $;try{$=await o(`${R}/${e}/resolve/${encodeURIComponent(t)}/${n.path.split("/").map(encodeURIComponent).join("/")}`,{headers:z,redirect:"follow",signal:h.signal})}catch(m){throw new Error(`${n.path}: ${h.signal.aborted?h.signal.reason?.message:m?.cause?.code||m?.message||m}`)}if(!$.ok||!$.body){const m=new Error(`${n.path}: Hugging Face answered ${$.status}${$.status===401||$.status===403?" — the repo needs a sign-in or accepting its licence on huggingface.co":""}`);throw m.permanent=pt.has($.status),m}const w=d&&$.status===206;let S=w?f:0;w&&(l+=f,c({file:n.path,bytes:l,total:s,fileBytes:S,fileTotal:n.size,skipped:!0}));const Q=new TransformStream({transform(m,Z){y(),S+=m.byteLength,l+=m.byteLength,c({file:n.path,bytes:l,total:s,fileBytes:S,fileTotal:n.size}),Z.enqueue(m)}});try{await V(X.fromWeb($.body.pipeThrough(Q)),J(u,{mode:384,flags:w?"a":"w"}))}catch(m){throw String(m?.message)==="cancelled"?m:new Error(`${n.path}: ${h.signal.aborted?h.signal.reason?.message:m?.cause?.code||m?.code||m?.message||m} after ${S} bytes`)}if(n.size&&_(u).size!==n.size)throw new Error(`${n.path}: ${_(u).size} of ${n.size} bytes arrived`);return K(u,r),l}finally{clearTimeout(g)}}async function _t(e,{root:t,fetchImpl:n=globalThis.fetch,token:r=null,onProgress:o=()=>{}}={}){const{commit:i,siblings:c}=await U(e,{fetchImpl:n,token:r}),{files:s,total:l}=nt(c);if(!s.length)throw new Error(`${e}: nothing to download (no weights or config listed)`);const a=k(t,e),u=p.join(a,"snapshots",i),f=await W({repo:e,commit:i,files:s,total:l,destOf:d=>p.join(u,d),fetchImpl:n,token:r,onProgress:o});return C(p.join(a,"refs"),{recursive:!0,mode:448}),L(p.join(a,"refs","main"),i,{mode:384}),{dir:u,commit:i,files:s.map(d=>d.path),bytes:f,total:l}}async function dt(e,{fetchImpl:t=globalThis.fetch,token:n=null,knows:r=null,engineVersion:o=null}={}){const i=M(e);if(!i)throw new Error(`not a model id: ${e}`);const{commit:c,siblings:s}=await U(i.repo,{fetchImpl:t,token:n}),l=F(s),a=l.alts.length?["main","alt"]:["main"];let u=null;const f=[];for(const h of a){let g;try{g=it(s,i.quant,{layout:h})}catch(w){if(h==="main")throw w;continue}const y=r?await ut(i.repo,c,g.main,{fetchImpl:t,token:n}):null;if((y&&r?r(y):null)===!1){f.push(y);continue}u={layout:h,arch:y,...g};break}if(!u){const h=[...new Set(f)].join(" or "),g=new Error(`${i.repo}: llama.cpp${o?` ${o}`:""} on this machine cannot run ${h} models. Update it on its row in Settings › Runtime — and if that says it is up to date, support for ${h} is not in a llama.cpp release yet: the model has to wait for the next one.`);throw g.code="unsupported_arch",g.arch=f[0],g}const d=ot(l.projectors),z=at(l.drafts);return{repo:i.repo,commit:c,quant:i.quant||j(u.main),layout:u.layout,arch:u.arch,weights:u.files,total:u.total,main:u.main,projector:d?{path:d.path,size:d.size}:null,draft:z?{path:z.path,size:z.size,spec:N(z.path)}:null,quants:ct(s)}}function St(e,t){const n=M(t);if(!n)return{};try{const r=JSON.parse(x(p.join(e,"gguf",n.repo.replace("/","--"),"recipe.json"),"utf8"));return{...r.projector&&b(r.projector)?{projector:r.projector}:{},...r.draft?.path&&b(r.draft.path)?{draft:{path:r.draft.path,spec:r.draft.spec||N(r.draft.path)}}:{},...H(e,t)}}catch{return H(e,t)}}const O=new Map;function H(e,t){const n=$t(e,t);if(!n)return{};let r;try{r=`${n}:${_(n).mtimeMs}`}catch{return{}}O.has(r)||O.set(r,Y(n));const o=O.get(r);return o?{recommended:o}:{}}async function xt(e,{root:t,fetchImpl:n=globalThis.fetch,token:r=null,onProgress:o=()=>{},knows:i=null,engineVersion:c=null,vision:s=!0,draft:l=!0}={}){const a=await dt(e,{fetchImpl:n,token:r,knows:i,engineVersion:c}),u=[...s&&a.projector?[a.projector]:[],...l&&a.draft?[a.draft]:[]],f=[...a.weights,...u],d=f.reduce((w,S)=>w+(S.size||0),0),z=await W({repo:a.repo,commit:a.commit,files:f,total:d,destOf:w=>E(t,a.repo,w),fetchImpl:n,token:r,onProgress:o}),h=w=>w?E(t,a.repo,w.path):null,g={projector:s?h(a.projector):null,draft:l&&a.draft?{path:h(a.draft),spec:a.draft.spec}:null,arch:a.arch,layout:a.layout},y=p.join(t,"gguf",a.repo.replace("/","--"),"recipe.json");let $={};try{$=JSON.parse(x(y,"utf8"))}catch{}return L(y,JSON.stringify({...$,...Object.fromEntries(Object.entries(g).filter(([,w])=>w))},null,2),{mode:384}),{main:E(t,a.repo,a.main),files:a.weights.map(w=>E(t,a.repo,w.path)),bytes:z,total:d,projector:g.projector,draft:g.draft}}function mt(e,t){const n=k(e,t);try{const r=x(p.join(n,"refs","main"),"utf8").trim();return!!r&&b(p.join(n,"snapshots",r))&&b(p.join(n,"snapshots",r,"config.json"))}catch{return!1}}function Et(e){const t=p.join(e,"hub"),n=[];for(const r of I(t)){const o=/^models--([^-][^/]*?)--(.+)$/.exec(r);if(!o)continue;const i=`${o[1]}/${o[2]}`;if(mt(e,i))try{const c=k(e,i),s=p.join(c,"snapshots",x(p.join(c,"refs","main"),"utf8").trim()),l=I(s);if(!l.some(f=>/\.safetensors$/i.test(f)))continue;const a=JSON.parse(x(p.join(s,"config.json"),"utf8"));let u=0;for(const f of l)if(/\.safetensors$/i.test(f))try{u+=_(p.join(s,f)).size}catch{}n.push({id:i,architectures:Array.isArray(a.architectures)?a.architectures.map(String):[],modelType:String(a.model_type||""),mlx:!!(a.quantization&&typeof a.quantization=="object"&&"bits"in a.quantization),quantMethod:String(a.quantization_config?.quant_method||""),bytes:u})}catch{}}return n}function $t(e,t){const n=M(t);if(!n)return null;const r=p.join(e,"gguf",n.repo.replace("/","--"));if(!b(r))return null;const o=(n.quant||"Q4_K_M").toLowerCase(),i=I(r).filter(s=>A(s,/\.gguf$/i)&&!s.endsWith(".part"));let c=i.filter(s=>v(s,o)).sort();if(!c.length&&!n.quant&&i.length){const s=i.map(a=>({path:a,size:(()=>{try{return _(p.join(r,a)).size}catch{return 0}})()})),l=D(s);c=i.filter(a=>j(a)===l).sort()}return c.length?p.join(r,c[0]):null}function I(e){try{return P(e)}catch{return[]}}export{ft as DOWNLOAD_RETRY,R as HF_API,Et as cachedRepos,U as describeRepo,W as downloadFiles,N as draftSpecOf,ut as ggufArchitecture,lt as ggufHeaderArch,$t as ggufInstalled,F as ggufKinds,E as ggufPath,ct as ggufQuants,St as ggufRecipe,M as parseModelRef,at as pickDraft,ot as pickProjector,it as planGgufFiles,dt as planGgufRecipe,nt as planRepoFiles,xt as pullGguf,_t as pullRepo,j as quantOf,k as repoCacheDir,mt as repoInstalled};
package/src/router.js CHANGED
@@ -1 +1 @@
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};
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 a=new URL(e);return/^(localhost|127\.0\.0\.1|\[::1\])$/i.test(a.hostname)?a.port||(a.protocol==="https:"?"443":"80"):null}catch{return null}}function m(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),s=new Set(a.map(t=>t.id)),l=[...a.filter(t=>t.type==="agent"),...P.filter(t=>!s.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...a.filter(t=>t.type!=="agent")],o=R(),c=new Set(a.filter(t=>t.service).map(t=>t.service));for(let t=l.length-1;t>=0;t--){const i=l[t];if(i.type!=="api"||i.service)continue;const r=o.get(K(i.baseUrl));if(r){if(c.has(r)){l.splice(t,1);continue}l[t]={...i,id:r,service:r,aliasOf:i.id},c.add(r)}}if(e.backend==="api"&&!a.some(t=>t.type==="api")){const t=i=>({...i?.redact===!0?{redact:!0}:{},...i?.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,a,s,{destination:l="",down:o=()=>!1}={}){const c=m(a),t=s==="anthropic",i=r=>(t?r.protocol==="anthropic":r.protocol!=="anthropic")&&!o(r);return l?c.find(r=>r.id===l)||null:e&&c.find(r=>Array.isArray(r.models)&&r.models.includes(e))||e&&c.find(r=>r.id===e||r.agent===e)||e&&e.includes("/")&&c.find(r=>r.type==="agent"&&(r.agent===e.slice(0,e.indexOf("/"))||r.id===e.slice(0,e.indexOf("/"))))||e&&F(e,c,i)||c.find(r=>a.backend==="bridge"?r.type==="agent":r.type==="api"&&i(r))||c.find(r=>(a.backend==="bridge"?r.type==="agent":r.type==="api")&&!o(r))||c.find(r=>!o(r))||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 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 S(e,a,s,l){const o=j({id:e,owned_by:a,provider_type:s.type==="agent"?"agent":"openai"},s);if(s.type==="agent")return{reach:o};const c=!!k(s.baseUrl),t=T({dest:s,loopback:c,card:E(l,e),otherwise:o});return{reach:t.reach,...c?{reach_why:t.why,...t.engine?{engine:t.engine}:{}}:{}}}function N(e){const a=[],s=new Set,l=(o,c,t)=>{if(!o||s.has(o))return;s.add(o);const i=U(t),r=C(t);a.push({id:o,object:"model",owned_by:c,...r?{configured:!1,reason:r}:{},provider:t.id,provider_type:t.type==="agent"?"agent":t.protocol==="anthropic"?"anthropic":"openai",api:i.api,endpoints:i.endpoints,...S(o,c,t,null)})};for(const o of m(e))if(o.type==="agent")for(const c of o.models?.length?o.models:[o.id])l(c,"chatpanel-bridge",o);else for(const c of o.models||[])l(c,o.id,o);return{object:"list",data:a}}async function D(e,a,s){const l=await O(e);if(!l||!a)return new Map;const o=M(e.bridge?.token),c=[...a.entries()].filter(([,i])=>i).map(([i])=>i),t=new Map;return await Promise.all(c.map(async i=>{try{const r=await fetch(`${l}/list-models`,{method:"POST",headers:{"content-type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({agent:i}),signal:AbortSignal.timeout(s)});if(!r.ok)return;const g=await r.json(),h=(Array.isArray(g?.models)?g.models:[]).map(b=>typeof b=="string"?b:b?.id||b?.name||"").map(b=>String(b).trim()).filter(Boolean);h.length&&t.set(i,h.slice(0,40))}catch{}})),t}async function I(e,a){const s=await O(e);if(!s)return null;try{const l=M(e.bridge?.token),o=await fetch(`${s}/health`,{headers:{Accept:"application/json",...l?{Authorization:`Bearer ${l}`}:{}},signal:AbortSignal.timeout(a)});if(!o.ok)return null;const c=await o.json();if(!Array.isArray(c?.agents))return null;const t=new Map(c.agents.map(i=>[i.id,!!i.available]));return t.noTools=new Set(c.agents.filter(i=>i.tools===!1).map(i=>i.id)),t}catch{return null}}const z=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let y={at:0,key:"",value:null,inflight:null};function H(e){try{return JSON.stringify([m(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 ee(){y={at:0,key:"",value:null,inflight:null}}function te(e,a){const s=String(a||"");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,a,s){const l=(y.value?.data||[]).find(o=>o?.id===e&&o.owned_by!=="chatpanel-bridge");return l&&a.find(o=>o.id===l.owned_by&&o.type==="api"&&s(o))||null}async function ne(e,a){if(!y.value)try{await G(e,a)}catch{}}async function G(e,{timeoutMs:a=4e3,fresh:s=!1,now:l=Date.now,serviceHealth:o=null,engineAt:c=null}={}){const t=H(e),i=y.value&&y.key===t,r=!i||l()-y.at>z;if(i&&!s&&!r)return y.value;const g=()=>(y.inflight||(y.inflight=J(e,{timeoutMs:a,serviceHealth:o,engineAt:c}).then(h=>(y={at:l(),key:t,value:h,inflight:null},h)).catch(h=>{throw y.inflight=null,h})),y.inflight);return i&&!s?(g().catch(()=>{}),y.value):g()}async function J(e,{timeoutMs:a=4e3,serviceHealth:s=null,engineAt:l=null}={}){const o=N(e),c=new Set(o.data.map(n=>n.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 n=new Map(m(e).map(p=>[p.id,p]));for(const p of o.data){const u=n.get(p.provider);u&&t.has(u.id)&&Object.assign(p,S(p.id,p.owned_by,u,t.get(u.id)))}}const i=s?await s():null,r=new Map(m(e).filter(n=>n.service).map(n=>[n.id,n.service])),g=n=>{if(r.get(n.owned_by)&&i){const u=i(n.owned_by);u!=="unknown"&&(n.available=u==="up");const f=u==="down"&&typeof i.why=="function"?i.why(n.owned_by):"";f&&(n.state=f);const d=typeof i.window=="function"?i.window(n.owned_by):null;d&&(n.context_window=d);const w=typeof i.card=="function"?i.card(n.owned_by):null;w&&(n.card=w)}return n};for(const n of o.data)g(n);const h=await I(e,a);if(h){o.data=o.data.filter(n=>n.owned_by!=="chatpanel-bridge"||h.get(n.id)!==!1);for(const n of o.data)n.owned_by==="chatpanel-bridge"&&(n.available=h.get(n.id)??!1,h.noTools?.has(n.id)&&(n.tools=!1))}const b=await D(e,h,a);for(const[n,p]of b){const u=o.data.find(f=>f.id===n);if(u)for(const f of p){const d=`${n}/${f}`;c.has(d)||(c.add(d),o.data.push({...u,id:d,model:f,available:!0,reach:x(f)}))}}const A=m(e).filter(n=>n.type==="api"&&n.baseUrl),_=new Array(A.length).fill(null);return await Promise.all(A.map(async(n,p)=>{const u=new AbortController,f=setTimeout(()=>u.abort(),a);try{const d={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(d["x-api-key"]=n.apiKey,d["anthropic-version"]="2023-06-01"):d.authorization=`Bearer ${n.apiKey}`);const w=await $(`${n.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((n,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(n),w=C(n);o.data.push(g({id:f,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:d.api,endpoints:d.endpoints,...w?{configured:!1,reason:w}:{},...S(f,n.id,n,t.get(n.id)||null)}))}}}),o}export{te as agentOwnsModel,N as aggregateModels,G as aggregateModelsAsync,ne as ensureModelCatalog,m as listDestinations,ee as resetModelsCache,Z as resolveDestination};
@@ -1 +1 @@
1
- const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for vLLM-Metal and MLX."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(i=>i.id===t)||A(t):s(n).some(i=>i.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:i=null,platform:m=process.platform,installed:c=()=>!1}={}){const r=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>i==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${r(a.ramMB)} of memory while loaded — the container engine has ${r(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${r(a.ramMB)} while loaded — the engine has ${r(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,R as modelsFor,w as vllmTaskOf};
1
+ const x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,A=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),w=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),p=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function v(t){return p.find(a=>a.id===t)?.task||"chat"}const u=Object.freeze([{id:"mlx-community/Qwen3-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for vLLM-Metal and MLX."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),k=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),L=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function y(t){const a=String(t||"").trim();return L.test(a)||/^(\/|[A-Za-z]:\\)/.test(a)&&/\.gguf$/i.test(a)&&!/[\s"'`$;|&<>]/.test(a)}const T={reranker:A,opendecision:w,vllm:p,"vllm-metal":u,mlx:u,llama:k};function c(t){return T[t]||[]}function E(t,a){if(typeof a!="string"||!a.trim())return!1;const n=a.trim();return t==="llama"?c(t).some(l=>l.id===n)||y(n):c(t).some(l=>l.id===n)||x.test(n)}function G(t){return`models--${String(t).replace(/\//g,"--")}`}const R=/(ForCausalLM|ForConditionalGeneration|LMHeadModel)$/,Q=new Set(["","mlx"]);function _(t,a=[]){return(Array.isArray(a)?a:[]).filter(n=>n?.id&&n.architectures?.some(l=>R.test(l))).filter(n=>t==="mlx"||t==="vllm-metal"?n.mlx||Q.has(n.quantMethod):t==="vllm"?!n.mlx:!1)}function z(t,{active:a=null,engineRamMB:n=0,engine:l=null,platform:d=process.platform,installed:h=()=>!1,onDisk:M=[]}={}){const s=e=>`${Math.round(e/1024*10)/10} GB`,g=e=>l==="podman"&&d!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((e.ramMB+2048)/2048)*2048)} && podman machine start`:l==="docker"&&d!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,o=c(t).map(e=>{const i=n>0&&e.ramMB>n,r=!i&&Number(e.minRamMB)>0&&n>0&&n<e.minRamMB;return{...e,installed:h(e.id),recommended:!!e.recommended&&!i&&!r,...i?{unavailable:`needs about ${s(e.ramMB)} of memory while loaded — the container engine has ${s(n)}${g(e)?`; raise it: ${g(e)}`:""}`}:{},...r?{ramNote:`needs about ${s(e.ramMB)} while loaded — the engine has ${s(n)}; expect it to slow things down`}:{}}}),m=e=>`${Math.round(e/2**30*10)/10} GB`,B=_(t,M).filter(e=>e.id!==a||!o.some(i=>i.id===e.id));for(const e of B){const i=o.find(f=>f.id===e.id);if(i){i.installed=!0,i.onDisk=!0;continue}const r=e.bytes?Math.ceil(e.bytes*1.2/2**20):0,b=n>0&&r>n;o.unshift({id:e.id,label:e.id.split("/").pop(),lang:"—",tier:"on-disk",custom:!0,installed:!0,onDisk:!0,...r?{ramMB:r}:{},note:`Already on this machine${e.bytes?` (${m(e.bytes)})`:""} — no download.${e.mlx||t==="vllm"?"":" Original weights: MLX converts them as it loads; an MLX 4-bit copy would use less memory."}`,...b?{unavailable:`needs about ${m(r*2**20)} of memory while loaded — the engine has ${m(n*2**20)}`}:{}})}return a&&!o.some(e=>e.id===a)&&o.push({id:a,label:/\.gguf$/i.test(a)?a.split(/[\\/]/).pop():a,lang:"—",tier:"custom",custom:!0,installed:h(a),note:/\.gguf$/i.test(a)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),o}export{w as DECIDE_MODEL_CATALOG,x as HF_ID,k as LLAMA_MODEL_CATALOG,A as RERANK_MODEL_CATALOG,u as VLLM_METAL_MODEL_CATALOG,p as VLLM_MODEL_CATALOG,G as cacheDirName,c as catalogFor,y as isLlamaModelId,E as isValidModelId,z as modelsFor,_ as reusableFor,v as vllmTaskOf};
package/src/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import{promisify as xt}from"node:util";import{execFile as Pt}from"node:child_process";import{existsSync as Qe,mkdirSync as pe,writeFileSync as be,accessSync as Nn,openSync as Et,closeSync as Ot,constants as Ln}from"node:fs";import{randomBytes as Bt,createHash as Nt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Tn,isValidModelId as Cn,catalogFor as $e,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Rn,pickLlamaEngine as Lt,pickMlxEngine as Tt,pickAppleEngine as Ct,recommendEngine as Rt,detectAccelerator as Gt,hostShape as Ut}from"./inference-engines.js";import{tuningArgs as ve,tuningRows as Gn,patchTunings as Un,profilesFor as Hn,resolveTunings as In,splitTunings as ge,ENGINE_DOCS as Ht}from"./engine-tunings.js";import{IMAGE_RECIPES as It}from"./images.js";import{pullRepo as Ft,pullGguf as jt,repoInstalled as Dt,ggufInstalled as Fn,ggufRecipe as Ye,planGgufRecipe as Xt}from"./model-pull.js";import{llamaKnows as jn,llamaFlags as zt}from"./llama-arch.js";import{installBuild as Vt,installedBuild as Wt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as Dn,DEFAULT_LLAMA_BUILD as Jt}from"./llama-builds.js";import{liveFit as qt,kvCacheMB as Kt,cachedConfigPath as Qt,needMB as Xn}from"./host-memory.js";import{APPLE_HELPER as Ze,APPLE_MODEL_ID as Yt,APPLE_MIN_DARWIN as Zt,appleHelperDirs as er,appleInstallDoor as nr,darwinMajor as zn}from"./apple-model.js";import{transferRate as tr}from"./transfer-rate.js";import{capabilityList as Se,primaryProvider as rr,withProvider as Vn,withoutProvider as Wn}from"./capability-config.js";import{isEmbeddedModel as ir}from"./embedded-models.js";import{spawn as ar}from"node:child_process";import{readFileSync as Jn,unlinkSync as qn,realpathSync as or,readdirSync as Kn}from"node:fs";const sr=xt(Pt),Me=["podman","docker"],ae="hf-cache",F=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(r,l)=>{try{return(await l(`${r}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(r.search?.searxng?.url||""),configure:(r,l)=>{r.search=r.search||{},r.search.searxng={...r.search.searxng||{},url:l}},unconfigure:(r,l)=>{r.search?.searxng?.url===l&&(r.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>_e(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>xe(r,"rerank",f=>f.url===l)},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",retired:{why:"Retired — decisions are answered in the gateway with the same zero-shot models. Bring another decision model on the Models page.",instead:"Models › Decide"},model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data",`MODEL_ID=${r.model}`],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>_e(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>xe(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Rn({...r,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:r=>[`${$.join(r,ae)}:/data`],env:r=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${r.model}`,...r.installed?["HF_HUB_OFFLINE=1"]:[]],args:(r,l)=>["--model",r.model,"--host","0.0.0.0","--port","8000",...he(r.model)==="embed"?["--task","embed"]:[],...ve("vllm",r.tunings,{task:he(r.model),model:r.model,backend:l?.backend||null})],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String(Ae(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||Ae(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,R=he(f.model);Qn(r),R==="chat"?(r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm"&&h?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:p,models:[f.model],service:"vllm"})):R==="embed"?_e(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):R==="transcription"&&_e(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Qn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Rn(r),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["vllm",["serve",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("vllm-metal",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="vllm-metal"&&p?.id!=="vllm-metal"),r.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:r=>Lt(r),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:r=>/\.gguf$/i.test(r)?r.split(/[\\/]/).pop().replace(/\.gguf$/i,""):r.split("/").pop().split(":")[0],command:(r,l)=>["llama-server",[...r.file?["-m",r.file]:/\.gguf$/i.test(r.model)?["-m",r.model]:["-hf",r.model],"--host","127.0.0.1","--port",String(r.port),"--alias",r.alias(r.model),"--jinja",...ve("llama",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="llama"&&p?.id!=="llama"),r.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:r=>Tt(r),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(r,l)=>["mlx_lm.server",["--model",r.model,"--host","127.0.0.1","--port",String(r.port),...ve("mlx",r.tunings,l)]],answers:async(r,l)=>{try{return(await l(`${r}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{r.destinations=(r.destinations||[]).filter(p=>p?.service!=="mlx"&&p?.id!=="mlx"),r.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Ze,engineOf:r=>Ct(r),only:{platform:"darwin",arch:"arm64",minDarwin:Zt,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:r=>[Ze,["serve","--port",String(r.port)]],answers:async(r,l)=>{try{const f=await l(`${r}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:r=>String((r.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l)=>{r.destinations=(r.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),r.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[Yt],service:"apple"})},unconfigure:r=>{Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),oe=r=>r.only?.label||`${r.only?.platform||"this platform"} ${r.only?.arch||""}`.trim();function Qn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),xe(r,"embed",l=>l.service==="vllm"),xe(r,"stt",l=>l.service==="vllm")}function Ae(r,l,f){return Se(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function en(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function _e(r,l,f){en(r,l,Vn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function xe(r,l,f){r.capabilities?.[l]&&en(r,l,Wn(r.capabilities[l],l,f))}const A=r=>F.find(l=>l.id===r)||null,lr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:R,args:h,env:z,caps:Pe,command:Ee,engineOf:tn,alias:Oe,...B})=>B,ur=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),cr=Object.freeze(["brave","qwant"]);function dr(r=[]){const l=r.length?r:ur,f=cr.filter(p=>!l.includes(p));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(p=>[` - name: ${p}`," disabled: false"]),...f.flatMap(p=>[` - name: ${p}`," disabled: true"]),""].join(`
2
- `)}function nn(r=process.platform){return r==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:r==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function Yn(r,l){const f=l==="podman"?Array.isArray(r.Names)?r.Names[0]:String(r.Names||""):String(r.Names||r.Name||""),p=l==="podman"?Array.isArray(r.Ports)?r.Ports.map(h=>`${h.host_ip||""}:${h.host_port}->${h.container_port}/${h.protocol||"tcp"}`):[]:String(r.Ports||"").split(",").map(h=>h.trim()).filter(Boolean),R=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:R,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const mr=15e3;function Tr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:R=(x,q,G={})=>sr(x,q,{timeout:6e4,killSignal:"SIGKILL",...G}),platform:h=process.platform,arch:z=process.arch,osRelease:Pe=ie.release(),spawn:Ee=ar,lookup:tn=null,archKnower:Oe=null,fetchImpl:B=globalThis.fetch,stateDir:N=$.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Be=x=>new Promise(q=>setTimeout(q,x)),totalMem:rn=()=>ie.totalmem(),memoryProbe:Zn=x=>h==="darwin"&&r?.runtime?.heatwatch!==!1?qt(x,{fetchImpl:B}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:et=process.env.CHATPANEL_RUNTIME_AUTO,every:an=(x,q)=>{const G=setInterval(x,q);return G.unref?.(),G}}={}){const x=ie.homedir(),q=h==="win32"?[$.join(x,"AppData","Local","Microsoft","WinGet","Links"),$.join(x,".local","bin"),$.join(x,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",$.join(x,".local","bin"),$.join(x,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...h==="darwin"?er({home:x}):[]],G=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=q.filter(o=>!t.split(e).includes(o));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},y=async(n,e,t={})=>{try{const i=await R(n,e,{...t,env:G(t.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},w=n=>String(r.runtime?.services?.[n.id]?.model||n.model||"");let Ne=null;const on=async()=>(Ne===null&&(Ne=await Gt({exec:R,platform:h,arch:z})),Ne),K={},nt=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t)try{return Nn($.join(i,n+o),Ln.X_OK),!0}catch{}return!1},Le=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",""]:[""];for(const i of G().PATH.split(e).filter(Boolean))for(const o of t){const s=$.join(i,n+o);try{return Nn(s,Ln.X_OK),s}catch{}}return null},Q={},U=async(n,e=["--version"])=>{if(K[n])return!0;if(Q[n]!==void 0&&se()-Q[n]<mr)return!1;const t=(tn||nt)(n)||(await y(n,e,{timeout:8e3})).ok;return t?(K[n]=!0,delete Q[n]):Q[n]=se(),t},ne=n=>{const e=Le(n);let t;try{t=or(e)}catch{return null}const i=/[\\/]Cellar[\\/][^\\/]+[\\/]([^\\/]+)[\\/]/.exec(t);if(i)return i[1].replace(/_\d+$/,"");try{const o=$.join($.dirname(t),"..","lib");for(const s of Kn(o)){const a=$.join(o,s,"site-packages"),c=Kn(a).find(u=>/\.dist-info$/.test(u)&&u.toLowerCase().startsWith(`${$.basename($.dirname($.dirname(t))).replace(/-/g,"_").toLowerCase()}-`));if(c){const u=c.replace(/\.dist-info$/,"");return u.slice(u.lastIndexOf("-")+1)}}}catch{}return null},te=()=>r.runtime?.services?.llama?.build==="system"?"system":Jt,Y=n=>n?.id==="llama"&&te()==="unsloth",V=()=>Wt(N,h),le=()=>te()==="system"?"llama-server":V()?.bin||null,Te=()=>te()==="system"?Le("llama-server"):V()?.bin||null,sn=()=>te()==="system"?ne("llama-server"):V()?.tag||null,tt=Object.freeze({command:`downloaded from github.com/${v.repo} (${v.tag}), checked against its SHA-256`,note:`${v.label}: ${v.why}.`,url:`https://github.com/${v.repo}/releases`,update:{command:`the newest ${v.label} release, checked against its SHA-256`,steps:[["unsloth-llama"]]}});async function Ce(n,{tag:e=v.tag}={}){n.kind=n.kind==="update"?"update":"install",n.detail=v.label,P(n,`fetching ${v.label} (${e==="latest"?"the newest release":e}) from github.com/${v.repo}`);try{const t=await Vt({stateDir:N,platform:h,arch:z,accelerator:await on(),tag:e,fetchImpl:B,run:y,onProgress:gn(n)});return P(n,t.already?`${v.label} ${t.tag} — already here`:`${v.label} ${t.tag} — checked against its published SHA-256`),{ok:!0,...t}}catch(t){return{ok:!1,error:n.cancelled?"cancelled":t.message}}}const ln=(n,e)=>e?.missing||`\`${n.runner}\` is not on PATH — install it first (${e?.command||""}), or click Install`;let Re=null;const ke=async()=>(Re||(Re=await Ut({exec:R,platform:h,totalmem:rn,cpus:()=>ie.cpus()})),Re),H=async n=>({platform:h,arch:z,accelerator:await on(),engine:n,vllmOnPath:await U("vllm"),llamaOnPath:await U("llama-server"),mlxOnPath:h==="darwin"&&z==="arm64"?await U("mlx_lm.server",["--help"]):!1,osMajor:h==="darwin"?zn(Pe):0,appleOnPath:h==="darwin"&&z==="arm64"?await U(Ze):!1,appleInstall:h==="darwin"?nr({home:x}):null,...await ke()}),C=n=>!n.only||(!n.only.platform||n.only.platform===h)&&(!n.only.arch||n.only.arch===z)&&(!n.only.minDarwin||zn(Pe)>=n.only.minDarwin),ue=n=>$.join(N,`${n.id}.pid`),re=n=>{try{const e=Number(Jn(ue(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ce=n=>C(n)?re(n)?"running":"stopped":"unsupported",Z={};async function Ge(n){const e=de(n);if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};if(re(e))return e.auto&&!e.configured(r)&&(e.configure(r,_(e),e),p()),{ok:!0,already:!0,url:_(e)};if(e.auto&&await e.answers(_(e),B)){const M=await st(e.port);if(M)return pe(N,{recursive:!0,mode:448}),be(ue(e),String(M),{mode:384}),Z[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(r,_(e),e),p(),S(`[runtime] ${e.label} was already answering on ${_(e)} (pid ${M}) — adopted`),{ok:!0,adopted:!0,url:_(e),answering:!0,provides:e.provides}}const t=await H(null),i=e.engineOf(t);if(Y(e)?!le():!await U(e.runner,e.runnerCheck))return Y(e)?{ok:!1,error:`${v.label} is not downloaded yet — Start fetches it`}:{ok:!1,error:ln(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Qe(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[o,s]=e.command(e,D(e,e.model,i,t)),a=e.id==="llama"?le():o,c=$.join(N,ae);pe(c,{recursive:!0,mode:448});const u={bin:a,argv:s,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:c,LLAMA_CACHE:c,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};Z[e.id]=u.record;const d=$.join(N,`${e.id}.log`);let m,k=null;try{try{k=Et(d,"w",384)}catch{k=null}m=Ee(u.bin,u.argv,{...u.opts,env:G(u.opts?.env),detached:!0,stdio:["ignore",k??"ignore",k??"ignore"]}),m.unref?.()}catch(M){return{ok:!1,error:`${u.bin}: ${M.message}`,install:i.install}}finally{if(k!==null)try{Ot(k)}catch{}}if(!m?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};be(ue(e),String(m.pid),{mode:384});const g=_(e);let O=!1;for(let M=0;M<120&&!O&&re(e);M++)O=await e.answers(g,B),O||await Be(1e3);if(!re(e)){try{qn(ue(e))}catch{}let M="";try{M=Jn(d,"utf8").trim().split(`
3
- `).filter(T=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(T)).slice(-3).map(T=>T.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{M=""}return{ok:!1,error:`${e.label} exited on start${M?` — ${M}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:d}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Z[e.id].layer}${O?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:O,provides:e.provides,model:w(e),sandbox:Z[e.id]}}const Ue=n=>r.runtime?.services?.[n.id]?.off===!0,un=(n,e)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const t={...r.runtime.services[n.id]||{}};e?t.off=!0:delete t.off,r.runtime.services[n.id]=t},cn=()=>r.runtime?.auto!==!1&&String(et||"").toLowerCase()!=="off",L={};async function dn(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!cn())return{ok:!1,skipped:"automatic start is switched off"};if(!C(n))return{ok:!1,skipped:`runs on ${oe(n)} only`};if(Ue(n))return{ok:!1,skipped:"stopped by the person"};if(!await U(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!re(n)){const t=await y(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return L[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:L[n.id]}}}const e=await Ge(n);return e.ok?(delete L[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(L[n.id]=e.error,{ok:!1,skipped:e.error})}const mn=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{},r.runtime.services[n.id]={...r.runtime.services[n.id]||{},pulling:{model:e,start:!!t}},p()},He=n=>{const e=r.runtime?.services?.[n.id];e?.pulling&&(delete e.pulling,p())};function fn(){let n=!1;for(const e of F.filter(t=>t.retired))for(const t of e.provides||[]){const i=r.capabilities?.[t];if(!i||!Se(i,t).providers.some(c=>c.service===e.id))continue;const o=Se(i,t).providers.find(c=>c.service===e.id),s={provider:"embedded",...ir(t,o?.model)?{model:o.model}:{}},a=Se(i,t).providers.some(c=>c.provider==="embedded"&&(c.model||null)===(s.model||null));en(r,t,a?Wn(i,t,c=>c.service===e.id):Vn(i,t,s,{match:c=>c.service===e.id})),S(`[runtime] ${e.label} is retired: ${t} now answers in the gateway${s.model?` with ${s.model}`:""}`),n=!0}n&&p()}async function rt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.retired)return{ok:!1,error:`${e.label} is not retired — stop it instead`};const t=(await E()).preferred;if(!t)return{ok:!1,error:"no container engine"};const i=await y(t,["rm","-f",e.container],{timeout:6e4});if(!i.ok&&!/no such container/i.test(i.err||""))return{ok:!1,error:`${t} rm: ${i.err||i.out}`};const o=await y(t,["rmi",e.image],{timeout:6e4});return e.unconfigure(r,_(e)),p(),S(`[runtime] ${e.label} removed (container${o.ok?" and image":""})`),{ok:!0,removed:{container:!0,image:!!o.ok}}}async function it(){const n=[];if(!cn())return n;for(const e of F.filter(t=>t.pull)){const t=r.runtime?.services?.[e.id]?.pulling;if(t){if(t.model!==w(e)||J(e,w(e))){He(e),J(e,w(e))&&t.start&&n.push({id:e.id,...await ee(e.id).catch(i=>({ok:!1,error:i.message}))});continue}S(`[runtime] ${e.label}: resuming the download of ${t.model} a previous run left under way`),n.push({id:e.id,resumed:t.model,...await(t.start?ee(e.id):xn(e.id)).catch(i=>({ok:!1,error:i.message}))})}}return n}async function at(){try{fn()}catch(e){S(`[runtime] retiring: ${e.message}`)}try{pn()}catch(e){S(`[runtime] settings per model: ${e.message}`)}const n=[...await it().catch(()=>[])];for(const e of F.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await dn(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function ot(n){const e=A(n);return e?.auto?dn(e):{ok:!1,skipped:"not a service that starts by itself"}}async function st(n){if(h==="win32")return 0;const e=await y("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
4
- `)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function we(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{qn(ue(n))}catch{}return n.unconfigure(r,_(n)),p(),{ok:!0}}const de=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:j(n,w(n)),...n.id==="llama"?{file:ut(w(n))}:{}}:n,W=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx",j=(n,e)=>{const t=r.runtime?.services?.[n.id]||{},{engine:i,model:o}=ge(t.tunings),s=e&&t.byModel?.[e]?t.byModel[e]:e&&e===w(n)?o:{};return{...i,...s}},Ie=(n,e,t)=>{r.runtime=r.runtime||{},r.runtime.services=r.runtime.services||{};const i=r.runtime.services[n.id]||{},{engine:o,model:s}=ge(t),a={...i.byModel||{}};e&&(Object.keys(s).length?a[e]=s:delete a[e]),r.runtime.services[n.id]={...i,tunings:o,...Object.keys(a).length?{byModel:a}:{}},Object.keys(a).length||delete r.runtime.services[n.id].byModel};function pn(){let n=!1;for(const e of F.filter(W)){const t=r.runtime?.services?.[e.id];if(!t?.tunings)continue;const{model:i}=ge(t.tunings);if(!Object.keys(i).length)continue;const o=w(e);o?Ie(e,o,{...i,...(t.byModel||{})[o]||{},...ge(t.tunings).engine}):t.tunings=ge(t.tunings).engine,n=!0}n&&p()}function lt(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=$e(n.id).filter(c=>!c.minRamMB||t>0&&t>=c.minRamMB);if(!o.length||!t)return null;const s=o.slice().sort((c,u)=>(i[u.tier]??-1)-(i[c.tier]??-1)||c.ramMB-u.ramMB)[0],a=Math.round(s.ramMB/1024*10)/10;return{model:s.id,label:s.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${s.label} well — about ${a} GB while loaded${s.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:w(n)===s.id}}async function hn(n,{model:e,ctx:t,needMB:i}={}){const o=A(n);if(!o||!o.model)return{ok:!1,error:o?`${o.label} takes no model`:`unknown service ${n}`};const s=String(e||w(o)),a=$e(n).find(Ke=>Ke.id===s)||null,c=Number(i)>0?Number(i):a?.ramMB||null;if(!c)return{ok:!1,error:`${s} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(t)>0?Number(t):En(n),d=/\.gguf$/i.test(s)||o.id==="llama"?null:Qt(X(),s),m=u&&d?Kt(d,u):null,k=Xn({ramMB:c,kvMB:m||0}),g=o.kind==="native"?await Zn(k):null,O=((await ke()).ramGB||0)*1024,M=g?g.fits:O>0&&k<=O,T=Ke=>`${Math.round(Ke/102.4)/10} GB`,_t=g?g.fits?`${s} fits: needs about ${T(k)}, ${T(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${T(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${s} needs about ${T(k)} and ${T(g.availableMB)} is free now — ${T(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${s} needs about ${T(k)} of the machine's ${T(O)} — ${M?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:o.id,model:s,needMB:k,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:M,live:g,advice:_t}}const D=(n,e,t,i={})=>({task:n.id==="vllm"?he(e):"chat",model:e,backend:t?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0,...n.id==="llama"?{recipe:Ye(X(),e),flags:zt(Te())}:{}}),X=()=>$.join(N,ae),J=(n,e)=>/\.gguf$/i.test(e)?Qe(e):n.id==="llama"?!!Fn(X(),e):Dt(X(),e),ut=n=>/\.gguf$/i.test(n)?n:Fn(X(),n),b={},fr=n=>b[n.id]||null;function gn(n){const e=tr();return t=>{if(n.cancelled)throw new Error("cancelled");t.retry&&P(n,`retrying ${String(t.file||"").split("/").pop()} in ${Math.round(t.retry.inMs/1e3)} s (try ${t.retry.attempt} of ${t.retry.of}) — ${t.retry.error}`),n.progress={bytes:t.bytes,total:t.total,file:t.file,...t.retry?{retrying:t.retry}:{},...e(t.bytes,{skipped:!!t.skipped,total:t.total})}}}function me(n,e,t={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},b[n.id]}function P(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const ye=(n,e,t,{timeout:i=36e5*4}={})=>new Promise(o=>{if(n.cancelled)return o({ok:!1,code:-1,error:"cancelled"});let s;try{s=Ee(e,t,{stdio:["ignore","pipe","pipe"],env:G()})}catch(d){return o({ok:!1,code:-1,error:d.message})}n.child=s;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const k of m)P(n,k)};s.stdout?.on("data",c),s.stderr?.on("data",c);const u=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}},i);u.unref?.(),s.on("error",d=>{clearTimeout(u),n.child=null,o({ok:!1,code:-1,error:d.message})}),s.on("exit",d=>{clearTimeout(u),n.child=null,a&&P(n,a),o({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),kn={install:Promise.resolve(),build:Promise.resolve()},Fe={install:0,build:0},wn=(n,e,t)=>{Fe[n]>0&&(e.waiting=!0,P(e,`waiting for the other ${n} to finish first — one at a time`)),Fe[n]++;const i=kn[n];let o;const s=new Promise(a=>{o=a});return kn[n]=i.then(()=>s),i.then(async()=>{e.waiting&&(P(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{Fe[n]--,o()}})},yn=async(n,e)=>(await y(n,["image","exists",e],{timeout:2e4})).ok;async function ct(n,e,t,i){const o=e?.image||t.image;if(await yn(n,o))return{ok:!0};const s=e?.sources?.length?e.sources:[o],a=[];for(const m of s){if(i.kind="pull-image",i.detail=m,P(i,`pulling ${m}`),(await ye(i,n,["pull",m])).ok)return m!==o&&await y(n,["tag",m,o],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?It[e.recipe]:null;if(!c)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=$.join(N,"images",e.recipe);return pe(u,{recursive:!0,mode:448}),be($.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=o,i.minutes=c.minutes,P(i,`no registry has ${o} for this machine — building it here (about ${c.minutes} minutes)`),S(`[runtime] building ${o} from the ${e.recipe} recipe in ${u}`),(await wn("build",i,()=>ye(i,n,["build","-t",o,"-f",$.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function bn(n,e){const t=w(n);if(!t||J(n,t))return{ok:!0};if(/\.gguf$/i.test(t))return{ok:!1,error:`no such file: ${t}`};e.kind="pull-model",e.detail=t;const i=gn(e);try{if(n.id==="llama"){const o=j(n,t);await jt(t,{root:X(),fetchImpl:B,onProgress:i,knows:(Oe||jn)(Te()),engineVersion:sn(),vision:o.vision!=="off",draft:o.draftModel!=="off"})}else await Ft(t,{root:X(),fetchImpl:B,onProgress:i});return{ok:!0}}catch(o){return{ok:!1,error:`pull ${t}: ${o.message}`}}}async function dt(n,e,t){const i=[];return Y(n)&&!le()&&i.push("runner"),n.kind!=="native"&&e&&!await yn(e,t?.image||n.image)&&i.push("image"),n.pull&&n.model&&!J(n,w(n))&&i.push("model"),i}async function $n(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&h!=="linux"){const t=await y("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?i:0}if(n==="docker"&&h!=="linux"){const t=await y("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(rn()/1048576)}async function E(){const n={};for(const t of Me){const i=await y(t,["--version"],{timeout:5e3});if(!i.ok){n[t]={installed:!1};continue}const o=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let s=!1,a=null;if(t==="podman")if(h==="linux")s=(await y("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await y("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(c.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,s=!!d?.Running}catch{a=null}}else s=(await y("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:o,running:s,...t==="podman"&&h!=="linux"?{machine:a}:{}}}const e=Me.find(t=>n[t]?.installed&&n[t].running)||Me.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:nn(h)}}}async function je(n="podman"){if(!Me.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await E())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:nn(h)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(h!=="linux"){if(!e.machine){const i=await y("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await y("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function vn(){const n=await E(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await y("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(o=>Yn(o,"podman"))}catch{return[]}}const t=await y("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
5
- `).filter(Boolean).map(i=>{try{return Yn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Sn(n,e){const t=await y(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function De(n,e){const t=await y(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const s of e)i[s]="absent";return i}const o=new Map(t.out.split(`
6
- `).map(s=>s.split(" ")).filter(s=>s[0]).map(([s,a])=>[s,/running/i.test(a||"")?"running":"stopped"]));for(const s of e)i[s]=o.get(s)||"absent";return i}const _=n=>`http://127.0.0.1:${n.port}`;async function Mn(){const n=await E(),e=n.preferred,t=await $n(e,n),i={},o=await H(e),s=e&&n[e].running?await De(e,F.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of F){const c=_(a);let u="no-engine";if(a.kind==="native"?u=ce(a):e&&n[e].running?u=s[a.container]||"absent":e&&(u="engine-stopped"),a.retired&&!["running","stopped","exited","created","paused"].includes(u))continue;const d=a.model?w(a):null,m=a.engineOf?Y(a)?{...a.engineOf({...o,llamaOnPath:!0}),install:tt}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...lr(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(r),answering:u==="running"?await a.answers(c,B):!1,...a.helper?{asleep:I.has(a.id),idleMinutes:On()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!C(a)?{why:`${a.label} runs on ${oe(a)} only`}:{},...a.id==="llama"&&C(a)?{...d&&Ye(X(),d).recommended?{recommended:Ye(X(),d).recommended}:{},build:te(),builds:[{id:"unsloth",label:v.label,why:v.why,installed:!!V(),version:V()?.tag||null,default:!0},{id:"system",label:"The system’s llama.cpp",why:"Homebrew’s, or one you built — `llama-server` on PATH",installed:!!Le("llama-server"),version:ne("llama-server")}],...te()==="unsloth"?V()?{runnerVersion:V().tag,updatable:!0}:{}:K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{}}:a.kind==="native"&&a.runner&&C(a)&&K[a.runner]?{runnerVersion:ne(a.runner),updatable:!!m?.install?.update?.steps?.length}:{},...a.auto&&u!=="running"&&C(a)?{auto:!0,...Ue(a)?{why:"Stopped here — Start turns it back on"}:L[a.id]?{why:L[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&C(a)&&L[a.id]?{why:L[a.id]}:{},...a.kind==="native"&&Z[a.id]?{sandbox:Z[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...W(a)?{profiles:Hn(a.id,j(a,d),D(a,d,m,o)),docs:Ht[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:lt(a,o)}:{},...a.model?{model:d,default:a.model,models:Tn(a.id,{active:d,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g)}),machine:{engineRamMB:k}}:{},...W(a)?{tunings:Gn(a.id,j(a,d),D(a,d,m,o))}:{}}}return i}async function mt(){const n=await E(),e=await H(n.preferred);return{platform:h,arch:z,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Rt(e)}}function An(n,{settingsFile:e=null,secret:t=null,pick:i=null,cpus:o=null}={}){const s=de(n),a=["run","-d","--name",s.container,"--restart","no","-p",`127.0.0.1:${s.port}:${s.containerPort}`];s.helper&&o&&a.push("--cpus",String(o));for(const u of s.volumes?s.volumes(N):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of s.env?s.env(s):[])a.push("-e",u);s.helper&&o&&a.push("-e",`THREADS=${o}`),t&&a.push("-e",`SEARXNG_SECRET=${t}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${s.port}/`),a.push("--cap-drop","ALL");for(const u of s.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||s.image,...s.args?s.args(s,i):[]);const c=Nt("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${c}`),{args:a,hash:c}}const Xe={};async function ft(n){if(Xe[n]==null){const e=await y(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);Xe[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(Xe[n]/2))}async function ee(n,{force:e=!1}={}){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(t.retired)return{ok:!1,error:t.retired.why,retired:!0};I.delete(t.id),qe(t.id),t.auto&&Ue(t)&&un(t,!1);const i=b[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let o=null;if(t.kind!=="native"){const d=await E();if(o=d.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:nn(h)};if(!d[o].running){const m=await je(o);if(!m.ok)return m}}else if(!C(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await H(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await U(t.runner,t.runnerCheck))return{ok:!1,error:ln(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!Qe(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const d=await hn(t.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await dt(t,o,a);if(!c.length){if(delete b[t.id],t.kind!=="native")return ze(t,o);const d=await Ge(t);return d.ok?delete L[t.id]:L[t.id]=d.error,d}const u=me(t,c[0]==="runner"?"install":c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="runner"?v.label:c[0]==="image"?a?.image||t.image:w(t)});return c.includes("model")&&mn(t,w(t),!0),u.then=(async()=>{try{if(c.includes("runner")){const m=await Ce(u);if(!m.ok)throw new Error(m.error)}if(c.includes("image")){const m=await ct(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await bn(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const d=t.kind==="native"?await Ge(t):await ze(t,o);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,S(`[runtime] ${t.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,S(`[runtime] ${t.label}: ${u.error}`)}finally{c.includes("model")&&He(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function pt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=b[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return P(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function ze(n,e){let t=await Sn(e,n.container);const i=n.helper?await ft(e):null,o=n.engineOf?n.engineOf(await H(e)):null,s=n.id==="searxng"?$.join(N,"searxng-settings.yml"):null,a=An(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const d=await y(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(S(`[runtime] ${n.label}: made with older settings — re-creating it`),await y(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const d=await y(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{pe(N,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(be(s,dr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Bt(32).toString("hex")),n.volumes&&pe($.join(N,ae),{recursive:!0,mode:448});const{args:m}=An(n,{settingsFile:s,secret:d,pick:o,cpus:i});S(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await y(e,m,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const c=_(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,B),u||await Be(1e3);return n.configure(r,c,de(n)),p(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:w(n)}:{}}}async function ht(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(I.delete(e.id),delete Je[e.id],e.auto&&un(e,!0),e.kind==="native")return we(e);const t=await E(),i=t.preferred;if(i&&t[i].running){const o=await y(i,["stop",e.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${i} stop: ${o.err||o.out}`}}return e.unconfigure(r,_(e)),p(),{ok:!0}}async function gt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!Dn.includes(e))return{ok:!1,error:`one of ${Dn.join(", ")}`};r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{};const i={...r.runtime.services.llama||{}};e==="system"?i.build="system":delete i.build,r.runtime.services.llama=i,p();const o=await Ve(t,null,await E());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function kt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a recipe is for llama.cpp (a GGUF repo)"};const i=String(e||"").trim();if(!Cn(n,i)||/\.gguf$/i.test(i))return{ok:!1,error:`not a Hugging Face id: ${JSON.stringify(e)} — owner/name, or owner/name:QUANT`};const o=((await ke()).ramGB||0)*1024,s=a=>o?Xn({ramMB:a/2**20})<=o*.75:null;try{const a=await Xt(i,{fetchImpl:B,knows:(Oe||jn)(Te()),engineVersion:sn()}),c=(a.projector?.size||0)+(a.draft?.size||0);return{ok:!0,model:`${a.repo}:${a.quant}`,quant:a.quant,arch:a.arch,layout:a.layout,main:a.main,size:a.total,projector:a.projector,draft:a.draft,quants:a.quants.map(u=>({...u,fits:s(u.size+c)})),ramGB:o/1024,fits:s(a.total+c)}}catch(a){return{ok:!1,error:a.message,...a.code?{code:a.code,arch:a.arch}:{}}}}async function wt(n,e,{tunings:t=null}={}){const i=A(n);if(!i)return{ok:!1,error:`unknown service ${n}`};if(!i.model)return{ok:!1,error:`${i.label} takes no model`};const o=String(e||"").trim();if(!Cn(n,o))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await E(),a=s.preferred,c=i.kind==="native"?((await ke()).ramGB||0)*1024:await $n(a,s),u=Tn(n,{active:o,engineRamMB:c,engine:i.kind==="native"?"host":a,platform:h,installed:g=>J(i,g)}).find(g=>g.id===o);if(u?.unavailable)return{ok:!1,error:`${o} ${u.unavailable}`};let d=null;if(t&&W(i)){const g=await H(a);if(d=Un(i.id,j(i,o),t,D(i,o,i.engineOf?i.engineOf(g):null,g)),d.error)return{ok:!1,error:d.error}}r.runtime=r.runtime||{services:{}},r.runtime.services=r.runtime.services||{},r.runtime.services[n]={...r.runtime.services[n]||{},model:o},d&&Ie(i,o,d);const m=_(i);i.configured(r)===m&&i.configure(r,m,de(i)),p();const k=await Ve(i,a,s);return k.ok?{ok:!0,model:o,restarted:k.restarted,...k.pending?{pending:k.pending}:{},...u?.ramNote?{note:u.ramNote}:{}}:k}async function Ve(n,e,t){if(n.kind==="native"){if(ce(n)!=="running")return{ok:!0,restarted:!1};we(n);const s=await ee(n.id,{force:!0});return s.ok?{ok:!0,restarted:!0,...s.pending?{pending:s.pending}:{}}:s}if(!e||!t[e].running)return{ok:!0,restarted:!1};const i=await Sn(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const o=await y(e,["rm","-f",n.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${e} rm: ${o.err||o.out}`};if(i==="running"){const s=await ee(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function yt(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await E(),o=await H(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Hn(t.id,j(t,w(t)),D(t,w(t),s,o)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Pn(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function We(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(le())return{ok:!0,installed:!0};const s=me(e,"install",{detail:v.label});return s.then=(async()=>{const a=await Ce(s);s.done=!0,a.ok||(s.error=a.error),S(`[runtime] install ${v.label}: ${s.error||"ok"}`)})(),{ok:!0,pending:{kind:s.kind,since:s.since,detail:s.detail}}}if(delete K[e.runner],delete Q[e.runner],await U(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await H(null))?.install;return o?.steps?.length?_n(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function _n(n,e,t){const i=me(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=wn("install",i,async()=>{const a=async d=>{for(const[m,...k]of d){P(i,`$ ${m} ${k.join(" ")}`);let g=await ye(i,m,k,{timeout:36e5});for(let O=0;!g.ok&&!i.cancelled&&O<6&&i.lines.some(M=>/already locked|Please wait for it to finish/i.test(M));O++)P(i,`another ${m} holds the lock — waiting 20 s (${O+1}/6)`),await Be(2e4),g=await ye(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(O=>new RegExp(e.upToDate,"i").test(O))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(e.steps);!c.ok&&!i.cancelled&&e.fallback?.length&&(P(i,`${c.error} — trying the other way`),c=await a(e.fallback)),delete K[n.runner],delete Q[n.runner];const u=c.ok&&await U(n.runner,n.runnerCheck);if(u&&t==="update"){const d=ne(n.runner);if(P(i,d&&s&&d!==s?`${n.label} ${s} → ${d}`:`${n.label}${d?` ${d}`:""} — up to date`),o&&!i.cancelled){we(n),i.done=!0;const m=await ee(n.id,{force:!0});if(m.ok||(L[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;b[n.id]||(b[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":c.ok?u||(i.error=`${n.runner} still not found after the ${t} — open a new terminal and run \`${e.command}\` by hand`):i.error=`${t} failed: ${c.error}${i.lines.length?` (${i.lines.slice(-2).join(" | ")})`:""}`,S(`[runtime] ${t} ${n.runner}: ${i.error||"ok"}`)}),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function bt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(!le())return We(n);const o=V()?.tag,s=ce(e)==="running",a=me(e,"update",{detail:v.label});return a.then=(async()=>{const c=await Ce(a,{tag:"latest"});if(!c.ok){a.done=!0,a.error=`update failed: ${c.error}`;return}if(P(a,c.tag!==o?`${v.label} ${o} → ${c.tag}`:`${v.label} ${c.tag} — up to date`),a.done=!0,s&&c.tag!==o&&!a.cancelled){we(e);const u=await ee(e.id,{force:!0});u.ok||(L[e.id]=u.error),b[e.id]||(b[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete K[e.runner],delete Q[e.runner],!await U(e.runner,e.runnerCheck))return We(n);const i=e.engineOf(await H(null))?.install;return i?.update?.steps?.length?_n(e,i.update,"update"):{ok:!1,error:`no updater for ${e.label} on this platform${i?.url?` — newer builds are at ${i.url}`:""}`,install:i||null}}async function xn(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(J(e,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=me(e,"pull-model",{detail:w(e)});return mn(e,w(e),!1),i.then=(async()=>{const o=await bn(e,i);i.done=!0,o.ok||(i.error=o.error),He(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Pn(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await E(),o=i.preferred,s=w(t),a=await H(o),c=t.engineOf?t.engineOf(a):null,u=Un(t.id,j(t,s),e,D(t,s,c,a));if(u.error)return{ok:!1,error:u.error};Ie(t,s,u),p();const d=await Ve(t,o,i);return d.ok?{ok:!0,tunings:Gn(t.id,u,D(t,s,c,a)),restarted:d.restarted}:d}async function $t(){const n=await E(),e=n.preferred,t=e&&n[e].running?await De(e,F.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(F.map(async s=>{const a=s.kind==="native"?ce(s):e&&n[e].running?t[s.container]||"absent":"no-engine";i[s.id]=a==="running"&&await s.answers(_(s),B)?"up":"down";const c=(s.provides||[]).some(u=>["embedded","none"].includes(rr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!c&&s.configured(r)!==_(s)&&(s.configure(r,_(s),de(s)),o=!0)})),o&&p(),i}function En(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(In(e.id,j(e,w(e)),D(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function vt(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=In(e.id,j(e,t),D(e,t,null,{})),o=$e(e.id).find(a=>a.id===t)||null,s=e.id==="vllm"?he(t):"chat";return{engine:e.id,backend:Z[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:s,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:s==="chat"&&!!i.vision,tools:!!(s==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:s==="chat"&&!!i.reasoning&&i.reasoning!=="off",...o?{tier:o.tier||null,licence:o.licence||null,languages:o.lang||null,label:o.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const St=10,On=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:St)*6e4},Mt=se(),Je={},I=new Set,fe={};function qe(n){Je[n]=se()}async function At(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(qe(t.id),!I.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await vn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};I.add(t.id)}return fe[t.id]||(fe[t.id]=(async()=>{const i=await E(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await je(o);if(!a.ok)return a}const s=await ze(t,o);return s.ok&&(I.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Bn(){const n=On();if(!n)return[];const e=F.filter(a=>a.helper&&a.configured(r)&&!I.has(a.id)&&!fe[a.id]&&!(b[a.id]&&!b[a.id].done)&&se()-(Je[a.id]??Mt)>=n);if(!e.length)return[];const t=await E(),i=t.preferred;if(!i||!t[i].running){for(const a of e)I.add(a.id);return e.map(a=>a.id)}const o=await De(i,e.map(a=>a.container)),s=[];for(const a of e){if(o[a.container]==="running"){if(!(await y(i,["stop",a.container],{timeout:6e4})).ok)continue;S(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}I.add(a.id),s.push(a.id)}return s}return an&&an(()=>{Bn().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:qe,wake:At,sweepIdle:Bn,health:$t,contextWindow:En,modelCard:vt,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),E(),Mn(),vn(),mt()]);return{machine:o,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:t}},startEngine:je,startService:ee,stopService:ht,ensureDefaults:at,retireServices:fn,removeService:rt,upcastTunings:pn,revive:ot,plan:hn,recipe:kt,setBuild:gt,isAsleep:n=>I.has(n),setModel:wt,setTunings:Pn,setProfile:yt,pullModel:xn,installRunner:We,updateRunner:bt,cancelJob:pt,services:Mn,catalogFor:$e}}export{ur as SEARXNG_DEFAULT_ENGINES,F as SERVICES,Yn as containerRow,Tr as createRuntime,nn as installDoor,dr as searxngSettings};
1
+ import{promisify as Bt}from"node:util";import{execFile as Nt}from"node:child_process";import{existsSync as Ye,mkdirSync as pe,writeFileSync as $e,accessSync as Tn,openSync as Lt,closeSync as Tt,constants as Cn}from"node:fs";import{randomBytes as Ct,createHash as Rt}from"node:crypto";import ie from"node:os";import $ from"node:path";import{modelsFor as Rn,isValidModelId as Gn,catalogFor as ve,vllmTaskOf as he}from"./runtime-models.js";import{pickInferenceEngine as Un,pickLlamaEngine as Gt,pickMlxEngine as Ut,pickAppleEngine as Ht,recommendEngine as It,detectAccelerator as Ft,hostShape as Dt}from"./inference-engines.js";import{tuningArgs as Se,tuningRows as Hn,patchTunings as In,profilesFor as Fn,resolveTunings as Dn,splitTunings as ge,ENGINE_DOCS as jt}from"./engine-tunings.js";import{IMAGE_RECIPES as Xt}from"./images.js";import{pullRepo as zt,pullGguf as Vt,repoInstalled as Wt,ggufInstalled as jn,ggufRecipe as Ze,planGgufRecipe as Jt,cachedRepos as qt}from"./model-pull.js";import{llamaKnows as Xn,llamaFlags as Kt}from"./llama-arch.js";import{installBuild as Qt,installedBuild as Yt,UNSLOTH_LLAMA as v,LLAMA_BUILDS as zn,DEFAULT_LLAMA_BUILD as Zt}from"./llama-builds.js";import{liveFit as er,kvCacheMB as nr,cachedConfigPath as tr,needMB as Vn}from"./host-memory.js";import{APPLE_HELPER as en,APPLE_MODEL_ID as rr,APPLE_MIN_DARWIN as ir,appleHelperDirs as ar,appleInstallDoor as or,darwinMajor as Wn}from"./apple-model.js";import{transferRate as sr}from"./transfer-rate.js";import{capabilityList as Me,primaryProvider as lr,withProvider as Jn,withoutProvider as qn}from"./capability-config.js";import{isEmbeddedModel as ur}from"./embedded-models.js";import{spawn as cr}from"node:child_process";import{readFileSync as Kn,unlinkSync as Qn,realpathSync as dr,readdirSync as Yn}from"node:fs";const mr=Bt(Nt),Ae=["podman","docker"],ae="hf-cache",D=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(_e(r,"rerank","reranker")?.url||""),configure:(r,l,f)=>xe(r,"rerank",{url:l,adapter:f.adapter,model:f.model,service:f.id}),unconfigure:(r,l)=>Pe(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(_e(r,"decide","opendecision")?.url||""),configure:(r,l,f)=>xe(r,"decide",{url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}),unconfigure:(r,l)=>Pe(r,"decide",f=>f.url===l)},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:r=>Un({...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"]:[],...Se("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(_e(r,"embed","vllm")?.url?.replace(/\/v1$/,"")||_e(r,"stt","vllm")?.url?.replace(/\/v1$/,"")||(r.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(r,l,f)=>{const p=`${l}/v1`,G=he(f.model);Zn(r),G==="chat"?(r.destinations=(r.destinations||[]).filter(h=>h?.service!=="vllm"&&h?.id!=="vllm"),r.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:p,models:[f.model],service:"vllm"})):G==="embed"?xe(r,"embed",{url:p,adapter:"openai",model:f.model,service:"vllm"}):G==="transcription"&&xe(r,"stt",{provider:"container",url:p,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:r=>Zn(r)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:r=>Un(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),...Se("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=>Gt(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",...Se("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=>Ut(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),...Se("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:en,engineOf:r=>Ht(r),only:{platform:"darwin",arch:"arm64",minDarwin:ir,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=>[en,["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:[rr],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 Zn(r){Array.isArray(r.destinations)&&(r.destinations=r.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),Pe(r,"embed",l=>l.service==="vllm"),Pe(r,"stt",l=>l.service==="vllm")}function _e(r,l,f){return Me(r.capabilities?.[l],l).providers.find(p=>p.service===f)||null}function nn(r,l,f){r.capabilities=r.capabilities||{},f?r.capabilities[l]=f:delete r.capabilities[l]}function xe(r,l,f){nn(r,l,Jn(r.capabilities?.[l],l,f,{match:p=>p.service===f.service}))}function Pe(r,l,f){r.capabilities?.[l]&&nn(r,l,qn(r.capabilities[l],l,f))}const A=r=>D.find(l=>l.id===r)||null,fr=({answers:r,configured:l,configure:f,unconfigure:p,volumes:G,args:h,env:z,caps:Ee,command:Oe,engineOf:rn,alias:Be,...B})=>B,pr=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),hr=Object.freeze(["brave","qwant"]);function gr(r=[]){const l=r.length?r:pr,f=hr.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 tn(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 et(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),G=String(r.State||"").toLowerCase()||(/^up/i.test(String(r.Status||""))?"running":"exited");return{name:f,image:String(r.Image||""),state:G,status:String(r.Status||""),ports:p,ours:f.startsWith("chatpanel-"),engine:l}}const kr=15e3;function Hr({cfg:r,bridgeHealth:l,workers:f=()=>[],persist:p=()=>{},exec:G=(x,q,U={})=>mr(x,q,{timeout:6e4,killSignal:"SIGKILL",...U}),platform:h=process.platform,arch:z=process.arch,osRelease:Ee=ie.release(),spawn:Oe=cr,lookup:rn=null,archKnower:Be=null,fetchImpl:B=globalThis.fetch,stateDir:N=$.join(ie.homedir(),".chatpanel","runtime"),log:S=()=>{},sleep:Ne=x=>new Promise(q=>setTimeout(q,x)),totalMem:an=()=>ie.totalmem(),memoryProbe:nt=x=>h==="darwin"&&r?.runtime?.heatwatch!==!1?er(x,{fetchImpl:B}):Promise.resolve(null),now:se=()=>Date.now(),autoEnv:tt=process.env.CHATPANEL_RUNTIME_AUTO,every:on=(x,q)=>{const U=setInterval(x,q);return U.unref?.(),U}}={}){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"?ar({home:x}):[]],U=(n=process.env)=>{const e=h==="win32"?";":":",t=String(n.PATH||n.Path||""),i=q.filter(o=>!t.split(e).includes(o));return{...n,PATH:[...t.split(e).filter(Boolean),...i].join(e)}},y=async(n,e,t={})=>{try{const i=await G(n,e,{...t,env:U(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 Le=null;const sn=async()=>(Le===null&&(Le=await Ft({exec:G,platform:h,arch:z})),Le),K={},rt=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of U().PATH.split(e).filter(Boolean))for(const o of t)try{return Tn($.join(i,n+o),Cn.X_OK),!0}catch{}return!1},Te=n=>{const e=h==="win32"?";":":",t=h==="win32"?[".exe",""]:[""];for(const i of U().PATH.split(e).filter(Boolean))for(const o of t){const s=$.join(i,n+o);try{return Tn(s,Cn.X_OK),s}catch{}}return null},Q={},H=async(n,e=["--version"])=>{if(K[n])return!0;if(Q[n]!==void 0&&se()-Q[n]<kr)return!1;const t=(rn||rt)(n)||(await y(n,e,{timeout:8e3})).ok;return t?(K[n]=!0,delete Q[n]):Q[n]=se(),t},ne=n=>{const e=Te(n);let t;try{t=dr(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 Yn(o)){const a=$.join(o,s,"site-packages"),c=Yn(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":Zt,Y=n=>n?.id==="llama"&&te()==="unsloth",V=()=>Yt(N,h),le=()=>te()==="system"?"llama-server":V()?.bin||null,Ce=()=>te()==="system"?Te("llama-server"):V()?.bin||null,ln=()=>te()==="system"?ne("llama-server"):V()?.tag||null,it=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 Re(n,{tag:e=v.tag}={}){n.kind=n.kind==="update"?"update":"install",n.detail=v.label,P(n,`fetching ${v.label} (${e==="latest"?"the newest release":e}) from github.com/${v.repo}`);try{const t=await Qt({stateDir:N,platform:h,arch:z,accelerator:await sn(),tag:e,fetchImpl:B,run:y,onProgress:kn(n)});return P(n,t.already?`${v.label} ${t.tag} — already here`:`${v.label} ${t.tag} — checked against its published SHA-256`),{ok:!0,...t}}catch(t){return{ok:!1,error:n.cancelled?"cancelled":t.message}}}const un=(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 Dt({exec:G,platform:h,totalmem:an,cpus:()=>ie.cpus()})),Ge),I=async n=>({platform:h,arch:z,accelerator:await sn(),engine:n,vllmOnPath:await H("vllm"),llamaOnPath:await H("llama-server"),mlxOnPath:h==="darwin"&&z==="arm64"?await H("mlx_lm.server",["--help"]):!1,osMajor:h==="darwin"?Wn(Ee):0,appleOnPath:h==="darwin"&&z==="arm64"?await H(en):!1,appleInstall:h==="darwin"?or({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||Wn(Ee)>=n.only.minDarwin),ue=n=>$.join(N,`${n.id}.pid`),re=n=>{try{const e=Number(Kn(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 Ue(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 ut(e.port);if(M)return pe(N,{recursive:!0,mode:448}),$e(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 I(null),i=e.engineOf(t);if(Y(e)?!le():!await H(e.runner,e.runnerCheck))return Y(e)?{ok:!1,error:`${v.label} is not downloaded yet — Start fetches it`}:{ok:!1,error:un(e,i.install),install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Ye(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[o,s]=e.command(e,X(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=Lt(d,"w",384)}catch{k=null}m=Oe(u.bin,u.argv,{...u.opts,env:U(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{Tt(k)}catch{}}if(!m?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};$e(ue(e),String(m.pid),{mode:384});const g=_(e);let O=!1;for(let M=0;M<120&&!O&&re(e);M++)O=await e.answers(g,B),O||await Ne(1e3);if(!re(e)){try{Qn(ue(e))}catch{}let M="";try{M=Kn(d,"utf8").trim().split(`
3
+ `).filter(T=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(T)).slice(-3).map(T=>T.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{M=""}return{ok:!1,error:`${e.label} exited on start${M?` — ${M}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:d}}return e.configure(r,g,e),p(),S(`[runtime] ${e.label} started (pid ${m.pid}) on ${g}, sandbox ${Z[e.id].layer}${O?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:g,answering:O,provides:e.provides,model:w(e),sandbox:Z[e.id]}}const He=n=>r.runtime?.services?.[n.id]?.off===!0,cn=(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},dn=()=>r.runtime?.auto!==!1&&String(tt||"").toLowerCase()!=="off",L={};async function mn(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!dn())return{ok:!1,skipped:"automatic start is switched off"};if(!C(n))return{ok:!1,skipped:`runs on ${oe(n)} only`};if(He(n))return{ok:!1,skipped:"stopped by the person"};if(!await H(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!re(n)){const t=await y(n.runner,["check"],{timeout:8e3});if(!t.ok){let i="";try{i=JSON.parse(t.out||"{}").message||""}catch{i=""}return L[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:L[n.id]}}}const e=await Ue(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 fn=(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()},Ie=n=>{const e=r.runtime?.services?.[n.id];e?.pulling&&(delete e.pulling,p())};function pn(){let n=!1;for(const e of D.filter(t=>t.retired))for(const t of e.provides||[]){const i=r.capabilities?.[t];if(!i||!Me(i,t).providers.some(c=>c.service===e.id))continue;const o=Me(i,t).providers.find(c=>c.service===e.id),s={provider:"embedded",...ur(t,o?.model)?{model:o.model}:{}},a=Me(i,t).providers.some(c=>c.provider==="embedded"&&(c.model||null)===(s.model||null));nn(r,t,a?qn(i,t,c=>c.service===e.id):Jn(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 at(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.retired)return{ok:!1,error:`${e.label} is not retired — stop it instead`};const t=(await E()).preferred;if(!t)return{ok:!1,error:"no container engine"};const i=await y(t,["rm","-f",e.container],{timeout:6e4});if(!i.ok&&!/no such container/i.test(i.err||""))return{ok:!1,error:`${t} rm: ${i.err||i.out}`};const o=await y(t,["rmi",e.image],{timeout:6e4});return e.unconfigure(r,_(e)),p(),S(`[runtime] ${e.label} removed (container${o.ok?" and image":""})`),{ok:!0,removed:{container:!0,image:!!o.ok}}}async function ot(){const n=[];if(!dn())return n;for(const e of D.filter(t=>t.pull)){const t=r.runtime?.services?.[e.id]?.pulling;if(t){if(t.model!==w(e)||J(e,w(e))){Ie(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):Pn(e.id)).catch(i=>({ok:!1,error:i.message}))})}}return n}async function st(){try{pn()}catch(e){S(`[runtime] retiring: ${e.message}`)}try{hn()}catch(e){S(`[runtime] settings per model: ${e.message}`)}const n=[...await ot().catch(()=>[])];for(const e of D.filter(t=>t.auto))n.push({id:e.id,label:e.label,...await mn(e).catch(t=>({ok:!1,skipped:t.message}))});return n}async function lt(n){const e=A(n);return e?.auto?mn(e):{ok:!1,skipped:"not a service that starts by itself"}}async function ut(n){if(h==="win32")return 0;const e=await y("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),t=Number(String(e.out||"").split(`
4
+ `)[0]);return e.ok&&Number.isInteger(t)&&t>1?t:0}function we(n){const e=re(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{Qn(ue(n))}catch{}return n.unconfigure(r,_(n)),p(),{ok:!0}}const de=n=>n.model?{...n,model:w(n),installed:J(n,w(n)),tunings:j(n,w(n)),...n.id==="llama"?{file:mt(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}},Fe=(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 hn(){let n=!1;for(const e of D.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?Fe(e,o,{...i,...(t.byModel||{})[o]||{},...ge(t.tunings).engine}):t.tunings=ge(t.tunings).engine,n=!0}n&&p()}function ct(n,e){const t=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},o=ve(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 gn(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=ve(n).find(Qe=>Qe.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):Bn(n),d=/\.gguf$/i.test(s)||o.id==="llama"?null:tr(F(),s),m=u&&d?nr(d,u):null,k=Vn({ramMB:c,kvMB:m||0}),g=o.kind==="native"?await nt(k):null,O=((await ke()).ramGB||0)*1024,M=g?g.fits:O>0&&k<=O,T=Qe=>`${Math.round(Qe/102.4)/10} GB`,Ot=g?g.fits?`${s} fits: needs about ${T(k)}, ${T(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${T(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${s} needs about ${T(k)} and ${T(g.availableMB)} is free now — ${T(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${s} needs about ${T(k)} of the machine's ${T(O)} — ${M?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:o.id,model:s,needMB:k,weightsMB:c,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:M,live:g,advice:Ot}}const X=(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:Ze(F(),e),flags:Kt(Ce())}:{}}),F=()=>$.join(N,ae);let ye={at:0,list:[]};const dt=()=>{if(Date.now()-ye.at>3e4)try{ye={at:Date.now(),list:qt(F())}}catch{ye={at:Date.now(),list:[]}}return ye.list},J=(n,e)=>/\.gguf$/i.test(e)?Ye(e):n.id==="llama"?!!jn(F(),e):Wt(F(),e),mt=n=>/\.gguf$/i.test(n)?n:jn(F(),n),b={},wr=n=>b[n.id]||null;function kn(n){const e=sr();return t=>{if(n.cancelled)throw new Error("cancelled");t.retry&&P(n,`retrying ${String(t.file||"").split("/").pop()} in ${Math.round(t.retry.inMs/1e3)} s (try ${t.retry.attempt} of ${t.retry.of}) — ${t.retry.error}`),n.progress={bytes:t.bytes,total:t.total,file:t.file,...t.retry?{retrying:t.retry}:{},...e(t.bytes,{skipped:!!t.skipped,total:t.total})}}}function me(n,e,t={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...t},b[n.id]}function P(n,e){const t=String(e||"").trim();if(!t)return;n.lines.push(t.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(t);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const 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=Oe(e,t,{stdio:["ignore","pipe","pipe"],env:U()})}catch(d){return o({ok:!1,code:-1,error:d.message})}n.child=s;let a="";const c=d=>{a+=String(d);const m=a.split(/\r?\n|\r/);a=m.pop();for(const k of m)P(n,k)};s.stdout?.on("data",c),s.stderr?.on("data",c);const u=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}},i);u.unref?.(),s.on("error",d=>{clearTimeout(u),n.child=null,o({ok:!1,code:-1,error:d.message})}),s.on("exit",d=>{clearTimeout(u),n.child=null,a&&P(n,a),o({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),wn={install:Promise.resolve(),build:Promise.resolve()},De={install:0,build:0},yn=(n,e,t)=>{De[n]>0&&(e.waiting=!0,P(e,`waiting for the other ${n} to finish first — one at a time`)),De[n]++;const i=wn[n];let o;const s=new Promise(a=>{o=a});return wn[n]=i.then(()=>s),i.then(async()=>{e.waiting&&(P(e,"the other one finished — going"),e.waiting=!1);try{return await t()}finally{De[n]--,o()}})},bn=async(n,e)=>(await y(n,["image","exists",e],{timeout:2e4})).ok;async function ft(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,P(i,`pulling ${m}`),(await be(i,n,["pull",m])).ok)return m!==o&&await y(n,["tag",m,o],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const c=e?.recipe?Xt[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}),$e($.join(u,"Dockerfile"),c.dockerfile,{mode:384}),i.kind="build-image",i.detail=o,i.minutes=c.minutes,P(i,`no registry has ${o} for this machine — building it here (about ${c.minutes} minutes)`),S(`[runtime] building ${o} from the ${e.recipe} recipe in ${u}`),(await yn("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 $n(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=kn(e);try{if(n.id==="llama"){const o=j(n,t);await Vt(t,{root:F(),fetchImpl:B,onProgress:i,knows:(Be||Xn)(Ce()),engineVersion:ln(),vision:o.vision!=="off",draft:o.draftModel!=="off"})}else await zt(t,{root:F(),fetchImpl:B,onProgress:i});return{ok:!0}}catch(o){return{ok:!1,error:`pull ${t}: ${o.message}`}}}async function pt(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 vn(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&h!=="linux"){const t=await y("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?i:0}if(n==="docker"&&h!=="linux"){const t=await y("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(t.out,10);return t.ok&&i>0?Math.round(i/1048576):0}return Math.round(an()/1048576)}async function E(){const n={};for(const t of Ae){const i=await y(t,["--version"],{timeout:5e3});if(!i.ok){n[t]={installed:!1};continue}const o=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let s=!1,a=null;if(t==="podman")if(h==="linux")s=(await y("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await y("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(c.out||"[]")[0]||null;a=d?{name:d.Name,running:!!d.Running}:null,s=!!d?.Running}catch{a=null}}else s=(await y("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[t]={installed:!0,version:o,running:s,...t==="podman"&&h!=="linux"?{machine:a}:{}}}const e=Ae.find(t=>n[t]?.installed&&n[t].running)||Ae.find(t=>n[t]?.installed)||null;return{...n,preferred:e,...e?{}:{install:tn(h)}}}async function je(n="podman"){if(!Ae.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await E())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:tn(h)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(h!=="linux"){if(!e.machine){const i=await y("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const t=await y("podman",["machine","start"],{timeout:3e5});if(!t.ok&&!/already running/i.test(t.err))return{ok:!1,error:`podman machine start: ${t.err||t.out}`}}return{ok:!0}}async function Sn(){const n=await E(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await y("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(o=>et(o,"podman"))}catch{return[]}}const t=await y("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return t.ok?t.out.split(`
5
+ `).filter(Boolean).map(i=>{try{return et(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Mn(n,e){const t=await y(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return t.ok?/running/i.test(t.out)?"running":"stopped":"absent"}async function Xe(n,e){const t=await y(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!t.ok){for(const s of e)i[s]="absent";return i}const o=new Map(t.out.split(`
6
+ `).map(s=>s.split(" ")).filter(s=>s[0]).map(([s,a])=>[s,/running/i.test(a||"")?"running":"stopped"]));for(const s of e)i[s]=o.get(s)||"absent";return i}const _=n=>`http://127.0.0.1:${n.port}`;async function An(){const n=await E(),e=n.preferred,t=await vn(e,n),i={},o=await I(e),s=e&&n[e].running?await Xe(e,D.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of D){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:it}:a.engineOf(o):null,k=a.kind==="native"?(o.ramGB||0)*1024:t;i[a.id]={...fr(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(r),answering:u==="running"?await a.answers(c,B):!1,...a.helper?{asleep:R.has(a.id),idleMinutes:Nn()/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&&Ze(F(),d).recommended?{recommended:Ze(F(),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:!!Te("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,...He(a)?{why:"Stopped here — Start turns it back on"}:L[a.id]?{why:L[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&C(a)&&L[a.id]?{why:L[a.id]}:{},...a.kind==="native"&&Z[a.id]?{sandbox:Z[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...W(a)?{profiles:Fn(a.id,j(a,d),X(a,d,m,o)),docs:jt[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:ct(a,o)}:{},...a.model?{model:d,default:a.model,models:Rn(a.id,{active:d,engineRamMB:k,engine:a.kind==="native"?"host":e,platform:h,installed:g=>J(a,g),onDisk:dt()}),machine:{engineRamMB:k}}:{},...W(a)?{tunings:Hn(a.id,j(a,d),X(a,d,m,o))}:{}}}return i}async function ht(){const n=await E(),e=await I(n.preferred);return{platform:h,arch:z,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:It(e)}}function _n(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=Rt("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 ze={};async function gt(n){if(ze[n]==null){const e=await y(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),t=Number.parseInt(e.out,10);ze[n]=Number.isFinite(t)&&t>0?t:ie.cpus()?.length||2}return Math.max(1,Math.floor(ze[n]/2))}async function ee(n,{force:e=!1}={}){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(t.retired)return{ok:!1,error:t.retired.why,retired:!0};R.delete(t.id),Ke(t.id),t.auto&&He(t)&&cn(t,!1);const i=b[t.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let o=null;if(t.kind!=="native"){const d=await E();if(o=d.preferred,!o)return{ok:!1,error:"no container engine — install Podman first",install:tn(h)};if(!d[o].running){const m=await je(o);if(!m.ok)return m}}else if(!C(t))return{ok:!1,error:`${t.label} runs on ${oe(t)} only`};const s=await I(o),a=t.engineOf?t.engineOf(s):null;if(t.kind==="native"&&!Y(t)&&!await H(t.runner,t.runnerCheck))return{ok:!1,error:un(t,a?.install),install:a?.install};if(t.model&&/\.gguf$/i.test(w(t))&&!Ye(w(t)))return{ok:!1,error:`no such file: ${w(t)}`};if(t.kind==="native"&&t.model&&!e){const d=await gn(t.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await pt(t,o,a);if(!c.length){if(delete b[t.id],t.kind!=="native")return Ve(t,o);const d=await Ue(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")&&fn(t,w(t),!0),u.then=(async()=>{try{if(c.includes("runner")){const m=await Re(u);if(!m.ok)throw new Error(m.error)}if(c.includes("image")){const m=await ft(o,a,t,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await $n(t,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=t.label;const d=t.kind==="native"?await Ue(t):await Ve(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")&&Ie(t)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function kt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const t=b[e.id];if(!t||t.done)return{ok:!0,nothing:!0};if(t.cancelled=!0,t.child){try{t.child.kill("SIGTERM")}catch{}const i=t.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return P(t,"cancelled"),S(`[runtime] ${e.label}: job cancelled (${t.kind})`),{ok:!0,cancelled:t.kind}}async function Ve(n,e){let t=await Mn(e,n.container);const i=n.helper?await gt(e):null,o=n.engineOf?n.engineOf(await I(e)):null,s=n.id==="searxng"?$.join(N,"searxng-settings.yml"):null,a=_n(n,{settingsFile:s,secret:n.id==="searxng"?"x":null,pick:o,cpus:i});if(t!=="absent"){const d=await y(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(S(`[runtime] ${n.label}: made with older settings — re-creating it`),await y(e,["rm","-f",n.container],{timeout:6e4}),t="absent")}if(t!=="running")if(t==="stopped"){const d=await y(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{pe(N,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&($e(s,gr(String(r.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=Ct(32).toString("hex")),n.volumes&&pe($.join(N,ae),{recursive:!0,mode:448});const{args:m}=_n(n,{settingsFile:s,secret:d,pick:o,cpus:i});S(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await y(e,m,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const c=_(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,B),u||await Ne(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 wt(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(R.delete(e.id),delete qe[e.id],e.auto&&cn(e,!0),e.kind==="native")return we(e);const t=await E(),i=t.preferred;if(i&&t[i].running){const o=await y(i,["stop",e.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${i} stop: ${o.err||o.out}`}}return e.unconfigure(r,_(e)),p(),{ok:!0}}async function yt(n,e){const t=A(n);if(!t||t.id!=="llama")return{ok:!1,error:"a build is chosen for llama.cpp"};if(!zn.includes(e))return{ok:!1,error:`one of ${zn.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 We(t,null,await E());return o.ok?{ok:!0,build:e,restarted:o.restarted,...o.pending?{pending:o.pending}:{}}:o}async function bt(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(!Gn(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?Vn({ramMB:a/2**20})<=o*.75:null;try{const a=await Jt(i,{fetchImpl:B,knows:(Be||Xn)(Ce()),engineVersion:ln()}),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 $t(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(!Gn(n,o))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await E(),a=s.preferred,c=i.kind==="native"?((await ke()).ramGB||0)*1024:await vn(a,s),u=Rn(n,{active:o,engineRamMB:c,engine:i.kind==="native"?"host":a,platform:h,installed:g=>J(i,g)}).find(g=>g.id===o);if(u?.unavailable)return{ok:!1,error:`${o} ${u.unavailable}`};let d=null;if(t&&W(i)){const g=await I(a);if(d=In(i.id,j(i,o),t,X(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&&Fe(i,o,d);const m=_(i);i.configured(r)===m&&i.configure(r,m,de(i)),p();const k=await We(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 We(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 Mn(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const o=await y(e,["rm","-f",n.container],{timeout:6e4});if(!o.ok&&!/no such container/i.test(o.err))return{ok:!1,error:`${e} rm: ${o.err||o.out}`};if(i==="running"){const s=await ee(n.id);return s.ok?{ok:!0,restarted:!0}:s}return{ok:!0,restarted:!1}}async function vt(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no profile`};const i=await E(),o=await I(i.preferred),s=t.engineOf?t.engineOf(o):null,a=Fn(t.id,j(t,w(t)),X(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 En(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function Je(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(le())return{ok:!0,installed:!0};const s=me(e,"install",{detail:v.label});return s.then=(async()=>{const a=await Re(s);s.done=!0,a.ok||(s.error=a.error),S(`[runtime] install ${v.label}: ${s.error||"ok"}`)})(),{ok:!0,pending:{kind:s.kind,since:s.since,detail:s.detail}}}if(delete K[e.runner],delete Q[e.runner],await H(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const o=e.engineOf(await I(null))?.install;return o?.steps?.length?xn(e,o,"install"):{ok:!1,error:`no installer for ${e.label} on this platform${o?.url?` — see ${o.url}`:""}`,install:o||null}}function xn(n,e,t){const i=me(n,t,{detail:n.runner}),o=t==="update"&&ce(n)==="running",s=ne(n.runner);return i.then=yn("install",i,async()=>{const a=async d=>{for(const[m,...k]of d){P(i,`$ ${m} ${k.join(" ")}`);let g=await be(i,m,k,{timeout:36e5});for(let O=0;!g.ok&&!i.cancelled&&O<6&&i.lines.some(M=>/already locked|Please wait for it to finish/i.test(M));O++)P(i,`another ${m} holds the lock — waiting 20 s (${O+1}/6)`),await Ne(2e4),g=await be(i,m,k,{timeout:36e5});if(!g.ok&&e.upToDate&&i.lines.some(O=>new RegExp(e.upToDate,"i").test(O))&&(g={ok:!0}),!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(e.steps);!c.ok&&!i.cancelled&&e.fallback?.length&&(P(i,`${c.error} — trying the other way`),c=await a(e.fallback)),delete K[n.runner],delete Q[n.runner];const u=c.ok&&await H(n.runner,n.runnerCheck);if(u&&t==="update"){const d=ne(n.runner);if(P(i,d&&s&&d!==s?`${n.label} ${s} → ${d}`:`${n.label}${d?` ${d}`:""} — up to date`),o&&!i.cancelled){we(n),i.done=!0;const m=await ee(n.id,{force:!0});if(m.ok||(L[n.id]=m.error,S(`[runtime] ${n.label} after the update: ${m.error}`)),m.pending)return;b[n.id]||(b[n.id]=i)}}i.done=!0,i.cancelled?i.error="cancelled":c.ok?u||(i.error=`${n.runner} still not found after the ${t} — open a new terminal and run \`${e.command}\` by hand`):i.error=`${t} failed: ${c.error}${i.lines.length?` (${i.lines.slice(-2).join(" | ")})`:""}`,S(`[runtime] ${t} ${n.runner}: ${i.error||"ok"}`)}),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function St(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!C(e))return{ok:!1,error:`${e.label} runs on ${oe(e)} only`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(Y(e)){if(!le())return Je(n);const o=V()?.tag,s=ce(e)==="running",a=me(e,"update",{detail:v.label});return a.then=(async()=>{const c=await Re(a,{tag:"latest"});if(!c.ok){a.done=!0,a.error=`update failed: ${c.error}`;return}if(P(a,c.tag!==o?`${v.label} ${o} → ${c.tag}`:`${v.label} ${c.tag} — up to date`),a.done=!0,s&&c.tag!==o&&!a.cancelled){we(e);const u=await ee(e.id,{force:!0});u.ok||(L[e.id]=u.error),b[e.id]||(b[e.id]=a)}})(),{ok:!0,pending:{kind:a.kind,since:a.since,detail:a.detail}}}if(delete K[e.runner],delete Q[e.runner],!await H(e.runner,e.runnerCheck))return Je(n);const i=e.engineOf(await I(null))?.install;return i?.update?.steps?.length?xn(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 Pn(n){const e=A(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const t=b[e.id];if(t&&!t.done)return{ok:!0,pending:{kind:t.kind,since:t.since,detail:t.detail||null}};if(J(e,w(e)))return{ok:!0,installed:!0,model:w(e)};const i=me(e,"pull-model",{detail:w(e)});return fn(e,w(e),!1),i.then=(async()=>{const o=await $n(e,i);i.done=!0,o.ok||(i.error=o.error),Ie(e)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function En(n,e){const t=A(n);if(!t)return{ok:!1,error:`unknown service ${n}`};if(!W(t))return{ok:!1,error:`${t.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await E(),o=i.preferred,s=w(t),a=await I(o),c=t.engineOf?t.engineOf(a):null,u=In(t.id,j(t,s),e,X(t,s,c,a));if(u.error)return{ok:!1,error:u.error};Fe(t,s,u),p();const d=await We(t,o,i);return d.ok?{ok:!0,tunings:Hn(t.id,u,X(t,s,c,a)),restarted:d.restarted}:d}async function Mt(){const n=await E(),e=n.preferred,t=e&&n[e].running?await Xe(e,D.filter(s=>s.kind!=="native").map(s=>s.container)):{},i={};let o=!1;return await Promise.all(D.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",On[s.id]=i[s.id]==="up"?"":a==="running"?"starting":R.has(s.id)?"asleep":"stopped";const c=(s.provides||[]).some(u=>["embedded","none"].includes(lr(r.capabilities?.[u],u)?.provider));i[s.id]==="up"&&s.configure&&!s.retired&&!c&&s.configured(r)!==_(s)&&(s.configure(r,_(s),de(s)),o=!0)})),o&&p(),i}const On={};function At(n){return On[n]||""}function Bn(n){const e=A(n);if(e?.window)return e.window;if(!e||!W(e))return null;const t=Number(Dn(e.id,j(e,w(e)),X(e,w(e),null,{})).maxModelLen);return Number.isFinite(t)&&t>0?t:null}function _t(n){const e=A(n);if(e?.card)return e.card;if(!e||!W(e))return null;const t=w(e),i=Dn(e.id,j(e,t),X(e,t,null,{})),o=ve(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 xt=10,Nn=()=>{const n=Number(r.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:xt)*6e4},Pt=se(),qe={},R=new Set,fe={};function Ke(n){qe[n]=se()}async function Et(n,{force:e=!1}={}){const t=A(n);if(!t||!t.helper)return{ok:!0};if(Ke(t.id),!R.has(t.id)&&!e){const i=t.container&&t.configured?.(r)?(await Sn()).find(o=>o.name===t.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};R.add(t.id)}return fe[t.id]||(fe[t.id]=(async()=>{const i=await E(),o=i.preferred;if(!o)return{ok:!1,error:"no container engine"};if(!i[o].running){const a=await je(o);if(!a.ok)return a}const s=await Ve(t,o);return s.ok&&(R.delete(t.id),S(`[runtime] ${t.label}: woken for a request`)),s})().finally(()=>{delete fe[t.id]})),fe[t.id]}async function Ln(){const n=Nn();if(!n)return[];const e=D.filter(a=>a.helper&&a.configured(r)&&!R.has(a.id)&&!fe[a.id]&&!(b[a.id]&&!b[a.id].done)&&se()-(qe[a.id]??Pt)>=n);if(!e.length)return[];const t=await E(),i=t.preferred;if(!i||!t[i].running){for(const a of e)R.add(a.id);return e.map(a=>a.id)}const o=await Xe(i,e.map(a=>a.container)),s=[];for(const a of e){if(o[a.container]==="running"){if(!(await y(i,["stop",a.container],{timeout:6e4})).ok)continue;S(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}R.add(a.id),s.push(a.id)}return s}return on&&on(()=>{Ln().catch(n=>S(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:Ke,wake:Et,sweepIdle:Ln,health:Mt,contextWindow:Bn,whyDown:At,modelCard:_t,async status(){const[n,e,t,i,o]=await Promise.all([l().catch(()=>null),E(),An(),Sn(),ht()]);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:wt,ensureDefaults:st,retireServices:pn,removeService:at,upcastTunings:hn,revive:lt,plan:gn,recipe:bt,setBuild:yt,isAsleep:n=>R.has(n),setModel:$t,setTunings:En,setProfile:vt,pullModel:Pn,installRunner:Je,updateRunner:St,cancelJob:kt,services:An,catalogFor:ve}}export{pr as SEARXNG_DEFAULT_ENGINES,D as SERVICES,et as containerRow,Hr as createRuntime,tn as installDoor,gr as searxngSettings};
package/src/server.js CHANGED
@@ -15,9 +15,9 @@ data: ${u}
15
15
 
16
16
  `),t.end(),N?.end("error",{code:"bridge_error"}),at(c.id),h?.commit(),Wt(c)},onUsage:H=>{k.add(H),N?.add(H)}};for(;;){if(F=null,await sn(c,D)!=="parked"||!F)return;const G=c.ownerApprovals,oe=new AbortController,ee=()=>oe.abort();t.once("close",ee);const X=setInterval(()=>{ft(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);X.unref?.();let V;try{V=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:oe.signal})}finally{clearInterval(X),t.off("close",ee)}if(oe.signal.aborted||t.writableEnded){Wt(c);return}try{await ko(c,JSON.stringify(V))}catch(Z){D.onError(Z);return}}}function Wt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function di(t,c,{kind:u,adapter:h,agent:w,run:k=null,owner:N=null,linkTurn:M=null},$,b,x,O,z,F=null,D=null){const{messages:H,system:G}=h.toTurn($),{agentModel:oe}=Vt($?.model,x),ee=qo(x,{...oe?{model:oe}:{},...k||{}}),X=nt(x.bridge.token),V=At(u,$?.model||w),Z={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Ar(x.redaction,O),entities:[]},he=await rt(x),C=an({vault:b,redactOpts:Z,bridgeUrl:he,token:X,harness:F});N&&(C.ownerApprovals={...N,conversation:N.conversation||`partner.${N.device}.turn-${C.id}`,turnScoped:!N.conversation}),M&&(C.linkTurn=M,C.onEnd=()=>M.end("aborted")),b&&(C.redaction=x.redaction);let Y;try{Y=await nn({bridgeUrl:he,agent:w,token:X,messages:H,system:G,specs:ln(z),options:ee,signal:void 0,approvals:!!N||dn(z)})}catch(xe){return M?.end("error",{code:"bridge_error"}),at(C.id),D?.commit(),a(c,502,{error:{message:`bridge: ${xe.message}`,type:"bridge_error"}})}return C.reader=Y.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(V.sseHead()),mr(c,C,V,D)}async function ci(t,c,u,h,w=null){ft(c.id),c.rounds=(c.rounds||0)+1;try{const N=w?w.clock():0;await ko(c,u),w&&w.lap("redact",N)}catch(N){return c.linkTurn?.end("error",{code:"tool_result"}),at(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${N.message}`,type:"bridge_error"}})}const k=At("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(k.sseHead()),mr(t,c,k,w)}function Kt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function ui(t,c,{kind:u,adapter:h,redactable:w,pathname:k,agentOverride:N,harness:M,trace:$,run:b=null,owner:x=null,link:O=null},z,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${k} not supported by the bridge backend`});if(u==="openai"){const de=h.extractLatestToolResult(z);if(de){const ne=So(de.tool_call_id),fe=ne&&vo(ne.gwId);if(fe)return ci(c,fe,de.content,z?.model,$)}const ye=h.extractTools(z);if((ye.length||x)&&z?.stream===!0){const ne=N||dr(z?.model,D),fe=O?zt.begin({...O,agentId:ne}):null;return di(t,c,{kind:u,adapter:h,agent:ne,run:b,owner:x,linkTurn:fe},z,F,D,H,ye,M,$)}}const{messages:G,system:oe}=h.toTurn(z),ee=N||dr(z?.model,D),X=O?zt.begin({...O,agentId:ee}):null,V=z?.stream===!0,Z=At(u,z?.model||ee),he=nt(D.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Y}=Vt(z?.model,D),xe={bridgeUrl:await rt(D),agent:ee,token:he,messages:G,system:oe,signal:C.signal,options:qo(D,{...Y?{model:Y}:{},...b||{}})};if(!V)try{let de="";const ye=Kt(),ne=$?$.clock():0;await wo(xe,Ze=>{de+=Ze},null,Ze=>ye.add(Ze)),$&&$.lap("upstream",ne);const fe=$?$.clock():0,Ge=Z.full($r(de,F),ye.value);return $&&$.lap("restore",fe),c.writeHead(200,{"content-type":Z.contentType}),c.end(Ge),X?.add(ye.value),X?.end("ok"),$?.commit()}catch(de){return X?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.commit(),a(c,502,{error:{message:`bridge backend failed: ${de.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Z.sseHead());const _e=mo(F),Le=$?$.clock():0;let Xe=Le;const De=Kt();let Ae="",je=!1;try{let de=!0;await wo(xe,ne=>{$&&de&&($.lap("upstream",Le),Xe=$.clock(),de=!1);const fe=_e.push(ne);fe&&(Ae+=fe,c.write(Z.sseDelta(fe)))},Z.sseActivity?ne=>{try{c.write(Z.sseActivity(Pr(ne,F)))}catch{}}:null,ne=>De.add(ne));const ye=_e.flush();ye&&(Ae+=ye,c.write(Z.sseDelta(ye))),c.write(Z.sseTail(De.value))}catch(de){je=!0,c.write(`data: ${JSON.stringify({error:{message:de.message,type:"bridge_error"}})}
18
+ `)},15e3);X.unref?.();let U;try{U=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:oe.signal})}finally{clearInterval(X),t.off("close",ee)}if(oe.signal.aborted||t.writableEnded){Wt(c);return}try{await ko(c,JSON.stringify(U))}catch(Z){D.onError(Z);return}}}function Wt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function di(t,c,{kind:u,adapter:h,agent:w,run:k=null,owner:N=null,linkTurn:M=null},$,b,x,O,z,F=null,D=null){const{messages:H,system:G}=h.toTurn($),{agentModel:oe}=Vt($?.model,x),ee=qo(x,{...oe?{model:oe}:{},...k||{}}),X=nt(x.bridge.token),U=At(u,$?.model||w),Z={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Ar(x.redaction,O),entities:[]},he=await rt(x),C=an({vault:b,redactOpts:Z,bridgeUrl:he,token:X,harness:F});N&&(C.ownerApprovals={...N,conversation:N.conversation||`partner.${N.device}.turn-${C.id}`,turnScoped:!N.conversation}),M&&(C.linkTurn=M,C.onEnd=()=>M.end("aborted")),b&&(C.redaction=x.redaction);let Y;try{Y=await nn({bridgeUrl:he,agent:w,token:X,messages:H,system:G,specs:ln(z),options:ee,signal:void 0,approvals:!!N||dn(z)})}catch(xe){return M?.end("error",{code:"bridge_error"}),at(C.id),D?.commit(),a(c,502,{error:{message:`bridge: ${xe.message}`,type:"bridge_error"}})}return C.reader=Y.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(U.sseHead()),mr(c,C,U,D)}async function ci(t,c,u,h,w=null){ft(c.id),c.rounds=(c.rounds||0)+1;try{const N=w?w.clock():0;await ko(c,u),w&&w.lap("redact",N)}catch(N){return c.linkTurn?.end("error",{code:"tool_result"}),at(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${N.message}`,type:"bridge_error"}})}const k=At("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(k.sseHead()),mr(t,c,k,w)}function Kt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function ui(t,c,{kind:u,adapter:h,redactable:w,pathname:k,agentOverride:N,harness:M,trace:$,run:b=null,owner:x=null,link:O=null},z,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${k} not supported by the bridge backend`});if(u==="openai"){const de=h.extractLatestToolResult(z);if(de){const ne=So(de.tool_call_id),fe=ne&&vo(ne.gwId);if(fe)return ci(c,fe,de.content,z?.model,$)}const ye=h.extractTools(z);if((ye.length||x)&&z?.stream===!0){const ne=N||dr(z?.model,D),fe=O?zt.begin({...O,agentId:ne}):null;return di(t,c,{kind:u,adapter:h,agent:ne,run:b,owner:x,linkTurn:fe},z,F,D,H,ye,M,$)}}const{messages:G,system:oe}=h.toTurn(z),ee=N||dr(z?.model,D),X=O?zt.begin({...O,agentId:ee}):null,U=z?.stream===!0,Z=At(u,z?.model||ee),he=nt(D.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Y}=Vt(z?.model,D),xe={bridgeUrl:await rt(D),agent:ee,token:he,messages:G,system:oe,signal:C.signal,options:qo(D,{...Y?{model:Y}:{},...b||{}})};if(!U)try{let de="";const ye=Kt(),ne=$?$.clock():0;await wo(xe,Ze=>{de+=Ze},null,Ze=>ye.add(Ze)),$&&$.lap("upstream",ne);const fe=$?$.clock():0,Ge=Z.full($r(de,F),ye.value);return $&&$.lap("restore",fe),c.writeHead(200,{"content-type":Z.contentType}),c.end(Ge),X?.add(ye.value),X?.end("ok"),$?.commit()}catch(de){return X?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.commit(),a(c,502,{error:{message:`bridge backend failed: ${de.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Z.sseHead());const _e=mo(F),Le=$?$.clock():0;let Xe=Le;const De=Kt();let Ae="",je=!1;try{let de=!0;await wo(xe,ne=>{$&&de&&($.lap("upstream",Le),Xe=$.clock(),de=!1);const fe=_e.push(ne);fe&&(Ae+=fe,c.write(Z.sseDelta(fe)))},Z.sseActivity?ne=>{try{c.write(Z.sseActivity(Pr(ne,F)))}catch{}}:null,ne=>De.add(ne));const ye=_e.flush();ye&&(Ae+=ye,c.write(Z.sseDelta(ye))),c.write(Z.sseTail(De.value))}catch(de){je=!0,c.write(`data: ${JSON.stringify({error:{message:de.message,type:"bridge_error"}})}
19
19
 
20
- `)}$&&$.lap("stream",Xe),c.end(),X&&(X.add(De.value),X.end(C.signal.aborted?"aborted":je?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&Ae&&uo(Ae,D.redaction)}function mi(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const pr=9e4,Qt=60,hr=Qt*16e3*4,pi=4e3;function hi(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let k=0;k<w.length;k++){const N=k*h,M=Math.floor(N),$=Math.min(t.length-1,M+1),b=N-M;w[k]=t[M]*(1-b)+t[$]*b}return w}const yr=new WeakMap,yi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function fr(t,c){const u=vt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Uo(u):null}function Yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ke(t,c,u,h,{method:w="GET",timeoutMs:k=8e3,pick:N=M=>M}={}){const M=await rt(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=nt(u.bridge?.token),b=w!=="GET"&&w!=="DELETE";try{const x=b?(await v(t,u.maxBodyBytes)).toString("utf8"):"",O=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...b?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...b?{body:x||"{}"}:{},signal:AbortSignal.timeout(k)}),z=await O.json().catch(()=>({}));return O.ok?a(c,200,N(z)):a(c,O.status,{error:{message:z?.error||`bridge ${O.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Xt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ye(t,c){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function fi(t,c,{adapter:u,kind:h,pathname:w,search:k,base:N,destKey:M,destProtocol:$,harness:b,trace:x,link:O=null},z,F){let D;const H=x?x.clock():0,G=O?zt.begin(O):null;let oe=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(oe=!0,ee.abort())});const X=(C,Y)=>{G&&(G.add(Y),G.end(oe?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=li(t.headers,N);M&&($==="anthropic"?(C["x-api-key"]=M,delete C.authorization):C.authorization=`Bearer ${M}`);const Y=Cr(mi(N,w,k)).toString();D=await fetch(Y,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:ee.signal})}catch(C){return oe?(X(499),x?.commit()):(G?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const V=D.headers.get("content-type")||"",Z={};if(D.headers.forEach((C,Y)=>{sr.has(Y.toLowerCase())||(Z[Y]=C)}),V.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(D.status,Z);const Y=G?qn():null,xe=Y?D.body.pipeThrough(Y.stream):D.body,_e=h==="openai"?Er(xe,c,F,b):Or(xe,c,F);return Promise.resolve(_e).catch(Le=>{if(!oe)throw Le}).finally(()=>{x&&x.lap("stream",C),X(D.status,Y?.usage()),x?.commit()})}let he;try{he=Buffer.from(await D.arrayBuffer())}catch(C){if(oe)return X(499),x?.commit();throw C}if(x&&x.lap("upstream",H),G&&X(D.status,V.includes("json")?ea(he.toString("utf8")):null),F&&V.includes("application/json"))try{const C=x?x.clock():0,Y=u.restoreResponse(JSON.parse(he.toString("utf8")),F,b);return x&&x.lap("restore",C),c.writeHead(D.status,{...Z,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Y),"utf8")),x?.commit()}catch{}c.writeHead(D.status,Z),c.end(he),x?.commit()}function gi(t=co()){const c=Kn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Qn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Ao(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===No,name:String(o.id===No?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",k=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),N=r=>(/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)||r==="/v1/research")&&r!=="/v1/history/stream",M=zr({first:async r=>{const o=Number(new URL(r).port),y=wa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await ee())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=jr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Gr(r),newId:()=>Hr()}),b=$a({version:le}),x=qa({log:r=>console.log(` ${r}`)}),O=t.link?.enabled===!1?null:Aa({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:q,signal:W})=>fetch(`http://127.0.0.1:${Ne.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Re()||Pe(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Jo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${cs}`));let z=null;const F=()=>{if(!z){const r=t.read||{};z=Pa({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return z};let D=null;const H=()=>(D||(D=ha({wrap:(r,o,y,i)=>ya().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),D);let G={at:0,fn:()=>"unknown"},oe=null;async function ee(){if(Date.now()-G.at<1e4)return G.fn;let r=new Map;try{const i=await V().health();for(const[q,W]of Object.entries(i)){const Se=(t.destinations||[]).filter(ge=>ge?.service===q).flatMap(ge=>[ge.id,...ge.models||[]]);for(const ge of[q,...Se])r.set(ge,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return V().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return V().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),G={at:Date.now(),fn:o},G.fn}let X=null;const V=()=>(X||(X=ga({cfg:t,bridgeHealth:async()=>{const r=await rt(t);if(!r)return null;const o=nt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Fe.join(Fe.dirname(te()),"runtime"),workers:()=>{const r=D?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),X),Z=Number(t.runtime?.idleMinutes),he=va({warmMs:(Number.isFinite(Z)&&Z>=0?Z:10)*6e4,log:r=>console.log(r)}),C=ba({cfg:t,wake:(r,o)=>V().wake(r,o),embedded:he,asleep:r=>V().isAsleep(r)});let Y=null;const xe=Ea(()=>Re()||Pe()),_e=()=>(Y||(Y=Oa({viewKey:xe,store:_a({log:r=>console.warn(`[kb] ${r}`)}),extract:H,embedded:he,cfg:t,rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>F(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const W=Re()||Pe(),Se=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ge=await Se.json().catch(()=>({}));return Se.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:r=>console.warn(r),team:r=>Ae().teamOf(r),remoteCards:()=>de().remoteCards(),reveal:(r,o)=>Qa(r,o),confined:()=>!!wt({stateDir:Fe.dirname(te())}).on})),Y);let Le=null;const Xe=()=>Le||=Ka();let De=null;const Ae=()=>(De||(De=Wa({store:_e().store,kb:()=>_e(),profiles:Xe(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Ue(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),De);let je=null;const de=()=>(je||(je=Fa({cfg:t,kb:()=>_e(),buckets:Ae(),profiles:Xe(),search:async(r,{limit:o=8}={})=>{ye();const y=await fe().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ya(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await et([pt(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},fetchFn:(r,o)=>Ue(r,o),persist:()=>we(t,te()),log:r=>console.log(r)})),je),ye=()=>{t.search?.searxng?.url&&V().wake("searxng").catch(()=>{})};let ne=null;const fe=()=>{if(!ne){const r=t.search||{},o=r.searxng?.url?rs({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;ne=es({reader:F(),searxng:o,engines:()=>ns(t),wakeSearxng:()=>V().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await et([pt(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return ne};Ir(t.allowedExtensionIds||[]);const Ge=[],Ze=r=>{Ge.push(r),Ge.length>50&&Ge.shift()},Ne=Tr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!Ot(r.headers.host))return a(o,403,{error:"loopback only"});if(!qs(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ot(t.host)&&Ba(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&ei(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Ao(r.headers);Yn(e)&&(r.chatpanelOidc=await u.verify(e))}if(r.chatpanelViewOnly=!1,w()==="credential"&&N(i)&&!k(h(r),i)&&r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)&&y.searchParams.get("k"))r.chatpanelViewOnly=!0;else if(w()==="credential"&&N(i)&&!k(h(r),i))return r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)?a(o,403,{error:{message:"this citation link has no viewer key (links made before gateway 0.163.0 have none) — ask Chap again, or open the passage from the chat, and the new link opens here",type:"forbidden"}}):a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await v(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return st("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(st("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{xt(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{we(t,te())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return st("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Jr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Lr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${tt(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${tt(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await bo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=tt(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(po(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await bo(t);return a(o,200,{ok:!0,status:n,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=tt(r);return a(o,200,{ok:!0,trust:e,paired:po(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Vr(t,{version:le,startedAt:ir,managed:ot(),certificates:{...Wr(),wanted:ho(t)},linkPartners:O?O.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Fe.dirname(te())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Jn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Gn()})}if(i==="/update"&&r.method==="POST"){const e=jn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
20
+ `)}$&&$.lap("stream",Xe),c.end(),X&&(X.add(De.value),X.end(C.signal.aborted?"aborted":je?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&Ae&&uo(Ae,D.redaction)}function mi(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const pr=9e4,Qt=60,hr=Qt*16e3*4,pi=4e3;function hi(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let k=0;k<w.length;k++){const N=k*h,M=Math.floor(N),$=Math.min(t.length-1,M+1),b=N-M;w[k]=t[M]*(1-b)+t[$]*b}return w}const yr=new WeakMap,yi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function fr(t,c){const u=vt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Uo(u):null}function Yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ke(t,c,u,h,{method:w="GET",timeoutMs:k=8e3,pick:N=M=>M}={}){const M=await rt(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=nt(u.bridge?.token),b=w!=="GET"&&w!=="DELETE";try{const x=b?(await v(t,u.maxBodyBytes)).toString("utf8"):"",O=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...b?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...b?{body:x||"{}"}:{},signal:AbortSignal.timeout(k)}),z=await O.json().catch(()=>({}));return O.ok?a(c,200,N(z)):a(c,O.status,{error:{message:z?.error||`bridge ${O.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Xt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ye(t,c){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function fi(t,c,{adapter:u,kind:h,pathname:w,search:k,base:N,destKey:M,destProtocol:$,harness:b,trace:x,link:O=null},z,F){let D;const H=x?x.clock():0,G=O?zt.begin(O):null;let oe=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(oe=!0,ee.abort())});const X=(C,Y)=>{G&&(G.add(Y),G.end(oe?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=li(t.headers,N);M&&($==="anthropic"?(C["x-api-key"]=M,delete C.authorization):C.authorization=`Bearer ${M}`);const Y=Cr(mi(N,w,k)).toString();D=await fetch(Y,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:ee.signal})}catch(C){return oe?(X(499),x?.commit()):(G?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const U=D.headers.get("content-type")||"",Z={};if(D.headers.forEach((C,Y)=>{sr.has(Y.toLowerCase())||(Z[Y]=C)}),U.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(D.status,Z);const Y=G?qn():null,xe=Y?D.body.pipeThrough(Y.stream):D.body,_e=h==="openai"?Er(xe,c,F,b):Or(xe,c,F);return Promise.resolve(_e).catch(Le=>{if(!oe)throw Le}).finally(()=>{x&&x.lap("stream",C),X(D.status,Y?.usage()),x?.commit()})}let he;try{he=Buffer.from(await D.arrayBuffer())}catch(C){if(oe)return X(499),x?.commit();throw C}if(x&&x.lap("upstream",H),G&&X(D.status,U.includes("json")?ea(he.toString("utf8")):null),F&&U.includes("application/json"))try{const C=x?x.clock():0,Y=u.restoreResponse(JSON.parse(he.toString("utf8")),F,b);return x&&x.lap("restore",C),c.writeHead(D.status,{...Z,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Y),"utf8")),x?.commit()}catch{}c.writeHead(D.status,Z),c.end(he),x?.commit()}function gi(t=co()){const c=Kn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Qn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Ao(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===No,name:String(o.id===No?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",k=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),N=r=>(/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)||r==="/v1/research")&&r!=="/v1/history/stream",M=zr({first:async r=>{const o=Number(new URL(r).port),y=wa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await ee())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=jr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Gr(r),newId:()=>Hr()}),b=$a({version:le}),x=qa({log:r=>console.log(` ${r}`)}),O=t.link?.enabled===!1?null:Aa({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:q,signal:W})=>fetch(`http://127.0.0.1:${Ne.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Re()||Pe(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Jo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${cs}`));let z=null;const F=()=>{if(!z){const r=t.read||{};z=Pa({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return z};let D=null;const H=()=>(D||(D=ha({wrap:(r,o,y,i)=>ya().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),D);let G={at:0,fn:()=>"unknown"},oe=null;async function ee(){if(Date.now()-G.at<1e4)return G.fn;let r=new Map;try{const i=await U().health();for(const[q,W]of Object.entries(i)){const Se=(t.destinations||[]).filter(ge=>ge?.service===q).flatMap(ge=>[ge.id,...ge.models||[]]);for(const ge of[q,...Se])r.set(ge,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return U().contextWindow(y.get(i)||i)}catch{return null}},o.why=i=>{try{return U().whyDown(y.get(i)||i)}catch{return""}},o.card=i=>{try{return U().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),G={at:Date.now(),fn:o},G.fn}let X=null;const U=()=>(X||(X=ga({cfg:t,bridgeHealth:async()=>{const r=await rt(t);if(!r)return null;const o=nt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Fe.join(Fe.dirname(te()),"runtime"),workers:()=>{const r=D?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),X),Z=Number(t.runtime?.idleMinutes),he=va({warmMs:(Number.isFinite(Z)&&Z>=0?Z:10)*6e4,log:r=>console.log(r)}),C=ba({cfg:t,wake:(r,o)=>U().wake(r,o),embedded:he,asleep:r=>U().isAsleep(r)});let Y=null;const xe=Ea(()=>Re()||Pe()),_e=()=>(Y||(Y=Oa({viewKey:xe,store:_a({log:r=>console.warn(`[kb] ${r}`)}),extract:H,embedded:he,cfg:t,rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>F(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const W=Re()||Pe(),Se=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ge=await Se.json().catch(()=>({}));return Se.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:r=>console.warn(r),team:r=>Ae().teamOf(r),remoteCards:()=>de().remoteCards(),reveal:(r,o)=>Qa(r,o),confined:()=>!!wt({stateDir:Fe.dirname(te())}).on})),Y);let Le=null;const Xe=()=>Le||=Ka();let De=null;const Ae=()=>(De||(De=Wa({store:_e().store,kb:()=>_e(),profiles:Xe(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Ue(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),De);let je=null;const de=()=>(je||(je=Fa({cfg:t,kb:()=>_e(),buckets:Ae(),profiles:Xe(),search:async(r,{limit:o=8}={})=>{ye();const y=await fe().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ya(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await et([pt(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},fetchFn:(r,o)=>Ue(r,o),persist:()=>we(t,te()),log:r=>console.log(r)})),je),ye=()=>{t.search?.searxng?.url&&U().wake("searxng").catch(()=>{})};let ne=null;const fe=()=>{if(!ne){const r=t.search||{},o=r.searxng?.url?rs({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;ne=es({reader:F(),searxng:o,engines:()=>ns(t),wakeSearxng:()=>U().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await et([pt(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return ne};Ir(t.allowedExtensionIds||[]);const Ge=[],Ze=r=>{Ge.push(r),Ge.length>50&&Ge.shift()},Ne=Tr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!Ot(r.headers.host))return a(o,403,{error:"loopback only"});if(!qs(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ot(t.host)&&Ba(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&ei(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Ao(r.headers);Yn(e)&&(r.chatpanelOidc=await u.verify(e))}if(r.chatpanelViewOnly=!1,w()==="credential"&&N(i)&&!k(h(r),i)&&r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)&&y.searchParams.get("k"))r.chatpanelViewOnly=!0;else if(w()==="credential"&&N(i)&&!k(h(r),i))return r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)?a(o,403,{error:{message:"this citation link has no viewer key (links made before gateway 0.163.0 have none) — ask Chap again, or open the passage from the chat, and the new link opens here",type:"forbidden"}}):a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await v(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return st("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(st("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{xt(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{we(t,te())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return st("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Jr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Lr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${tt(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${tt(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await bo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=tt(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(po(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await bo(t);return a(o,200,{ok:!0,status:n,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=tt(r);return a(o,200,{ok:!0,trust:e,paired:po(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Vr(t,{version:le,startedAt:ir,managed:ot(),certificates:{...Wr(),wanted:ho(t)},linkPartners:O?O.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Fe.dirname(te())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Jn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Gn()})}if(i==="/update"&&r.method==="POST"){const e=jn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
@@ -30,7 +30,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
30
30
 
31
31
  `);let f=y.searchParams.has("after")?Number(y.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:pe.get(n),after:f}});const g=pe.watch(n,_=>{_.seq>f&&(f=_.seq,p(_))});for(const _ of pe.eventsSince(n,f))f=_.seq,p(_);const S=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(S),g()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:Ke.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await Ke.get(n)});if(r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await Ke.append({agentId:n,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Qe.fromRating(Ke.chains.get(n)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&r.method==="GET")return a(o,200,ma(t,{version:le,reader:z,searcher:ne,extract:H(),proxy:C}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:j.health().model||t.ner?.model||null,companions:j.companions()};let n=null;try{n=await V().status()}catch{n=null}return a(o,200,aa({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(Sa.map(n=>{const s=Jt(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ka[n],threads:he.threads,...s.kind==="embedded"?he.health(n,s.model):{}}]}));return a(o,200,{...await V().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await V().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await V().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=V(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await C.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await C.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await pa(e,{ensure:()=>gt(t),model:j.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await xa(e,{service:H()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Za*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await za(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ha(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Va(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await Ua(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await Ta(e,{service:H()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await F().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ye();const n=await fe().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):os.aliasRead;ye();const s=await fe().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?ts(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await F().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(as(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Qe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Qe.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||oi(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Qe.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
33
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(S),g()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:Ke.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await Ke.get(n)});if(r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await Ke.append({agentId:n,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Qe.fromRating(Ke.chains.get(n)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&r.method==="GET")return a(o,200,ma(t,{version:le,reader:z,searcher:ne,extract:H(),proxy:C}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:j.health().model||t.ner?.model||null,companions:j.companions()};let n=null;try{n=await U().status()}catch{n=null}return a(o,200,aa({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(Sa.map(n=>{const s=Jt(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ka[n],threads:he.threads,...s.kind==="embedded"?he.health(n,s.model):{}}]}));return a(o,200,{...await U().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await U().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await U().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=U(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await C.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await C.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await pa(e,{ensure:()=>gt(t),model:j.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await xa(e,{service:H()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Za*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await za(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ha(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Va(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!J(r)||Ie(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await Ua(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await Ta(e,{service:H()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await F().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ye();const n=await fe().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):os.aliasRead;ye();const s=await fe().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?ts(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await F().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(as(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Qe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Qe.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||oi(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Qe.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
34
34
 
35
35
  `)}catch{}};e({type:"hello",at:Date.now()});const n=re.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
38
38
 
39
39
  `),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(n),after:m}});const p=re.watch(n,g=>{g.seq==null?l(g):g.seq>m&&(m=g.seq,l(g))});for(const g of re.eventsSince(n,m))m=g.seq,l(g);const f=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});_o||=fn({store:e,notify:We,audit:st});const n=async l=>{const d=(await v(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await gn(r,o,{pathname:i,api:_o,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Fs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Ws(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(g,{maxTokens:S=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Re()||Pe(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:S,temperature:.2})}),ve=await Q.json().catch(()=>({}));return Q.ok?String(ve?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await Pn(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,ids:Array.isArray(e.ids)?e.ids.filter(g=>typeof g=="string"&&/^(chat|note|meeting|brief):[^\s]{1,200}$/.test(g)).slice(0,2e3):null,parallel:3});return a(o,200,$n(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(bt*4/3)+1024:t.maxBodyBytes;try{const l=(await v(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await de().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Xa]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await v(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ls({cfg:t,apply:xt,persist:()=>we(t,te()),isSelf:l=>Ds(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await _e().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:!r.chatpanelViewOnly&&J(r),agent:r.chatpanelViewOnly?"":String(r.headers["x-chatpanel-agent"]||""),local:!Ie(r.headers),viewOnly:!!r.chatpanelViewOnly});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:Ut.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ut.push(er({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,Math.max(t.maxBodyBytes||0,ii))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const S={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&S.removes.push(T.id);return}try{const R=Co(T);R&&S.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=Nt(),R=T?da((ae,Ee)=>ia(T,{salt:ae,iterations:Ee})):null,Q=async ae=>{if(!R||!ae.blob)return null;const Ee=await R(ae.blob),U=ae.blob.compression&&ae.blob.compression!=="none"?ca(ua,ae.blob.compression):null;return la(ae.blob,Ee,{codec:U})},ve=await e.upsertEntries(n.entries,{open:Q});d.push(...ve.written),m+=ve.sealed;for(const ae of ve.written)_(e.get(ae))}return(S.upserts.length||S.removes.length)&&L.bulk(S),d.length&&We({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Me)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});_o||=fn({store:e,notify:We,audit:st});const n=async l=>{const d=(await v(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await gn(r,o,{pathname:i,api:_o,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Fs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Ws(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(g,{maxTokens:S=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Re()||Pe(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:S,temperature:.2})}),ve=await Q.json().catch(()=>({}));return Q.ok?String(ve?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await Pn(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,ids:Array.isArray(e.ids)?e.ids.filter(g=>typeof g=="string"&&/^(chat|note|meeting|brief):[^\s]{1,200}$/.test(g)).slice(0,2e3):null,parallel:3});return a(o,200,$n(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(bt*4/3)+1024:t.maxBodyBytes;try{const l=(await v(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await de().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Xa]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await v(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ls({cfg:t,apply:xt,persist:()=>we(t,te()),isSelf:l=>Ds(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await v(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await _e().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:!r.chatpanelViewOnly&&J(r),agent:r.chatpanelViewOnly?"":String(r.headers["x-chatpanel-agent"]||""),local:!Ie(r.headers),viewOnly:!!r.chatpanelViewOnly});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:Ut.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ut.push(er({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,Math.max(t.maxBodyBytes||0,ii))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const S={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&S.removes.push(T.id);return}try{const R=Co(T);R&&S.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=Nt(),R=T?da((ae,Ee)=>ia(T,{salt:ae,iterations:Ee})):null,Q=async ae=>{if(!R||!ae.blob)return null;const Ee=await R(ae.blob),V=ae.blob.compression&&ae.blob.compression!=="none"?ca(ua,ae.blob.compression):null;return la(ae.blob,Ee,{codec:V})},ve=await e.upsertEntries(n.entries,{open:Q});d.push(...ve.written),m+=ve.sealed;for(const ae of ve.written)_(e.get(ae))}return(S.upserts.length||S.removes.length)&&L.bulk(S),d.length&&We({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Me)try{m.write(`event: deleted
42
42
  data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
43
43
 
44
44
  `)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:K.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:na(m?.source))===Mo,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${Mo}" is this gateway's own log`})),d=ta(K,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:K.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return K?a(o,200,{ok:!0,cursor:K.cursor(),count:K.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=oa(K.all());return a(o,200,{ok:!0,stats:e,year:ra(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Do(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=K.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>Dt(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=Do(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
@@ -55,13 +55,13 @@ data: ${JSON.stringify({pending:d})}
55
55
  `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}return Ro.some(s=>s.id===n.decision)?x.answer(e[1],n.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${Ro.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&r.method==="GET")return a(o,200,b.status());if(i==="/v1/browser/stream"&&r.method==="GET"){b.stream(r,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const n=i==="/v1/browser/call"?await b.call(e,r):i==="/v1/browser/announce"?b.announce(e):b.result(e);return a(o,n.status,n.body)}if(i==="/v1/history/stream"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
56
56
  data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:le,prefsRevision:me.revision})}
57
57
 
58
- `),o.chatpanelCredentialed=!!h(r),$e.add(o),r.on("close",()=>$e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...L.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=String(y.searchParams.get("id")||""),l=L.get(s,{maxChars:e,offset:n})||(Po(s)!==s?L.get(Po(s),{maxChars:e,offset:n}):null);return l?a(o,200,{ok:!0,record:l}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:xo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?hn(String(e.passphrase)):yn();const n=e.passphrase?await Ct(L,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&We(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ct(L,Nt());return e.ok&&e.whole&&We(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await ur(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await gt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=cr(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),s=await Ue(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ft(t)});try{let n=e;const s=await Te(t.pro?.entitlementToken);await gt(t);const l=await et([pt(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:lr(l.vault,"types")||[],detector:Ft(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Rt.totalmem()/1048576),s=hs(jo,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:mn(),recommendation:To(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Rt.totalmem()/1048576),l=To(jo.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Go(d)||zo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&Zo(t,n);try{we(t,te())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=un(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!(Go(n)||zo(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Zo(t,n);try{we(t,te())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Ve,n={platform:process.platform,arch:process.arch,helper:!!Mt()},s=ys.map(l=>{const d=Ho(l,n);return{...l,installed:A.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:ws,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(fs(n)||gs(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=Ho(vt(n),{platform:process.platform,arch:process.arch,helper:!!Mt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=vt(n)?.license||null;if(l){const m=Uo(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&bs(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{we(t,te())}catch{}return A.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Yt(t,{installing:!0}),licenseAccepted:fr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=ds.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),segment:ls.health(),translate:Je.health(),indictrans:ss.health(),aec:It.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Jo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{we(t,te())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=I.health().model||t.tts?.model||Yo(Lt()),n=Lt(),s=Vo.find(d=>d.id===e)||null,l=Vo.map(d=>({...d,installed:I.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:I.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:I.state(),progress:I.progress(),available:l,voice:t.tts?.voice||(Tt(e)==="pocket-tts"?kt:Be),arch:I.arch(),supportsVoices:I.arch()?I.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:I.arch()?I.supportsCustomVoices():!!s?.customVoices,sampleRate:I.sampleRate(),voices:I.isPocket()||!I.arch()&&Tt(e)==="pocket-tts"?(I.builtinVoices().length?I.builtinVoices():Os).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:I.builtinVoices().includes(d)})):I.arch()&&I.arch()!=="style-tts2"?[]:vs.map(d=>({...d,installed:I.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:I.health().dtype,runtime:I.health().runtime,dtypes:Ts})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ks(n)||Ss(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ue.parseCustomVoice(s);if(!(d?!!ue.getVoice(d):St(s)||Fo(s)&&Wo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&xs(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ko,voice:Be,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=_s(n),m=ue.parseCustomVoice(t.tts.voice||""),p=!!(m&&ue.getVoice(m));if(d&&!p)if(Tt(n)==="pocket-tts")t.tts.voice=kt;else{const g=ue.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!d&&p&&(t.tts.voice=Be);const f=Tt(n)==="pocket-tts";f&&!ue.parseCustomVoice(t.tts.voice||"")&&!St(t.tts.voice)&&(t.tts.voice=kt),!f&&St(t.tts.voice)&&(t.tts.voice=Be)}l&&(t.tts.dtype=l==="auto"?null:l);try{we(t,te())}catch{}return n&&I.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:I.state(),progress:I.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ue.listVoices(),usable:I.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ue.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ue.renameVoice(l,n),usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=us(P.activeModel())?.dim===ue.EMBED_DIM;if(d&&!P.isReady()){const _=P.download({onLog:Q=>console.log(Q)}),T=Symbol("timeout"),R=await Promise.race([_.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(T),pr))]);if(R===T||!P.isReady())return a(o,503,{error:{message:R===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const _=await I.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(hi(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const g=l?ue.replaceVoice(l,{vec:p,pocket:f}):ue.saveVoice({name:n,vec:p,pocket:f}),S=l&&n&&n!==g.name?ue.renameVoice(l,n):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${S.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...S,usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ue.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ue.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Be;try{we(t,te())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Qo)return a(o,413,{error:{message:`text too long (max ${Qo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Es(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Be);if(l&&!$s(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ae,contentType:Ee,redacted:U}=await Ps({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Ee,"Content-Length":String(ae.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ae)}if(!await I.ready({onLog:ae=>console.log(ae),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Yo(Lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:I.health().error||"tts model not ready",type:"tts_unavailable"}});const g=As({requested:d,configured:m,engine:I,voices:ue,isPocketVoice:St,isKnownVoice:Fo,isValidVoiceId:Wo,defaultVoice:Be,defaultPocketVoice:kt});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:S,customId:_,speakerEmbedding:T}=g,R=await I.synth(n,{voice:S,speed:s,speakerEmbedding:T}),Q=I.sampleRate(),ve=p==="pcm"?Buffer.from(new Float32Array(R).buffer):I.toWav(R,Q);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ve.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||I.isPocket()||I.supportsVoices()?{"X-Tts-Voice":S}:{}}),o.end(ve)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ms(await v(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(S){return a(o,S.code===413?413:415,{error:{message:S.message,type:"bad_request"}})}const n=S=>e.find(_=>_.name===S&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(S=>S.name==="file"&&S.filename)||e.find(S=>S.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await ps(s.data)}catch(S){return a(o,S.code===415?415:500,{error:{message:S.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=Jt(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=Lo(m,{fetchImpl:Ue})}catch(S){return a(o,500,{error:{message:`stt provider: ${S.message}`,type:"bad_provider"}})}if(!p&&!A.isReady()&&await A.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),onLog:S=>console.log(S)}),!p&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:S=>console.log(S)});const g=Date.now();try{const{id:S}=A.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),_=[],T=[];let R=null;A.subscribe(S,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"?R=U.lang:U.type==="error"&&T.push(U.message||U.code)});const Q=16e3*5;for(let U=0;U<l.pcm.length;U+=Q)A.pushAudio(S,l.pcm.subarray(U,Math.min(l.pcm.length,U+Q))),await A.decodeNow(S);if(await A.endSession(S),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let ve=0;const ae=_.map((U,kr)=>{const lo=typeof U.startMs=="number"?U.startMs/1e3:ve,Sr=(U.durationMs||0)/1e3;return ve=lo+Sr,{id:kr,start:Math.round(lo*100)/100,end:Math.round(ve*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(mt=>({start:Math.round(mt.startMs/10)/100,end:Math.round((mt.startMs+mt.durationMs)/10)/100,speaker:mt.speaker}))}:{}}}),Ee=ae.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Ee)):d==="verbose_json"?a(o,200,{task:"transcribe",language:R||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Ee,segments:ae,provider:m.kind,took_ms:Date.now()-g}):a(o,200,{text:Ee})}catch(S){return a(o,S.code==="too_many_sessions"?429:500,{error:{message:S.message,type:S.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>hr)return a(o,413,{error:{message:`at most ${Qt} s of audio`,type:"too_large"}});let n;try{n=await v(r,hr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Qt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=A.toFloat32(n);if(s.length<pi)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),pr).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=Jt(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Lo(n,{fetchImpl:Ue})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),licenseAccepted:fr(t,t.stt?.model||Ve),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&It.state()==="off"&&It.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,g=t.stt?.model||Ve,S=f&&!s?is(f,{engine:vt(g)?.engine||"",englishOnly:/\.en$/.test(g)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",R=l&&e?.vectors===!0,{id:Q}=A.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:R,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:Q,state:A.state(),format:T,..._?{poll:!0}:{},...R?{vectors:!0}:{},...S.length?{languagesMissing:S}:{},...d?{translate:Je.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await et([pt(()=>f,g=>{f=g})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=A.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const g=d.remote?"ready":A.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...A.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Je.state())?p.push({type:"translate-progress",state:Je.state(),...Je.progress()||{}}):yr.get(d)!==g&&(yr.set(d,g),p.push({type:"state",state:g}))}const f=d?.redact?await Te(t.pro?.entitlementToken):!0;for(const g of m)d?p.push(await s(d,g,f)):g.type!=="final"&&g.type!=="interim"&&g.type!=="translation"&&p.push(g);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=A.getSession(n)||A.endedSession(n);try{const m=await v(r,t.maxBodyBytes);A.pushAudio(n,A.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=A.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
58
+ `),o.chatpanelCredentialed=!!h(r),$e.add(o),r.on("close",()=>$e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...L.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=String(y.searchParams.get("id")||""),l=L.get(s,{maxChars:e,offset:n})||(Po(s)!==s?L.get(Po(s),{maxChars:e,offset:n}):null);return l?a(o,200,{ok:!0,record:l}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:xo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?hn(String(e.passphrase)):yn();const n=e.passphrase?await Ct(L,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&We(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ct(L,Nt());return e.ok&&e.whole&&We(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await ur(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await gt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=cr(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),s=await Ue(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ft(t)});try{let n=e;const s=await Te(t.pro?.entitlementToken);await gt(t);const l=await et([pt(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:lr(l.vault,"types")||[],detector:Ft(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Rt.totalmem()/1048576),s=hs(jo,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:mn(),recommendation:To(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Rt.totalmem()/1048576),l=To(jo.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Go(d)||zo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&Zo(t,n);try{we(t,te())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=un(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!(Go(n)||zo(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Zo(t,n);try{we(t,te())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Ve,n={platform:process.platform,arch:process.arch,helper:!!Mt()},s=ys.map(l=>{const d=Ho(l,n);return{...l,installed:A.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:ws,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(fs(n)||gs(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=Ho(vt(n),{platform:process.platform,arch:process.arch,helper:!!Mt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=vt(n)?.license||null;if(l){const m=Uo(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&bs(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{we(t,te())}catch{}return A.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Yt(t,{installing:!0}),licenseAccepted:fr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=ds.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),segment:ls.health(),translate:Je.health(),indictrans:ss.health(),aec:It.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Jo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{we(t,te())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=I.health().model||t.tts?.model||Yo(Lt()),n=Lt(),s=Vo.find(d=>d.id===e)||null,l=Vo.map(d=>({...d,installed:I.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:I.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:I.state(),progress:I.progress(),available:l,voice:t.tts?.voice||(Tt(e)==="pocket-tts"?kt:Be),arch:I.arch(),supportsVoices:I.arch()?I.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:I.arch()?I.supportsCustomVoices():!!s?.customVoices,sampleRate:I.sampleRate(),voices:I.isPocket()||!I.arch()&&Tt(e)==="pocket-tts"?(I.builtinVoices().length?I.builtinVoices():Os).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:I.builtinVoices().includes(d)})):I.arch()&&I.arch()!=="style-tts2"?[]:vs.map(d=>({...d,installed:I.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:I.health().dtype,runtime:I.health().runtime,dtypes:Ts})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ks(n)||Ss(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ue.parseCustomVoice(s);if(!(d?!!ue.getVoice(d):St(s)||Fo(s)&&Wo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&xs(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ko,voice:Be,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=_s(n),m=ue.parseCustomVoice(t.tts.voice||""),p=!!(m&&ue.getVoice(m));if(d&&!p)if(Tt(n)==="pocket-tts")t.tts.voice=kt;else{const g=ue.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!d&&p&&(t.tts.voice=Be);const f=Tt(n)==="pocket-tts";f&&!ue.parseCustomVoice(t.tts.voice||"")&&!St(t.tts.voice)&&(t.tts.voice=kt),!f&&St(t.tts.voice)&&(t.tts.voice=Be)}l&&(t.tts.dtype=l==="auto"?null:l);try{we(t,te())}catch{}return n&&I.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:I.state(),progress:I.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ue.listVoices(),usable:I.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ue.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ue.renameVoice(l,n),usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=us(P.activeModel())?.dim===ue.EMBED_DIM;if(d&&!P.isReady()){const _=P.download({onLog:Q=>console.log(Q)}),T=Symbol("timeout"),R=await Promise.race([_.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(T),pr))]);if(R===T||!P.isReady())return a(o,503,{error:{message:R===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const _=await I.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(hi(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const g=l?ue.replaceVoice(l,{vec:p,pocket:f}):ue.saveVoice({name:n,vec:p,pocket:f}),S=l&&n&&n!==g.name?ue.renameVoice(l,n):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${S.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...S,usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ue.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ue.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Be;try{we(t,te())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Qo)return a(o,413,{error:{message:`text too long (max ${Qo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Es(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Be);if(l&&!$s(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ae,contentType:Ee,redacted:V}=await Ps({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Ee,"Content-Length":String(ae.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(V)}),o.end(ae)}if(!await I.ready({onLog:ae=>console.log(ae),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Yo(Lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:I.health().error||"tts model not ready",type:"tts_unavailable"}});const g=As({requested:d,configured:m,engine:I,voices:ue,isPocketVoice:St,isKnownVoice:Fo,isValidVoiceId:Wo,defaultVoice:Be,defaultPocketVoice:kt});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:S,customId:_,speakerEmbedding:T}=g,R=await I.synth(n,{voice:S,speed:s,speakerEmbedding:T}),Q=I.sampleRate(),ve=p==="pcm"?Buffer.from(new Float32Array(R).buffer):I.toWav(R,Q);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ve.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||I.isPocket()||I.supportsVoices()?{"X-Tts-Voice":S}:{}}),o.end(ve)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ms(await v(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(S){return a(o,S.code===413?413:415,{error:{message:S.message,type:"bad_request"}})}const n=S=>e.find(_=>_.name===S&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(S=>S.name==="file"&&S.filename)||e.find(S=>S.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await ps(s.data)}catch(S){return a(o,S.code===415?415:500,{error:{message:S.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=Jt(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=Lo(m,{fetchImpl:Ue})}catch(S){return a(o,500,{error:{message:`stt provider: ${S.message}`,type:"bad_provider"}})}if(!p&&!A.isReady()&&await A.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),onLog:S=>console.log(S)}),!p&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:S=>console.log(S)});const g=Date.now();try{const{id:S}=A.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),_=[],T=[];let R=null;A.subscribe(S,V=>{V.type==="final"&&V.text?_.push(V):V.type==="language"?R=V.lang:V.type==="error"&&T.push(V.message||V.code)});const Q=16e3*5;for(let V=0;V<l.pcm.length;V+=Q)A.pushAudio(S,l.pcm.subarray(V,Math.min(l.pcm.length,V+Q))),await A.decodeNow(S);if(await A.endSession(S),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let ve=0;const ae=_.map((V,kr)=>{const lo=typeof V.startMs=="number"?V.startMs/1e3:ve,Sr=(V.durationMs||0)/1e3;return ve=lo+Sr,{id:kr,start:Math.round(lo*100)/100,end:Math.round(ve*100)/100,text:V.text,...V.speaker?{speaker:V.speaker}:{},...V.turns?{turns:V.turns.map(mt=>({start:Math.round(mt.startMs/10)/100,end:Math.round((mt.startMs+mt.durationMs)/10)/100,speaker:mt.speaker}))}:{}}}),Ee=ae.map(V=>V.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Ee)):d==="verbose_json"?a(o,200,{task:"transcribe",language:R||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Ee,segments:ae,provider:m.kind,took_ms:Date.now()-g}):a(o,200,{text:Ee})}catch(S){return a(o,S.code==="too_many_sessions"?429:500,{error:{message:S.message,type:S.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>hr)return a(o,413,{error:{message:`at most ${Qt} s of audio`,type:"too_large"}});let n;try{n=await v(r,hr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Qt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=A.toFloat32(n);if(s.length<pi)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),pr).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=Jt(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Lo(n,{fetchImpl:Ue})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),licenseAccepted:fr(t,t.stt?.model||Ve),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&It.state()==="off"&&It.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,g=t.stt?.model||Ve,S=f&&!s?is(f,{engine:vt(g)?.engine||"",englishOnly:/\.en$/.test(g)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",R=l&&e?.vectors===!0,{id:Q}=A.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:R,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:Q,state:A.state(),format:T,..._?{poll:!0}:{},...R?{vectors:!0}:{},...S.length?{languagesMissing:S}:{},...d?{translate:Je.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await et([pt(()=>f,g=>{f=g})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=A.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const g=d.remote?"ready":A.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...A.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Je.state())?p.push({type:"translate-progress",state:Je.state(),...Je.progress()||{}}):yr.get(d)!==g&&(yr.set(d,g),p.push({type:"state",state:g}))}const f=d?.redact?await Te(t.pro?.entitlementToken):!0;for(const g of m)d?p.push(await s(d,g,f)):g.type!=="final"&&g.type!=="interim"&&g.type!=="translation"&&p.push(g);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=A.getSession(n)||A.endedSession(n);try{const m=await v(r,t.maxBodyBytes);A.pushAudio(n,A.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=A.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
59
59
 
60
60
  `),p=d.redact?await Te(t.pro?.entitlementToken):!0,f=T=>s(d,T,p);m({type:"state",state:d.remote?"ready":A.state()});const g=setInterval(()=>{const T=d.remote?"ready":A.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...A.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(g);return}if(d.diarize){const R=P.state();if(R==="downloading"||R==="loading"){m({type:"diarize-progress",state:R,...P.progress()||{}});return}}if(d.translateTo){const R=Je.state();if(R==="downloading"||R==="loading"){m({type:"translate-progress",state:R,...Je.progress()||{}});return}}m({type:"state",state:T}),clearInterval(g)},500);g.unref?.();let S=Promise.resolve();const _=A.subscribe(n,T=>{S=S.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(g),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(g),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=A.getSession(n);await A.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...Ge].reverse()});if(i==="/config"&&r.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,Xo(t,{proUnlocked:e,policy:ht()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const p=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{xt(p,{capabilities:e.capabilities})}catch(g){if(g?.code==="SHAPE")return a(o,400,{error:g.message});throw g}const f=Object.keys(e.capabilities).map(g=>js(g,t.capabilities?.[g],p.capabilities?.[g])).find(Boolean);if(f&&!await Te(t.pro?.entitlementToken))return a(o,403,{error:f,needs:"pro"})}try{xt(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}yo(t),JSON.stringify(t.sandbox||null)!==n&&it?.restart("sandbox settings changed");try{we(t,te())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=j.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&j.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Te(t.pro?.entitlementToken);return a(o,200,Xo(t,{proUnlocked:m,policy:ht()}))}if(r.method==="GET"&&i==="/skills")return ke(r,o,t,`/skills${Ye(y,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(r.method==="POST"&&i==="/v1/threads/send"){if(!J(r))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=L.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(n.to||""),l=String(n.message||"").trim();if(!l||l.length>$o)return a(o,400,{error:{message:`threads/send: a message of 1–${$o} characters`,type:"invalid_request"}});const d=n.from&&typeof n.from=="object"?{id:String(n.from.id||"").slice(0,200),title:String(n.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=xn(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(n.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:p.model});const f=_n({fromTitle:d?.title,message:l}),g={thread:{id:p.thread,...m.title?{title:m.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let S="";try{const T=await fetch(`http://127.0.0.1:${r.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Re()||Pe(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(g))},body:JSON.stringify({model:p.model,messages:[...On(m),{role:"user",content:f}],stream:!1}),signal:AbortSignal.timeout(6e5)}),R=await T.json().catch(()=>null);if(!T.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${R?.error?.message||`HTTP ${T.status}`}`,type:"upstream"}});S=String(R?.choices?.[0]?.message?.content||"")}catch(T){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${T?.message||T}`,type:"upstream"}})}const _=En(e.get(s)||m,{question:f,reply:S,model:p.model,from:d});e.write([_],{host:"gateway",at:Date.now()});try{const T=Co(e.get(s));T&&L.bulk({upserts:[T],removes:[]})}catch{}return We({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:p.model,reply:S})}const q=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(r.method==="POST"&&q)return J(r)?r.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ke(r,o,t,q,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/skills-quarantined")return ke(r,o,t,`/skills-quarantined${Ye(y,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&r.method==="POST")return J(r)?ke(r,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&r.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Xt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):J(r)?ke(r,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&r.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]);return Xt(n)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):J(r)?ke(r,o,t,`/skills/${encodeURIComponent(n)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(r.method==="GET"&&i==="/agent-defs")return ke(r,o,t,`/agent-defs${Ye(y,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(r.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Xt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ke(r,o,t,`/agent-defs/${encodeURIComponent(e)}${Ye(y,t)}`)}if(i.startsWith("/a2a/")){if(!J(r))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(r.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:rn()});if(r.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Zr(e.url||"");const n=await yt(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:n.card,fingerprint:n.fingerprint,fresh:n.fresh,changed:!!n.changed,url:n.url})}if(r.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await yt(e.url,{auth:String(e.auth||"")})).card,s=await qr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(r.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await yt(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
61
61
  data: ${JSON.stringify(d)}
62
62
 
63
- `);try{const l=await en({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await yt(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await on({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await tn({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof go||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof go&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?ke(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(e)}${Ye(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await rt(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=nt(t.bridge?.token);try{const s=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ye(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await ee(),n=e.sig!==void 0&&e.sig!==oe;return oe=e.sig,a(o,200,await Gs(t,{serviceHealth:async()=>e,fresh:n,engineAt:M.engineAt}))}if(yi.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=ni(i,r.headers,t);let Se;try{Se=await v(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let ge=null,E=null,qe=Se,qt=0,eo=0,to=0,Oe=!1,Ce=!1,oo="",ze=!0;const se=t.logRequests&&W.redactable&&r.method==="POST"?ri(Ze):null,gr=Date.now();if(W.redactable&&r.method==="POST"&&Se.length){try{E=JSON.parse(Se.toString("utf8"))}catch{E=null}if(E&&ai(E,W.kind))qe=Se;else if(E){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(E.tools)&&E.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Qs,g=e.narrowAll?null:_=>!Ys.test(nr(_)),S=E.tools.length;E.tools=Nr(E.tools,Zs(E,W.kind),{cap:f,keep:g,name:nr,description:Xs}),to=S-E.tools.length}if(ze=await Te(t.pro?.entitlementToken),Oe=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!Oe){const f=_t(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:()=>!1}),g=f?.type==="api"?await M.decide(f,E?.model).catch(()=>null):null;Ce=g?.redact===!1,oo=Ce?g.engine||"declared":""}if(!Oe&&!Ce){const f=Ns(t,ze);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Oe&&!Ce&&await gt(t);const n=Oe?[]:W.adapter.collectSegments(E,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=se?se.clock():0,{vault:d,count:m,sanitized:p}=Oe?{vault:null,count:0,sanitized:0}:await et(n,t.redaction,{signal:s.signal,isPro:ze,sanitizeOnly:Ce,onEgress:f=>Ut.push(er({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(se&&se.lap("redact",l),W.adapter.joinTextParts?.(E),ge=d,qt=m,eo=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!ze&&m>0){Bs(t,ze);try{we(t,te())}catch{}}if(!Oe&&!Ce&&Array.isArray(E.tools)&&E.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=_t(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:S=>!!S.service&&G.fn(S.id)==="down"}),g=!(f&&f.type==="api");W.adapter.injectSystemNote(E,Mr({toolData:t.tools?.toolData,ownTools:g}))}else!Oe&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(E,Dr());qe=Buffer.from(JSON.stringify(E),"utf8")}}const ro=Br({vault:ge,toolData:t.tools?.toolData}),lt=E&&typeof E.chatpanel=="object"&&E.chatpanel||null;if(lt&&(delete E.chatpanel,qe=Buffer.from(JSON.stringify(E),"utf8")),typeof E?.model=="string"&&E.model.startsWith("fusion:")){const e=sa(E.model,t,await ee());if(e?.error)return se?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(E.model=e.model,qe=Buffer.from(JSON.stringify(E),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ie={destination:String(r.headers["x-chatpanel-destination"]||lt?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||lt?.reach||"").trim(),run:Zt(r.headers["x-chatpanel-run"],lt?.run)},dt=await ee(),no=e=>!!e.service&&dt(e.id)==="down";let B=_t(E?.model,t,W.kind,{destination:ie.destination,down:no});B?.type==="agent"&&E?.model&&!ie.destination&&!Us(B,E.model)&&(await Hs(t,{serviceHealth:async()=>dt,engineAt:M.engineAt}),B=_t(E?.model,t,W.kind,{destination:ie.destination,down:no}));const ao=B?.service&&dt(B.id)==="down"?await V().revive(B.service).catch(()=>null):null;if(ao?.ok&&(G.at=0),B?.service&&dt(B.id)==="down"&&!ao?.ok)return se?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(E?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ie.destination&&(!B||B.id!==ie.destination))return se?.commit(),a(o,404,{error:{message:`no destination "${ie.destination}" is configured on this gateway`,type:"unknown_destination",known:zs(t).map(e=>e.id)}});const ce=Ie(r.headers);if(ce&&!Da(ce,B?.type==="api"?"api":"agent"))return se?.commit(),a(o,403,{error:{message:`link: partner "${ce.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ce.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ct=ce&&W.redactable&&r.method==="POST"&&E?{caller:ce,surface:Zn(ce,ce.kind==="partner"?"":O?.deviceNameOf(ce.device)),model:E.model||null,startedAt:gr}:null;se&&(se.meta={t:Date.now(),model:E?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:qt,sanitized:eo,narrowed:to,detail:lr(ge,t.logDetail),redaction:Oe?"off":Ce?`on-device (${oo})`:t.redaction.tier||"basic",...ce?.kind==="partner"?{via:Ca(ce)}:{}});const ut=ht();if(ut&&B){const e=B.type==="api"?fo(ut,{model:E?.model||"",endpoint:B.baseUrl||""}):Yr(ut,B.agent||B.id)?fo(ut,{model:E?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return se?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?si(B.baseUrl,t)?(se?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):fi(r,o,{...W,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:ro,trace:se,link:ct&&{...ct,agentId:B.id,dest:{type:"api",id:B.id}}},qe,ge):(se?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const Pt=tt(r),so=Pt==="local"&&t.bridge?.openAgentLane?"token":Pt;if(so==="local")return se?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const io=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),wr=new Set(["thread","ephemeral","workingDir","worker"]),$t=ce?.kind==="partner";if(Pt==="token"&&r.headers["x-chatpanel-link-device"]&&!$t&&!(ie.run&&Object.keys(ie.run).some(e=>!wr.has(e)))){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));e&&(ie.run={...e,...ie.run||{}})}if($t){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));ie.run={...e||{},...Ra(ie.run,ce.device)};const n=O?.partnerFolderOf(ce.device);if(!n)return se?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ie.run.workingDir=n,ie.reach="",Array.isArray(E?.tools)&&(E.tools=E.tools.filter(s=>!Io(s?.function?.name??s?.name)))}const He=Rr({...ie.run||{},...ie.reach?{reach:ie.reach}:{},...io?{askDepth:io}:{}},so);He.reach&&o.setHeader("x-chatpanel-reach-used",He.reach);const br=$t?{inbox:x,partner:ce.partner,device:ce.device,conversation:He.thread?.id||null}:null,vr=ct&&{...ct,dest:{type:"agent",id:B?.id||"bridge"},threadId:He.thread?.id||null};return ui(r,o,{...W,pathname:i,agentOverride:B?.agent,harness:ro,trace:se,run:Object.keys(He).length?He:null,owner:br,link:vr},E,ge,t,ze)});return Ne.on("close",()=>{D?.stop("closed"),fa(),b.close(),O?.stop(),x.stop()}),Ne.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(O&&i.startsWith(Ma)){O.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
63
+ `);try{const l=await en({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await yt(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await on({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await tn({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof go||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof go&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?ke(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(e)}${Ye(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await rt(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=nt(t.bridge?.token);try{const s=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ye(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await ee(),n=e.sig!==void 0&&e.sig!==oe;return oe=e.sig,a(o,200,await Gs(t,{serviceHealth:async()=>e,fresh:n,engineAt:M.engineAt}))}if(yi.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=ni(i,r.headers,t);let Se;try{Se=await v(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let ge=null,E=null,qe=Se,qt=0,eo=0,to=0,Oe=!1,Ce=!1,oo="",ze=!0;const se=t.logRequests&&W.redactable&&r.method==="POST"?ri(Ze):null,gr=Date.now();if(W.redactable&&r.method==="POST"&&Se.length){try{E=JSON.parse(Se.toString("utf8"))}catch{E=null}if(E&&ai(E,W.kind))qe=Se;else if(E){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(E.tools)&&E.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Qs,g=e.narrowAll?null:_=>!Ys.test(nr(_)),S=E.tools.length;E.tools=Nr(E.tools,Zs(E,W.kind),{cap:f,keep:g,name:nr,description:Xs}),to=S-E.tools.length}if(ze=await Te(t.pro?.entitlementToken),Oe=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!Oe){const f=_t(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:()=>!1}),g=f?.type==="api"?await M.decide(f,E?.model).catch(()=>null):null;Ce=g?.redact===!1,oo=Ce?g.engine||"declared":""}if(!Oe&&!Ce){const f=Ns(t,ze);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Oe&&!Ce&&await gt(t);const n=Oe?[]:W.adapter.collectSegments(E,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=se?se.clock():0,{vault:d,count:m,sanitized:p}=Oe?{vault:null,count:0,sanitized:0}:await et(n,t.redaction,{signal:s.signal,isPro:ze,sanitizeOnly:Ce,onEgress:f=>Ut.push(er({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(se&&se.lap("redact",l),W.adapter.joinTextParts?.(E),ge=d,qt=m,eo=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!ze&&m>0){Bs(t,ze);try{we(t,te())}catch{}}if(!Oe&&!Ce&&Array.isArray(E.tools)&&E.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=_t(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:S=>!!S.service&&G.fn(S.id)==="down"}),g=!(f&&f.type==="api");W.adapter.injectSystemNote(E,Mr({toolData:t.tools?.toolData,ownTools:g}))}else!Oe&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(E,Dr());qe=Buffer.from(JSON.stringify(E),"utf8")}}const ro=Br({vault:ge,toolData:t.tools?.toolData}),lt=E&&typeof E.chatpanel=="object"&&E.chatpanel||null;if(lt&&(delete E.chatpanel,qe=Buffer.from(JSON.stringify(E),"utf8")),typeof E?.model=="string"&&E.model.startsWith("fusion:")){const e=sa(E.model,t,await ee());if(e?.error)return se?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(E.model=e.model,qe=Buffer.from(JSON.stringify(E),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ie={destination:String(r.headers["x-chatpanel-destination"]||lt?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||lt?.reach||"").trim(),run:Zt(r.headers["x-chatpanel-run"],lt?.run)},dt=await ee(),no=e=>!!e.service&&dt(e.id)==="down";let B=_t(E?.model,t,W.kind,{destination:ie.destination,down:no});B?.type==="agent"&&E?.model&&!ie.destination&&!Us(B,E.model)&&(await Hs(t,{serviceHealth:async()=>dt,engineAt:M.engineAt}),B=_t(E?.model,t,W.kind,{destination:ie.destination,down:no}));const ao=B?.service&&dt(B.id)==="down"?await U().revive(B.service).catch(()=>null):null;if(ao?.ok&&(G.at=0),B?.service&&dt(B.id)==="down"&&!ao?.ok)return se?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(E?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ie.destination&&(!B||B.id!==ie.destination))return se?.commit(),a(o,404,{error:{message:`no destination "${ie.destination}" is configured on this gateway`,type:"unknown_destination",known:zs(t).map(e=>e.id)}});const ce=Ie(r.headers);if(ce&&!Da(ce,B?.type==="api"?"api":"agent"))return se?.commit(),a(o,403,{error:{message:`link: partner "${ce.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ce.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ct=ce&&W.redactable&&r.method==="POST"&&E?{caller:ce,surface:Zn(ce,ce.kind==="partner"?"":O?.deviceNameOf(ce.device)),model:E.model||null,startedAt:gr}:null;se&&(se.meta={t:Date.now(),model:E?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:qt,sanitized:eo,narrowed:to,detail:lr(ge,t.logDetail),redaction:Oe?"off":Ce?`on-device (${oo})`:t.redaction.tier||"basic",...ce?.kind==="partner"?{via:Ca(ce)}:{}});const ut=ht();if(ut&&B){const e=B.type==="api"?fo(ut,{model:E?.model||"",endpoint:B.baseUrl||""}):Yr(ut,B.agent||B.id)?fo(ut,{model:E?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return se?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?si(B.baseUrl,t)?(se?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):fi(r,o,{...W,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:ro,trace:se,link:ct&&{...ct,agentId:B.id,dest:{type:"api",id:B.id}}},qe,ge):(se?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const Pt=tt(r),so=Pt==="local"&&t.bridge?.openAgentLane?"token":Pt;if(so==="local")return se?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const io=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),wr=new Set(["thread","ephemeral","workingDir","worker"]),$t=ce?.kind==="partner";if(Pt==="token"&&r.headers["x-chatpanel-link-device"]&&!$t&&!(ie.run&&Object.keys(ie.run).some(e=>!wr.has(e)))){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));e&&(ie.run={...e,...ie.run||{}})}if($t){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));ie.run={...e||{},...Ra(ie.run,ce.device)};const n=O?.partnerFolderOf(ce.device);if(!n)return se?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ie.run.workingDir=n,ie.reach="",Array.isArray(E?.tools)&&(E.tools=E.tools.filter(s=>!Io(s?.function?.name??s?.name)))}const He=Rr({...ie.run||{},...ie.reach?{reach:ie.reach}:{},...io?{askDepth:io}:{}},so);He.reach&&o.setHeader("x-chatpanel-reach-used",He.reach);const br=$t?{inbox:x,partner:ce.partner,device:ce.device,conversation:He.thread?.id||null}:null,vr=ct&&{...ct,dest:{type:"agent",id:B?.id||"bridge"},threadId:He.thread?.id||null};return ui(r,o,{...W,pathname:i,agentOverride:B?.agent,harness:ro,trace:se,run:Object.keys(He).length?He:null,owner:br,link:vr},E,ge,t,ze)});return Ne.on("close",()=>{D?.stop("closed"),fa(),b.close(),O?.stop(),x.stop()}),Ne.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(O&&i.startsWith(Ma)){O.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
64
64
  connection: close\r
65
65
  content-length: 0\r
66
66
  \r
67
- `)}catch{}}),Ne.once("listening",()=>{V()}),Ne.linkHost=O,Ne.teamBuckets=Ae,Ne.runtimeDefaults=()=>V().ensureDefaults(),Ne}function Zt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const h={};if(Array.isArray(u.grants)&&(h.grants=u.grants.map(k=>String(k).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const k=u.workspace;h.workspace={repo:String(k.repo).slice(0,400),projectId:String(k.projectId||"").slice(0,120),jobId:String(k.jobId||"").slice(0,120),...k.base?{base:String(k.base).slice(0,120)}:{}}}if(u.connectionId&&(h.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(h.workingDir=u.workingDir.trim().slice(0,1024)),Rs.includes(u.permissionMode)&&u.permissionMode!=="default"&&(h.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const k=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(b=>String(b).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),N=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(b=>String(b).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,$=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(b=>String(b).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(k.length||N.length||M||$.length)&&(h.sandbox={...k.length?{hosts:k}:{},...N.length?{write:N}:{},...M?{outside:!0}:{},...$.length?{signIn:$}:{}})}const w=vn(u.thread);return w&&(h.thread=w),u.ephemeral===!0&&(h.ephemeral=!0),u.worker===!0&&(h.worker=!0,h.ephemeral=!0),u.lean===!0&&(h.lean=!0,h.ephemeral=!0),Object.keys(h).length?h:null}let it=null,Et=null;async function _d(t=co()){pn();let c=null;try{c=await Kr()}catch(b){throw b instanceof Qr&&(console.error(`[chatpanel-gateway] org policy: ${b.message}`),process.exit(78)),b}const u=c?.policy||null;u&&(yo(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const h=Fr({enabled:ho(t)});console.log(`[chatpanel-gateway] certificates: ${h.on?`this computer's list is trusted too (${h.added} added to the runtime's own)`:`the runtime's own list only — ${h.why}`}`),Ur(globalThis,{allow:u?.egress?(b,{local:x})=>Xr(u,b,{local:x}):null}),Pe();const w=gi(t),k=cn(t),N=xr(t);let M=!1;w.on("error",b=>{if(b&&b.code==="EADDRINUSE"){const x=Ot(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(O=>O.ok?O.json():null).catch(()=>null).then(O=>{const z=!!(O?.version&&typeof O.tier=="string"),F=kn({name:"gateway",self:le,holder:z?{ours:z,version:O.version}:null,managedBy:Sn(process.env),port:t.port});if(F.action==="standby"||M&&!O){if(!M)for(const D of F.lines)console.error(D);M=!0,setTimeout(()=>w.listen(t.port,t.host),Tn);return}if(z){const D=O.managedBy?` (run by ${O.managedBy})`:"";for(const[H,G]of F.lines.entries())console.error(H===0?G.replace(` on ${t.port}`,` at http://${x}:${t.port}${D}`):G)}else{const D=In(t.port);console.error(`Port ${t.port} is held by ${D||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${b?.message||b}`),process.exit(1)}),w.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${le} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(b=>console.log(` link : not started (${b?.message||b})`)),(t.context?.providers||[]).some(b=>b?.kind==="bucket"&&b.enabled!==!1))try{w.teamBuckets?.().start()}catch(b){console.log(` team : not started (${b?.message||b})`)}w.runtimeDefaults?.().then(b=>{for(const x of b||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(b=>console.log(` runtime : defaults not started (${b?.message||b})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const b of Js(t))console.log(` ⚠ sandbox : ${b}`);console.log(` confined : ${Hn(wt({stateDir:Fe.dirname(te())}))}`),Et={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Rn(t,{childEnv:()=>({...Is(t,process.env,ht()),...Cs(t)})}).then(b=>{it=b}).catch(b=>{Et={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${b?.message||b})`},console.log(` bridge : not supervised (${b?.message||b})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Ot(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),xo()&&Ct(L,Nt()).then(b=>{b?.ok&&(console.log(` warm : seeded ${b.ingested} records from ${b.file}`),b.whole&&We())}).catch(()=>{});const $=()=>{k?.stop(),N.stop(),it?.stop(),Ks(w)};return process.on("SIGINT",$),process.on("SIGTERM",$),w}export{ii as RECORDS_MAX_BYTES,Pd as VERSION,gi as createGateway,mi as joinUpstream,Vt as parseAgentModel,_d as start};
67
+ `)}catch{}}),Ne.once("listening",()=>{U()}),Ne.linkHost=O,Ne.teamBuckets=Ae,Ne.runtimeDefaults=()=>U().ensureDefaults(),Ne}function Zt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const h={};if(Array.isArray(u.grants)&&(h.grants=u.grants.map(k=>String(k).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const k=u.workspace;h.workspace={repo:String(k.repo).slice(0,400),projectId:String(k.projectId||"").slice(0,120),jobId:String(k.jobId||"").slice(0,120),...k.base?{base:String(k.base).slice(0,120)}:{}}}if(u.connectionId&&(h.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(h.workingDir=u.workingDir.trim().slice(0,1024)),Rs.includes(u.permissionMode)&&u.permissionMode!=="default"&&(h.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const k=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(b=>String(b).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),N=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(b=>String(b).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,$=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(b=>String(b).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(k.length||N.length||M||$.length)&&(h.sandbox={...k.length?{hosts:k}:{},...N.length?{write:N}:{},...M?{outside:!0}:{},...$.length?{signIn:$}:{}})}const w=vn(u.thread);return w&&(h.thread=w),u.ephemeral===!0&&(h.ephemeral=!0),u.worker===!0&&(h.worker=!0,h.ephemeral=!0),u.lean===!0&&(h.lean=!0,h.ephemeral=!0),Object.keys(h).length?h:null}let it=null,Et=null;async function _d(t=co()){pn();let c=null;try{c=await Kr()}catch(b){throw b instanceof Qr&&(console.error(`[chatpanel-gateway] org policy: ${b.message}`),process.exit(78)),b}const u=c?.policy||null;u&&(yo(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const h=Fr({enabled:ho(t)});console.log(`[chatpanel-gateway] certificates: ${h.on?`this computer's list is trusted too (${h.added} added to the runtime's own)`:`the runtime's own list only — ${h.why}`}`),Ur(globalThis,{allow:u?.egress?(b,{local:x})=>Xr(u,b,{local:x}):null}),Pe();const w=gi(t),k=cn(t),N=xr(t);let M=!1;w.on("error",b=>{if(b&&b.code==="EADDRINUSE"){const x=Ot(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(O=>O.ok?O.json():null).catch(()=>null).then(O=>{const z=!!(O?.version&&typeof O.tier=="string"),F=kn({name:"gateway",self:le,holder:z?{ours:z,version:O.version}:null,managedBy:Sn(process.env),port:t.port});if(F.action==="standby"||M&&!O){if(!M)for(const D of F.lines)console.error(D);M=!0,setTimeout(()=>w.listen(t.port,t.host),Tn);return}if(z){const D=O.managedBy?` (run by ${O.managedBy})`:"";for(const[H,G]of F.lines.entries())console.error(H===0?G.replace(` on ${t.port}`,` at http://${x}:${t.port}${D}`):G)}else{const D=In(t.port);console.error(`Port ${t.port} is held by ${D||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${b?.message||b}`),process.exit(1)}),w.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${le} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(b=>console.log(` link : not started (${b?.message||b})`)),(t.context?.providers||[]).some(b=>b?.kind==="bucket"&&b.enabled!==!1))try{w.teamBuckets?.().start()}catch(b){console.log(` team : not started (${b?.message||b})`)}w.runtimeDefaults?.().then(b=>{for(const x of b||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(b=>console.log(` runtime : defaults not started (${b?.message||b})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const b of Js(t))console.log(` ⚠ sandbox : ${b}`);console.log(` confined : ${Hn(wt({stateDir:Fe.dirname(te())}))}`),Et={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Rn(t,{childEnv:()=>({...Is(t,process.env,ht()),...Cs(t)})}).then(b=>{it=b}).catch(b=>{Et={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${b?.message||b})`},console.log(` bridge : not supervised (${b?.message||b})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Ot(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),xo()&&Ct(L,Nt()).then(b=>{b?.ok&&(console.log(` warm : seeded ${b.ingested} records from ${b.file}`),b.whole&&We())}).catch(()=>{});const $=()=>{k?.stop(),N.stop(),it?.stop(),Ks(w)};return process.on("SIGINT",$),process.on("SIGTERM",$),w}export{ii as RECORDS_MAX_BYTES,Pd as VERSION,gi as createGateway,mi as joinUpstream,Vt as parseAgentModel,_d as start};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.163.2";export{o as VERSION};
1
+ const o="0.165.0";export{o as VERSION};