@chatpanel/gateway 0.143.2 → 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.143.2",
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.477.3",
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",
@@ -1,5 +1,5 @@
1
- import{createHash as f}from"node:crypto";import{paginateText as c,EXTRACT_TYPES as m}from"../extract-capability.js";import{pdfPages as g}from"./pdf.js";import{docxPages as h}from"./docx.js";import{xlsxPages as w,pptxPages as y,odfPages as b}from"./office-xml.js";const C="chatpanel-extract",T=[["pdf",[37,80,68,70,45]],["zip",[80,75,3,4]]],i={docx:"docx",xlsx:"xlsx",pptx:"pptx",odt:"odt",ods:"ods",odp:"odp",epub:"epub"},d={md:"md",markdown:"md",txt:"txt",text:"txt",csv:"csv",html:"html",htm:"html",json:"txt",xml:"txt",log:"txt"};function x(r){const e=/\.([a-z0-9]{1,8})$/i.exec(String(r||""));return e?e[1].toLowerCase():""}function v(r,{name:e="",hint:a=""}={}){const n=r.subarray(0,8);for(const[t,u]of T)if(u.every((p,l)=>n[l]===p)){if(t!=="zip")return t;const p=x(e);return i[p]?i[p]:i[a]?a:E(r)||"zip"}const o=x(e);if(d[o])return d[o];if(m.includes(a)&&a!=="pdf")return a;const s=r.subarray(0,4096);for(let t=0;t<s.length;t+=1)if(s[t]===0)return"binary";return"txt"}function E(r){const e=Buffer.from(r.subarray(0,4096)).toString("latin1");return e.includes("word/")?"docx":e.includes("xl/")?"xlsx":e.includes("ppt/")?"pptx":e.includes("mimetypeapplication/vnd.oasis.opendocument.text")?"odt":e.includes("mimetypeapplication/vnd.oasis.opendocument.spreadsheet")?"ods":e.includes("mimetypeapplication/vnd.oasis.opendocument.presentation")?"odp":""}function P(r){return f("sha256").update(r).digest("hex")}async function I(r,{name:e="",hint:a=""}={}){const n=r instanceof Uint8Array?r:new Uint8Array(r),o=v(n,{name:e,hint:a}),s={hash:P(n),type:o,title:""};switch(o){case"pdf":{const t=await g(n);return{...s,title:t.title,pages:t.pages,scanned:t.scanned}}case"docx":{const t=await h(n);return{...s,title:t.title,pages:c(t.markdown)}}case"xlsx":return{...s,pages:await w(n)};case"pptx":return{...s,pages:await y(n)};case"odt":case"ods":case"odp":{const t=await b(n,o);return{...s,pages:o==="odt"?c(t.text):t.pages}}case"md":case"txt":case"csv":case"html":{let t=Buffer.from(n).toString("utf8");return o==="html"&&(t=S(t)),{...s,pages:c(t)}}default:{const t=new Error(`extract: no reader for ${o==="binary"?"this file type":o}${e?` (${e})`:""}`);throw t.code="unsupported",t}}}function S(r){return String(r).replace(/<(script|style|noscript)\b[\s\S]*?<\/\1>/gi," ").replace(/<(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\b[^>]*>/gi,`
1
+ import{createHash as f}from"node:crypto";import{paginateText as p,EXTRACT_TYPES as m}from"../extract-capability.js";import{pdfPages as g}from"./pdf.js";import{docxPages as h}from"./docx.js";import{xlsxPages as w,pptxPages as b,odfPages as y}from"./office-xml.js";const B="chatpanel-extract",T=[["pdf",[37,80,68,70,45]],["zip",[80,75,3,4]]],c={docx:"docx",xlsx:"xlsx",pptx:"pptx",odt:"odt",ods:"ods",odp:"odp",epub:"epub"},d={md:"md",markdown:"md",txt:"txt",text:"txt",csv:"csv",html:"html",htm:"html",json:"txt",xml:"txt",log:"txt"};function l(r){const e=/\.([a-z0-9]{1,8})$/i.exec(String(r||""));return e?e[1].toLowerCase():""}function v(r,{name:e="",hint:s=""}={}){const n=r.subarray(0,8);for(const[t,u]of T)if(u.every((i,x)=>n[x]===i)){if(t!=="zip")return t;const i=l(e);return c[i]?c[i]:c[s]?s:E(r)||"zip"}const o=l(e);if(d[o])return d[o];if(m.includes(s)&&s!=="pdf")return s;const a=r.subarray(0,4096);for(let t=0;t<a.length;t+=1)if(a[t]===0)return"binary";return"txt"}function E(r){const e=Buffer.from(r.subarray(0,4096)).toString("latin1");return e.includes("word/")?"docx":e.includes("xl/")?"xlsx":e.includes("ppt/")?"pptx":e.includes("mimetypeapplication/vnd.oasis.opendocument.text")?"odt":e.includes("mimetypeapplication/vnd.oasis.opendocument.spreadsheet")?"ods":e.includes("mimetypeapplication/vnd.oasis.opendocument.presentation")?"odp":""}function P(r){return f("sha256").update(r).digest("hex")}async function C(r,{name:e="",hint:s=""}={}){const n=r instanceof Uint8Array?r:new Uint8Array(r),o=v(n,{name:e,hint:s}),a={hash:P(n),type:o,title:""};switch(o){case"pdf":{const t=await g(n);return{...a,title:t.title,pages:t.pages,scanned:t.scanned,markdown:!!t.markdown,labels:t.labels||[],outline:t.outline||[]}}case"docx":{const t=await h(n);return{...a,title:t.title,pages:p(t.markdown)}}case"xlsx":return{...a,pages:await w(n)};case"pptx":return{...a,pages:await b(n)};case"odt":case"ods":case"odp":{const t=await y(n,o);return{...a,pages:o==="odt"?p(t.text):t.pages}}case"md":case"txt":case"csv":case"html":{let t=Buffer.from(n).toString("utf8");return o==="html"&&(t=S(t)),{...a,pages:p(t)}}default:{const t=new Error(`extract: no reader for ${o==="binary"?"this file type":o}${e?` (${e})`:""}`);throw t.code="unsupported",t}}}function S(r){return String(r).replace(/<(script|style|noscript)\b[\s\S]*?<\/\1>/gi," ").replace(/<(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\b[^>]*>/gi,`
2
2
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/[ \t]+/g," ").replace(/\n[ \t]+/g,`
3
3
  `).replace(/\n{3,}/g,`
4
4
 
5
- `).trim()}export{C as PROVIDER_ID,P as hashOf,I as openDocument,v as typeOf};
5
+ `).trim()}export{B as PROVIDER_ID,P as hashOf,C as openDocument,v as typeOf};
@@ -1 +1 @@
1
- import{validateExtractRequest as w,validateExtractContextRequest as x,MAX_DOCUMENT_BYTES as m}from"../extract-capability.js";import{documentContext as b,documentBudget as _}from"@chatpanel/events/document-context.js";import{isSmallWindow as k}from"@chatpanel/events/context-window.js";import{PROVIDER_ID as h}from"./engine.js";function E(p){const a=p.status();return{id:"extract",route:"/v1/extract",providers:[h],default:h,types:["pdf","docx","xlsx","pptx","odt","ods","odp","md","txt","csv","html"],maxBytes:m,requirements:{egress:"none",deterministic:!0},stats:{opens:a.stats.opens,pages:a.stats.pages,msPerMBp50:a.stats.msPerMBp50},runtime:{name:"worker",state:a.running?"ready":"idle",sandbox:a.sandbox}}}async function B(p,{service:a}={}){let e;try{e=w(p)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}const s=(r,t,n,o={})=>({status:r,body:{error:{message:n,type:t},...o}});try{if(e.kind==="page"){const n=a.known(e.hash);if(!n)return s(404,"unknown_document","that document is not open here — send its bytes again");if(e.page>n.pages)return s(400,"invalid_request",`page must be 1–${n.pages}`);const o=await a.page(e.hash,e.page);return{status:200,body:{hash:e.hash,type:o.type,pages:o.pages,page:e.page,text:o.text,title:n.title||"",provider:h,ms:o.ms}}}const r=Buffer.from(e.data,"base64");if(!r.length)return s(400,"invalid_request","extract: data decoded to nothing");if(r.length>m)return s(413,"too_large",`extract: ${r.length} bytes is over the ${m}-byte limit`);if(e.budgetMs!=null){const n=a.predictMs(r.length);if(n!=null&&n>e.budgetMs)return{status:503,body:{error:{message:`predicted ${n} ms, over the ${e.budgetMs} ms budget`,type:"over_budget"},predictedMs:n}}}const t=await a.open(r,{name:e.name,hint:e.type||""});return{status:200,body:{hash:t.hash,type:t.type,pages:t.pages,title:t.title||"",scanned:!!t.scanned,provider:h,ms:t.ms}}}catch(r){const t=r?.code||"extract_error";return t==="unsupported"?s(415,"unsupported",r.message):t==="unknown_document"?s(404,"unknown_document",r.message):t==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):t==="invalid_request"?s(400,"invalid_request",r.message):s(500,"extract_error",r?.message||String(r))}}async function C(p,{service:a}={}){let e;try{e=x(p)}catch(t){return{status:400,body:{error:{message:t.message,type:"invalid_request"}}}}const s=(t,n,o)=>({status:t,body:{error:{message:o,type:n}}}),r=Date.now();try{const t=[],n=new Map;for(const[i,u]of e.documents.entries()){let c;if(u.hash){const d=a.known(u.hash);if(!d)return s(404,"unknown_document",`documents[${i}]: that document is not open here — send its bytes again`);c={hash:u.hash,pages:d.pages,title:d.title||""}}else{const d=Buffer.from(u.data,"base64");if(!d.length)return s(400,"invalid_request",`documents[${i}]: data decoded to nothing`);if(d.length>m)return s(413,"too_large",`documents[${i}]: ${d.length} bytes is over the ${m}-byte limit`);c=await a.open(d,{name:u.name,hint:u.type||""})}const l=`doc-${i+1}`,f=u.name||c.title||l;t.push({id:l,kind:"path",path:`/${f}`,title:f,isDir:!1,pages:c.pages,hash:c.hash}),n.set(l,{title:f,pages:c.pages,page:async d=>(await a.page(c.hash,d)).text||""})}const o=e.window?k(e.window):!0,y=e.budgetChars||_({window:e.window||4096,small:o}),g=await b({question:e.question,documents:t,open:async i=>n.get(i.id)||null,budgetChars:y});return{status:200,body:{attachment:g.attachment,read:g.read.map(i=>({...i,hash:t.find(u=>u.id===i.id)?.hash||""})),skipped:g.skipped,how:g.how,budgetChars:y,provider:h,ms:Date.now()-r}}}catch(t){const n=t?.code||"extract_error";return n==="unsupported"?s(415,"unsupported",t.message):n==="unknown_document"?s(404,"unknown_document",t.message):n==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):n==="invalid_request"?s(400,"invalid_request",t.message):s(500,"extract_error",t?.message||String(t))}}export{E as extractCapabilityEntry,B as handleExtract,C as handleExtractContext};
1
+ import{validateExtractRequest as w,validateExtractContextRequest as b,MAX_DOCUMENT_BYTES as m}from"../extract-capability.js";import{documentContext as x,documentBudget as _}from"@chatpanel/events/document-context.js";import{isSmallWindow as k}from"@chatpanel/events/context-window.js";import{PROVIDER_ID as h}from"./engine.js";function E(p){const a=p.status();return{id:"extract",route:"/v1/extract",providers:[h],default:h,types:["pdf","docx","xlsx","pptx","odt","ods","odp","md","txt","csv","html"],maxBytes:m,requirements:{egress:"none",deterministic:!0},stats:{opens:a.stats.opens,pages:a.stats.pages,msPerMBp50:a.stats.msPerMBp50},runtime:{name:"worker",state:a.running?"ready":"idle",sandbox:a.sandbox}}}async function B(p,{service:a}={}){let e;try{e=w(p)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}const s=(r,t,n,o={})=>({status:r,body:{error:{message:n,type:t},...o}});try{if(e.kind==="page"){const n=a.known(e.hash);if(!n)return s(404,"unknown_document","that document is not open here — send its bytes again");if(e.page>n.pages)return s(400,"invalid_request",`page must be 1–${n.pages}`);const o=await a.page(e.hash,e.page);return{status:200,body:{hash:e.hash,type:o.type,pages:o.pages,page:e.page,text:o.text,title:n.title||"",provider:h,ms:o.ms}}}const r=Buffer.from(e.data,"base64");if(!r.length)return s(400,"invalid_request","extract: data decoded to nothing");if(r.length>m)return s(413,"too_large",`extract: ${r.length} bytes is over the ${m}-byte limit`);if(e.budgetMs!=null){const n=a.predictMs(r.length);if(n!=null&&n>e.budgetMs)return{status:503,body:{error:{message:`predicted ${n} ms, over the ${e.budgetMs} ms budget`,type:"over_budget"},predictedMs:n}}}const t=await a.open(r,{name:e.name,hint:e.type||""});return{status:200,body:{hash:t.hash,type:t.type,pages:t.pages,title:t.title||"",scanned:!!t.scanned,provider:h,ms:t.ms,...t.markdown?{markdown:!0}:{},...t.labels?{labels:t.labels}:{},...t.outline?{outline:t.outline}:{}}}}catch(r){const t=r?.code||"extract_error";return t==="unsupported"?s(415,"unsupported",r.message):t==="unknown_document"?s(404,"unknown_document",r.message):t==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):t==="invalid_request"?s(400,"invalid_request",r.message):s(500,"extract_error",r?.message||String(r))}}async function C(p,{service:a}={}){let e;try{e=b(p)}catch(t){return{status:400,body:{error:{message:t.message,type:"invalid_request"}}}}const s=(t,n,o)=>({status:t,body:{error:{message:o,type:n}}}),r=Date.now();try{const t=[],n=new Map;for(const[d,u]of e.documents.entries()){let c;if(u.hash){const i=a.known(u.hash);if(!i)return s(404,"unknown_document",`documents[${d}]: that document is not open here — send its bytes again`);c={hash:u.hash,pages:i.pages,title:i.title||""}}else{const i=Buffer.from(u.data,"base64");if(!i.length)return s(400,"invalid_request",`documents[${d}]: data decoded to nothing`);if(i.length>m)return s(413,"too_large",`documents[${d}]: ${i.length} bytes is over the ${m}-byte limit`);c=await a.open(i,{name:u.name,hint:u.type||""})}const g=`doc-${d+1}`,f=u.name||c.title||g;t.push({id:g,kind:"path",path:`/${f}`,title:f,isDir:!1,pages:c.pages,hash:c.hash}),n.set(g,{title:f,pages:c.pages,page:async i=>(await a.page(c.hash,i)).text||""})}const o=e.window?k(e.window):!0,y=e.budgetChars||_({window:e.window||4096,small:o}),l=await x({question:e.question,documents:t,open:async d=>n.get(d.id)||null,budgetChars:y});return{status:200,body:{attachment:l.attachment,read:l.read.map(d=>({...d,hash:t.find(u=>u.id===d.id)?.hash||""})),skipped:l.skipped,how:l.how,budgetChars:y,provider:h,ms:Date.now()-r}}}catch(t){const n=t?.code||"extract_error";return n==="unsupported"?s(415,"unsupported",t.message):n==="unknown_document"?s(404,"unknown_document",t.message):n==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):n==="invalid_request"?s(400,"invalid_request",t.message):s(500,"extract_error",t?.message||String(t))}}export{E as extractCapabilityEntry,B as handleExtract,C as handleExtractContext};
@@ -1 +1 @@
1
- import{pageTextFromItems as f,looksScanned as m}from"@chatpanel/events/pdf-layout.js";let o=null;function d(){return o||(o=Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"),import("pdfjs-dist/legacy/build/pdf.worker.mjs")]).then(([t,s])=>(globalThis.pdfjsWorker||=s,t)).catch(t=>{throw o=null,t})),o}const h=1500;async function P(t,{maxPages:s=h}={}){const c=(await d()).getDocument({data:new Uint8Array(t),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),i=await c.promise;try{const l=await i.getMetadata().catch(()=>null),r=i.numPages,e=[];for(let n=1;n<=Math.min(r,s);n+=1){const a=await i.getPage(n);try{const g=await a.getTextContent(),u=a.getViewport({scale:1});e.push(f(g.items,{pageWidth:u.width}))}finally{a.cleanup()}}const p=l?.info||{};return{title:String(p.Title||"").trim(),pages:e,truncatedPages:r>e.length?r-e.length:0,scanned:m(e.map((n,a)=>({page:a+1,text:n})))}}finally{await c.destroy().catch(()=>{})}}export{h as PDF_MAX_PAGES,P as pdfPages};
1
+ import{linesFromItems as P,looksScanned as k}from"@chatpanel/events/pdf-layout.js";import{structurePages as F}from"@chatpanel/events/pdf-structure.js";let g=null;function S(){return g||(g=Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"),import("pdfjs-dist/legacy/build/pdf.worker.mjs")]).then(([t,s])=>(globalThis.pdfjsWorker||=s,t)).catch(t=>{throw g=null,t})),g}const b=1500;async function D(t,{maxPages:s=b}={}){const i=(await S()).getDocument({data:new Uint8Array(t),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),a=await i.promise;try{const n=await a.getMetadata().catch(()=>null),o=a.numPages,r=[],u=[],f=[];for(let e=1;e<=Math.min(o,s);e+=1){const c=await a.getPage(e);try{const y=await c.getTextContent(),d=c.getViewport({scale:1});r.push(P(y.items)),u.push(d.width),f.push(d.height)}finally{c.cleanup()}}const h=await x(a).catch(()=>[]),m=F(r,{pageWidths:u,pageHeights:f,outline:h}),l=m.pages.map(e=>e.text),w=n?.info||{};return{title:String(w.Title||"").trim(),pages:l,labels:m.pages.map(e=>e.label),outline:h,markdown:!0,truncatedPages:o>l.length?o-l.length:0,scanned:k(l.map((e,c)=>({page:c+1,text:e})))}}finally{await i.destroy().catch(()=>{})}}async function x(t){const s=[],p=async(i,a)=>{for(const n of i||[]){if(s.length>=400)return;let o=0;try{const r=typeof n.dest=="string"?await t.getDestination(n.dest):n.dest;Array.isArray(r)&&r[0]&&(o=await t.getPageIndex(r[0])+1)}catch{}s.push({title:String(n.title||"").trim(),page:o,level:a}),a<2&&n.items?.length&&await p(n.items,a+1)}};return await p(await t.getOutline(),1),s.filter(i=>i.title)}export{b as PDF_MAX_PAGES,D as pdfPages};
@@ -1,2 +1,2 @@
1
- import{spawn as S}from"node:child_process";import{createInterface as E}from"node:readline";import{tmpdir as _}from"node:os";import P from"node:path";import{fileURLToPath as I}from"node:url";const k=600*1e3,D=12e4,v=1e4;function L(){const d=process.execPath,f=P.basename(d).toLowerCase(),g=f.startsWith("node")||f.startsWith("bun"),h=I(new URL("../../bin/chatpanel-gateway.js",import.meta.url));return{program:d,args:[...g?[h]:[],"--extract-worker"]}}function G({wrap:d=null,idleMs:f=k,cacheDir:g=P.join(_(),"chatpanel-extract"),launch:h=L,onLog:T=()=>{}}={}){let a=null,w={layer:"none",reason:"not started"},B=0;const l=new Map;let c=null;const m=new Map,i={opens:0,msPerMB:[],pages:0};function M(){c&&clearTimeout(c),c=setTimeout(()=>x("idle"),f),c.unref&&c.unref()}function y(t){for(const[,n]of l)clearTimeout(n.timer),n.reject(Object.assign(new Error(t),{code:"worker_gone"}));l.clear()}async function O(){if(a)return a;const{program:t,args:n}=h();let r={bin:t,argv:n,opts:{stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_OPTIONS:""}},record:{layer:"none",reason:"no sandbox runner in this gateway"}};if(typeof d=="function")try{r=await d(r.bin,r.argv,r.opts,{engine:"extract",cwd:g})}catch(e){r.record={layer:"none",reason:`sandbox: ${e?.message||e}`}}w=r.record||w,a=S(r.bin,r.argv,{...r.opts,stdio:["pipe","pipe","pipe"]});const o=a;return E({input:o.stdout,crlfDelay:1/0}).on("line",e=>{let s;try{s=JSON.parse(e)}catch{return}const u=l.get(s?.id);u&&(l.delete(s.id),clearTimeout(u.timer),s.ok?u.resolve(s):u.reject(Object.assign(new Error(s.error||"extract failed"),{code:s.code||"extract_error"})))}),o.stderr.on("data",e=>T(String(e).trim())),o.on("exit",(e,s)=>{a===o&&(a=null),m.clear(),y(`extract worker exited (${s||e})`)}),M(),o}function x(t="stopped"){c&&(clearTimeout(c),c=null);const n=a;if(a=null,m.clear(),n){try{n.stdin.end()}catch{}setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},3e3).unref?.()}y(`extract worker ${t}`)}async function b(t,n){const r=await O(),o=++B;return M(),new Promise((p,e)=>{const s=setTimeout(()=>{l.delete(o),e(Object.assign(new Error("extract timed out"),{code:"timeout"})),x("timed out")},n);l.set(o,{resolve:p,reject:e,timer:s}),r.stdin.write(`${JSON.stringify({id:o,...t})}
2
- `)})}return{async open(t,{name:n="",hint:r=""}={}){const o=Date.now(),p=Buffer.isBuffer(t)?t.toString("base64"):Buffer.from(t).toString("base64"),e=await b({op:"open",name:n,hint:r,data:p},D),s=Date.now()-o,u=Math.max(.05,p.length*.75/(1024*1024));return i.opens+=1,i.msPerMB.push(s/u),i.msPerMB.length>50&&i.msPerMB.shift(),m.set(e.hash,{type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,at:Date.now()}),{hash:e.hash,type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,ms:s}},async page(t,n){const r=Date.now(),o=await b({op:"page",hash:t,page:n},v);return i.pages+=1,{text:o.text,pages:o.pages,type:o.type,ms:Date.now()-r}},known:t=>m.get(t)||null,predictMs(t){if(!i.msPerMB.length)return null;const n=[...i.msPerMB].sort((o,p)=>o-p),r=n[Math.floor(n.length/2)];return Math.round(r*Math.max(.05,t/(1024*1024)))},status(){const t=[...i.msPerMB].sort((n,r)=>n-r);return{running:!!a,pid:a?.pid||null,sandbox:w,open:m.size,stats:{opens:i.opens,pages:i.pages,msPerMBp50:t.length?Math.round(t[Math.floor(t.length/2)]):null}}},stop:x}}export{k as IDLE_MS,G as createExtractService,L as workerLaunch};
1
+ import{spawn as k}from"node:child_process";import{createInterface as E}from"node:readline";import{tmpdir as _}from"node:os";import T from"node:path";import{fileURLToPath as I}from"node:url";const D=600*1e3,v=12e4,L=1e4;function j(){const d=process.execPath,f=T.basename(d).toLowerCase(),g=f.startsWith("node")||f.startsWith("bun"),h=I(new URL("../../bin/chatpanel-gateway.js",import.meta.url));return{program:d,args:[...g?[h]:[],"--extract-worker"]}}function J({wrap:d=null,idleMs:f=D,cacheDir:g=T.join(_(),"chatpanel-extract"),launch:h=j,onLog:B=()=>{}}={}){let a=null,w={layer:"none",reason:"not started"},O=0;const l=new Map;let c=null;const m=new Map,i={opens:0,msPerMB:[],pages:0};function M(){c&&clearTimeout(c),c=setTimeout(()=>x("idle"),f),c.unref&&c.unref()}function y(t){for(const[,n]of l)clearTimeout(n.timer),n.reject(Object.assign(new Error(t),{code:"worker_gone"}));l.clear()}async function S(){if(a)return a;const{program:t,args:n}=h();let r={bin:t,argv:n,opts:{stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_OPTIONS:""}},record:{layer:"none",reason:"no sandbox runner in this gateway"}};if(typeof d=="function")try{r=await d(r.bin,r.argv,r.opts,{engine:"extract",cwd:g})}catch(e){r.record={layer:"none",reason:`sandbox: ${e?.message||e}`}}w=r.record||w,a=k(r.bin,r.argv,{...r.opts,stdio:["pipe","pipe","pipe"]});const o=a;return E({input:o.stdout,crlfDelay:1/0}).on("line",e=>{let s;try{s=JSON.parse(e)}catch{return}const u=l.get(s?.id);u&&(l.delete(s.id),clearTimeout(u.timer),s.ok?u.resolve(s):u.reject(Object.assign(new Error(s.error||"extract failed"),{code:s.code||"extract_error"})))}),o.stderr.on("data",e=>B(String(e).trim())),o.on("exit",(e,s)=>{a===o&&(a=null),m.clear(),y(`extract worker exited (${s||e})`)}),M(),o}function x(t="stopped"){c&&(clearTimeout(c),c=null);const n=a;if(a=null,m.clear(),n){try{n.stdin.end()}catch{}setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},3e3).unref?.()}y(`extract worker ${t}`)}async function b(t,n){const r=await S(),o=++O;return M(),new Promise((p,e)=>{const s=setTimeout(()=>{l.delete(o),e(Object.assign(new Error("extract timed out"),{code:"timeout"})),x("timed out")},n);l.set(o,{resolve:p,reject:e,timer:s}),r.stdin.write(`${JSON.stringify({id:o,...t})}
2
+ `)})}return{async open(t,{name:n="",hint:r=""}={}){const o=Date.now(),p=Buffer.isBuffer(t)?t.toString("base64"):Buffer.from(t).toString("base64"),e=await b({op:"open",name:n,hint:r,data:p},v),s=Date.now()-o,u=Math.max(.05,p.length*.75/(1024*1024));i.opens+=1,i.msPerMB.push(s/u),i.msPerMB.length>50&&i.msPerMB.shift();const P={...e.markdown?{markdown:!0}:{},...e.labels?{labels:e.labels}:{},...e.outline?{outline:e.outline}:{}};return m.set(e.hash,{type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,...P,at:Date.now()}),{hash:e.hash,type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,...P,ms:s}},async page(t,n){const r=Date.now(),o=await b({op:"page",hash:t,page:n},L);return i.pages+=1,{text:o.text,pages:o.pages,type:o.type,ms:Date.now()-r}},known:t=>m.get(t)||null,predictMs(t){if(!i.msPerMB.length)return null;const n=[...i.msPerMB].sort((o,p)=>o-p),r=n[Math.floor(n.length/2)];return Math.round(r*Math.max(.05,t/(1024*1024)))},status(){const t=[...i.msPerMB].sort((n,r)=>n-r);return{running:!!a,pid:a?.pid||null,sandbox:w,open:m.size,stats:{opens:i.opens,pages:i.pages,msPerMBp50:t.length?Math.round(t[Math.floor(t.length/2)]):null}}},stop:x}}export{D as IDLE_MS,J as createExtractService,j as workerLaunch};
@@ -1,3 +1,3 @@
1
- import{createInterface as c}from"node:readline";import{openDocument as p}from"./engine.js";const u=24,l=64*1024*1024,s=new Map;function h(n){const o=n.pages.reduce((e,t)=>e+t.length,0);s.delete(n.hash),s.set(n.hash,{...n,chars:o});let r=[...s.values()].reduce((e,t)=>e+t.chars,0);for(;s.size>u||r>l&&s.size>1;){const[e,t]=s.entries().next().value;s.delete(e),r-=t.chars}}async function d(n){const o=n?.id??null,r=(e,t)=>({id:o,ok:!1,code:e,error:t});try{if(n.op==="open"){const e=Buffer.from(String(n.data||""),"base64");if(!e.length)return r("invalid_request","no bytes");const t=await p(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),{name:n.name,hint:n.hint});return h(t),{id:o,ok:!0,hash:t.hash,type:t.type,title:t.title||"",pages:t.pages.length,scanned:!!t.scanned}}if(n.op==="page"){const e=s.get(String(n.hash||""));if(!e)return r("unknown_document","not open here — send the bytes again");const t=Number(n.page);return!Number.isInteger(t)||t<1||t>e.pages.length?r("invalid_request",`page must be 1–${e.pages.length}`):(s.delete(e.hash),s.set(e.hash,e),{id:o,ok:!0,text:e.pages[t-1],pages:e.pages.length,type:e.type})}return n.op==="status"?{id:o,ok:!0,docs:s.size,pid:process.pid}:r("invalid_request",`unknown op ${n.op}`)}catch(e){return r(e?.code==="unsupported"?"unsupported":"extract_error",e?.message||String(e))}}function f({input:n=process.stdin,output:o=process.stdout}={}){try{process.title="chatpanel-extract"}catch{}const r=c({input:n,crlfDelay:1/0});let e=Promise.resolve();r.on("line",t=>{if(!t.trim())return;let a;try{a=JSON.parse(t)}catch{o.write(`${JSON.stringify({id:null,ok:!1,code:"invalid_request",error:"not JSON"})}
1
+ import{createInterface as c}from"node:readline";import{openDocument as l}from"./engine.js";const u=24,p=64*1024*1024,s=new Map;function h(n){const o=n.pages.reduce((e,t)=>e+t.length,0);s.delete(n.hash),s.set(n.hash,{...n,chars:o});let r=[...s.values()].reduce((e,t)=>e+t.chars,0);for(;s.size>u||r>p&&s.size>1;){const[e,t]=s.entries().next().value;s.delete(e),r-=t.chars}}async function d(n){const o=n?.id??null,r=(e,t)=>({id:o,ok:!1,code:e,error:t});try{if(n.op==="open"){const e=Buffer.from(String(n.data||""),"base64");if(!e.length)return r("invalid_request","no bytes");const t=await l(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),{name:n.name,hint:n.hint});return h(t),{id:o,ok:!0,hash:t.hash,type:t.type,title:t.title||"",pages:t.pages.length,scanned:!!t.scanned,...t.markdown?{markdown:!0}:{},...t.labels?.some(Boolean)?{labels:t.labels}:{},...t.outline?.length?{outline:t.outline}:{}}}if(n.op==="page"){const e=s.get(String(n.hash||""));if(!e)return r("unknown_document","not open here — send the bytes again");const t=Number(n.page);return!Number.isInteger(t)||t<1||t>e.pages.length?r("invalid_request",`page must be 1–${e.pages.length}`):(s.delete(e.hash),s.set(e.hash,e),{id:o,ok:!0,text:e.pages[t-1],pages:e.pages.length,type:e.type})}return n.op==="status"?{id:o,ok:!0,docs:s.size,pid:process.pid}:r("invalid_request",`unknown op ${n.op}`)}catch(e){return r(e?.code==="unsupported"?"unsupported":"extract_error",e?.message||String(e))}}function f({input:n=process.stdin,output:o=process.stdout}={}){try{process.title="chatpanel-extract"}catch{}const r=c({input:n,crlfDelay:1/0});let e=Promise.resolve();r.on("line",t=>{if(!t.trim())return;let a;try{a=JSON.parse(t)}catch{o.write(`${JSON.stringify({id:null,ok:!1,code:"invalid_request",error:"not JSON"})}
2
2
  `);return}e=e.then(()=>d(a)).then(i=>{o.write(`${JSON.stringify(i)}
3
3
  `)})}),r.on("close",()=>process.exit(0))}process.argv[1]&&/worker\.js$/.test(process.argv[1])&&!process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED&&f();export{f as runExtractWorker};
