@chatpanel/gateway 0.160.1 → 0.161.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.160.1",
3
+ "version": "0.161.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/research.js CHANGED
@@ -1 +1 @@
1
- import{research as $,speakersIn as x}from"@chatpanel/events/research.js";import{runSearchModes as M,namesIn as k}from"@chatpanel/events/search-modes.js";const y=r=>String(r||"").toLowerCase().replace(/[^\p{L}\p{N} ]/gu," ").replace(/\s+/g," ").trim(),N=(r,t,e)=>Math.max(t,Math.min(e,Number(r)||t));function O(r={}){const t=(r.names||[]).map(y).filter(Boolean).map(n=>`"${n}"`);return t.length?t.join(" AND "):[...new Set((r.terms||[]).flatMap(n=>y(n).split(" ")).filter(n=>n.length>=2))].map(n=>`${n}*`).join(" OR ")}function R(r,t){const e=[],n=[];t&&(e.push("fts MATCH ?"),n.push(t)),r.kind&&(e.push("r.type = ?"),n.push(String(r.kind)));const s=Math.max(Number(r.after)||0,Number(r.since)||0);return s>0&&(e.push("r.date >= ?"),n.push(s)),Number(r.before)>0&&(e.push("r.date < ?"),n.push(Number(r.before))),{where:e.length?`WHERE ${e.join(" AND ")}`:"",args:n}}const T={month:"%Y-%m",week:"%Y-W%W",day:"%Y-%m-%d"},C=/^(?:(?:MEETING|CHAT|NOTE|BRIEF|Date|Platform|Tags|Agent):[^\n]*|[A-Z][A-Z ]{2,30}:[ \t]*)$/gm,S=r=>String(r||"").replace(/^\[\d{1,2}:\d{2}(?::\d{2})?\s*(?:[AaPp]\.?\s?[Mm]\.?)?\]\s*/gm,"").replace(C,"");function D(r,t={},{excludeId:e=null}={}){const n=O(t),{where:s,args:a}=R(t,n),o=e?`${s?" AND":"WHERE"} r.id != ?`:"",u=e?[...a,String(e)]:a,c="fts JOIN records r ON r.id = fts.id",E=t.sort==="newest"?"r.date DESC":t.sort==="oldest"?"r.date ASC":n?"bm25(fts, 0.0, 4.0, 1.0)":"r.date DESC",d=n?"snippet(fts, 2, '', '', '…', 16)":"substr(fts.text, 1, 220)",h=r.all(`SELECT r.id id, r.type type, r.title title, r.date date, ${d} snip FROM ${c} ${s}${o} ORDER BY ${E} LIMIT ?`,[...u,N(t.limit||8,1,50)]).map(i=>({id:i.id,kind:i.type,title:i.title||"",date:Number(i.date)||0,snippet:String(i.snip||"").replace(/\s+/g," ").trim()})),g=Number(r.get(`SELECT COUNT(*) c FROM ${c} ${s}${o}`,u)?.c)||0,p={rows:h,count:g},m=T[t.group];if(m)p.groups=r.all(`SELECT strftime('${m}', r.date / 1000, 'unixepoch', 'localtime') k, COUNT(*) n FROM ${c} ${s}${o}${s||o?" AND":"WHERE"} r.date > 0 GROUP BY k ORDER BY k DESC LIMIT 36`,u).map(i=>({key:i.k,count:Number(i.n)||0}));else if(t.group==="person"){const i=new Map;for(const f of r.all(`SELECT fts.text text FROM ${c} ${s}${o} ORDER BY r.date DESC LIMIT 2000`,u))for(const l of new Set(x(S(f.text)).map(b=>b.name)))i.set(l,(i.get(l)||0)+1);p.groups=[...i].sort((f,l)=>l[1]-f[1]||f[0].localeCompare(l[0])).slice(0,36).map(([f,l])=>({key:f,count:l}))}return p}function w(r,{excludeId:t=null}={}){return r?.db?.all?async e=>D(r.db,e,{excludeId:t}):async e=>{const n=[...e.names||[],...e.terms||[]].join(" "),s=Math.max(Number(e.after)||0,Number(e.since)||0);let a=n?r.search(n,{limit:50,type:e.kind||null,since:s||null,before:e.before?e.before-1:null}):r.list({limit:50,type:e.kind||null}).items;return a=a.filter(o=>o.id!==t),e.sort==="newest"&&a.sort((o,u)=>(u.date||0)-(o.date||0)),e.sort==="oldest"&&a.sort((o,u)=>(o.date||0)-(u.date||0)),{rows:a.slice(0,N(e.limit||8,1,50)).map(o=>({id:o.id,kind:o.type,title:o.title||"",date:Number(o.date)||0,snippet:o.snippet||""})),count:a.length,approximate:!0}}}function A(r,{excludeId:t=null}={}){const e=w(r,{excludeId:t});return async({terms:n=[],phrase:s=!1,kind:a="",sinceAt:o=0,limit:u=20}={})=>{const c=(n||[]).map(String).filter(Boolean);return c.length?(await e({kind:a,names:s?[c.join(" ")]:[],terms:s?[]:c,since:o,sort:"relevance",limit:u})).rows:[]}}async function Y(r,{store:t,memories:e=[],complete:n=null,previous:s=null,self:a="",excludeId:o=null,mapWindow:u=0,answerWindow:c=0,parallel:E=1,corrections:d=null,limits:h,now:g}={}){const p=A(t,{excludeId:o});return $(String(r||"").slice(0,600),{previous:s,memories:e,knownNames:e.flatMap(m=>k(m?.text||"")),query:w(t,{excludeId:o}),readText:async m=>{const i=t.get(m);return i?{id:i.id,title:i.title,date:i.date,text:S(i.text)}:null},searchModes:m=>M(String(m).slice(0,500),{lexical:p,memories:e,self:a,excludeId:o,limit:8,modes:["memory","keyword","graph","hybrid"],corrections:d}),complete:n,mapWindow:u,answerWindow:c,parallel:E,corrections:d,self:a,...h?{limits:h}:{},...g?{now:g}:{}})}function L(r){const t=r.read?.[0]||r.rows?.find(n=>!String(n.id).startsWith("memory:"))||null,e=Number(t?.date)||0;return{plan:r.plan,top:t?.id||null,answer:e?new Date(e).toISOString().slice(0,10):""}}function H(r,t,{size:e=0,newest:n=null}={}){return{ok:!0,question:String(r||""),plan:t.plan,how:t.how,framedBy:t.framedBy||"rules",count:t.count,rows:t.rows||[],groups:t.groups||null,read:(t.read||[]).map(s=>({id:s.id,title:s.title||"",date:Number(s.date)||0,parts:s.chunks,of:s.of,speakers:s.speakers||[],notes:s.notes||[]})),memory:t.memory||[],rounds:t.rounds,verdict:t.verdict||null,ms:t.ms,next:L(t),attachment:t.attachment?{title:t.attachment.title,text:t.attachment.text}:null,size:e,newest:n}}export{O as matchOf,S as readable,H as researchResponse,Y as researchStore,D as sqliteQuery,A as storeLexical,w as storeQuery};
1
+ import{research as k,speakersIn as A}from"@chatpanel/events/research.js";import{runSearchModes as O,namesIn as R}from"@chatpanel/events/search-modes.js";const w=e=>String(e||"").toLowerCase().replace(/[^\p{L}\p{N} ]/gu," ").replace(/\s+/g," ").trim(),$=(e,t,r)=>Math.max(t,Math.min(r,Number(e)||t));function T(e={}){const t=(e.names||[]).map(w).filter(Boolean).map(s=>`"${s}"`);return t.length?t.join(" AND "):[...new Set((e.terms||[]).flatMap(s=>w(s).split(" ")).filter(s=>s.length>=2))].map(s=>`${s}*`).join(" OR ")}function C(e,t){const r=[],s=[];t&&(r.push("fts MATCH ?"),s.push(t)),e.kind&&(r.push("r.type = ?"),s.push(String(e.kind)));const n=Math.max(Number(e.after)||0,Number(e.since)||0);return n>0&&(r.push("r.date >= ?"),s.push(n)),Number(e.before)>0&&(r.push("r.date < ?"),s.push(Number(e.before))),{where:r.length?`WHERE ${r.join(" AND ")}`:"",args:s}}const D={month:"%Y-%m",week:"%Y-W%W",day:"%Y-%m-%d"},L=/^(?:(?:MEETING|CHAT|NOTE|BRIEF|Date|Platform|Tags|Agent):[^\n]*|[A-Z][A-Z ]{2,30}:[ \t]*)$/gm,b=e=>String(e||"").replace(/^\[\d{1,2}:\d{2}(?::\d{2})?\s*(?:[AaPp]\.?\s?[Mm]\.?)?\]\s*/gm,"").replace(L,"");function I(e,t={},{excludeId:r=null,ids:s=null}={}){const n=T(t),{where:a,args:c}=C(t,n),i=Array.isArray(s)&&s.length?s.slice(0,2e3).map(String):null,o=[...r?["r.id != ?"]:[],...i?[`r.id IN (${i.map(()=>"?").join(",")})`]:[]],l=o.length?`${a?" AND":"WHERE"} ${o.join(" AND ")}`:"",h=[...c,...r?[String(r)]:[],...i||[]],f="fts JOIN records r ON r.id = fts.id",y=t.sort==="newest"?"r.date DESC":t.sort==="oldest"?"r.date ASC":n?"bm25(fts, 0.0, 4.0, 1.0)":"r.date DESC",E=n?"snippet(fts, 2, '', '', '…', 16)":"substr(fts.text, 1, 220)",N=e.all(`SELECT r.id id, r.type type, r.title title, r.date date, ${E} snip FROM ${f} ${a}${l} ORDER BY ${y} LIMIT ?`,[...h,$(t.limit||8,1,50)]).map(u=>({id:u.id,kind:u.type,title:u.title||"",date:Number(u.date)||0,snippet:String(u.snip||"").replace(/\s+/g," ").trim()})),p=Number(e.get(`SELECT COUNT(*) c FROM ${f} ${a}${l}`,h)?.c)||0,m={rows:N,count:p},S=D[t.group];if(S)m.groups=e.all(`SELECT strftime('${S}', r.date / 1000, 'unixepoch', 'localtime') k, COUNT(*) n FROM ${f} ${a}${l}${a||l?" AND":"WHERE"} r.date > 0 GROUP BY k ORDER BY k DESC LIMIT 36`,h).map(u=>({key:u.k,count:Number(u.n)||0}));else if(t.group==="person"){const u=new Map;for(const g of e.all(`SELECT fts.text text FROM ${f} ${a}${l} ORDER BY r.date DESC LIMIT 2000`,h))for(const d of new Set(A(b(g.text)).map(M=>M.name)))u.set(d,(u.get(d)||0)+1);m.groups=[...u].sort((g,d)=>d[1]-g[1]||g[0].localeCompare(d[0])).slice(0,36).map(([g,d])=>({key:g,count:d}))}return m}function x(e,{excludeId:t=null,ids:r=null}={}){if(e?.db?.all)return async n=>I(e.db,n,{excludeId:t,ids:r});const s=Array.isArray(r)&&r.length?new Set(r):null;return async n=>{const a=[...n.names||[],...n.terms||[]].join(" "),c=Math.max(Number(n.after)||0,Number(n.since)||0);let i=a?e.search(a,{limit:50,type:n.kind||null,since:c||null,before:n.before?n.before-1:null}):e.list({limit:50,type:n.kind||null}).items;return i=i.filter(o=>o.id!==t&&(!s||s.has(o.id))),n.sort==="newest"&&i.sort((o,l)=>(l.date||0)-(o.date||0)),n.sort==="oldest"&&i.sort((o,l)=>(o.date||0)-(l.date||0)),{rows:i.slice(0,$(n.limit||8,1,50)).map(o=>({id:o.id,kind:o.type,title:o.title||"",date:Number(o.date)||0,snippet:o.snippet||""})),count:i.length,approximate:!0}}}function B(e,{excludeId:t=null,ids:r=null}={}){const s=x(e,{excludeId:t,ids:r});return async({terms:n=[],phrase:a=!1,kind:c="",sinceAt:i=0,limit:o=20}={})=>{const l=(n||[]).map(String).filter(Boolean);return l.length?(await s({kind:c,names:a?[l.join(" ")]:[],terms:a?[]:l,since:i,sort:"relevance",limit:o})).rows:[]}}async function W(e,{store:t,memories:r=[],complete:s=null,previous:n=null,self:a="",excludeId:c=null,ids:i=null,mapWindow:o=0,answerWindow:l=0,parallel:h=1,corrections:f=null,limits:y,now:E}={}){const N=B(t,{excludeId:c,ids:i});return k(String(e||"").slice(0,600),{previous:n,memories:r,knownNames:r.flatMap(p=>R(p?.text||"")),query:x(t,{excludeId:c,ids:i}),readText:async p=>{if(Array.isArray(i)&&i.length&&!i.includes(p))return null;const m=t.get(p);return m?{id:m.id,title:m.title,date:m.date,text:b(m.text)}:null},searchModes:p=>O(String(p).slice(0,500),{lexical:N,memories:r,self:a,excludeId:c,limit:8,modes:["memory","keyword","graph","hybrid"],corrections:f}),complete:s,mapWindow:o,answerWindow:l,parallel:h,corrections:f,self:a,...y?{limits:y}:{},...E?{now:E}:{}})}function j(e){const t=e.read?.[0]||e.rows?.find(s=>!String(s.id).startsWith("memory:"))||null,r=Number(t?.date)||0;return{plan:e.plan,top:t?.id||null,answer:r?new Date(r).toISOString().slice(0,10):""}}function q(e,t,{size:r=0,newest:s=null}={}){return{ok:!0,question:String(e||""),plan:t.plan,how:t.how,framedBy:t.framedBy||"rules",count:t.count,rows:t.rows||[],groups:t.groups||null,read:(t.read||[]).map(n=>({id:n.id,title:n.title||"",date:Number(n.date)||0,parts:n.chunks,of:n.of,speakers:n.speakers||[],notes:n.notes||[]})),memory:t.memory||[],rounds:t.rounds,verdict:t.verdict||null,ms:t.ms,next:j(t),attachment:t.attachment?{title:t.attachment.title,text:t.attachment.text}:null,size:r,newest:s}}export{T as matchOf,b as readable,q as researchResponse,W as researchStore,I as sqliteQuery,B as storeLexical,x as storeQuery};
package/src/server.js CHANGED
@@ -17,7 +17,7 @@ data: ${u}
17
17
 
