@chatpanel/gateway 0.144.0 → 0.144.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.144.0",
3
+ "version": "0.144.1",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.52.0",
27
- "@chatpanel/events": "^0.478.0",
27
+ "@chatpanel/events": "^0.479.0",
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),h.unref?.()};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 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};
package/src/server.js CHANGED
@@ -60,7 +60,7 @@ data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ue,prefsRe
60
60
  `),h=d.redact?await ke(t.pro?.entitlementToken):!0,y=x=>s(d,x,h);m({type:"state",state:d.remote?"ready":N.state()});const w=setInterval(()=>{const x=d.remote?"ready":N.state();if(x==="downloading"||x==="loading"){m({type:"progress",state:x,...N.progress()||{}});return}if(x==="error"){m({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const D=$.state();if(D==="downloading"||D==="loading"){m({type:"diarize-progress",state:D,...$.progress()||{}});return}}if(d.translateTo){const D=$e.state();if(D==="downloading"||D==="loading"){m({type:"translate-progress",state:D,...$e.progress()||{}});return}}m({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let v=Promise.resolve();const O=N.subscribe(r,x=>{v=v.then(async()=>{m(await y(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),O?.()});return}if(!e[2]&&n.method==="DELETE"){const d=N.getSession(r);await N.endSession(r);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...I].reverse()});if(i==="/config"&&n.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,Mo(t,{proUnlocked:e,policy:et()}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const h=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{Bo(h,{capabilities:e.capabilities})}catch(w){if(w?.code==="SHAPE")return a(o,400,{error:w.message});throw w}const y=Object.keys(e.capabilities).map(w=>ds(w,t.capabilities?.[w],h.capabilities?.[w])).find(Boolean);if(y&&!await ke(t.pro?.entitlementToken))return a(o,403,{error:y,needs:"pro"})}try{Bo(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}qt(t),JSON.stringify(t.sandbox||null)!==r&&Fe?.restart("sandbox settings changed");try{be(t,ce())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=L.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&L.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await ke(t.pro?.entitlementToken);return a(o,200,Mo(t,{proUnlocked:m,policy:et()}))}if(n.method==="GET"&&i==="/skills")return ve(n,o,t,`/skills${Le(g,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!j(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.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=R.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>po)return a(o,400,{error:{message:`threads/send: a message of 1–${po} characters`,type:"invalid_request"}});const d=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.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 h=an(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:h.model});const y=sn({fromTitle:d?.title,message:l}),w={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let v="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Be()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:h.model,messages:[...ln(m),{role:"user",content:y}],stream:!1}),signal:AbortSignal.timeout(6e5)}),D=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${D?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});v=String(D?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const O=dn(e.get(s)||m,{question:y,reply:v,model:h.model,from:d});e.write([O],{host:"gateway",at:Date.now()});try{const x=fo(e.get(s));x&&R.bulk({upserts:[x],removes:[]})}catch{}return Ie({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:v})}const q=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&q)return j(n)?n.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"}}):ve(n,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(n.method==="GET"&&i==="/skills-quarantined")return ve(n,o,t,`/skills-quarantined${Le(g,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return j(n)?ve(n,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)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Jt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):j(n)?ve(n,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)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return Jt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):j(n)?ve(n,o,t,`/skills/${encodeURIComponent(r)}/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(n.method==="GET"&&i==="/agent-defs")return ve(n,o,t,`/agent-defs${Le(g,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Jt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Le(g,t)}`)}if(i.startsWith("/a2a/")){if(!j(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:Lr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Dr(e.url||"");const r=await ot(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=await Cr({card:r,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(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(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 Ir({card:r,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(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Jr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Rr({card:r,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 r=e instanceof to||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof to&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return j(n)?ve(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.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"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Le(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!j(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ge(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=He(t.bridge?.token);try{const s=n.method==="POST"?(await k(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.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(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Le(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await z(),r=e.sig!==void 0&&e.sig!==J;return J=e.sig,a(o,200,await cs(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(Js.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ue}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const H=Es(i,n.headers,t);let K;try{K=await k(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let W=null,S=null,ie=K,We=0,Ae=0,jt=0,Se=!1,Pe=!1,zt="",Ne=!0;const ae=t.logRequests&&H.redactable&&n.method==="POST"?Os(ee):null,qo=Date.now();if(H.redactable&&n.method==="POST"&&K.length){try{S=JSON.parse(K.toString("utf8"))}catch{S=null}if(S&&Ps(S,H.kind))ie=K;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ws,w=e.narrowAll?null:O=>!bs.test(jo(O)),v=S.tools.length;S.tools=pr(S.tools,ks(S,H.kind),{cap:y,keep:w,name:jo,description:vs}),jt=v-S.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&j(n),!Se){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:()=>!1}),w=y?.type==="api"?await c.decide(y,S?.model).catch(()=>null):null;Pe=w?.redact===!1,zt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const y=os(t,Ne);if(!y.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${y.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:H.adapter.collectSegments(S,t.redaction,{skipPublic:j(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:d,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:y=>Nt.push(Io({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(ae&&ae.lap("redact",l),H.adapter.joinTextParts?.(S),W=d,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){rs(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!Pe&&Array.isArray(S.tools)&&S.tools.length&&typeof H.adapter.injectSystemNote=="function"){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),w=!(y&&y.type==="api");H.adapter.injectSystemNote(S,yr({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(S,fr());ie=Buffer.from(JSON.stringify(S),"utf8")}}const Gt=hr({vault:W,toolData:t.tools?.toolData}),Ke=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;if(Ke&&(delete S.chatpanel,ie=Buffer.from(JSON.stringify(S),"utf8")),typeof S?.model=="string"&&S.model.startsWith("fusion:")){const e=Jn(S.model,t,await z());if(e?.error)return ae?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(S.model=e.model,ie=Buffer.from(JSON.stringify(S),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Lt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await z(),Ht=e=>!!e.service&&Qe(e.id)==="down";let M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht});M?.type==="agent"&&S?.model&&!se.destination&&!ps(M,S.model)&&(await ms(t,{serviceHealth:async()=>Qe,engineAt:c.engineAt}),M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht}));const Ut=M?.service&&Qe(M.id)==="down"?await P().revive(M.service).catch(()=>null):null;if(Ut?.ok&&(_.at=0),M?.service&&Qe(M.id)==="down"&&!Ut?.ok)return ae?.commit(),a(o,503,{error:{message:`${M.id} is not running — the model ${JSON.stringify(S?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:M.service}});if(se.destination&&(!M||M.id!==se.destination))return ae?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:us(t).map(e=>e.id)}});const le=De(n.headers);if(le&&!ua(le,M?.type==="api"?"api":"agent"))return ae?.commit(),a(o,403,{error:{message:`link: partner "${le.partner}" may not use ${M?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${le.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Ye=le&&H.redactable&&n.method==="POST"&&S?{caller:le,surface:An(le,le.kind==="partner"?"":f?.deviceNameOf(le.device)),model:S.model||null,startedAt:qo}:null;ae&&(ae.meta={t:Date.now(),model:S?.model||null,dest:M?M.id:null,type:M?M.type:null,redacted:We,sanitized:Ae,narrowed:jt,detail:Uo(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${zt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:ma(le)}:{}});const Xe=et();if(Xe&&M){const e=M.type==="api"?eo(Xe,{model:S?.model||"",endpoint:M.baseUrl||""}):Mr(Xe,M.agent||M.id)?eo(Xe,{model:S?.model||""}):{ok:!1,reason:`agent "${M.agent||M.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ae?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(M&&M.type==="api")return M.baseUrl?$s(M.baseUrl,t)?(ae?.commit(),a(o,508,{error:{message:`destination "${M.id}" points back at the gateway (${M.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ls(n,o,{...H,pathname:i,search:g.search,base:M.baseUrl,destKey:M.apiKey,destProtocol:M.protocol,harness:Gt,trace:ae,link:Ye&&{...Ye,agentId:M.id,dest:{type:"api",id:M.id}}},ie,W):(ae?.commit(),a(o,502,{error:`destination "${M.id}" has no baseUrl`}));const mt=je(n),Vt=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Vt==="local")return ae?.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 Ft=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),er=new Set(["thread","ephemeral","workingDir","worker"]),pt=le?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(se.run&&Object.keys(se.run).some(e=>!er.has(e)))){const e=Lt(null,mo(uo(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Lt(null,mo(uo(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));se.run={...e||{},...pa(se.run,le.device)};const r=f?.partnerFolderOf(le.device);if(!r)return ae?.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"}});se.run.workingDir=r,se.reach="",Array.isArray(S?.tools)&&(S.tools=S.tools.filter(s=>!wo(s?.function?.name??s?.name)))}const Me=wr({...se.run||{},...se.reach?{reach:se.reach}:{},...Ft?{askDepth:Ft}:{}},Vt);Me.reach&&o.setHeader("x-chatpanel-reach-used",Me.reach);const tr=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Me.thread?.id||null}:null,or=Ye&&{...Ye,dest:{type:"agent",id:M?.id||"bridge"},threadId:Me.thread?.id||null};return Ds(n,o,{...H,pathname:i,agentOverride:M?.agent,harness:Gt,trace:ae,run:Object.keys(Me).length?Me:null,owner:tr,link:or},S,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Kn(),p.close(),f?.stop(),b.stop()}),pe.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(f&&i.startsWith(ca)){f.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
63
+ `);try{const l=await Ir({card:r,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(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Jr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Rr({card:r,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 r=e instanceof to||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof to&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return j(n)?ve(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.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"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Le(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!j(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ge(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=He(t.bridge?.token);try{const s=n.method==="POST"?(await k(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.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(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Le(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await z(),r=e.sig!==void 0&&e.sig!==J;return J=e.sig,a(o,200,await cs(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(Js.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ue}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const H=Es(i,n.headers,t);let K;try{K=await k(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let W=null,S=null,ie=K,We=0,Ae=0,jt=0,Se=!1,Pe=!1,zt="",Ne=!0;const ae=t.logRequests&&H.redactable&&n.method==="POST"?Os(ee):null,qo=Date.now();if(H.redactable&&n.method==="POST"&&K.length){try{S=JSON.parse(K.toString("utf8"))}catch{S=null}if(S&&Ps(S,H.kind))ie=K;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ws,w=e.narrowAll?null:O=>!bs.test(jo(O)),v=S.tools.length;S.tools=pr(S.tools,ks(S,H.kind),{cap:y,keep:w,name:jo,description:vs}),jt=v-S.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&j(n),!Se){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:()=>!1}),w=y?.type==="api"?await c.decide(y,S?.model).catch(()=>null):null;Pe=w?.redact===!1,zt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const y=os(t,Ne);if(!y.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${y.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"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:H.adapter.collectSegments(S,t.redaction,{skipPublic:j(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:d,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:y=>Nt.push(Io({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(ae&&ae.lap("redact",l),H.adapter.joinTextParts?.(S),W=d,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){rs(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!Pe&&Array.isArray(S.tools)&&S.tools.length&&typeof H.adapter.injectSystemNote=="function"){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),w=!(y&&y.type==="api");H.adapter.injectSystemNote(S,yr({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(S,fr());ie=Buffer.from(JSON.stringify(S),"utf8")}}const Gt=hr({vault:W,toolData:t.tools?.toolData}),Ke=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;if(Ke&&(delete S.chatpanel,ie=Buffer.from(JSON.stringify(S),"utf8")),typeof S?.model=="string"&&S.model.startsWith("fusion:")){const e=Jn(S.model,t,await z());if(e?.error)return ae?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(S.model=e.model,ie=Buffer.from(JSON.stringify(S),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Lt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await z(),Ht=e=>!!e.service&&Qe(e.id)==="down";let M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht});M?.type==="agent"&&S?.model&&!se.destination&&!ps(M,S.model)&&(await ms(t,{serviceHealth:async()=>Qe,engineAt:c.engineAt}),M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht}));const Ut=M?.service&&Qe(M.id)==="down"?await P().revive(M.service).catch(()=>null):null;if(Ut?.ok&&(_.at=0),M?.service&&Qe(M.id)==="down"&&!Ut?.ok)return ae?.commit(),a(o,503,{error:{message:`${M.id} is not running — the model ${JSON.stringify(S?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:M.service}});if(se.destination&&(!M||M.id!==se.destination))return ae?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:us(t).map(e=>e.id)}});const le=De(n.headers);if(le&&!ua(le,M?.type==="api"?"api":"agent"))return ae?.commit(),a(o,403,{error:{message:`link: partner "${le.partner}" may not use ${M?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${le.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Ye=le&&H.redactable&&n.method==="POST"&&S?{caller:le,surface:An(le,le.kind==="partner"?"":f?.deviceNameOf(le.device)),model:S.model||null,startedAt:qo}:null;ae&&(ae.meta={t:Date.now(),model:S?.model||null,dest:M?M.id:null,type:M?M.type:null,redacted:We,sanitized:Ae,narrowed:jt,detail:Uo(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${zt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:ma(le)}:{}});const Xe=et();if(Xe&&M){const e=M.type==="api"?eo(Xe,{model:S?.model||"",endpoint:M.baseUrl||""}):Mr(Xe,M.agent||M.id)?eo(Xe,{model:S?.model||""}):{ok:!1,reason:`agent "${M.agent||M.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ae?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(M&&M.type==="api")return M.baseUrl?$s(M.baseUrl,t)?(ae?.commit(),a(o,508,{error:{message:`destination "${M.id}" points back at the gateway (${M.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ls(n,o,{...H,pathname:i,search:g.search,base:M.baseUrl,destKey:M.apiKey,destProtocol:M.protocol,harness:Gt,trace:ae,link:Ye&&{...Ye,agentId:M.id,dest:{type:"api",id:M.id}}},ie,W):(ae?.commit(),a(o,502,{error:`destination "${M.id}" has no baseUrl`}));const mt=je(n),Vt=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Vt==="local")return ae?.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 Ft=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),er=new Set(["thread","ephemeral","workingDir","worker"]),pt=le?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(se.run&&Object.keys(se.run).some(e=>!er.has(e)))){const e=Lt(null,mo(uo(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Lt(null,mo(uo(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));se.run={...e||{},...pa(se.run,le.device)};const r=f?.partnerFolderOf(le.device);if(!r)return ae?.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"}});se.run.workingDir=r,se.reach="",Array.isArray(S?.tools)&&(S.tools=S.tools.filter(s=>!wo(s?.function?.name??s?.name)))}const Me=wr({...se.run||{},...se.reach?{reach:se.reach}:{},...Ft?{askDepth:Ft}:{}},Vt);Me.reach&&o.setHeader("x-chatpanel-reach-used",Me.reach);const tr=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Me.thread?.id||null}:null,or=Ye&&{...Ye,dest:{type:"agent",id:M?.id||"bridge"},threadId:Me.thread?.id||null};return Ds(n,o,{...H,pathname:i,agentOverride:M?.agent,harness:Gt,trace:ae,run:Object.keys(Me).length?Me:null,owner:tr,link:or},S,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Kn(),p.close(),f?.stop(),b.stop()}),pe.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(f&&i.startsWith(ca)){f.acceptTunnel(n,o,g).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
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.144.0";export{o as VERSION};
1
+ const o="0.144.1";export{o as VERSION};