@chatpanel/gateway 0.142.0 → 0.143.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.142.0",
3
+ "version": "0.143.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.470.2",
27
+ "@chatpanel/events": "^0.477.2",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
@@ -1 +1 @@
1
- import{pageTextFromItems as f,looksScanned as d}from"@chatpanel/events/pdf-layout.js";let a=null;function m(){return a||(a=import("pdfjs-dist/legacy/build/pdf.mjs").catch(o=>{throw a=null,o})),a}const h=1500;async function P(o,{maxPages:r=h}={}){const c=(await m()).getDocument({data:new Uint8Array(o),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),s=await c.promise;try{const l=await s.getMetadata().catch(()=>null),i=s.numPages,t=[];for(let e=1;e<=Math.min(i,r);e+=1){const n=await s.getPage(e);try{const g=await n.getTextContent(),u=n.getViewport({scale:1});t.push(f(g.items,{pageWidth:u.width}))}finally{n.cleanup()}}const p=l?.info||{};return{title:String(p.Title||"").trim(),pages:t,truncatedPages:i>t.length?i-t.length:0,scanned:d(t.map((e,n)=>({page:n+1,text:e})))}}finally{await c.destroy().catch(()=>{})}}export{h as PDF_MAX_PAGES,P as pdfPages};
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};
@@ -0,0 +1,2 @@
1
+ import{execFile as c}from"node:child_process";import{existsSync as d}from"node:fs";import{delimiter as f,join as u}from"node:path";const p=10*6e4,m=120,h=["on run argv"," activate"," set f to choose folder with prompt (item 1 of argv)"," return POSIX path of f","end run"].join(`
2
+ `),g="Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = $env:CHAP_PICK_PROMPT; $d.ShowNewFolderButton = $false; if ($d.ShowDialog() -eq 'OK') { [Console]::Out.Write($d.SelectedPath) }";function y(s,e,{has:n=()=>!0}={}){return s==="darwin"?{file:"/usr/bin/osascript",args:["-e",h,e],cancelled:r=>/-128|User canceled/i.test(String(r?.stderr||r?.message||""))}:s==="win32"?{file:"powershell.exe",args:["-NoProfile","-STA","-Command",g],env:{CHAP_PICK_PROMPT:e},cancelled:()=>!1}:n("zenity")?{file:"zenity",args:["--file-selection","--directory",`--title=${e}`],cancelled:r=>r?.code===1}:n("kdialog")?{file:"kdialog",args:["--getexistingdirectory","~","--title",e],cancelled:r=>r?.code===1}:null}let a=!1;async function C(s={},{platform:e=process.platform,run:n=P,has:r=w}={}){const l=String(s?.prompt||"Choose a folder for Chap to index").replace(/[\r\n\t]+/g," ").trim().slice(0,m)||"Choose a folder",t=y(e,l,{has:r});if(!t)return{status:501,body:{error:{message:"no folder chooser on this system — type the folder's path instead",type:"unsupported"}}};if(a)return{status:409,body:{error:{message:"a folder chooser is already open — finish or cancel it first",type:"conflict"}}};a=!0;try{const o=await n(t.file,t.args,{timeout:p,env:t.env?{...process.env,...t.env}:process.env}),i=String(o||"").replace(/[\r\n]+$/,"").replace(/(.)\/$/,"$1");return{status:200,body:i?{path:i}:{cancelled:!0}}}catch(o){return t.cancelled(o)?{status:200,body:{cancelled:!0}}:{status:502,body:{error:{message:o?.killed?"the folder chooser did not answer in time":`the folder chooser failed: ${String(o?.stderr||o?.message||o).trim().slice(0,200)}`,type:"upstream"}}}}finally{a=!1}}function P(s,e,n){return new Promise((r,l)=>{c(s,e,{...n,maxBuffer:64*1024,windowsHide:!1},(t,o,i)=>{t?(t.stderr=i,l(t)):r(o)})})}function w(s){return String(process.env.PATH||"").split(f).some(e=>!!e&&d(u(e,s)))}export{p as PICK_FOLDER_TIMEOUT_MS,y as chooserFor,C as handlePickFolder};
package/src/kb.js CHANGED
@@ -1,2 +1,3 @@
1
- import{readFileSync as X,statSync as Y,readdirSync as he,realpathSync as H}from"node:fs";import{join as me,basename as _,extname as J,resolve as ge}from"node:path";import be from"node:os";import{createKb as Q,addDocument as M,removeDocument as V,addNote as ke,setNoteStatus as ye,searchKb as we,embedMissing as ve,kbStatus as S,readPage as xe,chunkById as Se,refreshKb as F,setKbAccess as $e,kbMayUse as Z}from"@chatpanel/events/kb-index.js";import{kbResearch as _e}from"@chatpanel/events/kb-research.js";import{neighbours as Te,pathBetween as Ee,resolveNode as q,graphReport as Oe}from"@chatpanel/events/kb-graph.js";import{outlineOf as ee}from"@chatpanel/events/kb-chunk.js";import{routeKb as Pe,validateKbCreate as Ke,validateKbAdd as ze,validateKbSearch as De,validateKbResearch as Me,validateKbGraph as Fe,validateKbNote as je,validateKbNoteStatus as Ae,validateKbAccess as Be,validateKbSync as Ge}from"@chatpanel/events/kb-capability.js";import{planFolderSync as Le,folderDocId as Ne,folderSource as Ce,knownFiles as Re}from"@chatpanel/events/kb-folder-sync.js";import{secretReason as te,SKIP_DIR_NAMES as We,sniffType as Ie,checkAttachablePath as Ue}from"@chatpanel/events/attached-paths.js";import{paginateText as j,MAX_DOCUMENT_BYTES as A}from"./extract-capability.js";import{defaultEmbeddedModel as Xe}from"./embedded-models.js";import{primaryProvider as Ye}from"./capability-config.js";const T=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),ne=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),He=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),h=(g,E,x,O={})=>({status:g,body:{error:{type:E,message:x},...O}}),b=g=>({status:200,body:g});function ct({store:g,extract:E=null,embedded:x=null,cfg:O={},rerank:B=null,read:G=null,completer:L=null,log:N=()=>{},now:k=()=>Date.now(),home:C=be.homedir()}={}){const P=()=>{const e=Ye(O.capabilities?.embed,"embed",{destinations:O.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Xe("embed")||""},R=(e="passage")=>{const t=P();if(!x||!t)return null;const i=x.health("embed",t);return i.state!=="ready"&&!i.installed?(x.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async o=>(await x.embed(t,o,{kind:e})).vectors},se=typeof B=="function"?B:null;async function K(e,{late:t=()=>!1}={}){const i=R("passage");if(!i)return 0;try{return await ve(e,i,{model:P(),late:t})}catch(o){return N(`[kb] ${e.id}: embedding failed — ${o.message}`),0}}async function re(e,t,i=""){const o=Ie(e,t);if(o.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(o.text){const d=Buffer.from(e).toString("utf8"),u=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(d.split(`
2
- `).find(r=>r.trim())||"");return{type:o.label||"text",pages:j(d).map((r,s)=>({page:s+1,text:r})),title:u?u[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!E)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=E(),c=await a.open(e,{name:t,hint:i}),n=[];for(let d=1;d<=c.pages;d+=1){let u="";try{u=String((await a.page(c.hash,d)).text||"")}catch(r){N(`[kb] ${t} p.${d}: ${r.message}`)}n.push({page:d,text:u})}return{type:c.type,pages:n,title:c.title||"",hash:c.hash,scanned:!!c.scanned}}async function D(e,t,{name:i,hint:o="",title:a="",source:c={},reach:n="",id:d=""}){const u=await re(t,i,o),r=M(e,{id:d,title:a||u.title||_(i),pages:u.pages,source:{kind:c.kind||"bytes",name:i,...c},hash:u.hash||"",type:u.type,reach:n,now:k});return{id:r.doc.id,title:r.doc.title,pages:r.doc.pages,chunks:r.doc.chunks,replaced:r.replaced,...u.scanned?{scanned:!0}:{}}}function ae(e,t){const i=J(e).toLowerCase();return!ne.has(i)&&!He.has(i)?!1:t?.length?t.some(o=>{const a=String(o).toLowerCase().replace(/^\*/,"");return i===(a.startsWith(".")?a:`.${a}`)||e.toLowerCase().endsWith(a)}):!0}function W(e,{recursive:t=!0,include:i=null}={}){const o=Ue(e,{home:C,cwd:process.cwd()});if(!o.ok)throw Object.assign(new Error(o.reason||"that path cannot be attached"),{code:"refused"});const a=H(ge(e.replace(/^~(?=$|\/)/,C))),c=[],n=[];let d=0;const u=(l,p)=>{if(c.length>=T.files)return n.push({path:p,why:`stopped at ${T.files} files`}),!1;if(te(l))return n.push({path:p,why:"withheld (a credential store)"}),!0;let f;try{f=Y(l)}catch{return!0}const y=ne.has(J(l).toLowerCase())?A:T.textBytes;return f.size>y?(n.push({path:p,why:`too large (${Math.round(f.size/1048576)} MB)`}),!0):d+f.size>T.bytes?(n.push({path:p,why:"stopped: the folder is past the size limit"}),!1):(d+=f.size,c.push({full:l,rel:p,size:f.size,mtime:Math.floor(f.mtimeMs)}),!0)};if(!Y(a).isDirectory())return u(a,_(a)),{root:a,files:c,skipped:n,single:!0};const s=(l,p,f)=>{if(f>T.depth)return!0;let y=[];try{y=he(l,{withFileTypes:!0}).sort((m,w)=>m.name.localeCompare(w.name))}catch{return!0}for(const m of y){const w=m.name;if(w.startsWith(".")&&m.isDirectory())continue;const v=me(l,w),$=p?`${p}/${w}`:w;if(m.isDirectory()){if(We.has(w)||!t)continue;try{if(!H(v).startsWith(a)){n.push({path:$,why:"links outside the folder"});continue}}catch{continue}if(!s(v,$,f+1))return!1;continue}if(!(!m.isFile()&&!m.isSymbolicLink())){if(te(v)){n.push({path:$,why:"withheld (a credential store)"});continue}if(ae(w,i)&&!u(v,$))return!1}}return!0};return s(a,"",0),{root:a,files:c,skipped:n}}async function oe(e,{path:t,recursive:i=!0,include:o=null,title:a=""}){const{files:c,skipped:n,single:d}=W(t,{recursive:i,include:o}),u=[];for(const r of c)try{const s=await D(e,X(r.full),{name:_(r.full),title:u.length===0&&(d||!r.rel.includes("/"))?a:"",source:{kind:"file",path:r.full},reach:"internal"});u.push({...s,path:r.rel})}catch(s){n.push({path:r.rel,why:s.message})}return{added:u,skipped:n}}async function ie(e,{path:t,include:i=null}){const{root:o,files:a,skipped:c}=W(t,{recursive:!0,include:i}),n=Ce(e,o,{include:i}),d=Le({known:Re(n),listing:a.map(f=>({path:f.full,size:f.size,mtime:f.mtime}))}),u=new Map(a.map(f=>[f.full,f])),r=[];for(const f of d.remove){V(e,f,{now:k});for(const[y,m]of Object.entries(n.files))m.id===f&&(delete n.files[y],r.push(y.startsWith(`${o}/`)?y.slice(o.length+1):y))}const s=[],l=[],p=async(f,y)=>{const m=u.get(f),w=Ne(f);try{const v=await D(e,X(f),{name:_(f),source:{kind:"file",path:f},reach:"internal",id:w});n.files[f]={id:w,size:m.size,mtime:m.mtime},y.push({...v,path:m.rel})}catch(v){c.push({path:m.rel,why:v.message})}};for(const f of d.add)await p(f,s);for(const f of d.change)await p(f.path,l);return n.syncedAt=k(),{root:o,added:s,changed:l,removed:r,same:d.same,skipped:c}}async function ce(e,{url:t,title:i=""}){if(!G)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await G().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const a=String(o.body.markdown||o.body.text||"");if(!a.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const c=j(a).map((d,u)=>({page:u+1,text:d})),n=M(e,{title:i||o.body.title||t,pages:c,source:{kind:"url",url:o.body.url||t,name:o.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 de(e,t,{admin:i=!1}={}){const o=k();let a=[],c=[];if(t.kind==="bytes"){const d=Buffer.from(t.data,"base64");if(!d.length)return h(400,"invalid_request","kb: data decoded to nothing");if(d.length>A)return h(413,"too_large",`kb: ${d.length} bytes is over the ${A}-byte limit`);try{a.push(await D(e,d,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(u){return z(u)}}else if(t.kind==="path"){if(!i)return h(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:c}=await oe(e,t))}catch(d){return z(d)}}else if(t.kind==="url")try{a.push(await ce(e,t))}catch(d){return z(d)}else if(t.kind==="text"){const d=j(t.text).map((r,s)=>({page:s+1,text:r})),u=M(e,{title:t.title||t.name,pages:d,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:k});a.push({id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced})}const n=a.length?await K(e):0;return g.save(e),b({added:a,skipped:c,embedded:n,kb:S(e),ms:k()-o})}function z(e){const t=e?.code||"";return t==="refused"?h(403,"refused",`kb: ${e.message}`):t==="unsupported"?h(415,"unsupported",`kb: ${e.message}`):t==="too_large"?h(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?h(502,"read_failed",`kb: ${e.message}`):t==="timeout"?h(504,"extract_timeout","kb: the document took too long to parse"):h(500,"kb_error",`kb: ${e?.message||e}`)}const I=(e,t)=>we(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:R("query"),rerank:t.rerank===!1?null:se,now:k}),ue=(e,t)=>e.docs.find(i=>i.id===t)?.title||t,U=(e,t)=>{const i=Se(e,t);if(!i)return null;const o=i.kind==="note"?"Note":ue(e,i.doc);return{...i,title:o,cite:i.kind==="note"?`[note ${i.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${i.page}]`}};function le(e,t){F(e);const i=q(e.graph,t.node);if(!i)return b({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=c=>{const n=e.graph.nodes.find(d=>d.id===c);return{id:c,label:n?.label||c.replace(/^chunk:/,"passage "),kind:n?.kind||"chunk"}},a={node:{id:i.id,kind:i.kind,label:i.label},neighbours:Te(e.graph,i.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const c=q(e.graph,t.to);a.to=t.to,a.path=c?(Ee(e.graph,i.id,c.id)||[]).map(o):null,c&&!a.path.length&&(a.path=null)}return b(a)}async function fe(e,t,{admin:i=!1}={}){if(t.model&&!i)return h(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof L=="function"?L(t.model):null,a=S(e),c=await _e(t.question,{search:(n,d)=>I(e,{query:n,limit:d.limit||10,hops:d.hops??1,docs:d.docs||t.docs||null}),outline:async n=>n?ee(e.chunks,{doc:n}):e.outline,read:async n=>U(e,n),complete:o,kbName:e.name,docs:a.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:k});return b({attachment:c.attachment,read:c.read,hits:c.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:c.queries,verdict:c.verdict,rounds:c.rounds,ask:c.ask,how:c.how,frame:{whole:c.frame.whole,docs:c.frame.docs},ms:c.ms})}async function pe({method:e="GET",pathname:t="",query:i=new URLSearchParams,body:o=null,admin:a=!1,agent:c=""}={}){const n=Pe(t);if(!n)return h(404,"not_found",`no route ${t}`);if(n.bad)return h(400,"invalid_request",`kb: "${n.bad}" is not a valid id or route`);const d={admin:a,agent:String(c||i.get("agent")||"").trim().toLowerCase()},u=s=>{try{return{value:s()}}catch(l){return{res:h(400,"invalid_request",l.message)}}};if(!n.id){if(e==="GET")return b({kbs:g.list().filter(({manifest:s})=>Z({access:s.access},d)).map(({manifest:s})=>({id:s.id,name:s.name,docs:(s.docs||[]).length,updatedAt:s.updatedAt,vectors:s.vectors?.count||0,model:s.vectors?.model||"",access:s.access||{agents:"all"}}))});if(e==="POST"){const s=u(()=>Ke(o||{}));if(s.res)return s.res;const l=s.value;if(l.id&&g.load(l.id))return b({kb:S(g.load(l.id)),existed:!0});const p=Q({id:l.id,name:l.name,embed:l.embed,now:k});return g.save(p),{status:201,body:{kb:S(p)}}}return h(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(n.sub==="sync"){if(e!=="POST")return h(405,"method_not_allowed","kb: sync is POST");if(!a)return h(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");const s=u(()=>Ge(o||{}));if(s.res)return s.res;const l=s.value;let p=g.load(n.id);const f=!p;p||(p=Q({id:n.id,name:l.name||_(String(l.path).replace(/[\\/]+$/,""))||n.id,now:k}));const y=k();let m;try{m=await ie(p,l)}catch($){return z($)}const w=m.added.length+m.changed.length+m.removed.length,v=m.added.length||m.changed.length?await K(p):0;return(w||f)&&g.save(p),b({folder:m.root,added:m.added,changed:m.changed,removed:m.removed,same:m.same,skipped:m.skipped,embedded:v,made:f,kb:S(p),ms:k()-y})}const r=g.load(n.id);if(!r)return h(404,"not_found",`kb: no knowledge base ${n.id} — POST /v1/kb to create one`);if(!Z(r,d))return h(404,"not_found",`kb: no knowledge base ${n.id} for ${d.agent||"this caller"} — the owner can grant it (POST /v1/kb/${n.id}/access)`);if(!n.sub)return e==="GET"?b({kb:{...S(r),bytes:g.sizeOf(r.id),dir:a?g.dirOf(r.id):void 0}}):e==="DELETE"?a?(g.remove(r.id),b({ok:!0})):h(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):h(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(n.sub){case"documents":{if(e==="POST"&&!n.rest){const s=u(()=>ze(o||{}));return s.res?s.res:de(r,s.value,{admin:a})}if(e==="DELETE"&&n.rest)return a?V(r,n.rest,{now:k})?(g.save(r),b({ok:!0,kb:S(r)})):h(404,"not_found",`kb: no document ${n.rest}`):h(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&n.rest){const s=Number(i.get("page"))||1,l=xe(r,n.rest,s);return l?b(l):h(404,"not_found",`kb: no document ${n.rest}`)}if(e==="GET")return b({documents:S(r).documents});break}case"passages":{if(e==="GET"&&n.rest){const s=U(r,n.rest);return s?b(s):h(404,"not_found",`kb: no passage ${n.rest}`)}break}case"outline":{if(e==="GET"){F(r);const s=i.get("doc");return b({outline:s?ee(r.chunks,{doc:s}):r.outline})}break}case"search":{if(e==="POST"){const s=u(()=>De(o||{}));return s.res?s.res:b(await I(r,s.value))}break}case"research":{if(e==="POST"){const s=u(()=>Me(o||{}));return s.res?s.res:fe(r,s.value,{admin:a})}break}case"graph":{if(e==="POST"){const s=u(()=>Fe(o||{}));return s.res?s.res:le(r,s.value)}break}case"report":{if(e==="GET")return F(r),{status:200,text:Oe(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return b({notes:r.notes});if(e==="POST"&&!n.rest){const s=u(()=>je(o||{}));if(s.res)return s.res;const l=s.value,p=l.status==="accepted"&&a?"accepted":"proposed",f=ke(r,{text:l.text,cites:l.cites||[],by:l.by||(a?"user":"agent"),status:p,now:k});return await K(r),g.save(r),{status:201,body:{note:f}}}if(e==="POST"&&n.rest){if(!a)return h(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const s=u(()=>Ae(o||{}));if(s.res)return s.res;const l=s.value,p=ye(r,n.rest,l.status,{now:k});return p?(g.save(r),b({note:p,removed:l.status==="removed"})):h(404,"not_found",`kb: no note ${n.rest}`)}break}case"access":{if(e==="GET")return b({access:r.access});if(e==="POST"){if(!a)return h(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const s=u(()=>Be(o||{}));if(s.res)return s.res;const l=$e(r,s.value,{now:k});return g.save(r),b({access:l})}break}case"embed":{if(e==="POST"){const s=P(),l=x&&s?x.health("embed",s):{state:"off"},p=await K(r);return p&&g.save(r),b({embedded:p,vectors:r.vectors.by.size,model:r.vectors.model||s,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return h(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:pe,store:g,embedModel:P}}export{T as KB_WALK_LIMITS,ct as createKbService};
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(`
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/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createServer as ar}from"node:http";import{loadConfig as Kt}from"./config.js";import{startEntitlementRefresh as sr,maybeRevalidate as ir}from"./entitlement-refresh.js";import{redactSegments as qe,segment as ht,rememberAnswer as Qt}from"./redact.js";import{pipeRestoredStream as lr,pipeRestoredOpenAIStream as dr,makeTokenRestorer as Yt,restoreDeep as cr}from"./stream.js";import{restoreText as ur,gatedDictionary as mr,narrowSpecs as pr,makeToolHarness as hr,placeholderToolNote as yr,placeholderNote as fr,assertEndpointUrl as gr,capRunOptions as wr,isPaired as Xt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Be,isAdminAuthorized as z,callerTrustOf as Je,setPinnedExtensionIds as br,issuePairingCode as vr,claimPairingCode as kr}from"./gateway-token.js";import{createPairAsk as Sr,nativeConfirm as Tr}from"./pair-prompt.js";import{createEngineProbe as xr}from"./local-engine-probe.js";import{randomUUID as _r}from"node:crypto";import{installEgressLedger as Or,egressAudit as Er}from"./egress.js";import{trustSystemCertificates as Pr,systemCaWanted as Zt,systemCaState as $r}from"./system-ca.js";import{initPolicy as Ar,activePolicy as et,applyPolicyToConfig as qt,managedSummary as je,PolicyLoadError as Nr}from"./policy.js";import{routeAllowed as eo,agentAllowed as Mr,egressAllowed as Br}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ze}from"./bridge.js";import{secureFetch as tt}from"./secure-fetch.js";import{fetchCard as ot,forgetCard as Dr,sendMessage as Cr,streamMessage as Ir,getTask as Rr,cancelTask as Lr,knownAgents as Jr,A2AError as to}from"./a2a.js";import{streamBridgeChat as oo,readBridgeToken as Ge,openBridgeChat as jr,acceptedBridgeToken as ro}from"./bridge.js";import{createRelaySession as zr,getRelaySession as no,endRelaySession as He,pumpBridgeStream as Gr,deliverToolResult as ao,toolsToSpecs as Hr,wantsApprovals as Ur,parseToolCallId as so,touchRelaySession as rt}from"./toolrelay.js";import{shaperFor as yt}from"./shape.js";import{startNer as Vr,ensureNer as nt,unionForThisMachine as Fr,skippedCompanions as Wr}from"./ner.js";import{recommendDetector as io}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Kr}from"./log.js";import{saveBackupSecret as Qr,clearBackupSecret as Yr,loadBackupSecret as ft,hasBackupSecret as lo}from"./history-store.js";import{createContextsApi as Xr,handleContexts as Zr}from"./contexts-api.js";let co=null;import{createMemoryStore as qr}from"./memory-store.js";import{createPrefsStore as en}from"./prefs-store.js";import{agentCardFor as uo,runHintFor as mo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as tn}from"@chatpanel/events/agent-thread.js";import{portClashPlan as on,serviceManagerOf as rn,STANDBY_POLL_MS as nn}from"@chatpanel/events/service-standby.js";import{threadTarget as an,frameQuestion as sn,wireMessages as ln,appendExchange as dn,MAX_MESSAGE as po}from"@chatpanel/events/thread-send.js";import{researchStore as cn,researchResponse as un}from"./research.js";import{createTeamStore as mn,loadOrCreateKey as gt}from"./team-store.js";import{createScorecardStore as pn}from"./scorecard-store.js";import{createEngineLedgerStore as hn}from"./engine-ledger-store.js";import{createProjectStore as yn}from"./project-store.js";import{applicationsFor as fn,recruitPass as gn}from"./recruiting.js";import{ensureBridge as wn,holderOf as bn}from"./bridge-supervisor.js";import{checkForUpdate as vn,updateStatus as kn,startUpdate as Sn,updateJob as Tn,installKind as xn}from"./update.js";import{confinedStatus as wt,confinedLine as _n}from"./confine.js";import{appleHelperWanted as On,findAppleHelper as bt}from"./apple-helper-fetch.js";import{createHistoryStore as En}from"./sqlite-store.js";import{createEventStore as Pn}from"./event-store.js";import{createLinkActivity as $n,linkSurface as An,sseUsageTap as Nn,usageOfBody as Mn,GATEWAY_HOST as ho}from"./link-activity.js";import{ingestCloudEvents as Bn,cursorOf as yo}from"./event-sync.js";import{eventStats as Dn,projectYear as Cn}from"./event-stats.js";import{toCloudEvent as vt,ceHostOf as In}from"./cloudevents.js";import{fusionsDocument as Rn,resolveFusionModel as Ln}from"./fusions.js";import{ingestBackups as kt}from"./backup-ingest.js";import{toSearchRecord as fo}from"@chatpanel/events/library.js";import{deriveBackupKey as Jn,openRecord as jn,keyCache as zn,nodeCodec as Gn}from"@chatpanel/events/backup-envelope.js";import Hn from"node:zlib";import*as J from"./ner-engine.js";import St from"node:os";import{capabilitiesDocument as Un,handleDetect as Vn}from"./capabilities.js";import{createExtractService as Fn}from"./extract/service.js";import{workerSandbox as Wn,disposeWorkerSandbox as Kn}from"./worker-sandbox.js";import{createRuntime as Qn,SERVICES as Yn}from"./runtime.js";import{createCapabilityProxy as Xn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Zn}from"./capability-embedded.js";import{EMBEDDED_MODELS as qn,EMBEDDED_IDS as ea}from"./embedded-models.js";import{handleExtract as ta,handleExtractContext as oa}from"./extract/handler.js";import{createKbStore as ra}from"./kb-store.js";import{createKbService as na}from"./kb.js";import{MAX_DOCUMENT_BYTES as Tt}from"./extract-capability.js";import{createReader as aa}from"./retrieval/read.js";import{createBrowserRelayHost as sa}from"./browser-relay.js";import{createLinkHost as ia}from"./link-host.js";import{checkLinkRoute as la,tunnelHeader as da,LINK_TUNNEL_ROOM_PATH as ca}from"@chatpanel/events/link-routes.js";import{linkCallerOf as Ue,linkDestinationAllowed as ua,linkVia as ma,partnerRunHint as pa,PARTNER_APPROVAL_DECISIONS as go,partnerFilePath as ha}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as ya,readPartnerFile as fa,writePartnerFile as ga,removePartnerFile as wa}from"./link-files.js";import{handleFileWrite as ba}from"./file-write.js";import{handleFileRead as va}from"./file-read.js";import{handleAppleNotes as ka}from"./apple-notes.js";import{WRITE_MAX_BYTES as Sa}from"@chatpanel/events/file-write.js";import{isPermissionTool as wo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as Ta}from"./link-approvals.js";import{createSearcher as xa,toJinaSearch as _a,SEARCH_DEFAULTS as Oa}from"./retrieval/search.js";import{createSearxng as Ea}from"./retrieval/search-searxng.js";import{searchEngines as Pa}from"./retrieval/search-apis.js";import{toJinaText as $a}from"./read-document.js";import*as N from"./stt-engine.js";import*as $ from"./diarize-engine.js";import*as $e from"./translate-engine.js";import*as Aa from"./indictrans-engine.js";import*as xt from"./aec-engine.js";import{speechCoverage as Na}from"@chatpanel/events/speech-language.js";import*as Ma from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as Ba,DEFAULT_DIARIZE_MODEL as Da,isKnownDiarizeModel as bo,diarizeModelEntry as Ca}from"./diarize-models.js";import{providerOf as _t}from"./providers.js";import{createRemoteTranscriber as vo}from"./stt-remote.js";import{parseMultipart as Ia,decodeAudioFile as Ra}from"./audio-file.js";import{MODEL_CATALOG as ko,isKnownModel as So,isValidCustomModelId as To,recommendFor as La}from"./models.js";import{STT_MODEL_CATALOG as Ja,isKnownSttModel as ja,isValidCustomSttId as za,DEFAULT_STT_MODEL as De,STT_DTYPES as Ga,isValidDtype as Ha,sttModel as at,sttModelUnavailable as xo,licenseAcceptance as _o}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as Oo,TTS_VOICES as Ua,isKnownTtsModel as Va,isValidCustomTtsId as Fa,isKnownVoice as Eo,isValidVoiceId as Po,DEFAULT_TTS_MODEL as $o,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Wa,isValidTtsDtype as Ka,MAX_TTS_CHARS as Ao,ttsModelHasCustomVoices as Qa,resolveDefaultModel as No,POCKET_VOICES as Ya,DEFAULT_POCKET_VOICE as st,isPocketVoice as it,ttsModelEngine as lt}from"./tts-models.js";import{ttsDestination as Xa,synthesizeRemote as Za,isValidRemoteVoice as qa}from"./tts-remote.js";import{rawOrtAvailable as Ot}from"./ort.js";import*as de from"./tts-voices.js";import{resolveTtsVoice as es}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as ts,consume as os,usage as rs}from"./freegate.js";import{publicConfig as Mo,applyConfigPatch as Bo,registryChildEnv as ns,applyNerModelSelection as Do,persistConfig as be,configPath as ce,bridgeAgentOptions as Co,PERMISSION_MODES as as,sandboxEnvFor as ss,sandboxProblems as is}from"./configstore.js";import{freeLimitProblem as ls}from"./capability-config.js";import Ve from"node:path";import{resolveDestination as dt,aggregateModelsAsync as ds,listDestinations as cs,ensureModelCatalog as us,agentOwnsModel as ms}from"./router.js";import{makeAccessEvent as Io}from"./observability.js";import{createPersistentAccessLog as ps}from"./access-log-store.js";import{planQueries as hs,multiSearch as ys}from"./rrf.js";import*as Et from"./openai.js";import*as Ro from"./responses.js";import*as Pt from"./anthropic.js";import{closeAndExit as fs}from"./shutdown.js";import{VERSION as ue}from"./version.js";import{VERSION as Rl}from"./version.js";const R=await En(),xe=new Set;function Ce({ids:t=[]}={}){const c=R.lossless;if(!c||!xe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const p of xe)try{p.write(`event: records
1
+ import{createServer as ar}from"node:http";import{loadConfig as Kt}from"./config.js";import{startEntitlementRefresh as sr,maybeRevalidate as ir}from"./entitlement-refresh.js";import{redactSegments as qe,segment as ht,rememberAnswer as Qt}from"./redact.js";import{pipeRestoredStream as lr,pipeRestoredOpenAIStream as dr,makeTokenRestorer as Yt,restoreDeep as cr}from"./stream.js";import{restoreText as ur,gatedDictionary as mr,narrowSpecs as pr,makeToolHarness as hr,placeholderToolNote as yr,placeholderNote as fr,assertEndpointUrl as gr,capRunOptions as wr,isPaired as Xt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Be,isAdminAuthorized as j,callerTrustOf as je,setPinnedExtensionIds as br,issuePairingCode as vr,claimPairingCode as kr}from"./gateway-token.js";import{createPairAsk as Sr,nativeConfirm as Tr}from"./pair-prompt.js";import{createEngineProbe as xr}from"./local-engine-probe.js";import{randomUUID as _r}from"node:crypto";import{installEgressLedger as Or,egressAudit as Er}from"./egress.js";import{trustSystemCertificates as Pr,systemCaWanted as Zt,systemCaState as $r}from"./system-ca.js";import{initPolicy as Ar,activePolicy as et,applyPolicyToConfig as qt,managedSummary as ze,PolicyLoadError as Nr}from"./policy.js";import{routeAllowed as eo,agentAllowed as Mr,egressAllowed as Br}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Ge}from"./bridge.js";import{secureFetch as tt}from"./secure-fetch.js";import{fetchCard as ot,forgetCard as Dr,sendMessage as Cr,streamMessage as Ir,getTask as Rr,cancelTask as Jr,knownAgents as Lr,A2AError as to}from"./a2a.js";import{streamBridgeChat as oo,readBridgeToken as He,openBridgeChat as jr,acceptedBridgeToken as ro}from"./bridge.js";import{createRelaySession as zr,getRelaySession as no,endRelaySession as Ue,pumpBridgeStream as Gr,deliverToolResult as ao,toolsToSpecs as Hr,wantsApprovals as Ur,parseToolCallId as so,touchRelaySession as rt}from"./toolrelay.js";import{shaperFor as yt}from"./shape.js";import{startNer as Vr,ensureNer as nt,unionForThisMachine as Fr,skippedCompanions as Wr}from"./ner.js";import{recommendDetector as io}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Kr}from"./log.js";import{saveBackupSecret as Qr,clearBackupSecret as Yr,loadBackupSecret as ft,hasBackupSecret as lo}from"./history-store.js";import{createContextsApi as Xr,handleContexts as Zr}from"./contexts-api.js";let co=null;import{createMemoryStore as qr}from"./memory-store.js";import{createPrefsStore as en}from"./prefs-store.js";import{agentCardFor as uo,runHintFor as mo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as tn}from"@chatpanel/events/agent-thread.js";import{portClashPlan as on,serviceManagerOf as rn,STANDBY_POLL_MS as nn}from"@chatpanel/events/service-standby.js";import{threadTarget as an,frameQuestion as sn,wireMessages as ln,appendExchange as dn,MAX_MESSAGE as po}from"@chatpanel/events/thread-send.js";import{researchStore as cn,researchResponse as un}from"./research.js";import{createTeamStore as mn,loadOrCreateKey as gt}from"./team-store.js";import{createScorecardStore as pn}from"./scorecard-store.js";import{createEngineLedgerStore as hn}from"./engine-ledger-store.js";import{createProjectStore as yn}from"./project-store.js";import{applicationsFor as fn,recruitPass as gn}from"./recruiting.js";import{ensureBridge as wn,holderOf as bn}from"./bridge-supervisor.js";import{checkForUpdate as vn,updateStatus as kn,startUpdate as Sn,updateJob as Tn,installKind as xn}from"./update.js";import{confinedStatus as wt,confinedLine as _n}from"./confine.js";import{appleHelperWanted as On,findAppleHelper as bt}from"./apple-helper-fetch.js";import{createHistoryStore as En}from"./sqlite-store.js";import{createEventStore as Pn}from"./event-store.js";import{createLinkActivity as $n,linkSurface as An,sseUsageTap as Nn,usageOfBody as Mn,GATEWAY_HOST as ho}from"./link-activity.js";import{ingestCloudEvents as Bn,cursorOf as yo}from"./event-sync.js";import{eventStats as Dn,projectYear as Cn}from"./event-stats.js";import{toCloudEvent as vt,ceHostOf as In}from"./cloudevents.js";import{fusionsDocument as Rn,resolveFusionModel as Jn}from"./fusions.js";import{ingestBackups as kt}from"./backup-ingest.js";import{toSearchRecord as fo}from"@chatpanel/events/library.js";import{deriveBackupKey as Ln,openRecord as jn,keyCache as zn,nodeCodec as Gn}from"@chatpanel/events/backup-envelope.js";import Hn from"node:zlib";import*as L from"./ner-engine.js";import St from"node:os";import{capabilitiesDocument as Un,handleDetect as Vn}from"./capabilities.js";import{createExtractService as Fn}from"./extract/service.js";import{workerSandbox as Wn,disposeWorkerSandbox as Kn}from"./worker-sandbox.js";import{createRuntime as Qn,SERVICES as Yn}from"./runtime.js";import{createCapabilityProxy as Xn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Zn}from"./capability-embedded.js";import{EMBEDDED_MODELS as qn,EMBEDDED_IDS as ea}from"./embedded-models.js";import{handleExtract as ta,handleExtractContext as oa}from"./extract/handler.js";import{createKbStore as ra}from"./kb-store.js";import{createKbService as na}from"./kb.js";import{MAX_DOCUMENT_BYTES as Tt}from"./extract-capability.js";import{createReader as aa}from"./retrieval/read.js";import{createBrowserRelayHost as sa}from"./browser-relay.js";import{createLinkHost as ia}from"./link-host.js";import{checkLinkRoute as la,tunnelHeader as da,LINK_TUNNEL_ROOM_PATH as ca}from"@chatpanel/events/link-routes.js";import{linkCallerOf as De,linkDestinationAllowed as ua,linkVia as ma,partnerRunHint as pa,PARTNER_APPROVAL_DECISIONS as go,partnerFilePath as ha}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as ya,readPartnerFile as fa,writePartnerFile as ga,removePartnerFile as wa}from"./link-files.js";import{handleFileWrite as ba}from"./file-write.js";import{handleFileRead as va}from"./file-read.js";import{handleAppleNotes as ka}from"./apple-notes.js";import{handlePickFolder as Sa}from"./folder-picker.js";import{WRITE_MAX_BYTES as Ta}from"@chatpanel/events/file-write.js";import{isPermissionTool as wo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as xa}from"./link-approvals.js";import{createSearcher as _a,toJinaSearch as Oa,SEARCH_DEFAULTS as Ea}from"./retrieval/search.js";import{createSearxng as Pa}from"./retrieval/search-searxng.js";import{searchEngines as $a}from"./retrieval/search-apis.js";import{toJinaText as Aa}from"./read-document.js";import*as N from"./stt-engine.js";import*as $ from"./diarize-engine.js";import*as $e from"./translate-engine.js";import*as Na from"./indictrans-engine.js";import*as xt from"./aec-engine.js";import{speechCoverage as Ma}from"@chatpanel/events/speech-language.js";import*as Ba from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as Da,DEFAULT_DIARIZE_MODEL as Ca,isKnownDiarizeModel as bo,diarizeModelEntry as Ia}from"./diarize-models.js";import{providerOf as _t}from"./providers.js";import{createRemoteTranscriber as vo}from"./stt-remote.js";import{parseMultipart as Ra,decodeAudioFile as Ja}from"./audio-file.js";import{MODEL_CATALOG as ko,isKnownModel as So,isValidCustomModelId as To,recommendFor as La}from"./models.js";import{STT_MODEL_CATALOG as ja,isKnownSttModel as za,isValidCustomSttId as Ga,DEFAULT_STT_MODEL as Ce,STT_DTYPES as Ha,isValidDtype as Ua,sttModel as at,sttModelUnavailable as xo,licenseAcceptance as _o}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as Oo,TTS_VOICES as Va,isKnownTtsModel as Fa,isValidCustomTtsId as Wa,isKnownVoice as Eo,isValidVoiceId as Po,DEFAULT_TTS_MODEL as $o,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Ka,isValidTtsDtype as Qa,MAX_TTS_CHARS as Ao,ttsModelHasCustomVoices as Ya,resolveDefaultModel as No,POCKET_VOICES as Xa,DEFAULT_POCKET_VOICE as st,isPocketVoice as it,ttsModelEngine as lt}from"./tts-models.js";import{ttsDestination as Za,synthesizeRemote as qa,isValidRemoteVoice as es}from"./tts-remote.js";import{rawOrtAvailable as Ot}from"./ort.js";import*as de from"./tts-voices.js";import{resolveTtsVoice as ts}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as os,consume as rs,usage as ns}from"./freegate.js";import{publicConfig as Mo,applyConfigPatch as Bo,registryChildEnv as as,applyNerModelSelection as Do,persistConfig as be,configPath as ce,bridgeAgentOptions as Co,PERMISSION_MODES as ss,sandboxEnvFor as is,sandboxProblems as ls}from"./configstore.js";import{freeLimitProblem as ds}from"./capability-config.js";import Ve from"node:path";import{resolveDestination as dt,aggregateModelsAsync as cs,listDestinations as us,ensureModelCatalog as ms,agentOwnsModel as ps}from"./router.js";import{makeAccessEvent as Io}from"./observability.js";import{createPersistentAccessLog as hs}from"./access-log-store.js";import{planQueries as ys,multiSearch as fs}from"./rrf.js";import*as Et from"./openai.js";import*as Ro from"./responses.js";import*as Pt from"./anthropic.js";import{closeAndExit as gs}from"./shutdown.js";import{VERSION as ue}from"./version.js";import{VERSION as Ll}from"./version.js";const R=await En(),xe=new Set;function Ie({ids:t=[]}={}){const c=R.lossless;if(!c||!xe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const p of xe)try{p.write(`event: records
2
2
  data: ${u}
3
3
 
4
4
  `)}catch{xe.delete(p)}}setInterval(()=>{for(const t of xe)try{t.write(`: ping
@@ -8,29 +8,29 @@ data: ${JSON.stringify(vt(t))}
8
8
 
9
9
  `;for(const u of Ee)try{u.write(c)}catch{Ee.delete(u)}}),setInterval(()=>{for(const t of Ee)try{t.write(`: ping
10
10
 
11
- `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await qr(),me=en(),Ie=pn({key:gt()}),Re=hn({key:gt()}),he=yn({key:gt()}),re=mn({scorecards:Ie,engines:Re}),At=new Set,Lo=(t,c)=>{for(const p of At)try{p({applied:t,by:c,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const p of xe)try{p.write(`event: prefs
11
+ `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await qr(),me=en(),Re=pn({key:gt()}),Je=hn({key:gt()}),he=yn({key:gt()}),re=mn({scorecards:Re,engines:Je}),At=new Set,Jo=(t,c)=>{for(const p of At)try{p({applied:t,by:c,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const p of xe)try{p.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{xe.delete(p)}},Nt=ps(),Jo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),gs=16,ws=/^mcp[_-]/i,jo=t=>t&&t.function&&t.function.name||t&&t.name||"",bs=t=>t&&t.function&&t.function.description||t&&t.description||"";function zo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function vs(t,c){if(!t)return"";if(c==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>zo(b&&(b.content??b))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return zo(u[p].content);return""}const Go=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ks(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function Ss(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Ho=Date.now();function Ts(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function xs(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function _s(t){const c=performance.now(),u={};let p=!1;const b=(f,A)=>{u[f]=Math.round(A*10)/10};return{meta:{},timings:u,mark:b,lap(f,A){b(f,performance.now()-A)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("total",performance.now()-c);const f={...this.meta,timings:u};setImmediate(()=>{t(f),console.log(`[gateway] model=${f.model||"-"} → ${f.dest?`${f.dest}(${f.type})`:"none"} · ${f.redaction==="off"?"redaction OFF (client request)":`redacted ${f.redacted||0}`}${f.sanitized?` · scrubbed ${f.sanitized} hidden`:""}${f.narrowed?` · narrowed -${f.narrowed}`:""} · ${Ts(u)}`)})}}}function Uo(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[p,b]of t.byToken){const f=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),A=f?f[1]:"PII",B=p.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:A,value:b}:{token:B,type:A})}return u}function Os(t,c,u){return Pt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Ro.matches(t)?{kind:"responses",adapter:Ro,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Et,redactable:Et.matches(t),base:u.upstreams?.openai?.baseUrl}}function Mt(t,c){const u=String(t||"");if(Jo.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Jo.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:c.bridge.agent,agentModel:""}}function Vo(t,c){return Mt(t,c).agent}function Es(t,c){if(c!=="openai"||!t)return!1;const u=Et.extractLatestToolResult(t);if(!u)return!1;const p=so(u.tool_call_id);return!!(p&&no(p.gwId))}function Ps(t,c){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",f=u.port||(u.protocol==="https:"?"443":"80");return b&&String(f)===String(c.port)}catch{return!1}}const $s=25*1024*1024;async function k(t,c){const u=[];let p=0;for await(const b of t){if(p+=b.length,c&&p>c){const f=new Error("payload too large");throw f.code=413,f}u.push(b)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Fo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Bt(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const p=J.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:J.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function Wo(t){if(J.state()!=="off"){const u=J.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=Fo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await tt(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:p.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function As(t,c){const u={};for(const[p,b]of Object.entries(t)){const f=p.toLowerCase();f.startsWith("x-chatpanel-")||Go.has(f)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function Ko(t,c,u,p){const b=Yt(c.vault),f=Ct();t.on("close",()=>{t.writableFinished||He(c.id)});const A=c.linkTurn||null,B=p?p.clock():0;let E=B,T=!0;const _=()=>{p&&T&&(p.lap("upstream",B),E=p.clock(),T=!1)};let L="";const j=()=>{c.redaction&&L&&Qt(L,c.redaction),L=""};let F=null;const P={onText:V=>{_(),rt(c.id);const G=b.push(V);G&&(L+=G,t.write(u.sseDelta(G)))},onToolRequest:({name:V,restoredArgs:G,toolId:Z})=>{if(_(),rt(c.id),c.ownerApprovals&&wo(V)){F=G;return}const te=b.flush();te&&(L+=te,t.write(u.sseDelta(te))),t.write(u.sseToolCalls([{id:Z,name:V,arguments:JSON.stringify(G)}])),t.write(u.sseToolFinish(f.value)),p&&p.lap("stream",E),t.end(),p?.commit(),j()},onDone:()=>{const V=b.flush();V&&(L+=V,t.write(u.sseDelta(V))),t.write(u.sseTail(f.value)),p&&p.lap("stream",E),t.end(),A?.end("ok"),He(c.id),p?.commit(),j(),Dt(c)},onError:V=>{t.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
14
+ `)}catch{xe.delete(p)}},Nt=hs(),Lo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ws=16,bs=/^mcp[_-]/i,jo=t=>t&&t.function&&t.function.name||t&&t.name||"",vs=t=>t&&t.function&&t.function.description||t&&t.description||"";function zo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function ks(t,c){if(!t)return"";if(c==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>zo(b&&(b.content??b))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return zo(u[p].content);return""}const Go=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function Ss(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function Ts(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Ho=Date.now();function xs(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function _s(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function Os(t){const c=performance.now(),u={};let p=!1;const b=(f,A)=>{u[f]=Math.round(A*10)/10};return{meta:{},timings:u,mark:b,lap(f,A){b(f,performance.now()-A)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("total",performance.now()-c);const f={...this.meta,timings:u};setImmediate(()=>{t(f),console.log(`[gateway] model=${f.model||"-"} → ${f.dest?`${f.dest}(${f.type})`:"none"} · ${f.redaction==="off"?"redaction OFF (client request)":`redacted ${f.redacted||0}`}${f.sanitized?` · scrubbed ${f.sanitized} hidden`:""}${f.narrowed?` · narrowed -${f.narrowed}`:""} · ${xs(u)}`)})}}}function Uo(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[p,b]of t.byToken){const f=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),A=f?f[1]:"PII",B=p.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:A,value:b}:{token:B,type:A})}return u}function Es(t,c,u){return Pt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Ro.matches(t)?{kind:"responses",adapter:Ro,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Et,redactable:Et.matches(t),base:u.upstreams?.openai?.baseUrl}}function Mt(t,c){const u=String(t||"");if(Lo.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Lo.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:c.bridge.agent,agentModel:""}}function Vo(t,c){return Mt(t,c).agent}function Ps(t,c){if(c!=="openai"||!t)return!1;const u=Et.extractLatestToolResult(t);if(!u)return!1;const p=so(u.tool_call_id);return!!(p&&no(p.gwId))}function $s(t,c){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",f=u.port||(u.protocol==="https:"?"443":"80");return b&&String(f)===String(c.port)}catch{return!1}}const As=25*1024*1024;async function k(t,c){const u=[];let p=0;for await(const b of t){if(p+=b.length,c&&p>c){const f=new Error("payload too large");throw f.code=413,f}u.push(b)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Fo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Bt(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const p=L.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:L.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function Wo(t){if(L.state()!=="off"){const u=L.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=Fo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await tt(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:p.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function Ns(t,c){const u={};for(const[p,b]of Object.entries(t)){const f=p.toLowerCase();f.startsWith("x-chatpanel-")||Go.has(f)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function Ko(t,c,u,p){const b=Yt(c.vault),f=Ct();t.on("close",()=>{t.writableFinished||Ue(c.id)});const A=c.linkTurn||null,B=p?p.clock():0;let E=B,T=!0;const _=()=>{p&&T&&(p.lap("upstream",B),E=p.clock(),T=!1)};let J="";const z=()=>{c.redaction&&J&&Qt(J,c.redaction),J=""};let F=null;const P={onText:V=>{_(),rt(c.id);const G=b.push(V);G&&(J+=G,t.write(u.sseDelta(G)))},onToolRequest:({name:V,restoredArgs:G,toolId:Z})=>{if(_(),rt(c.id),c.ownerApprovals&&wo(V)){F=G;return}const te=b.flush();te&&(J+=te,t.write(u.sseDelta(te))),t.write(u.sseToolCalls([{id:Z,name:V,arguments:JSON.stringify(G)}])),t.write(u.sseToolFinish(f.value)),p&&p.lap("stream",E),t.end(),p?.commit(),z()},onDone:()=>{const V=b.flush();V&&(J+=V,t.write(u.sseDelta(V))),t.write(u.sseTail(f.value)),p&&p.lap("stream",E),t.end(),A?.end("ok"),Ue(c.id),p?.commit(),z(),Dt(c)},onError:V=>{t.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),A?.end("error",{code:"bridge_error"}),He(c.id),p?.commit(),Dt(c)},onUsage:V=>{f.add(V),A?.add(V)}};for(;;){if(F=null,await Gr(c,P)!=="parked"||!F)return;const G=c.ownerApprovals,Z=new AbortController,te=()=>Z.abort();t.once("close",te);const oe=setInterval(()=>{rt(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
16
+ `),t.end(),A?.end("error",{code:"bridge_error"}),Ue(c.id),p?.commit(),Dt(c)},onUsage:V=>{f.add(V),A?.add(V)}};for(;;){if(F=null,await Gr(c,P)!=="parked"||!F)return;const G=c.ownerApprovals,Z=new AbortController,te=()=>Z.abort();t.once("close",te);const oe=setInterval(()=>{rt(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);oe.unref?.();let ye;try{ye=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:Z.signal})}finally{clearInterval(oe),t.off("close",te)}if(Z.signal.aborted||t.writableEnded){Dt(c);return}try{await ao(c,JSON.stringify(ye))}catch(X){P.onError(X);return}}}function Dt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ns(t,c,{kind:u,adapter:p,agent:b,run:f=null,owner:A=null,linkTurn:B=null},E,T,_,L,j,F=null,P=null){const{messages:V,system:G}=p.toTurn(E),{agentModel:Z}=Mt(E?.model,_),te=Co(_,{...Z?{model:Z}:{},...f||{}}),oe=Ge(_.bridge.token),ye=yt(u,E?.model||b),X={tier:_.redaction.tier==="full"?"full":"basic",dictionary:mr(_.redaction,L),entities:[]},ge=await ze(_),I=zr({vault:T,redactOpts:X,bridgeUrl:ge,token:oe,harness:F});A&&(I.ownerApprovals={...A,conversation:A.conversation||`partner.${A.device}.turn-${I.id}`,turnScoped:!A.conversation}),B&&(I.linkTurn=B,I.onEnd=()=>B.end("aborted")),T&&(I.redaction=_.redaction);let ee;try{ee=await jr({bridgeUrl:ge,agent:b,token:oe,messages:V,system:G,specs:Hr(j),options:te,signal:void 0,approvals:!!A||Ur(j)})}catch(pe){return B?.end("error",{code:"bridge_error"}),He(I.id),P?.commit(),a(c,502,{error:{message:`bridge: ${pe.message}`,type:"bridge_error"}})}return I.reader=ee.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(ye.sseHead()),Ko(c,I,ye,P)}async function Ms(t,c,u,p,b=null){rt(c.id),c.rounds=(c.rounds||0)+1;try{const A=b?b.clock():0;await ao(c,u),b&&b.lap("redact",A)}catch(A){return c.linkTurn?.end("error",{code:"tool_result"}),He(c.id),b?.commit(),a(t,502,{error:{message:`tool-result: ${A.message}`,type:"bridge_error"}})}const f=yt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(f.sseHead()),Ko(t,c,f,b)}function Ct(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(c))c[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?c:null}}}async function Bs(t,c,{kind:u,adapter:p,redactable:b,pathname:f,agentOverride:A,harness:B,trace:E,run:T=null,owner:_=null,link:L=null},j,F,P,V){if(!b)return E?.commit(),a(c,404,{error:`endpoint ${f} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(j);if(K){const S=so(K.tool_call_id),ie=S&&no(S.gwId);if(ie)return Ms(c,ie,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||_)&&j?.stream===!0){const S=A||Vo(j?.model,P),ie=L?$t.begin({...L,agentId:S}):null;return Ns(t,c,{kind:u,adapter:p,agent:S,run:T,owner:_,linkTurn:ie},j,F,P,V,W,B,E)}}const{messages:G,system:Z}=p.toTurn(j),te=A||Vo(j?.model,P),oe=L?$t.begin({...L,agentId:te}):null,ye=j?.stream===!0,X=yt(u,j?.model||te),ge=Ge(P.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:ee}=Mt(j?.model,P),pe={bridgeUrl:await ze(P),agent:te,token:ge,messages:G,system:Z,signal:I.signal,options:Co(P,{...ee?{model:ee}:{},...T||{}})};if(!ye)try{let K="";const W=Ct(),S=E?E.clock():0;await oo(pe,Ae=>{K+=Ae},null,Ae=>W.add(Ae)),E&&E.lap("upstream",S);const ie=E?E.clock():0,We=X.full(ur(K,F),W.value);return E&&E.lap("restore",ie),c.writeHead(200,{"content-type":X.contentType}),c.end(We),oe?.add(W.value),oe?.end("ok"),E?.commit()}catch(K){return oe?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.commit(),a(c,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(X.sseHead());const n=Yt(F),o=E?E.clock():0;let g=o;const i=Ct();let q="",H=!1;try{let K=!0;await oo(pe,S=>{E&&K&&(E.lap("upstream",o),g=E.clock(),K=!1);const ie=n.push(S);ie&&(q+=ie,c.write(X.sseDelta(ie)))},X.sseActivity?S=>{try{c.write(X.sseActivity(cr(S,F)))}catch{}}:null,S=>i.add(S));const W=n.flush();W&&(q+=W,c.write(X.sseDelta(W))),c.write(X.sseTail(i.value))}catch(K){H=!0,c.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
18
+ `)},15e3);oe.unref?.();let ye;try{ye=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:Z.signal})}finally{clearInterval(oe),t.off("close",te)}if(Z.signal.aborted||t.writableEnded){Dt(c);return}try{await ao(c,JSON.stringify(ye))}catch(X){P.onError(X);return}}}function Dt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ms(t,c,{kind:u,adapter:p,agent:b,run:f=null,owner:A=null,linkTurn:B=null},E,T,_,J,z,F=null,P=null){const{messages:V,system:G}=p.toTurn(E),{agentModel:Z}=Mt(E?.model,_),te=Co(_,{...Z?{model:Z}:{},...f||{}}),oe=He(_.bridge.token),ye=yt(u,E?.model||b),X={tier:_.redaction.tier==="full"?"full":"basic",dictionary:mr(_.redaction,J),entities:[]},ge=await Ge(_),I=zr({vault:T,redactOpts:X,bridgeUrl:ge,token:oe,harness:F});A&&(I.ownerApprovals={...A,conversation:A.conversation||`partner.${A.device}.turn-${I.id}`,turnScoped:!A.conversation}),B&&(I.linkTurn=B,I.onEnd=()=>B.end("aborted")),T&&(I.redaction=_.redaction);let ee;try{ee=await jr({bridgeUrl:ge,agent:b,token:oe,messages:V,system:G,specs:Hr(z),options:te,signal:void 0,approvals:!!A||Ur(z)})}catch(pe){return B?.end("error",{code:"bridge_error"}),Ue(I.id),P?.commit(),a(c,502,{error:{message:`bridge: ${pe.message}`,type:"bridge_error"}})}return I.reader=ee.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(ye.sseHead()),Ko(c,I,ye,P)}async function Bs(t,c,u,p,b=null){rt(c.id),c.rounds=(c.rounds||0)+1;try{const A=b?b.clock():0;await ao(c,u),b&&b.lap("redact",A)}catch(A){return c.linkTurn?.end("error",{code:"tool_result"}),Ue(c.id),b?.commit(),a(t,502,{error:{message:`tool-result: ${A.message}`,type:"bridge_error"}})}const f=yt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(f.sseHead()),Ko(t,c,f,b)}function Ct(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(c))c[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?c:null}}}async function Ds(t,c,{kind:u,adapter:p,redactable:b,pathname:f,agentOverride:A,harness:B,trace:E,run:T=null,owner:_=null,link:J=null},z,F,P,V){if(!b)return E?.commit(),a(c,404,{error:`endpoint ${f} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(z);if(K){const S=so(K.tool_call_id),ie=S&&no(S.gwId);if(ie)return Bs(c,ie,K.content,z?.model,E)}const W=p.extractTools(z);if((W.length||_)&&z?.stream===!0){const S=A||Vo(z?.model,P),ie=J?$t.begin({...J,agentId:S}):null;return Ms(t,c,{kind:u,adapter:p,agent:S,run:T,owner:_,linkTurn:ie},z,F,P,V,W,B,E)}}const{messages:G,system:Z}=p.toTurn(z),te=A||Vo(z?.model,P),oe=J?$t.begin({...J,agentId:te}):null,ye=z?.stream===!0,X=yt(u,z?.model||te),ge=He(P.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:ee}=Mt(z?.model,P),pe={bridgeUrl:await Ge(P),agent:te,token:ge,messages:G,system:Z,signal:I.signal,options:Co(P,{...ee?{model:ee}:{},...T||{}})};if(!ye)try{let K="";const W=Ct(),S=E?E.clock():0;await oo(pe,Ae=>{K+=Ae},null,Ae=>W.add(Ae)),E&&E.lap("upstream",S);const ie=E?E.clock():0,We=X.full(ur(K,F),W.value);return E&&E.lap("restore",ie),c.writeHead(200,{"content-type":X.contentType}),c.end(We),oe?.add(W.value),oe?.end("ok"),E?.commit()}catch(K){return oe?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.commit(),a(c,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(X.sseHead());const n=Yt(F),o=E?E.clock():0;let g=o;const i=Ct();let q="",H=!1;try{let K=!0;await oo(pe,S=>{E&&K&&(E.lap("upstream",o),g=E.clock(),K=!1);const ie=n.push(S);ie&&(q+=ie,c.write(X.sseDelta(ie)))},X.sseActivity?S=>{try{c.write(X.sseActivity(cr(S,F)))}catch{}}:null,S=>i.add(S));const W=n.flush();W&&(q+=W,c.write(X.sseDelta(W))),c.write(X.sseTail(i.value))}catch(K){H=!0,c.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
19
19
 
20
- `)}E&&E.lap("stream",g),c.end(),oe&&(oe.add(i.value),oe.end(I.signal.aborted?"aborted":H?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&q&&Qt(q,P.redaction)}function Ds(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(c||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+c+u:p+c+u}const Qo=9e4,It=60,Yo=It*16e3*4,Cs=4e3;function Is(t,c,u){if(c===u)return t;const p=c/u,b=new Float32Array(Math.floor(t.length/p));for(let f=0;f<b.length;f++){const A=f*p,B=Math.floor(A),E=Math.min(t.length-1,B+1),T=A-B;b[f]=t[B]*(1-T)+t[E]*T}return b}const Xo=new WeakMap,Rs=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function Zo(t,c){const u=at(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?_o(u):null}function Rt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,c,u,p,{method:b="GET",timeoutMs:f=8e3,pick:A=B=>B}={}){const B=await ze(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=Ge(u.bridge?.token),T=b!=="GET"&&b!=="DELETE";try{const _=T?(await k(t,u.maxBodyBytes)).toString("utf8"):"",L=await fetch(`${B}${p}`,{method:b,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:_||"{}"}:{},signal:AbortSignal.timeout(f)}),j=await L.json().catch(()=>({}));return L.ok?a(c,200,A(j)):a(c,L.status,{error:{message:j?.error||`bridge ${L.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Lt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Le(t,c){const u=new URLSearchParams;for(const f of t.searchParams.getAll("dir"))f&&u.append("dir",f);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function Ls(t,c,{adapter:u,kind:p,pathname:b,search:f,base:A,destKey:B,destProtocol:E,harness:T,trace:_,link:L=null},j,F){let P;const V=_?_.clock():0,G=L?$t.begin(L):null;let Z=!1;const te=new AbortController;c.on("close",()=>{c.writableFinished||(Z=!0,te.abort())});const oe=(I,ee)=>{G&&(G.add(ee),G.end(Z?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=As(t.headers,A);B&&(E==="anthropic"?(I["x-api-key"]=B,delete I.authorization):I.authorization=`Bearer ${B}`);const ee=gr(Ds(A,b,f)).toString();P=await fetch(ee,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:j,signal:te.signal})}catch(I){return Z?(oe(499),_?.commit()):(G?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const ye=P.headers.get("content-type")||"",X={};if(P.headers.forEach((I,ee)=>{Go.has(ee.toLowerCase())||(X[ee]=I)}),ye.includes("text/event-stream")&&P.body){_&&_.lap("upstream",V);const I=_?_.clock():0;c.writeHead(P.status,X);const ee=G?Nn():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?dr(pe,c,F,T):lr(pe,c,F);return Promise.resolve(n).catch(o=>{if(!Z)throw o}).finally(()=>{_&&_.lap("stream",I),oe(P.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(I){if(Z)return oe(499),_?.commit();throw I}if(_&&_.lap("upstream",V),G&&oe(P.status,ye.includes("json")?Mn(ge.toString("utf8")):null),F&&ye.includes("application/json"))try{const I=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,T);return _&&_.lap("restore",I),c.writeHead(P.status,{...X,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}c.writeHead(P.status,X),c.end(ge),_?.commit()}function Js(t=Kt()){const c=xr({first:async n=>{const o=Number(new URL(n).port),g=Yn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return g&&(await j())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=Sr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Tr(n),newId:()=>_r()}),p=sa({version:ue}),b=Ta({log:n=>console.log(` ${n}`)}),f=t.link?.enabled===!1?null:ia({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:i,device:q,signal:H})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:i,...H?{signal:H}:{},headers:{...g,"x-chatpanel-token":Be()||_e(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==$.activeModel()&&(bo(t.stt.diarizeModel)?$.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Da}`));let A=null;const B=()=>{if(!A){const n=t.read||{};A=aa({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return A};let E=null;const T=()=>(E||(E=Fn({wrap:(n,o,g,i)=>Wn().wrap(n,o,g,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let _={at:0,fn:()=>"unknown"},L=null;async function j(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const i=await P().health();for(const[q,H]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===q).flatMap(W=>[W.id,...W.models||[]]);for(const W of[q,...K])n.set(W,H)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",g=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return P().contextWindow(g.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(g.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let F=null;const P=()=>(F||(F=Qn({cfg:t,bridgeHealth:async()=>{const n=await ze(t);if(!n)return null;const o=Ge(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{be(t,ce())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ve.join(Ve.dirname(ce()),"runtime"),workers:()=>{const n=E?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),F),V=Number(t.runtime?.idleMinutes),G=Zn({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:n=>console.log(n)}),Z=Xn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:G,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=na({store:ra({log:n=>console.warn(`[kb] ${n}`)}),extract:T,embedded:G,cfg:t,rerank:async(n,o)=>{const g=await Z.call("rerank",{query:n,documents:o.map(q=>String(q).slice(0,2e3))});if(g.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of g.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>B(),completer:n=>async(o,{maxTokens:g=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const H=Be()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:g,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:n=>console.warn(n)})),te),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let X=null;const ge=()=>{if(!X){const n=t.search||{},o=n.searxng?.url?Ea({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;X=xa({reader:B(),searxng:o,engines:()=>Pa(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let i=g;return await qe([ht(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return X};br(t.allowedExtensionIds||[]);const I=[],ee=n=>{I.push(n),I.length>50&&I.shift()},pe=ar(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1");let i=g.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!ks(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&da(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&Ss(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return z(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!z(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=vr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=kr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Je(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Je(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await ro(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Je(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Xt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await ro(t);return a(o,200,{ok:!0,status:r,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Je(n);return a(o,200,{ok:!0,trust:e,paired:Xt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return z(n)?a(o,200,Er(t,{version:ue,startedAt:Ho,managed:je(),certificates:{...$r(),wanted:Zt(t)},linkPartners:f?f.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ve.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!z(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await vn(ue,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:ue,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Tn()})}if(i==="/update"&&n.method==="POST"){const e=Sn(ue);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!z(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&n.method!=="GET"&&i!=="/v1/contexts/suggest"&&!z(n))return a(o,403,{error:{message:"contexts write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!z(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!z(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!z(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!z(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!z(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ue} is running.
20
+ `)}E&&E.lap("stream",g),c.end(),oe&&(oe.add(i.value),oe.end(I.signal.aborted?"aborted":H?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&q&&Qt(q,P.redaction)}function Cs(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(c||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+c+u:p+c+u}const Qo=9e4,It=60,Yo=It*16e3*4,Is=4e3;function Rs(t,c,u){if(c===u)return t;const p=c/u,b=new Float32Array(Math.floor(t.length/p));for(let f=0;f<b.length;f++){const A=f*p,B=Math.floor(A),E=Math.min(t.length-1,B+1),T=A-B;b[f]=t[B]*(1-T)+t[E]*T}return b}const Xo=new WeakMap,Js=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function Zo(t,c){const u=at(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?_o(u):null}function Rt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,c,u,p,{method:b="GET",timeoutMs:f=8e3,pick:A=B=>B}={}){const B=await Ge(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=He(u.bridge?.token),T=b!=="GET"&&b!=="DELETE";try{const _=T?(await k(t,u.maxBodyBytes)).toString("utf8"):"",J=await fetch(`${B}${p}`,{method:b,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:_||"{}"}:{},signal:AbortSignal.timeout(f)}),z=await J.json().catch(()=>({}));return J.ok?a(c,200,A(z)):a(c,J.status,{error:{message:z?.error||`bridge ${J.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Jt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Le(t,c){const u=new URLSearchParams;for(const f of t.searchParams.getAll("dir"))f&&u.append("dir",f);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function Ls(t,c,{adapter:u,kind:p,pathname:b,search:f,base:A,destKey:B,destProtocol:E,harness:T,trace:_,link:J=null},z,F){let P;const V=_?_.clock():0,G=J?$t.begin(J):null;let Z=!1;const te=new AbortController;c.on("close",()=>{c.writableFinished||(Z=!0,te.abort())});const oe=(I,ee)=>{G&&(G.add(ee),G.end(Z?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=Ns(t.headers,A);B&&(E==="anthropic"?(I["x-api-key"]=B,delete I.authorization):I.authorization=`Bearer ${B}`);const ee=gr(Cs(A,b,f)).toString();P=await fetch(ee,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:te.signal})}catch(I){return Z?(oe(499),_?.commit()):(G?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const ye=P.headers.get("content-type")||"",X={};if(P.headers.forEach((I,ee)=>{Go.has(ee.toLowerCase())||(X[ee]=I)}),ye.includes("text/event-stream")&&P.body){_&&_.lap("upstream",V);const I=_?_.clock():0;c.writeHead(P.status,X);const ee=G?Nn():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?dr(pe,c,F,T):lr(pe,c,F);return Promise.resolve(n).catch(o=>{if(!Z)throw o}).finally(()=>{_&&_.lap("stream",I),oe(P.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(I){if(Z)return oe(499),_?.commit();throw I}if(_&&_.lap("upstream",V),G&&oe(P.status,ye.includes("json")?Mn(ge.toString("utf8")):null),F&&ye.includes("application/json"))try{const I=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,T);return _&&_.lap("restore",I),c.writeHead(P.status,{...X,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}c.writeHead(P.status,X),c.end(ge),_?.commit()}function js(t=Kt()){const c=xr({first:async n=>{const o=Number(new URL(n).port),g=Yn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return g&&(await z())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=Sr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Tr(n),newId:()=>_r()}),p=sa({version:ue}),b=xa({log:n=>console.log(` ${n}`)}),f=t.link?.enabled===!1?null:ia({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:i,device:q,signal:H})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:i,...H?{signal:H}:{},headers:{...g,"x-chatpanel-token":Be()||_e(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==$.activeModel()&&(bo(t.stt.diarizeModel)?$.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Ca}`));let A=null;const B=()=>{if(!A){const n=t.read||{};A=aa({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return A};let E=null;const T=()=>(E||(E=Fn({wrap:(n,o,g,i)=>Wn().wrap(n,o,g,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let _={at:0,fn:()=>"unknown"},J=null;async function z(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const i=await P().health();for(const[q,H]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===q).flatMap(W=>[W.id,...W.models||[]]);for(const W of[q,...K])n.set(W,H)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",g=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return P().contextWindow(g.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(g.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let F=null;const P=()=>(F||(F=Qn({cfg:t,bridgeHealth:async()=>{const n=await Ge(t);if(!n)return null;const o=He(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{be(t,ce())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ve.join(Ve.dirname(ce()),"runtime"),workers:()=>{const n=E?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),F),V=Number(t.runtime?.idleMinutes),G=Zn({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:n=>console.log(n)}),Z=Xn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:G,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=na({store:ra({log:n=>console.warn(`[kb] ${n}`)}),extract:T,embedded:G,cfg:t,rerank:async(n,o)=>{const g=await Z.call("rerank",{query:n,documents:o.map(q=>String(q).slice(0,2e3))});if(g.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of g.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>B(),completer:n=>async(o,{maxTokens:g=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const H=Be()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:g,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:n=>console.warn(n)})),te),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let X=null;const ge=()=>{if(!X){const n=t.search||{},o=n.searxng?.url?Pa({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;X=_a({reader:B(),searxng:o,engines:()=>$a(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let i=g;return await qe([ht(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return X};br(t.allowedExtensionIds||[]);const I=[],ee=n=>{I.push(n),I.length>50&&I.shift()},pe=ar(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1");let i=g.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!Ss(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&da(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&Ts(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return j(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!j(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=vr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=kr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${je(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${je(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await ro(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=je(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Xt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await ro(t);return a(o,200,{ok:!0,status:r,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=je(n);return a(o,200,{ok:!0,trust:e,paired:Xt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return j(n)?a(o,200,Er(t,{version:ue,startedAt:Ho,managed:ze(),certificates:{...$r(),wanted:Zt(t)},linkPartners:f?f.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ve.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!j(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await vn(ue,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:ue,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Tn()})}if(i==="/update"&&n.method==="POST"){const e=Sn(ue);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!j(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!j(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!j(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&n.method!=="GET"&&i!=="/v1/contexts/suggest"&&!j(n))return a(o,403,{error:{message:"contexts write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!j(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!j(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!j(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!j(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!j(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!j(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ue} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
24
24
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
25
- `);if(n.method==="GET"&&i==="/health"){const e=N.health(),r=C.health();return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...je()?{managed:je()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:xn(),confined:wt({stateDir:Ve.dirname(ce())}),...On({release:St.release()})?{appleHelper:!!bt()}:{},...Fe?{bridge:Fe.status()}:ut?{bridge:ut}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||$o,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:Y?{count:Y.count(),hosts:Y.hosts().length}:null,browser:p.health()})}if(i==="/status"&&n.method==="GET"){ir(t);const e=await ke(t.pro?.entitlementToken),r=await Wo(t);return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...je()?{managed:je()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:Bt(t),pro:{unlocked:e},usage:rs(t),uptimeSeconds:Math.floor((Date.now()-Ho)/1e3),update:kn(ue)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=me.put(e.sections||{},{by:e.by||""});return r.applied.length&&Lo(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?me.remove(e):!1;return r&&Lo([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
25
+ `);if(n.method==="GET"&&i==="/health"){const e=N.health(),r=C.health();return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...ze()?{managed:ze()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:xn(),confined:wt({stateDir:Ve.dirname(ce())}),...On({release:St.release()})?{appleHelper:!!bt()}:{},...Fe?{bridge:Fe.status()}:ut?{bridge:ut}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ce,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||$o,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:Y?{count:Y.count(),hosts:Y.hosts().length}:null,browser:p.health()})}if(i==="/status"&&n.method==="GET"){ir(t);const e=await ke(t.pro?.entitlementToken),r=await Wo(t);return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...ze()?{managed:ze()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:Bt(t),pro:{unlocked:e},usage:ns(t),uptimeSeconds:Math.floor((Date.now()-Ho)/1e3),update:kn(ue)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=me.put(e.sections||{},{by:e.by||""});return r.applied.length&&Jo(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?me.remove(e):!1;return r&&Jo([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
26
26
 
27
27
  `);e({type:"hello",revision:me.revision,stamps:me.stamps()});const r=l=>e({type:"changed",...l});At.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
28
28
 
29
- `)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:he.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:he.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const h=he.get(r);if(!h)return m();const y=h.jobs.find(v=>v.id===l);if(!y)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:me,scorecards:Ie,engines:Re,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const v=await fn(y,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:y,...v})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(y.status))return a(o,400,{error:{message:`job ${l} is ${y.status}; only an open job is recruited`,type:"project_error"}});try{const v=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(v.by||"evaluator").slice(0,80),x=await gn(y,{...w,record:h,reach:v.reach||"any",chatModel:v.chatModel||null,evaluation:v.evaluation||null,text:v.text??null,by:O});let D=null;for(const Q of x.events)Q.type==="job.updated"?D=he.updateJob(r,l,Q.job,{by:Q.by||O}):D=he.append(r,[Q]);return a(o,200,{ok:!0,project:D,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(v){return a(o,400,{error:{message:`recruit: ${v.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:g.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},y=String(h.by||"person").slice(0,80),w=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:y}):he.postJob(r,h.job||h,{by:y});return a(o,200,{ok:!0,project:w})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=O=>o.write(`data: ${JSON.stringify(O)}
29
+ `)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:he.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:he.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const h=he.get(r);if(!h)return m();const y=h.jobs.find(v=>v.id===l);if(!y)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:me,scorecards:Re,engines:Je,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const v=await fn(y,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:y,...v})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(y.status))return a(o,400,{error:{message:`job ${l} is ${y.status}; only an open job is recruited`,type:"project_error"}});try{const v=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(v.by||"evaluator").slice(0,80),x=await gn(y,{...w,record:h,reach:v.reach||"any",chatModel:v.chatModel||null,evaluation:v.evaluation||null,text:v.text??null,by:O});let D=null;for(const Q of x.events)Q.type==="job.updated"?D=he.updateJob(r,l,Q.job,{by:Q.by||O}):D=he.append(r,[Q]);return a(o,200,{ok:!0,project:D,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(v){return a(o,400,{error:{message:`recruit: ${v.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:g.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},y=String(h.by||"person").slice(0,80),w=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:y}):he.postJob(r,h.job||h,{by:y});return a(o,200,{ok:!0,project:w})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=O=>o.write(`data: ${JSON.stringify(O)}
30
30
 
31
31
  `);let y=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:he.get(r),after:y}});const w=he.watch(r,O=>{O.seq>y&&(y=O.seq,h(O))});for(const O of he.eventsSince(r,y))y=O.seq,h(O);const v=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(v),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ie.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Ie.get(r)});if(n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Ie.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Re.fromRating(Ie.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Un(t,{version:ue,reader:A,searcher:X,extract:T(),proxy:Z}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:J.health().model||t.ner?.model||null,companions:J.companions()};let r=null;try{r=await P().status()}catch{r=null}return a(o,200,Rn({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(ea.map(r=>{const s=_t(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:qn[r],threads:G.threads,...s.kind==="embedded"?G.health(r,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&n.method==="GET"){if(!z(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(n.url,"http://x").searchParams,r=await P().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,r.ok?200:400,r)}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await P().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!z(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=P(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model,{tunings:r.tunings||null}):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(r.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await Z.call("embed",e);return a(o,r.status,r.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await Z.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Vn(e,{ensure:()=>nt(t),model:J.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await oa(e,{service:T()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!z(n)||Ue(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Sa*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ba(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/files/fs"&&n.method==="POST"){if(!z(n)||Ue(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await va(e);return a(o,r.status,r.body)}if(i==="/v1/import/apple-notes"&&n.method==="POST"){if(!z(n)||Ue(n.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const r=await ka(e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await ta(e,{service:T()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await B().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ye();const r=await ge().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):Oa.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?_a(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await B().read({url:r,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end($a(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Re.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Re.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||xs(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Re.append({...s,engine:l,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
33
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(v),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Re.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Re.get(r)});if(n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Re.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Je.fromRating(Re.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Un(t,{version:ue,reader:A,searcher:X,extract:T(),proxy:Z}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:L.health().model||t.ner?.model||null,companions:L.companions()};let r=null;try{r=await P().status()}catch{r=null}return a(o,200,Rn({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(ea.map(r=>{const s=_t(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:qn[r],threads:G.threads,...s.kind==="embedded"?G.health(r,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&n.method==="GET"){if(!j(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(n.url,"http://x").searchParams,r=await P().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,r.ok?200:400,r)}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await P().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!j(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=P(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model,{tunings:r.tunings||null}):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(r.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await Z.call("embed",e);return a(o,r.status,r.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await Z.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Vn(e,{ensure:()=>nt(t),model:L.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await oa(e,{service:T()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!j(n)||De(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Ta*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ba(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/files/fs"&&n.method==="POST"){if(!j(n)||De(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await va(e);return a(o,r.status,r.body)}if(i==="/v1/files/pick-folder"&&n.method==="POST"){if(!j(n)||De(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await Sa(e);return a(o,r.status,r.body)}if(i==="/v1/import/apple-notes"&&n.method==="POST"){if(!j(n)||De(n.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const r=await ka(e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await ta(e,{service:T()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await B().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ye();const r=await ge().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):Ea.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?Oa(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await B().read({url:r,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(Aa(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Je.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Je.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||_s(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Je.append({...s,engine:l,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
34
34
 
35
35
  `)}catch{}};e({type:"hello",at:Date.now()});const r=re.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
38
38
 
39
39
  `),d=g.searchParams.has("after")?Number(g.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(r),after:m}});const h=re.watch(r,w=>{w.seq==null?l(w):w.seq>m&&(m=w.seq,l(w))});for(const w of re.eventsSince(r,m))m=w.seq,l(w);const y=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(y)});return}}}if(i.startsWith("/v1/contexts")){const e=R.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});if(co||=Xr({store:e,notify:Ce}),await Zr(n,o,{pathname:i,api:co,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:fe.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=hs(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await ys(s,y=>R.search(y,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(y=>y.type==="brief"),...m.filter(y=>y.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!z(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const O=new AbortController,x=setTimeout(()=>O.abort(),3e4);try{const D=Be()||_e(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),we=await Q.json().catch(()=>({}));return Q.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,m=me.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,y=await cn(r,{store:R,memories:fe.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,un(r,y,{size:R.size,newest:R.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await oe().handle({method:n.method,pathname:i,query:g.searchParams,body:e,admin:z(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:Nt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=Nt.push(Io({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await k(n,Math.max(t.maxBodyBytes||0,$s))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let m=0,h={},y=[],w=[];const v={upserts:[],removes:[]},O=x=>{if(!x||x.deletedAt){x?.id&&v.removes.push(x.id);return}try{const D=fo(x);D&&v.upserts.push(D)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(...x.written),h=x.revs,y=x.conflicts,w=x.merged;for(const D of x.written)O(e.get(D))}if(Array.isArray(r.entries)){const x=ft(),D=x?zn((ne,Te)=>Jn(x,{salt:ne,iterations:Te})):null,Q=async ne=>{if(!D||!ne.blob)return null;const Te=await D(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?Gn(Hn,ne.blob.compression):null;return jn(ne.blob,Te,{codec:U})},we=await e.upsertEntries(r.entries,{open:Q});d.push(...we.written),m+=we.sealed;for(const ne of we.written)O(e.get(ne))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ce({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:y,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="DELETE"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(g.searchParams.get(m)||""),r=g.searchParams.get("host"),s=e("all");if((r===null||r==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(r!==null&&r.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:r;if(!e("force")){const m=Y.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:r},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${r}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Y.deleteOf(l);for(const m of Ee)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(y)});return}}}if(i.startsWith("/v1/contexts")){const e=R.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});if(co||=Xr({store:e,notify:Ie}),await Zr(n,o,{pathname:i,api:co,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:fe.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=ys(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await fs(s,y=>R.search(y,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(y=>y.type==="brief"),...m.filter(y=>y.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!j(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const O=new AbortController,x=setTimeout(()=>O.abort(),3e4);try{const D=Be()||_e(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),we=await Q.json().catch(()=>({}));return Q.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,m=me.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,y=await cn(r,{store:R,memories:fe.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,un(r,y,{size:R.size,newest:R.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await oe().handle({method:n.method,pathname:i,query:g.searchParams,body:e,admin:j(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:Nt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=Nt.push(Io({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await k(n,Math.max(t.maxBodyBytes||0,As))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let m=0,h={},y=[],w=[];const v={upserts:[],removes:[]},O=x=>{if(!x||x.deletedAt){x?.id&&v.removes.push(x.id);return}try{const D=fo(x);D&&v.upserts.push(D)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(...x.written),h=x.revs,y=x.conflicts,w=x.merged;for(const D of x.written)O(e.get(D))}if(Array.isArray(r.entries)){const x=ft(),D=x?zn((ne,Te)=>Ln(x,{salt:ne,iterations:Te})):null,Q=async ne=>{if(!D||!ne.blob)return null;const Te=await D(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?Gn(Hn,ne.blob.compression):null;return jn(ne.blob,Te,{codec:U})},we=await e.upsertEntries(r.entries,{open:Q});d.push(...we.written),m+=we.sealed;for(const ne of we.written)O(e.get(ne))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ie({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:y,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="DELETE"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(g.searchParams.get(m)||""),r=g.searchParams.get("host"),s=e("all");if((r===null||r==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(r!==null&&r.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:r;if(!e("force")){const m=Y.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:r},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${r}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Y.deleteOf(l);for(const m of Ee)try{m.write(`event: deleted
42
42
  data: ${JSON.stringify({...s?{all:!0}:{host:r},deleted:d})}
43
43
 
44
44
  `)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:r},cursor:Y.cursor()})}if(i==="/v1/events"&&n.method==="POST"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:In(m?.source))===ho,l=r.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${ho}" is this gateway's own log`})),d=Bn(Y,l.length?r.filter(m=>!s(m)):r);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:Y.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return Y?a(o,200,{ok:!0,cursor:Y.cursor(),count:Y.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Dn(Y.all());return a(o,200,{ok:!0,stats:e,year:Cn(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=yo(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Y.since(e,{limit:Number(g.searchParams.get("limit"))||void 0,host:g.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>vt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(g.searchParams.has("cursor"))try{e=yo(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
@@ -47,7 +47,7 @@ data: ${JSON.stringify({cursor:Y.cursor(),count:Y.count(),version:ue})}
47
47
  `),Ee.add(o),n.on("close",()=>Ee.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Y.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
48
48
  data: ${JSON.stringify(vt(s))}
49
49
 
50
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...f?{enabled:!0,...f.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{be(t,ce())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!f)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=f.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await f.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await f.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!f)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=la({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{be(t,ce())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await f.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!f)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await f.remove(e)?(b.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=Ue(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=f?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=ha(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&d)return a(o,200,{folder:"its own",files:ya(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=fa(r,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,ga(r,m,await k(n,t.maxBodyBytes))):n.method==="DELETE"?wa(r,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const y=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,y,{error:{message:h?.message||String(h),type:y===404?"not_found":y===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:b.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=d=>o.write(`event: approvals
50
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...f?{enabled:!0,...f.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{be(t,ce())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!f)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=f.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await f.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await f.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!f)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=la({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{be(t,ce())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await f.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!f)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await f.remove(e)?(b.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=De(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=f?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=ha(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&d)return a(o,200,{folder:"its own",files:ya(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=fa(r,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,ga(r,m,await k(n,t.maxBodyBytes))):n.method==="DELETE"?wa(r,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const y=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,y,{error:{message:h?.message||String(h),type:y===404?"not_found":y===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:b.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=d=>o.write(`event: approvals
51
51
  data: ${JSON.stringify({pending:d})}
52
52
 
53
53
  `);r(b.list());const s=b.subscribe(r),l=setInterval(()=>o.write(`:
@@ -55,13 +55,13 @@ data: ${JSON.stringify({pending:d})}
55
55
  `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return go.some(s=>s.id===r.decision)?b.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${go.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,p.status());if(i==="/v1/browser/stream"&&n.method==="GET"){p.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await p.call(e,n):i==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
56
56
  data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ue,prefsRevision:me.revision})}
57
57
 
58
- `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=R.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:lo()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Qr(String(e.passphrase)):Yr();const r=e.passphrase?await kt(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await kt(R,ft());return e.ok&&e.whole&&Ce(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Wo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),J.state()!=="off"){if(!J.isReady()){const r=J.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await k(n,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await J.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Fo(t);if(!e){const r=J.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:J.state(),model:t.ner?.model||null})}try{const r=await k(n,t.maxBodyBytes),s=await tt(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Bt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await nt(t);const l=await qe([ht(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Uo(l.vault,"types")||[],detector:Bt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=J.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=La(ko,{totalRamMB:r}).map(l=>({...l,installed:J.modelOnDisk(l.id)}));for(const l of[e,...J.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:J.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:J.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Wr(),recommendation:io(s,{totalRamMB:r},[]),state:J.state(),progress:J.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(St.totalmem()/1048576),l=io(ko.map(d=>({...d,installed:J.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(So(d)||To(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||J.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&Do(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await J.setModel(r,{onLog:m=>console.log(m)});const d=Fr(t.ner,{log:m=>console.log(m)});for(const m of J.companions())d.includes(m.model)||await J.removeCompanion(m.model);for(const m of d)await J.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});J.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:J.companions(),state:J.state()})}if(!r||!(So(r)||To(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Do(t,r);try{be(t,ce())}catch{}return J.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:J.state(),progress:J.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=N.health().model||t.stt?.model||De,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=Ja.map(l=>{const d=xo(l,r);return{...l,installed:N.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:Ga,licenses:t.stt?.licenses||{}})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(ja(r)||za(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=xo(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=at(r)?.license||null;if(l){const m=_o(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&Ha(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{be(t,ce())}catch{}return N.setModel(r,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Rt(t,{installing:!0}),licenseAccepted:Zo(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:$.activeModel(),state:$.state(),installed:$.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=$.activeModel(),r=Ba.map(s=>({...s,installed:$.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:$.state(),threshold:$.activeThreshold(),segment:Ma.health(),translate:$e.health(),indictrans:Aa.health(),aec:xt.health(),progress:$.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!bo(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await $.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{be(t,ce())}catch{}return $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}return $.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=C.health().model||t.tts?.model||No(Ot()),r=Ot(),s=Oo.find(d=>d.id===e)||null,l=Oo.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(lt(e)==="pocket-tts"?st:Oe),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&lt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():Ya).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:Ua.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:Wa})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Va(r)||Fa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=de.parseCustomVoice(s);if(!(d?!!de.getVoice(d):it(s)||Eo(s)&&Po(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ka(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:$o,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Qa(r),m=de.parseCustomVoice(t.tts.voice||""),h=!!(m&&de.getVoice(m));if(d&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const w=de.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=Oe);const y=lt(r)==="pocket-tts";y&&!de.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!y&&it(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,ce())}catch{}return r&&C.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:de.listVoices(),usable:C.supportsCustomVoices(),embedder:$.activeModel(),embedderReady:$.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!de.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...de.renameVoice(l,r),usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=Ca($.activeModel())?.dim===de.EMBED_DIM;if(d&&!$.isReady()){const O=$.download({onLog:Q=>console.log(Q)}),x=Symbol("timeout"),D=await Promise.race([O.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(x),Qo))]);if(D===x||!$.isReady())return a(o,503,{error:{message:D===x?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const m=Float32Array.from(s),h=d?await $.embed(m):null;let y=null;try{const O=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:x=>console.log(x)});O&&(y=await O.encodeVoice(Is(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=l?de.replaceVoice(l,{vec:h,pocket:y}):de.saveVoice({name:r,vec:h,pocket:y}),v=l&&r&&r!==w.name?de.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...v,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=de.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=de.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,ce())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Ao)return a(o,413,{error:{message:`text too long (max ${Ao} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Xa(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Oe);if(l&&!qa(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ne,contentType:Te,redacted:U}=await Za({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await C.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||No(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=es({requested:d,configured:m,engine:C,voices:de,isPocketVoice:it,isKnownVoice:Eo,isValidVoiceId:Po,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,D=await C.synth(r,{voice:v,speed:s,speakerEmbedding:x}),Q=C.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),...O||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(we)}catch(y){return a(o,500,{error:{message:y.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Ia(await k(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const r=v=>e.find(O=>O.name===v&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Ra(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=vo(m,{fetchImpl:tt})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!N.isReady()&&await N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),onLog:v=>console.log(v)}),!h&&!N.isReady())return a(o,503,{error:{message:`speech model not ready: ${N.health().error||N.state()}`,type:"stt_not_ready"}});const y=r("diarize")==="true"&&t.stt?.diarize!==!1;y&&!$.isReady()&&await $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=N.createSession({lang:r("language")||void 0,diarize:y,interims:!1,remote:h}),O=[],x=[];let D=null;N.subscribe(v,U=>{U.type==="final"&&U.text?O.push(U):U.type==="language"?D=U.lang:U.type==="error"&&x.push(U.message||U.code)});const Q=16e3*5;for(let U=0;U<l.pcm.length;U+=Q)N.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+Q))),await N.decodeNow(v);if(await N.endSession(v),!O.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let we=0;const ne=O.map((U,rr)=>{const Wt=typeof U.startMs=="number"?U.startMs/1e3:we,nr=(U.durationMs||0)/1e3;return we=Wt+nr,{id:rr,start:Math.round(Wt*100)/100,end:Math.round(we*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(n.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(n.headers["content-length"])>Yo)return a(o,413,{error:{message:`at most ${It} s of audio`,type:"too_large"}});let r;try{r=await k(n,Yo)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${It} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=N.toFloat32(r);if(s.length<Cs)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!$.isReady()){const d=$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:y=>console.log(y)}),m=Symbol("timeout"),h=await Promise.race([d.then(()=>null,()=>null),new Promise(y=>{setTimeout(()=>y(m),Qo).unref?.()})]);if(!$.isReady())return a(o,503,{error:{message:h===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${$.health().error||$.state()}`,type:"speaker_not_ready"},...$.progress()?{progress:$.progress()}:{}})}const l=await $.embed(s);return l?a(o,200,{vec:$.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:$.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=vo(r,{fetchImpl:tt})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!N.isReady()&&N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),licenseAccepted:Zo(t,t.stt?.model||De),onLog:O=>console.log(O)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const y=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||De,v=y&&!s?Na(y,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const O=e?.poll===!0,x=e?.format==="pcm16"?"pcm16":"f32",D=l&&e?.vectors===!0,{id:Q}=N.createSession({lang:e?.lang,langs:y,translateTo:d,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:x});return a(o,201,{id:Q,state:N.state(),format:x,...O?{poll:!0}:{},...D?{vectors:!0}:{},...v.length?{languagesMissing:v}:{},...d?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let y=m.text;return await qe([ht(()=>y,w=>{y=w})],t.redaction,{isPro:h}),{...m,text:y}}catch{return m}},l=async d=>{const m=N.drainEvents(r);if(!m)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":N.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...N.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes($.state())?h.push({type:"diarize-progress",state:$.state(),...$.progress()||{}}):d.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Xo.get(d)!==w&&(Xo.set(d,w),h.push({type:"state",state:w}))}const y=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)d?h.push(await s(d,w,y)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=N.getSession(r)||N.endedSession(r);try{const m=await k(n,t.maxBodyBytes);N.pushAudio(r,N.toFloat32(m,d?.format));const h=await l(d);return a(o,200,{ok:!0,state:N.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=N.getSession(r);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=x=>o.write(`data: ${JSON.stringify(x)}
58
+ `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=R.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:lo()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Qr(String(e.passphrase)):Yr();const r=e.passphrase?await kt(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ie(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await kt(R,ft());return e.ok&&e.whole&&Ie(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Wo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),L.state()!=="off"){if(!L.isReady()){const r=L.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await k(n,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await L.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Fo(t);if(!e){const r=L.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:L.state(),model:t.ner?.model||null})}try{const r=await k(n,t.maxBodyBytes),s=await tt(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Bt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await nt(t);const l=await qe([ht(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Uo(l.vault,"types")||[],detector:Bt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=L.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=La(ko,{totalRamMB:r}).map(l=>({...l,installed:L.modelOnDisk(l.id)}));for(const l of[e,...L.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:L.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:L.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Wr(),recommendation:io(s,{totalRamMB:r},[]),state:L.state(),progress:L.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(St.totalmem()/1048576),l=io(ko.map(d=>({...d,installed:L.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(So(d)||To(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||L.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&Do(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await L.setModel(r,{onLog:m=>console.log(m)});const d=Fr(t.ner,{log:m=>console.log(m)});for(const m of L.companions())d.includes(m.model)||await L.removeCompanion(m.model);for(const m of d)await L.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});L.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:L.companions(),state:L.state()})}if(!r||!(So(r)||To(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Do(t,r);try{be(t,ce())}catch{}return L.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:L.state(),progress:L.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=N.health().model||t.stt?.model||Ce,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=ja.map(l=>{const d=xo(l,r);return{...l,installed:N.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:Ha,licenses:t.stt?.licenses||{}})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(za(r)||Ga(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=xo(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=at(r)?.license||null;if(l){const m=_o(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&Ua(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{be(t,ce())}catch{}return N.setModel(r,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Rt(t,{installing:!0}),licenseAccepted:Zo(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:$.activeModel(),state:$.state(),installed:$.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=$.activeModel(),r=Da.map(s=>({...s,installed:$.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:$.state(),threshold:$.activeThreshold(),segment:Ba.health(),translate:$e.health(),indictrans:Na.health(),aec:xt.health(),progress:$.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!bo(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await $.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{be(t,ce())}catch{}return $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}return $.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=C.health().model||t.tts?.model||No(Ot()),r=Ot(),s=Oo.find(d=>d.id===e)||null,l=Oo.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(lt(e)==="pocket-tts"?st:Oe),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&lt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():Xa).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:Va.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:Ka})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Fa(r)||Wa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=de.parseCustomVoice(s);if(!(d?!!de.getVoice(d):it(s)||Eo(s)&&Po(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Qa(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:$o,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Ya(r),m=de.parseCustomVoice(t.tts.voice||""),h=!!(m&&de.getVoice(m));if(d&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const w=de.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=Oe);const y=lt(r)==="pocket-tts";y&&!de.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!y&&it(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,ce())}catch{}return r&&C.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:de.listVoices(),usable:C.supportsCustomVoices(),embedder:$.activeModel(),embedderReady:$.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!de.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...de.renameVoice(l,r),usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=Ia($.activeModel())?.dim===de.EMBED_DIM;if(d&&!$.isReady()){const O=$.download({onLog:Q=>console.log(Q)}),x=Symbol("timeout"),D=await Promise.race([O.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(x),Qo))]);if(D===x||!$.isReady())return a(o,503,{error:{message:D===x?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const m=Float32Array.from(s),h=d?await $.embed(m):null;let y=null;try{const O=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:x=>console.log(x)});O&&(y=await O.encodeVoice(Rs(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=l?de.replaceVoice(l,{vec:h,pocket:y}):de.saveVoice({name:r,vec:h,pocket:y}),v=l&&r&&r!==w.name?de.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...v,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=de.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=de.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,ce())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Ao)return a(o,413,{error:{message:`text too long (max ${Ao} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Za(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Oe);if(l&&!es(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ne,contentType:Te,redacted:U}=await qa({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await C.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||No(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=ts({requested:d,configured:m,engine:C,voices:de,isPocketVoice:it,isKnownVoice:Eo,isValidVoiceId:Po,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,D=await C.synth(r,{voice:v,speed:s,speakerEmbedding:x}),Q=C.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),...O||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(we)}catch(y){return a(o,500,{error:{message:y.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Ra(await k(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const r=v=>e.find(O=>O.name===v&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Ja(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=vo(m,{fetchImpl:tt})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!N.isReady()&&await N.init({model:t.stt?.model||Ce,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),onLog:v=>console.log(v)}),!h&&!N.isReady())return a(o,503,{error:{message:`speech model not ready: ${N.health().error||N.state()}`,type:"stt_not_ready"}});const y=r("diarize")==="true"&&t.stt?.diarize!==!1;y&&!$.isReady()&&await $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=N.createSession({lang:r("language")||void 0,diarize:y,interims:!1,remote:h}),O=[],x=[];let D=null;N.subscribe(v,U=>{U.type==="final"&&U.text?O.push(U):U.type==="language"?D=U.lang:U.type==="error"&&x.push(U.message||U.code)});const Q=16e3*5;for(let U=0;U<l.pcm.length;U+=Q)N.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+Q))),await N.decodeNow(v);if(await N.endSession(v),!O.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let we=0;const ne=O.map((U,rr)=>{const Wt=typeof U.startMs=="number"?U.startMs/1e3:we,nr=(U.durationMs||0)/1e3;return we=Wt+nr,{id:rr,start:Math.round(Wt*100)/100,end:Math.round(we*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(n.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(n.headers["content-length"])>Yo)return a(o,413,{error:{message:`at most ${It} s of audio`,type:"too_large"}});let r;try{r=await k(n,Yo)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${It} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=N.toFloat32(r);if(s.length<Is)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!$.isReady()){const d=$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:y=>console.log(y)}),m=Symbol("timeout"),h=await Promise.race([d.then(()=>null,()=>null),new Promise(y=>{setTimeout(()=>y(m),Qo).unref?.()})]);if(!$.isReady())return a(o,503,{error:{message:h===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${$.health().error||$.state()}`,type:"speaker_not_ready"},...$.progress()?{progress:$.progress()}:{}})}const l=await $.embed(s);return l?a(o,200,{vec:$.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:$.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=vo(r,{fetchImpl:tt})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!N.isReady()&&N.init({model:t.stt?.model||Ce,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),licenseAccepted:Zo(t,t.stt?.model||Ce),onLog:O=>console.log(O)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const y=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||Ce,v=y&&!s?Ma(y,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const O=e?.poll===!0,x=e?.format==="pcm16"?"pcm16":"f32",D=l&&e?.vectors===!0,{id:Q}=N.createSession({lang:e?.lang,langs:y,translateTo:d,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:x});return a(o,201,{id:Q,state:N.state(),format:x,...O?{poll:!0}:{},...D?{vectors:!0}:{},...v.length?{languagesMissing:v}:{},...d?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let y=m.text;return await qe([ht(()=>y,w=>{y=w})],t.redaction,{isPro:h}),{...m,text:y}}catch{return m}},l=async d=>{const m=N.drainEvents(r);if(!m)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":N.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...N.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes($.state())?h.push({type:"diarize-progress",state:$.state(),...$.progress()||{}}):d.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Xo.get(d)!==w&&(Xo.set(d,w),h.push({type:"state",state:w}))}const y=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)d?h.push(await s(d,w,y)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=N.getSession(r)||N.endedSession(r);try{const m=await k(n,t.maxBodyBytes);N.pushAudio(r,N.toFloat32(m,d?.format));const h=await l(d);return a(o,200,{ok:!0,state:N.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=N.getSession(r);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=x=>o.write(`data: ${JSON.stringify(x)}
59
59
 
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=>ls(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=J.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&J.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(!z(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 Ce({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 z(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 z(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 Lt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):z(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 Lt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):z(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 Lt(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(!z(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:Jr()});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}
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 Lr({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 z(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(!z(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 ze(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Ge(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 j(),r=e.sig!==void 0&&e.sig!==L;return L=e.sig,a(o,200,await ds(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(Rs.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=Os(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"?_s(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&&Es(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):gs,w=e.narrowAll?null:O=>!ws.test(jo(O)),v=S.tools.length;S.tools=pr(S.tools,vs(S,H.kind),{cap:y,keep:w,name:jo,description:bs}),jt=v-S.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&z(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=ts(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:z(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){os(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=Ln(S.model,t,await j());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:Jt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await j(),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&&!ms(M,S.model)&&(await us(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:cs(t).map(e=>e.id)}});const le=Ue(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?Ps(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=Jt(null,mo(uo(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Jt(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 Bs(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). 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
64
64
  connection: close\r
65
65
  content-length: 0\r
66
66
  \r
67
- `)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=f,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Jt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(f=>String(f).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const f=u.workspace;p.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),as.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const f=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),A=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(f.length||A.length||B||E.length)&&(p.sandbox={...f.length?{hosts:f}:{},...A.length?{write:A}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const b=tn(u.thread);return b&&(p.thread=b),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Fe=null,ut=null;async function Dl(t=Kt()){Kr();let c=null;try{c=await Ar()}catch(T){throw T instanceof Nr&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=c?.policy||null;u&&(qt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const p=Pr({enabled:Zt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),Or(globalThis,{allow:u?.egress?(T,{local:_})=>Br(u,T,{local:_}):null}),_e();const b=Js(t),f=Vr(t),A=sr(t);let B=!1;b.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const _=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(L=>L.ok?L.json():null).catch(()=>null).then(L=>{const j=!!(L?.version&&typeof L.tier=="string"),F=on({name:"gateway",self:ue,holder:j?{ours:j,version:L.version}:null,managedBy:rn(process.env),port:t.port});if(F.action==="standby"||B&&!L){if(!B)for(const P of F.lines)console.error(P);B=!0,setTimeout(()=>b.listen(t.port,t.host),nn);return}if(j){const P=L.managedBy?` (run by ${L.managedBy})`:"";for(const[V,G]of F.lines.entries())console.error(V===0?G.replace(` on ${t.port}`,` at http://${_}:${t.port}${P}`):G)}else{const P=bn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ce()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),b.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${ue} on http://${t.host}:${t.port}`),b.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),b.runtimeDefaults?.().then(T=>{for(const _ of T||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of is(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${_n(wt({stateDir:Ve.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},wn(t,{childEnv:()=>({...ss(t,process.env,et()),...ns(t)})}).then(T=>{Fe=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),lo()&&kt(R,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ce())}).catch(()=>{});const E=()=>{f?.stop(),A.stop(),Fe?.stop(),fs(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{$s as RECORDS_MAX_BYTES,Rl as VERSION,Js as createGateway,Ds as joinUpstream,Mt as parseAgentModel,Dl as start};
67
+ `)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=f,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Lt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(f=>String(f).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const f=u.workspace;p.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),ss.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const f=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),A=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(f.length||A.length||B||E.length)&&(p.sandbox={...f.length?{hosts:f}:{},...A.length?{write:A}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const b=tn(u.thread);return b&&(p.thread=b),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Fe=null,ut=null;async function Il(t=Kt()){Kr();let c=null;try{c=await Ar()}catch(T){throw T instanceof Nr&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=c?.policy||null;u&&(qt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const p=Pr({enabled:Zt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),Or(globalThis,{allow:u?.egress?(T,{local:_})=>Br(u,T,{local:_}):null}),_e();const b=js(t),f=Vr(t),A=sr(t);let B=!1;b.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const _=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(J=>J.ok?J.json():null).catch(()=>null).then(J=>{const z=!!(J?.version&&typeof J.tier=="string"),F=on({name:"gateway",self:ue,holder:z?{ours:z,version:J.version}:null,managedBy:rn(process.env),port:t.port});if(F.action==="standby"||B&&!J){if(!B)for(const P of F.lines)console.error(P);B=!0,setTimeout(()=>b.listen(t.port,t.host),nn);return}if(z){const P=J.managedBy?` (run by ${J.managedBy})`:"";for(const[V,G]of F.lines.entries())console.error(V===0?G.replace(` on ${t.port}`,` at http://${_}:${t.port}${P}`):G)}else{const P=bn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ce()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),b.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${ue} on http://${t.host}:${t.port}`),b.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),b.runtimeDefaults?.().then(T=>{for(const _ of T||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of ls(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${_n(wt({stateDir:Ve.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},wn(t,{childEnv:()=>({...is(t,process.env,et()),...as(t)})}).then(T=>{Fe=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),lo()&&kt(R,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ie())}).catch(()=>{});const E=()=>{f?.stop(),A.stop(),Fe?.stop(),gs(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{As as RECORDS_MAX_BYTES,Ll as VERSION,js as createGateway,Cs as joinUpstream,Mt as parseAgentModel,Il as start};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.142.0";export{o as VERSION};
1
+ const o="0.143.1";export{o as VERSION};