18
18
  `)},15e3);X.unref?.();let V;try{V=await z.inbox.ask(F,{partner:z.partner,device:z.device,conversation:z.conversation,signal:oe.signal})}finally{clearInterval(X),t.off("close",ee)}if(oe.signal.aborted||t.writableEnded){Ft(c);return}try{await vo(c,JSON.stringify(V))}catch(Z){D.onError(Z);return}}}function Ft(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function si(t,c,{kind:u,adapter:h,agent:w,run:S=null,owner:B=null,linkTurn:M=null},$,b,x,O,G,F=null,D=null){const{messages:H,system:z}=h.toTurn($),{agentModel:oe}=Ut($?.model,x),ee=Xo(x,{...oe?{model:oe}:{},...S||{}}),X=ot(x.bridge.token),V=$t(u,$?.model||w),Z={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Pr(x.redaction,O),entities:[]},fe=await tt(x),C=rn({vault:b,redactOpts:Z,bridgeUrl:fe,token:X,harness:F});B&&(C.ownerApprovals={...B,conversation:B.conversation||`partner.${B.device}.turn-${C.id}`,turnScoped:!B.conversation}),M&&(C.linkTurn=M,C.onEnd=()=>M.end("aborted")),b&&(C.redaction=x.redaction);let Y;try{Y=await on({bridgeUrl:fe,agent:w,token:X,messages:H,system:z,specs:an(G),options:ee,signal:void 0,approvals:!!B||sn(G)})}catch(ve){return M?.end("error",{code:"bridge_error"}),rt(C.id),D?.commit(),a(c,502,{error:{message:`bridge: ${ve.message}`,type:"bridge_error"}})}return C.reader=Y.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(V.sseHead()),cr(c,C,V,D)}async function ii(t,c,u,h,w=null){ht(c.id),c.rounds=(c.rounds||0)+1;try{const B=w?w.clock():0;await vo(c,u),w&&w.lap("redact",B)}catch(B){return c.linkTurn?.end("error",{code:"tool_result"}),rt(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${B.message}`,type:"bridge_error"}})}const S=$t("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(S.sseHead()),cr(t,c,S,w)}function Wt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function li(t,c,{kind:u,adapter:h,redactable:w,pathname:S,agentOverride:B,harness:M,trace:$,run:b=null,owner:x=null,link:O=null},G,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${S} not supported by the bridge backend`});if(u==="openai"){const ae=h.extractLatestToolResult(G);if(ae){const se=ko(ae.tool_call_id),he=se&&bo(se.gwId);if(he)return ii(c,he,ae.content,G?.model,$)}const pe=h.extractTools(G);if((pe.length||x)&&G?.stream===!0){const se=B||ir(G?.model,D),he=O?zt.begin({...O,agentId:se}):null;return si(t,c,{kind:u,adapter:h,agent:se,run:b,owner:x,linkTurn:he},G,F,D,H,pe,M,$)}}const{messages:z,system:oe}=h.toTurn(G),ee=B||ir(G?.model,D),X=O?zt.begin({...O,agentId:ee}):null,V=G?.stream===!0,Z=$t(u,G?.model||ee),fe=ot(D.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Y}=Ut(G?.model,D),ve={bridgeUrl:await tt(D),agent:ee,token:fe,messages:z,system:oe,signal:C.signal,options:Xo(D,{...Y?{model:Y}:{},...b||{}})};if(!V)try{let ae="";const pe=Wt(),se=$?$.clock():0;await go(ve,ke=>{ae+=ke},null,ke=>pe.add(ke)),$&&$.lap("upstream",se);const he=$?$.clock():0,Ot=Z.full(Er(ae,F),pe.value);return $&&$.lap("restore",he),c.writeHead(200,{"content-type":Z.contentType}),c.end(Ot),X?.add(pe.value),X?.end("ok"),$?.commit()}catch(ae){return X?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.commit(),a(c,502,{error:{message:`bridge backend failed: ${ae.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Z.sseHead());const Je=uo(F),Me=$?$.clock():0;let Le=Me;const De=Wt();let $e="",Ye=!1;try{let ae=!0;await go(ve,se=>{$&&ae&&($.lap("upstream",Me),Le=$.clock(),ae=!1);const he=Je.push(se);he&&($e+=he,c.write(Z.sseDelta(he)))},Z.sseActivity?se=>{try{c.write(Z.sseActivity(Or(se,F)))}catch{}}:null,se=>De.add(se));const pe=Je.flush();pe&&($e+=pe,c.write(Z.sseDelta(pe))),c.write(Z.sseTail(De.value))}catch(ae){Ye=!0,c.write(`data: ${JSON.stringify({error:{message:ae.message,type:"bridge_error"}})}
19
19
 
20
- `)}$&&$.lap("stream",Le),c.end(),X&&(X.add(De.value),X.end(C.signal.aborted?"aborted":Ye?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&$e&&co($e,D.redaction)}function di(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const ur=9e4,Kt=60,mr=Kt*16e3*4,ci=4e3;function ui(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let S=0;S<w.length;S++){const B=S*h,M=Math.floor(B),$=Math.min(t.length-1,M+1),b=B-M;w[S]=t[M]*(1-b)+t[$]*b}return w}const pr=new WeakMap,mi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function hr(t,c){const u=wt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Go(u):null}function Qt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function Te(t,c,u,h,{method:w="GET",timeoutMs:S=8e3,pick:B=M=>M}={}){const M=await tt(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=ot(u.bridge?.token),b=w!=="GET"&&w!=="DELETE";try{const x=b?(await v(t,u.maxBodyBytes)).toString("utf8"):"",O=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...b?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...b?{body:x||"{}"}:{},signal:AbortSignal.timeout(S)}),G=await O.json().catch(()=>({}));return O.ok?a(c,200,B(G)):a(c,O.status,{error:{message:G?.error||`bridge ${O.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Qe(t,c){const u=new URLSearchParams;for(const S of t.searchParams.getAll("dir"))S&&u.append("dir",S);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function pi(t,c,{adapter:u,kind:h,pathname:w,search:S,base:B,destKey:M,destProtocol:$,harness:b,trace:x,link:O=null},G,F){let D;const H=x?x.clock():0,z=O?zt.begin(O):null;let oe=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(oe=!0,ee.abort())});const X=(C,Y)=>{z&&(z.add(Y),z.end(oe?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=ai(t.headers,B);M&&($==="anthropic"?(C["x-api-key"]=M,delete C.authorization):C.authorization=`Bearer ${M}`);const Y=Mr(di(B,w,S)).toString();D=await fetch(Y,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:G,signal:ee.signal})}catch(C){return oe?(X(499),x?.commit()):(z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const V=D.headers.get("content-type")||"",Z={};if(D.headers.forEach((C,Y)=>{nr.has(Y.toLowerCase())||(Z[Y]=C)}),V.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(D.status,Z);const Y=z?Xn():null,ve=Y?D.body.pipeThrough(Y.stream):D.body,Je=h==="openai"?_r(ve,c,F,b):xr(ve,c,F);return Promise.resolve(Je).catch(Me=>{if(!oe)throw Me}).finally(()=>{x&&x.lap("stream",C),X(D.status,Y?.usage()),x?.commit()})}let fe;try{fe=Buffer.from(await D.arrayBuffer())}catch(C){if(oe)return X(499),x?.commit();throw C}if(x&&x.lap("upstream",H),z&&X(D.status,V.includes("json")?Zn(fe.toString("utf8")):null),F&&V.includes("application/json"))try{const C=x?x.clock():0,Y=u.restoreResponse(JSON.parse(fe.toString("utf8")),F,b);return x&&x.lap("restore",C),c.writeHead(D.status,{...Z,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Y),"utf8")),x?.commit()}catch{}c.writeHead(D.status,Z),c.end(fe),x?.commit()}function hi(t=lo()){const c=Fn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Wn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Po(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===$o,name:String(o.id===$o?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",S=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),B=r=>/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)&&r!=="/v1/history/stream",M=jr({first:async r=>{const o=Number(new URL(r).port),y=fa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await ee())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=Jr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Lr(r),newId:()=>zr()}),b=Oa({version:de}),x=Ya({log:r=>console.log(` ${r}`)}),O=t.link?.enabled===!1?null:Ea({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:q,signal:W})=>fetch(`http://127.0.0.1:${ke.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Ge()||Ae(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>_e(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Ro(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${is}`));let G=null;const F=()=>{if(!G){const r=t.read||{};G=_a({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return G};let D=null;const H=()=>(D||(D=ma({wrap:(r,o,y,i)=>pa().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),D);let z={at:0,fn:()=>"unknown"},oe=null;async function ee(){if(Date.now()-z.at<1e4)return z.fn;let r=new Map;try{const i=await V().health();for(const[q,W]of Object.entries(i)){const xe=(t.destinations||[]).filter(ge=>ge?.service===q).flatMap(ge=>[ge.id,...ge.models||[]]);for(const ge of[q,...xe])r.set(ge,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return V().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return V().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),z={at:Date.now(),fn:o},z.fn}let X=null;const V=()=>(X||(X=ya({cfg:t,bridgeHealth:async()=>{const r=await tt(t);if(!r)return null;const o=ot(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Ve.join(Ve.dirname(te()),"runtime"),workers:()=>{const r=D?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),X),Z=Number(t.runtime?.idleMinutes),fe=wa({warmMs:(Number.isFinite(Z)&&Z>=0?Z:10)*6e4,log:r=>console.log(r)}),C=ga({cfg:t,wake:(r,o)=>V().wake(r,o),embedded:fe,asleep:r=>V().isAsleep(r)});let Y=null;const ve=()=>(Y||(Y=xa({store:Ta({log:r=>console.warn(`[kb] ${r}`)}),extract:H,embedded:fe,cfg:t,rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>F(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const W=Ge()||Ae(),xe=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ge=await xe.json().catch(()=>({}));return xe.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:r=>console.warn(r),team:r=>De().teamOf(r),remoteCards:()=>Ye().remoteCards(),reveal:(r,o)=>Fa(r,o),confined:()=>!!ft({stateDir:Ve.dirname(te())}).on})),Y);let Je=null;const Me=()=>Je||=Va();let Le=null;const De=()=>(Le||(Le=Ua({store:ve().store,kb:()=>ve(),profiles:Me(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>He(r,{...o,maxRedirects:0}),version:de,log:r=>console.log(r)})),Le);let $e=null;const Ye=()=>($e||($e=Ha({cfg:t,kb:()=>ve(),buckets:De(),profiles:Me(),search:async(r,{limit:o=8}={})=>{ae();const y=await se().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Wa(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await Ze([ut(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},fetchFn:(r,o)=>He(r,o),persist:()=>we(t,te()),log:r=>console.log(r)})),$e),ae=()=>{t.search?.searxng?.url&&V().wake("searxng").catch(()=>{})};let pe=null;const se=()=>{if(!pe){const r=t.search||{},o=r.searxng?.url?es({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;pe=Xa({reader:F(),searxng:o,engines:()=>ts(t),wakeSearxng:()=>V().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await Ze([ut(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return pe};Cr(t.allowedExtensionIds||[]);const he=[],Ot=r=>{he.push(r),he.length>50&&he.shift()},ke=kr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!xt(r.headers.host))return a(o,403,{error:"loopback only"});if(!Ys(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(xt(t.host)&&$a(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Xs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Po(r.headers);Kn(e)&&(r.chatpanelOidc=await u.verify(e))}if(w()==="credential"&&B(i)&&!S(h(r),i))return a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await v(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return nt("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(nt("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{St(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{we(t,te())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return nt("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Ae()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Rr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Ir(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${qe(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${qe(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await wo(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:Ge()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=qe(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(mo(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await wo(t);return a(o,200,{ok:!0,status:n,token:Ge()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=qe(r);return a(o,200,{ok:!0,trust:e,paired:mo(e),version:de})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Hr(t,{version:de,startedAt:ar,managed:et(),certificates:{...Vr(),wanted:po(t)},linkPartners:O?O.status().devices.filter(e=>e.kind==="partner"):[],confined:ft({stateDir:Ve.dirname(te())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Rn(de,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:de,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Ln()})}if(i==="/update"&&r.method==="POST"){const e=Jn(de);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${de} is running.
20
+ `)}$&&$.lap("stream",Le),c.end(),X&&(X.add(De.value),X.end(C.signal.aborted?"aborted":Ye?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&$e&&co($e,D.redaction)}function di(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const ur=9e4,Kt=60,mr=Kt*16e3*4,ci=4e3;function ui(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let S=0;S<w.length;S++){const B=S*h,M=Math.floor(B),$=Math.min(t.length-1,M+1),b=B-M;w[S]=t[M]*(1-b)+t[$]*b}return w}const pr=new WeakMap,mi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function hr(t,c){const u=wt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Go(u):null}function Qt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function Te(t,c,u,h,{method:w="GET",timeoutMs:S=8e3,pick:B=M=>M}={}){const M=await tt(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=ot(u.bridge?.token),b=w!=="GET"&&w!=="DELETE";try{const x=b?(await v(t,u.maxBodyBytes)).toString("utf8"):"",O=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...b?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...b?{body:x||"{}"}:{},signal:AbortSignal.timeout(S)}),G=await O.json().catch(()=>({}));return O.ok?a(c,200,B(G)):a(c,O.status,{error:{message:G?.error||`bridge ${O.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Qe(t,c){const u=new URLSearchParams;for(const S of t.searchParams.getAll("dir"))S&&u.append("dir",S);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function pi(t,c,{adapter:u,kind:h,pathname:w,search:S,base:B,destKey:M,destProtocol:$,harness:b,trace:x,link:O=null},G,F){let D;const H=x?x.clock():0,z=O?zt.begin(O):null;let oe=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(oe=!0,ee.abort())});const X=(C,Y)=>{z&&(z.add(Y),z.end(oe?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=ai(t.headers,B);M&&($==="anthropic"?(C["x-api-key"]=M,delete C.authorization):C.authorization=`Bearer ${M}`);const Y=Mr(di(B,w,S)).toString();D=await fetch(Y,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:G,signal:ee.signal})}catch(C){return oe?(X(499),x?.commit()):(z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const V=D.headers.get("content-type")||"",Z={};if(D.headers.forEach((C,Y)=>{nr.has(Y.toLowerCase())||(Z[Y]=C)}),V.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(D.status,Z);const Y=z?Xn():null,ve=Y?D.body.pipeThrough(Y.stream):D.body,Je=h==="openai"?_r(ve,c,F,b):xr(ve,c,F);return Promise.resolve(Je).catch(Me=>{if(!oe)throw Me}).finally(()=>{x&&x.lap("stream",C),X(D.status,Y?.usage()),x?.commit()})}let fe;try{fe=Buffer.from(await D.arrayBuffer())}catch(C){if(oe)return X(499),x?.commit();throw C}if(x&&x.lap("upstream",H),z&&X(D.status,V.includes("json")?Zn(fe.toString("utf8")):null),F&&V.includes("application/json"))try{const C=x?x.clock():0,Y=u.restoreResponse(JSON.parse(fe.toString("utf8")),F,b);return x&&x.lap("restore",C),c.writeHead(D.status,{...Z,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Y),"utf8")),x?.commit()}catch{}c.writeHead(D.status,Z),c.end(fe),x?.commit()}function hi(t=lo()){const c=Fn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Wn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Po(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===$o,name:String(o.id===$o?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",S=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),B=r=>(/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)||r==="/v1/research")&&r!=="/v1/history/stream",M=jr({first:async r=>{const o=Number(new URL(r).port),y=fa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await ee())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=Jr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Lr(r),newId:()=>zr()}),b=Oa({version:de}),x=Ya({log:r=>console.log(` ${r}`)}),O=t.link?.enabled===!1?null:Ea({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:q,signal:W})=>fetch(`http://127.0.0.1:${ke.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Ge()||Ae(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>_e(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Ro(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${is}`));let G=null;const F=()=>{if(!G){const r=t.read||{};G=_a({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return G};let D=null;const H=()=>(D||(D=ma({wrap:(r,o,y,i)=>pa().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),D);let z={at:0,fn:()=>"unknown"},oe=null;async function ee(){if(Date.now()-z.at<1e4)return z.fn;let r=new Map;try{const i=await V().health();for(const[q,W]of Object.entries(i)){const xe=(t.destinations||[]).filter(ge=>ge?.service===q).flatMap(ge=>[ge.id,...ge.models||[]]);for(const ge of[q,...xe])r.set(ge,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return V().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return V().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),z={at:Date.now(),fn:o},z.fn}let X=null;const V=()=>(X||(X=ya({cfg:t,bridgeHealth:async()=>{const r=await tt(t);if(!r)return null;const o=ot(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Ve.join(Ve.dirname(te()),"runtime"),workers:()=>{const r=D?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),X),Z=Number(t.runtime?.idleMinutes),fe=wa({warmMs:(Number.isFinite(Z)&&Z>=0?Z:10)*6e4,log:r=>console.log(r)}),C=ga({cfg:t,wake:(r,o)=>V().wake(r,o),embedded:fe,asleep:r=>V().isAsleep(r)});let Y=null;const ve=()=>(Y||(Y=xa({store:Ta({log:r=>console.warn(`[kb] ${r}`)}),extract:H,embedded:fe,cfg:t,rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>F(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const W=Ge()||Ae(),xe=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ge=await xe.json().catch(()=>({}));return xe.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:r=>console.warn(r),team:r=>De().teamOf(r),remoteCards:()=>Ye().remoteCards(),reveal:(r,o)=>Fa(r,o),confined:()=>!!ft({stateDir:Ve.dirname(te())}).on})),Y);let Je=null;const Me=()=>Je||=Va();let Le=null;const De=()=>(Le||(Le=Ua({store:ve().store,kb:()=>ve(),profiles:Me(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>He(r,{...o,maxRedirects:0}),version:de,log:r=>console.log(r)})),Le);let $e=null;const Ye=()=>($e||($e=Ha({cfg:t,kb:()=>ve(),buckets:De(),profiles:Me(),search:async(r,{limit:o=8}={})=>{ae();const y=await se().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Wa(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await Ze([ut(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},fetchFn:(r,o)=>He(r,o),persist:()=>we(t,te()),log:r=>console.log(r)})),$e),ae=()=>{t.search?.searxng?.url&&V().wake("searxng").catch(()=>{})};let pe=null;const se=()=>{if(!pe){const r=t.search||{},o=r.searxng?.url?es({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;pe=Xa({reader:F(),searxng:o,engines:()=>ts(t),wakeSearxng:()=>V().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await Ze([ut(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return pe};Cr(t.allowedExtensionIds||[]);const he=[],Ot=r=>{he.push(r),he.length>50&&he.shift()},ke=kr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!xt(r.headers.host))return a(o,403,{error:"loopback only"});if(!Ys(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(xt(t.host)&&$a(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Xs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Po(r.headers);Kn(e)&&(r.chatpanelOidc=await u.verify(e))}if(w()==="credential"&&B(i)&&!S(h(r),i))return a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await v(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return nt("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(nt("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{St(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{we(t,te())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return nt("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Ae()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Rr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Ir(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${qe(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${qe(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await wo(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:Ge()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=qe(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(mo(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await wo(t);return a(o,200,{ok:!0,status:n,token:Ge()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=qe(r);return a(o,200,{ok:!0,trust:e,paired:mo(e),version:de})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Hr(t,{version:de,startedAt:ar,managed:et(),certificates:{...Vr(),wanted:po(t)},linkPartners:O?O.status().devices.filter(e=>e.kind==="partner"):[],confined:ft({stateDir:Ve.dirname(te())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Rn(de,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:de,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Ln()})}if(i==="/update"&&r.method==="POST"){const e=Jn(de);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${de} 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).
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
38
38
 
39
39
  `),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(n),after:m}});const p=re.watch(n,g=>{g.seq==null?l(g):g.seq>m&&(m=g.seq,l(g))});for(const g of re.eventsSince(n,m))m=g.seq,l(g);const f=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});xo||=hn({store:e,notify:Fe,audit:nt});const n=async l=>{const d=(await v(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await yn(r,o,{pathname:i,api:xo,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Hs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Us(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(g,{maxTokens:k=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Ge()||Ae(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:k,temperature:.2})}),Se=await Q.json().catch(()=>({}));return Q.ok?String(Se?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await On(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,En(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(gt*4/3)+1024:t.maxBodyBytes;try{const l=(await v(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await Ye().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Ka]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await v(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Rs({cfg:t,apply:St,persist:()=>we(t,te()),isSelf:l=>Ns(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await v(r,Math.max(t.maxBodyBytes,Math.ceil(gt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await ve().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Re(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:Ht.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ht.push(Zo({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,Math.max(t.maxBodyBytes||0,ni))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const k={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&k.removes.push(T.id);return}try{const R=Mo(T);R&&k.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=At(),R=T?ia((ne,Ee)=>aa(T,{salt:ne,iterations:Ee})):null,Q=async ne=>{if(!R||!ne.blob)return null;const Ee=await R(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?la(da,ne.blob.compression):null;return sa(ne.blob,Ee,{codec:U})},Se=await e.upsertEntries(n.entries,{open:Q});d.push(...Se.written),m+=Se.sealed;for(const ne of Se.written)_(e.get(ne))}return(k.upserts.length||k.removes.length)&&L.bulk(k),d.length&&Fe({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Be)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});xo||=hn({store:e,notify:Fe,audit:nt});const n=async l=>{const d=(await v(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await yn(r,o,{pathname:i,api:xo,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Hs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Us(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(g,{maxTokens:k=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Ge()||Ae(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:k,temperature:.2})}),Se=await Q.json().catch(()=>({}));return Q.ok?String(Se?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await On(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,ids:Array.isArray(e.ids)?e.ids.filter(g=>typeof g=="string"&&/^(chat|note|meeting|brief):[^\s]{1,200}$/.test(g)).slice(0,2e3):null,parallel:3});return a(o,200,En(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(gt*4/3)+1024:t.maxBodyBytes;try{const l=(await v(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await Ye().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Ka]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await v(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Rs({cfg:t,apply:St,persist:()=>we(t,te()),isSelf:l=>Ns(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await v(r,Math.max(t.maxBodyBytes,Math.ceil(gt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await ve().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Re(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:Ht.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ht.push(Zo({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,Math.max(t.maxBodyBytes||0,ni))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const k={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&k.removes.push(T.id);return}try{const R=Mo(T);R&&k.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=At(),R=T?ia((ne,Ee)=>aa(T,{salt:ne,iterations:Ee})):null,Q=async ne=>{if(!R||!ne.blob)return null;const Ee=await R(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?la(da,ne.blob.compression):null;return sa(ne.blob,Ee,{codec:U})},Se=await e.upsertEntries(n.entries,{open:Q});d.push(...Se.written),m+=Se.sealed;for(const ne of Se.written)_(e.get(ne))}return(k.upserts.length||k.removes.length)&&L.bulk(k),d.length&&Fe({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Be)try{m.write(`event: deleted
42
42
  data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
43
43
 
44
44
  `)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:K.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:oa(m?.source))===No,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${No}" is this gateway's own log`})),d=qn(K,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:K.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return K?a(o,200,{ok:!0,cursor:K.cursor(),count:K.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=ea(K.all());return a(o,200,{ok:!0,stats:e,year:ta(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Bo(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=K.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>Mt(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=Bo(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.160.1";export{o as VERSION};
1
+ const o="0.161.0";export{o as VERSION};