package/src/kb.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import{readFileSync as te,statSync as se,readdirSync as xe,realpathSync as ne}from"node:fs";import{join as $e,basename as z,extname as re,resolve as Te,dirname as Oe}from"node:path";import _e from"node:os";import{createKb as ae,addDocument as R,removeDocument as G,addNote as Ee,setNoteStatus as Pe,searchKb as Ke,embedMissing as ze,kbStatus as T,readPage as Me,chunkById as je,refreshKb as U,setKbAccess as Ae,kbMayUse as ie}from"@chatpanel/events/kb-index.js";import{kbResearch as De}from"@chatpanel/events/kb-research.js";import{neighbours as Fe,pathBetween as Le,resolveNode as oe,graphReport as Ge}from"@chatpanel/events/kb-graph.js";import{outlineOf as ce}from"@chatpanel/events/kb-chunk.js";import{routeKb as Be,validateKbCreate as Ne,validateKbAdd as Ce,validateKbSearch as Ie,validateKbResearch as We,validateKbGraph as Re,validateKbNote as Ue,validateKbNoteStatus as Xe,validateKbAccess as He,validateKbSync as Ve}from"@chatpanel/events/kb-capability.js";import{planFolderSync as Ye,folderDocId as Je,folderSource as Qe,knownFiles as Ze}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as qe,markdownLinks as et,resolveLinks as tt,visibleTextHash as st,decodeText as nt}from"@chatpanel/events/kb-html.js";import{secretReason as de,SKIP_DIR_NAMES as rt,sniffType as at,checkAttachablePath as it}from"@chatpanel/events/attached-paths.js";import{paginateText as B,MAX_DOCUMENT_BYTES as X}from"./extract-capability.js";import{defaultEmbeddedModel as ot}from"./embedded-models.js";import{primaryProvider as ct}from"./capability-config.js";const M=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),le=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),dt=new Set([".html",".htm",".xhtml"]),lt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(b,j,E,A={})=>({status:b,body:{error:{type:j,message:E},...A}}),y=b=>({status:200,body:b});function Tt({store:b,extract:j=null,embedded:E=null,cfg:A={},rerank:H=null,read:V=null,completer:Y=null,log:D=()=>{},now:k=()=>Date.now(),home:J=_e.homedir()}={}){const F=()=>{const e=ct(A.capabilities?.embed,"embed",{destinations:A.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||ot("embed")||""},N=(e="passage")=>{const s=F();if(!E||!s)return null;const c=E.health("embed",s);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?(E.embed(s,["warm"],{kind:e}).catch(()=>{}),null):async d=>(await E.embed(s,d,{kind:e})).vectors},ue=typeof H=="function"?H:null,C=new Set;function Q(e){!e||C.has(e.id)||e.embed==="off"||!N("passage")||e.vectors.by.size>=e.chunks.length||(C.add(e.id),K(e).then(s=>{s&&(b.save(e),D(`[kb] ${e.id}: ${s} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>C.delete(e.id)))}async function K(e,{late:s=()=>!1}={}){const c=N("passage");if(!c)return 0;try{return await ze(e,c,{model:F(),late:s})}catch(d){return D(`[kb] ${e.id}: embedding failed — ${d.message}`),0}}async function fe(e,s,c=""){const d=at(e,s);if(d.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(d.text){const u=nt(e);if(/\.x?html?$/i.test(s)||/html/i.test(d.label||"")){const t=qe(u);return{type:"html",pages:B(t.markdown).map((o,f)=>({page:f+1,text:o})),title:t.title,links:t.links,markdown:!0}}const l=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(u.split(`
2
- `).find(t=>t.trim())||""),r=/\.(md|markdown)$/i.test(s);return{type:d.label||"text",pages:B(u).map((t,o)=>({page:o+1,text:t})),title:l?l[1].trim():"",links:r?et(u):[],markdown:r}}if(d.group!=="document")throw Object.assign(new Error(`${d.label||"binary"} is not a document`),{code:"unsupported"});if(!j)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=j(),i=await a.open(e,{name:s,hint:c}),n=[];for(let u=1;u<=i.pages;u+=1){let l="";try{l=String((await a.page(i.hash,u)).text||"")}catch(r){D(`[kb] ${s} p.${u}: ${r.message}`)}n.push({page:u,text:l})}return{type:i.type,pages:n,title:i.title||"",hash:i.hash,scanned:!!i.scanned}}async function I(e,s,{name:c,hint:d="",title:a="",source:i={},reach:n="",id:u="",root:l="",dedupe:r=!1}){const t=await fe(s,c,d),o=st(t.pages.map(w=>w.text).join(`
2
+ `).find(t=>t.trim())||""),r=/\.(md|markdown)$/i.test(s);return{type:d.label||"text",pages:B(u).map((t,o)=>({page:o+1,text:t})),title:l?l[1].trim():"",links:r?et(u):[],markdown:r}}if(d.group!=="document")throw Object.assign(new Error(`${d.label||"binary"} is not a document`),{code:"unsupported"});if(!j)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=j(),i=await a.open(e,{name:s,hint:c}),n=[];for(let u=1;u<=i.pages;u+=1){let l="";try{l=String((await a.page(i.hash,u)).text||"")}catch(r){D(`[kb] ${s} p.${u}: ${r.message}`)}n.push({page:u,text:l})}return{type:i.type,pages:n,title:i.title||"",hash:i.hash,scanned:!!i.scanned,markdown:!!i.markdown,labels:i.labels||[]}}async function I(e,s,{name:c,hint:d="",title:a="",source:i={},reach:n="",id:u="",root:l="",dedupe:r=!1}){const t=await fe(s,c,d),o=st(t.pages.map(w=>w.text).join(`
3
3
  `));if(r&&o){const w=e.docs.find(v=>v.textHash===o&&v.id!==u);if(w)return{duplicateOf:w}}const f=i.path&&t.links?.length?tt(i.path,t.links,{root:l||Oe(i.path)}):[],h=R(e,{id:u,title:a||t.title||z(c),pages:t.pages,source:{kind:i.kind||"bytes",name:c,...i},hash:t.hash||"",type:t.type,reach:n,now:k,links:f,textHash:o,markdownHeadings:!!t.markdown});return{id:h.doc.id,title:h.doc.title,pages:h.doc.pages,chunks:h.doc.chunks,replaced:h.replaced,...t.scanned?{scanned:!0}:{}}}function pe(e,s){const c=re(e).toLowerCase();return!le.has(c)&&!lt.has(c)?!1:s?.length?s.some(d=>{const a=String(d).toLowerCase().replace(/^\*/,"");return c===(a.startsWith(".")?a:`.${a}`)||e.toLowerCase().endsWith(a)}):!0}function Z(e,{recursive:s=!0,include:c=null}={}){const d=it(e,{home:J,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const a=ne(Te(e.replace(/^~(?=$|\/)/,J))),i=[],n=[];let u=0;const l=(o,f)=>{if(i.length>=M.files)return n.push({path:f,why:`stopped at ${M.files} files`}),!1;if(de(o))return n.push({path:f,why:"withheld (a credential store)"}),!0;let h;try{h=se(o)}catch{return!0}const w=re(o).toLowerCase(),v=le.has(w)||dt.has(w)?X:M.textBytes;return h.size>v?(n.push({path:f,why:`too large (${Math.round(h.size/1048576)} MB)`}),!0):u+h.size>M.bytes?(n.push({path:f,why:"stopped: the folder is past the size limit"}),!1):(u+=h.size,i.push({full:o,rel:f,size:h.size,mtime:Math.floor(h.mtimeMs)}),!0)};if(!se(a).isDirectory())return l(a,z(a)),{root:a,files:i,skipped:n,single:!0};const t=(o,f,h)=>{if(h>M.depth)return!0;let w=[];try{w=xe(o,{withFileTypes:!0}).sort((v,S)=>v.name.localeCompare(S.name))}catch{return!0}for(const v of w){const S=v.name;if(S.startsWith(".")&&v.isDirectory())continue;const O=$e(o,S),p=f?`${f}/${S}`:S;if(v.isDirectory()){if(rt.has(S)||!s)continue;try{if(!ne(O).startsWith(a)){n.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!t(O,p,h+1))return!1;continue}if(!(!v.isFile()&&!v.isSymbolicLink())){if(de(O)){n.push({path:p,why:"withheld (a credential store)"});continue}if(pe(S,c)&&!l(O,p))return!1}}return!0};return t(a,"",0),{root:a,files:i,skipped:n}}async function he(e,{path:s,recursive:c=!0,include:d=null,title:a=""}){const{files:i,skipped:n,single:u}=Z(s,{recursive:c,include:d}),l=[];for(const r of i)try{const t=await I(e,te(r.full),{name:z(r.full),title:l.length===0&&(u||!r.rel.includes("/"))?a:"",source:{kind:"file",path:r.full},reach:"internal"});l.push({...t,path:r.rel})}catch(t){n.push({path:r.rel,why:t.message})}return{added:l,skipped:n}}async function me(e,{path:s,include:c=null,rebuild:d=!1},{progress:a=null}={}){const{root:i,files:n,skipped:u}=Z(s,{recursive:!0,include:c}),l=Qe(e,i,{include:c});if(d){for(const p of Object.values(l.files))p?.id&&G(e,p.id,{now:k});l.files={}}const r=new Set(n.map(p=>p.full));for(const[p,x]of Object.entries(l.files))x?.dupOf&&!r.has(x.dupOf)&&delete l.files[p];const t=Ye({known:Ze(l),listing:n.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});a&&(a.total=t.add.length+t.change.length,a.done=0);const o=new Map(n.map(p=>[p.full,p])),f=[];for(const p of t.remove){G(e,p,{now:k});for(const[x,$]of Object.entries(l.files))$.id===p&&(delete l.files[x],f.push(x.startsWith(`${i}/`)?x.slice(i.length+1):x))}const h=[],w=[],v=[],S=p=>String(p||"").startsWith(`${i}/`)?p.slice(i.length+1):p,O=async(p,x)=>{if(a?.cancel)return;await new Promise(m=>setImmediate(m));const $=o.get(p),_=Je(p);try{const m=await I(e,te(p),{name:z(p),source:{kind:"file",path:p},reach:"internal",id:_,root:i,dedupe:!0});m.duplicateOf?(e.docs.some(W=>W.id===_)&&G(e,_,{now:k}),l.files[p]={id:_,size:$.size,mtime:$.mtime,dupOf:m.duplicateOf.source?.path||m.duplicateOf.id},v.push({path:$.rel,of:S(m.duplicateOf.source?.path||m.duplicateOf.title)})):(l.files[p]={id:_,size:$.size,mtime:$.mtime},x.push({...m,path:$.rel}))}catch(m){u.push({path:$.rel,why:m.message})}a&&(a.done+=1)};for(const p of t.add)await O(p,h);for(const p of t.change)await O(p.path,w);return l.syncedAt=k(),l.lastSync={at:l.syncedAt,added:h.length,changed:w.length,removed:f.length,same:t.same,duplicates:v.length,skipped:u.length,skippedSample:u.slice(0,20),duplicateSample:v.slice(0,20)},{root:i,added:h,changed:w,removed:f,same:t.same,duplicates:v,skipped:u}}async function ge(e,{url:s,title:c=""}){if(!V)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const d=await V().read({url:s,format:"markdown"});if(d.status!==200)throw Object.assign(new Error(d.body?.error?.message||`read failed (${d.status})`),{code:"read_failed"});const a=String(d.body.markdown||d.body.text||"");if(!a.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const i=B(a).map((u,l)=>({page:l+1,text:u})),n=R(e,{title:c||d.body.title||s,pages:i,source:{kind:"url",url:d.body.url||s,name:d.body.title||""},type:"html",reach:"web",now:k});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced}}async function be(e,s,{admin:c=!1}={}){const d=k();let a=[],i=[];if(s.kind==="bytes"){const u=Buffer.from(s.data,"base64");if(!u.length)return g(400,"invalid_request","kb: data decoded to nothing");if(u.length>X)return g(413,"too_large",`kb: ${u.length} bytes is over the ${X}-byte limit`);try{a.push(await I(e,u,{name:s.name,hint:s.type||"",title:s.title,reach:s.reach}))}catch(l){return L(l)}}else if(s.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:a,skipped:i}=await he(e,s))}catch(u){return L(u)}}else if(s.kind==="url")try{a.push(await ge(e,s))}catch(u){return L(u)}else if(s.kind==="text"){const u=B(s.text).map((r,t)=>({page:t+1,text:r})),l=R(e,{title:s.title||s.name,pages:u,source:{kind:"text",name:s.name},type:"text",reach:s.reach,now:k});a.push({id:l.doc.id,title:l.doc.title,pages:l.doc.pages,chunks:l.doc.chunks,replaced:l.replaced})}const n=a.length?await K(e):0;return b.save(e),y({added:a,skipped:i,embedded:n,kb:T(e),ms:k()-d})}function L(e){const s=e?.code||"";return s==="refused"?g(403,"refused",`kb: ${e.message}`):s==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):s==="too_large"?g(413,"too_large",`kb: ${e.message}`):s==="read_failed"||s==="empty"?g(502,"read_failed",`kb: ${e.message}`):s==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const q=(e,s)=>Ke(e,s.query,{limit:s.limit,hops:s.hops,docs:s.docs||null,queries:s.queries||[],embed:N("query"),rerank:s.rerank===!1?null:ue,now:k}),ke=(e,s)=>e.docs.find(c=>c.id===s)?.title||s,ee=(e,s)=>{const c=je(e,s);if(!c)return null;const d=c.kind==="note"?"Note":ke(e,c.doc);return{...c,title:d,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${d.replace(/[[\]]/g,"")} p.${c.page}]`}};function ye(e,s){U(e);const c=oe(e.graph,s.node);if(!c)return y({node:null,neighbours:[],message:`no node named "${s.node}"`});const d=i=>{const n=e.graph.nodes.find(u=>u.id===i);return{id:i,label:n?.label||i.replace(/^chunk:/,"passage "),kind:n?.kind||"chunk"}},a={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Fe(e.graph,c.id,{hops:s.hops,kinds:s.kinds||null,limit:s.limit})};if(s.to){const i=oe(e.graph,s.to);a.to=s.to,a.path=i?(Le(e.graph,c.id,i.id)||[]).map(d):null,i&&!a.path.length&&(a.path=null)}return y(a)}async function we(e,s,{admin:c=!1}={}){if(s.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const d=s.model&&typeof Y=="function"?Y(s.model):null,a=T(e),i=await De(s.question,{search:(n,u)=>q(e,{query:n,limit:u.limit||10,hops:u.hops??1,docs:u.docs||s.docs||null}),outline:async n=>n?ce(e.chunks,{doc:n}):e.outline,read:async n=>ee(e,n),complete:d,kbName:e.name,docs:a.documents,previous:s.previous||null,answer:s.answer||"",ask:s.ask!==!1,now:k});return y({attachment:i.attachment,read:i.read,hits:i.hits.map(n=>({id:n.id,doc:n.doc,title:n.title,page:n.page,section:n.section,cite:n.cite,lanes:n.lanes,via:n.via})),queries:i.queries,verdict:i.verdict,rounds:i.rounds,ask:i.ask,how:i.how,frame:{whole:i.frame.whole,docs:i.frame.docs},ms:i.ms})}const P=new Map;async function ve({method:e="GET",pathname:s="",query:c=new URLSearchParams,body:d=null,admin:a=!1,agent:i=""}={}){const n=Be(s);if(!n)return g(404,"not_found",`no route ${s}`);if(n.bad)return g(400,"invalid_request",`kb: "${n.bad}" is not a valid id or route`);const u={admin:a,agent:String(i||c.get("agent")||"").trim().toLowerCase()},l=t=>{try{return{value:t()}}catch(o){return{res:g(400,"invalid_request",o.message)}}};if(!n.id){if(e==="GET")return y({kbs:b.list().filter(({manifest:t})=>ie({access:t.access},u)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=l(()=>Ne(d||{}));if(t.res)return t.res;const o=t.value;if(o.id&&b.load(o.id))return y({kb:T(b.load(o.id)),existed:!0});const f=ae({id:o.id,name:o.name,embed:o.embed,now:k});return b.save(f),{status:201,body:{kb:T(f)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(n.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!a)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");const t=l(()=>Ve(d||{}));if(t.res)return t.res;const o=t.value,f=P.get(n.id);if(f)return{status:202,body:{running:!0,progress:{...f.progress},kb:f.base?T(f.base):null}};let h=b.load(n.id);const w=!h;h||(h=ae({id:n.id,name:o.name||z(String(o.path).replace(/[\\/]+$/,""))||n.id,now:k}),b.save(h));const v=k(),S={done:0,total:0},O=(async()=>{const m=await me(h,o,{progress:S});if(S.cancel)return{cancelled:!0};const W=m.added.length+m.changed.length+m.removed.length,Se=m.added.length||m.changed.length?await K(h):0;return(W||w)&&b.save(h),{folder:m.root,added:m.added,changed:m.changed,removed:m.removed,same:m.same,duplicates:m.duplicates,skipped:m.skipped,embedded:Se,made:w,kb:T(h),ms:k()-v}})();P.set(n.id,{progress:S,base:h}),O.catch(m=>D(`[kb] ${n.id}: sync failed — ${m?.message||m}`)).finally(()=>P.delete(n.id));const p=o.waitMs??5e3;if(p===0)return{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}};let x=null;const $=new Promise(m=>{x=setTimeout(()=>m(null),p)});let _;try{_=await Promise.race([O,$])}catch(m){return clearTimeout(x),L(m)}return clearTimeout(x),_?y(_):{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}}}const r=b.load(n.id);if(!r)return g(404,"not_found",`kb: no knowledge base ${n.id} — POST /v1/kb to create one`);if(!ie(r,u))return g(404,"not_found",`kb: no knowledge base ${n.id} for ${u.agent||"this caller"} — the owner can grant it (POST /v1/kb/${n.id}/access)`);if(!n.sub){if(e==="GET"){P.has(r.id)||Q(r);const t=T(r),o=a?(r.sources||[]).map(f=>({kind:f.kind,path:f.path,files:Object.keys(f.files||{}).length,syncedAt:f.syncedAt||0,...f.lastSync?{lastSync:f.lastSync}:{}})):void 0;return y({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:b.sizeOf(r.id),dir:a?b.dirOf(r.id):void 0,...o?.length?{sources:o}:{},...P.has(r.id)?{syncing:(({done:f,total:h})=>({done:f,total:h}))(P.get(r.id).progress)}:{}}})}if(e==="DELETE"){if(!a)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=P.get(r.id);return t&&(t.progress.cancel=!0),b.remove(r.id),y({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(n.sub){case"documents":{if(e==="POST"&&!n.rest){const t=l(()=>Ce(d||{}));return t.res?t.res:be(r,t.value,{admin:a})}if(e==="DELETE"&&n.rest)return a?G(r,n.rest,{now:k})?(b.save(r),y({ok:!0,kb:T(r)})):g(404,"not_found",`kb: no document ${n.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&n.rest){const t=Number(c.get("page"))||1,o=Me(r,n.rest,t);return o?y(o):g(404,"not_found",`kb: no document ${n.rest}`)}if(e==="GET")return y({documents:T(r).documents});break}case"passages":{if(e==="GET"&&n.rest){const t=ee(r,n.rest);return t?y(t):g(404,"not_found",`kb: no passage ${n.rest}`)}break}case"outline":{if(e==="GET"){U(r);const t=c.get("doc");return y({outline:t?ce(r.chunks,{doc:t}):r.outline})}break}case"search":{if(e==="POST"){const t=l(()=>Ie(d||{}));if(t.res)return t.res;const o=k(),f=await q(r,t.value);return Q(r),y({...f,ms:k()-o})}break}case"research":{if(e==="POST"){const t=l(()=>We(d||{}));return t.res?t.res:we(r,t.value,{admin:a})}break}case"graph":{if(e==="POST"){const t=l(()=>Re(d||{}));return t.res?t.res:ye(r,t.value)}break}case"report":{if(e==="GET")return U(r),{status:200,text:Ge(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return y({notes:r.notes});if(e==="POST"&&!n.rest){const t=l(()=>Ue(d||{}));if(t.res)return t.res;const o=t.value,f=o.status==="accepted"&&a?"accepted":"proposed",h=Ee(r,{text:o.text,cites:o.cites||[],by:o.by||(a?"user":"agent"),status:f,now:k});return await K(r),b.save(r),{status:201,body:{note:h}}}if(e==="POST"&&n.rest){if(!a)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=l(()=>Xe(d||{}));if(t.res)return t.res;const o=t.value,f=Pe(r,n.rest,o.status,{now:k});return f?(b.save(r),y({note:f,removed:o.status==="removed"})):g(404,"not_found",`kb: no note ${n.rest}`)}break}case"access":{if(e==="GET")return y({access:r.access});if(e==="POST"){if(!a)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=l(()=>He(d||{}));if(t.res)return t.res;const o=Ae(r,t.value,{now:k});return b.save(r),y({access:o})}break}case"embed":{if(e==="POST"){const t=F(),o=E&&t?E.health("embed",t):{state:"off"},f=await K(r);return f&&b.save(r),y({embedded:f,vectors:r.vectors.by.size,model:r.vectors.model||t,dims:r.vectors.dims,state:o.state,...o.progress?{progress:o.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${s} is not a route`)}return{handle:ve,store:b,embedModel:F}}export{M as KB_WALK_LIMITS,Tt as createKbService};
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.143.2";export{o as VERSION};
1
+ const o="0.144.1";export{o as VERSION};