@chatpanel/gateway 0.152.1 → 0.153.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.152.1",
3
+ "version": "0.153.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.52.0",
27
- "@chatpanel/events": "^0.496.0",
27
+ "@chatpanel/events": "^0.498.0",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/kb.js CHANGED
@@ -1,3 +1,3 @@
1
- import{readFileSync as le,statSync as ne,readdirSync as je,realpathSync as ue}from"node:fs";import{join as ze,basename as C,extname as fe,resolve as Be,dirname as De}from"node:path";import Fe from"node:os";import{createKb as pe,addDocument as se,removeDocument as V,addNote as Ne,setNoteStatus as Ce,searchKb as Ie,embedMissing as We,kbNeedsVectors as Re,kbStatus as Ue,readPage as Xe,chunkById as he,refreshKb as Y,setKbAccess as He,kbMayUse as re,graphWalk as Ve}from"@chatpanel/events/kb-index.js";import{kbResearch as Ye}from"@chatpanel/events/kb-research.js";import{neighbours as Je,pathBetween as Qe,resolveNode as ge,graphReport as Ze}from"@chatpanel/events/kb-graph.js";import{outlineOf as me}from"@chatpanel/events/kb-chunk.js";import{routeKb as qe,validateKbCreate as et,validateKbAdd as tt,validateKbSearch as nt,validateKbResearch as st,validateKbGraph as rt,validateKbNote as at,validateKbNoteStatus as ot,validateKbAccess as it,validateKbSync as ct,validateKbReveal as dt,kbGraphLimit as lt,KB_LOCAL_ACTIONS as ut}from"@chatpanel/events/kb-capability.js";import{communities as ft,topEntities as be}from"@chatpanel/events/kb-graph.js";import{kbCard as pt,pageStrip as ht}from"@chatpanel/events/kb-view.js";import{planFolderSync as gt,folderDocId as mt,folderSource as bt,knownFiles as kt}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as yt,markdownLinks as wt,resolveLinks as vt,visibleTextHash as St,decodeText as $t}from"@chatpanel/events/kb-html.js";import{secretReason as ke,SKIP_DIR_NAMES as Ot,sniffType as Tt,checkAttachablePath as xt}from"@chatpanel/events/attached-paths.js";import{paginateText as J,MAX_DOCUMENT_BYTES as ae}from"./extract-capability.js";import{defaultEmbeddedModel as _t}from"./embedded-models.js";import{primaryProvider as Et}from"./capability-config.js";function P(b,A){const S=Ue(b);return A?S:{...S,documents:S.documents.map(K=>{const{path:B,...L}=K.source||{};return{...K,source:L}})}}const I=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),ye=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Pt=new Set([".html",".htm",".xhtml"]),At=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(b,A,S,K={})=>({status:b,body:{error:{type:A,message:S},...K}}),w=b=>({status:200,body:b});function Kt(b,{limit:A=60}={}){Y(b);const S=b.graph||{nodes:[],edges:[]},K=new Set(be(S,{limit:A}).map(h=>h.id)),B=new Map(be(S,{limit:A}).map(h=>[h.id,h.weight])),L=S.nodes.filter(h=>h.kind==="entity"?K.has(h.id)||h.type==="person"||h.type==="role":h.kind!=="chunk").slice(0,A*6),D=new Set(L.map(h=>h.id)),j=S.edges.filter(h=>D.has(h.from)&&D.has(h.to)),y=h=>h.kind==="holds"||h.kind==="member"||h.kind==="has",W=[...j.filter(y),...j.filter(h=>!y(h))].slice(0,A*20),z=ft(S).map(h=>({...h,members:h.members.filter(R=>D.has(R))})).filter(h=>h.members.length>=2).slice(0,24);return{nodes:L.map(h=>({id:h.id,kind:h.kind,label:h.label,count:h.count,...h.type?{type:h.type}:{},...h.doc?{doc:h.doc}:{},...B.has(h.id)?{weight:B.get(h.id)}:{}})),edges:W,communities:z,total:{nodes:S.nodes.length,edges:S.edges.length}}}function Vt({store:b,extract:A=null,embedded:S=null,cfg:K={},rerank:B=null,read:L=null,completer:D=null,log:j=()=>{},now:y=()=>Date.now(),home:W=Fe.homedir(),team:z=()=>null,remoteCards:h=null,reveal:R=null,confined:we=()=>!1}={}){const N=()=>{const e=Et(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||_t("embed")||""},Q=(e="passage")=>{const t=N();if(!S||!t)return null;const c=S.health("embed",t);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?(S.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await S.embed(t,l,{kind:e})).vectors},ve=typeof B=="function"?B:null,Z=new Set;function oe(e){!e||Z.has(e.id)||e.embed==="off"||!Q("passage")||Re(e)&&(Z.add(e.id),F(e).then(t=>{t&&(b.save(e),j(`[kb] ${e.id}: ${t} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>Z.delete(e.id)))}async function F(e,{late:t=()=>!1}={}){const c=Q("passage");if(!c)return 0;try{return await We(e,c,{model:N(),late:t})}catch(l){return j(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function Se(e,t,c=""){const l=Tt(e,t);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=$t(e);if(/\.x?html?$/i.test(t)||/html/i.test(l.label||"")){const s=yt(r);return{type:"html",pages:J(s.markdown).map(($,T)=>({page:T+1,text:$})),title:s.title,links:s.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
2
- `).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(t);return{type:l.label||"text",pages:J(r).map((s,$)=>({page:$+1,text:s})),title:f?f[1].trim():"",links:k?wt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),a=await o.open(e,{name:t,hint:c}),u=[];for(let r=1;r<=a.pages;r+=1){let f="";try{f=String((await o.page(a.hash,r)).text||"")}catch(k){j(`[kb] ${t} p.${r}: ${k.message}`)}u.push({page:r,text:f,...a.labels?.[r-1]?{label:a.labels[r-1]}:{}})}return{type:a.type,pages:u,title:a.title||"",hash:a.hash,scanned:!!a.scanned,markdown:!!a.markdown,labels:a.labels||[]}}async function U(e,t,{name:c,hint:l="",title:o="",source:a={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const s=await Se(t,c,l),$=St(s.pages.map(i=>i.text).join(`
3
- `));if(k&&$){const i=e.docs.find(d=>d.textHash===$&&d.id!==r);if(i)return{duplicateOf:i}}const T=a.path&&s.links?.length?vt(a.path,s.links,{root:f||De(a.path)}):[],n=se(e,{id:r,title:o||s.title||C(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:y,links:T,textHash:$,markdownHeadings:!!s.markdown});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced,...s.scanned?{scanned:!0}:{}}}function $e(e,t){const c=fe(e).toLowerCase();return!ye.has(c)&&!At.has(c)?!1:t?.length?t.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function ie(e,{recursive:t=!0,include:c=null}={}){const l=xt(e,{home:W,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=ue(Be(e.replace(/^~(?=$|\/)/,W))),a=[],u=[];let r=0;const f=($,T)=>{if(a.length>=I.files)return u.push({path:T,why:`stopped at ${I.files} files`}),!1;if(ke($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let n;try{n=ne($)}catch{return!0}const i=fe($).toLowerCase(),d=ye.has(i)||Pt.has(i)?ae:I.textBytes;return n.size>d?(u.push({path:T,why:`too large (${Math.round(n.size/1048576)} MB)`}),!0):r+n.size>I.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=n.size,a.push({full:$,rel:T,size:n.size,mtime:Math.floor(n.mtimeMs)}),!0)};if(!ne(o).isDirectory())return f(o,C(o)),{root:o,files:a,skipped:u,single:!0};const s=($,T,n)=>{if(n>I.depth)return!0;let i=[];try{i=je($,{withFileTypes:!0}).sort((d,m)=>d.name.localeCompare(m.name))}catch{return!0}for(const d of i){const m=d.name;if(m.startsWith(".")&&d.isDirectory())continue;const v=ze($,m),p=T?`${T}/${m}`:m;if(d.isDirectory()){if(Ot.has(m)||!t)continue;try{if(!ue(v).startsWith(o)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(v,p,n+1))return!1;continue}if(!(!d.isFile()&&!d.isSymbolicLink())){if(ke(v)){u.push({path:p,why:"withheld (a credential store)"});continue}if($e(m,c)&&!f(v,p))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function Oe(e,{path:t,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=ie(t,{recursive:c,include:l}),f=[];for(const k of a)try{const s=await U(e,le(k.full),{name:C(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Te(e,{path:t,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=ie(t,{recursive:!0,include:c}),f=bt(e,a,{include:c});if(l){for(const p of Object.values(f.files))p?.id&&V(e,p.id,{now:y});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,x]of Object.entries(f.files))x?.dupOf&&!k.has(x.dupOf)&&delete f.files[p];const s=gt({known:kt(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const $=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){V(e,p,{now:y});for(const[x,E]of Object.entries(f.files))E.id===p&&(delete f.files[x],T.push(x.startsWith(`${a}/`)?x.slice(a.length+1):x))}const n=[],i=[],d=[],m=p=>String(p||"").startsWith(`${a}/`)?p.slice(a.length+1):p,v=async(p,x)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(p),G=mt(p);try{const _=await U(e,le(p),{name:C(p),source:{kind:"file",path:p},reach:"internal",id:G,root:a,dedupe:!0});_.duplicateOf?(e.docs.some(ee=>ee.id===G)&&V(e,G,{now:y}),f.files[p]={id:G,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},d.push({path:E.rel,of:m(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:G,size:E.size,mtime:E.mtime},x.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const p of s.add)await v(p,n);for(const p of s.change)await v(p.path,i);return f.syncedAt=y(),f.lastSync={at:f.syncedAt,added:n.length,changed:i.length,removed:T.length,same:s.same,duplicates:d.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:d.slice(0,20)},{root:a,added:n,changed:i,removed:T,same:s.same,duplicates:d,skipped:r}}async function xe(e,{url:t,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().read({url:t,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=J(o).map((r,f)=>({page:f+1,text:r})),u=se(e,{title:c||l.body.title||t,pages:a,source:{kind:"url",url:l.body.url||t,name:l.body.title||""},type:"html",reach:"web",now:y});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function _e(e,t,{admin:c=!1}={}){const l=y();let o=[],a=[];if(t.kind==="bytes"){const r=Buffer.from(t.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>ae)return g(413,"too_large",`kb: ${r.length} bytes is over the ${ae}-byte limit`);try{o.push(await U(e,r,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(f){return X(f)}}else if(t.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:o,skipped:a}=await Oe(e,t))}catch(r){return X(r)}}else if(t.kind==="url")try{o.push(await xe(e,t))}catch(r){return X(r)}else if(t.kind==="text"){const r=J(t.text).map((k,s)=>({page:s+1,text:k})),f=se(e,{title:t.title||t.name,pages:r,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:y});o.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=o.length?await F(e):0;return b.save(e),w({added:o,skipped:a,embedded:u,kb:P(e,c),ms:y()-l})}function X(e){const t=e?.code||"";return t==="refused"?g(403,"refused",`kb: ${e.message}`):t==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):t==="too_large"?g(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?g(502,"read_failed",`kb: ${e.message}`):t==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ee=e=>e.vectors?.model&&e.vectors.model!==N()?null:Q("query"),q=(e,t)=>Ie(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],...t.filters?{filters:t.filters}:{},embed:Ee(e),rerank:t.rerank===!1?null:ve,now:y}),Pe=(e,t)=>e.docs.find(c=>c.id===t)?.title||t,ce=(e,t)=>{const c=he(e,t);if(!c)return null;const l=c.kind==="note"?"Note":Pe(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Ae(e,t){Y(e);const c=t.node.replace(/^chunk:/,""),l=(/#\d+$/.test(c)&&he(e,c)?{id:`chunk:${c}`,kind:"chunk",label:c}:null)||ge(e.graph,t.node);if(!l)return w({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},a=Ve(e,l.id,{limit:Math.min(8,t.limit||6),...t.query?{query:t.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:Je(e.graph,l.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit}),passages:a.passages,next:a.next};if(t.to){const r=ge(e.graph,t.to);u.to=t.to,u.path=r?(Qe(e.graph,l.id,r.id)||[]).map(o):null,r&&!u.path.length&&(u.path=null)}return w(u)}async function Ke(e,t,{admin:c=!1}={}){if(t.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=t.model&&typeof D=="function"?D(t.model):null,o=P(e,c),a=await Ye(t.question,{search:(u,r)=>q(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||t.docs||null}),outline:async u=>u?me(e.chunks,{doc:u}):e.outline,read:async u=>ce(e,u),complete:l,kbName:e.name,docs:o.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:y});return w({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function de(e,t){const c=P(e,t),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=t?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return pt({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:z(e.id),now:y()})}async function Me({method:e="GET",pathname:t="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=qe(t);if(!r)return g(404,"not_found",`no route ${t}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ut.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=n=>{try{return{value:n()}}catch(i){return{res:g(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const n=[];for(const{manifest:d}of b.list()){if(!re({access:d.access},f))continue;const m=b.load(d.id);m&&n.push(de(m,o))}const i=o&&typeof h=="function"?await h({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return w({cards:n,...i.length?{remote:i}:{}})}if(e==="GET")return w({kbs:b.list().filter(({manifest:n})=>re({access:n.access},f)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=k(()=>et(l||{}));if(n.res)return n.res;const i=n.value;if(i.id&&b.load(i.id))return w({kb:P(b.load(i.id),o),existed:!0});const d=pe({id:i.id,name:i.name,embed:i.embed,now:y});return b.save(d),{status:201,body:{kb:P(d,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(z(r.id))return H(r.id);const n=k(()=>ct(l||{}));if(n.res)return n.res;const i=n.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let m=b.load(r.id);const v=!m;m||(m=pe({id:r.id,name:i.name||C(String(i.path).replace(/[\\/]+$/,""))||r.id,now:y}),b.save(m));const p=y(),x={done:0,total:0},E=(async()=>{const O=await Te(m,i,{progress:x});if(x.cancel)return{cancelled:!0};const Ge=O.added.length+O.changed.length+O.removed.length,Le=O.added.length||O.changed.length?await F(m):0;return(Ge||v)&&b.save(m),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Le,made:v,kb:P(m,o),ms:y()-p}})();M.set(r.id,{progress:x,base:m}),E.catch(O=>j(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const G=i.waitMs??5e3;if(G===0)return{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}};let _=null;const ee=new Promise(O=>{_=setTimeout(()=>O(null),G)});let te;try{te=await Promise.race([E,ee])}catch(O){return clearTimeout(_),X(O)}return clearTimeout(_),te?w(te):{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}}}const s=b.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=z(s.id)?.role==="replica",T=!!z(s.id);if(!re(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||oe(s);const n=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return w({kb:{...n,coverage:n.chunks?Math.round(n.vectors/n.chunks*100):0,bytes:b.sizeOf(s.id),dir:o?b.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:m})=>({done:d,total:m}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const n=M.get(s.id);return n&&(n.progress.cancel=!0),b.remove(s.id),w({ok:!0,...n?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>tt(l||{}));return n.res?n.res:_e(s,n.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?V(s,r.rest,{now:y})?(b.save(s),w({ok:!0,kb:P(s,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const n=Number(c.get("page"))||1,i=Xe(s,r.rest,n);return i?w(i):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return w({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const n=ce(s,r.rest);return n?w(n):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){Y(s);const n=c.get("doc");return w({outline:n?me(s.chunks,{doc:n}):s.outline})}break}case"search":{if(e==="POST"){const n=k(()=>nt(l||{}));if(n.res)return n.res;const i=y(),d=await q(s,n.value);return oe(s),w({...d,ms:y()-i})}break}case"research":{if(e==="POST"){const n=k(()=>st(l||{}));return n.res?n.res:Ke(s,n.value,{admin:o})}break}case"graph":{if(e==="GET")return w(Kt(s,{limit:lt(c.get("limit"))}));if(e==="POST"){const n=k(()=>rt(l||{}));return n.res?n.res:Ae(s,n.value)}break}case"report":{if(e==="GET")return Y(s),{status:200,text:Ze(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return w({notes:s.notes});if($&&e==="POST")return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>at(l||{}));if(n.res)return n.res;const i=n.value,d=i.status==="accepted"&&o?"accepted":"proposed",m=Ne(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:y});return await F(s),b.save(s),{status:201,body:{note:m}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=k(()=>ot(l||{}));if(n.res)return n.res;const i=n.value,d=Ce(s,r.rest,i.status,{now:y});return d?(b.save(s),w({note:d,removed:i.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return w({access:s.access});if($&&e==="POST")return H(s.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=k(()=>it(l||{}));if(n.res)return n.res;const i=He(s,n.value,{now:y});return b.save(s),w({access:i})}break}case"pages":{if(e!=="GET")break;const n=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===n);return i?w(ht(s.chunks,i)):g(404,"not_found",`kb: no document ${n||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(we())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(z(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof R!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const n=k(()=>dt(l||{}));if(n.res)return n.res;const i=n.value;let d="",m="file";if(i.doc){const v=s.docs.find(p=>p.id===i.doc);if(!v)return g(404,"not_found",`kb: no document ${i.doc}`);d=v.source?.path||"",d||(d=b.dirOf(s.id),m="index")}else if(i.source!=null){const v=(s.sources||[])[i.source];if(!v?.path)return g(404,"not_found",`kb: no kept folder ${i.source}`);d=v.path,m="folder"}else{const v=(s.sources||[]).find(p=>p.path);d=v?.path||b.dirOf(s.id),m=v?"folder":"index"}try{ne(d)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await R(d,{folder:m!=="file"})}catch(v){return g(502,"reveal_failed",`kb: the file manager did not open — ${v.message}`)}return w({ok:!0,revealed:m})}case"embed":{if(e==="POST"){const n=N(),i=S&&n?S.health("embed",n):{state:"off"},d=await F(s);return d&&b.save(s),w({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||n,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}function H(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:Me,store:b,embedModel:N,cardOf:de,addBytes:(e,t,c)=>U(e,t,c),embedAll:e=>F(e),searchBase:(e,t)=>q(e,t)}}export{I as KB_WALK_LIMITS,Vt as createKbService,P as kbStatusFor,Kt as wholeGraph};
1
+ import{readFileSync as oe,statSync as ae,readdirSync as Be,realpathSync as me}from"node:fs";import{join as De,basename as W,extname as Z,resolve as Fe,dirname as Ie}from"node:path";import Ne from"node:os";import{createKb as be,addDocument as ie,removeDocument as q,addNote as Re,setNoteStatus as We,searchKb as Ue,embedMissing as He,kbNeedsVectors as Xe,kbStatus as Ve,readPage as Ye,chunkById as ce,refreshKb as ee,setKbAccess as Je,kbMayUse as de,graphWalk as Qe}from"@chatpanel/events/kb-index.js";import{kbResearch as Ze}from"@chatpanel/events/kb-research.js";import{neighbours as qe,pathBetween as et,resolveNode as ke,graphReport as tt}from"@chatpanel/events/kb-graph.js";import{outlineOf as ye}from"@chatpanel/events/kb-chunk.js";import{routeKb as nt,validateKbCreate as st,validateKbAdd as rt,validateKbSearch as ot,validateKbResearch as at,validateKbGraph as it,validateKbNote as ct,validateKbNoteStatus as dt,validateKbAccess as lt,validateKbSync as ut,validateKbReveal as ft,kbGraphLimit as pt,KB_LOCAL_ACTIONS as ht}from"@chatpanel/events/kb-capability.js";import{communities as gt,topEntities as we}from"@chatpanel/events/kb-graph.js";import{kbCard as mt,pageStrip as bt}from"@chatpanel/events/kb-view.js";import{passagePageHtml as kt}from"@chatpanel/events/kb-cite.js";import{planFolderSync as yt,folderDocId as wt,folderSource as vt,knownFiles as St}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as $t,markdownLinks as xt,resolveLinks as Tt,visibleTextHash as Ot,decodeText as _t}from"@chatpanel/events/kb-html.js";import{secretReason as ve,SKIP_DIR_NAMES as Et,sniffType as Pt,checkAttachablePath as At}from"@chatpanel/events/attached-paths.js";import{paginateText as te,MAX_DOCUMENT_BYTES as le}from"./extract-capability.js";import{defaultEmbeddedModel as jt}from"./embedded-models.js";import{primaryProvider as Kt}from"./capability-config.js";function P(y,A){const $=Ve(y);return A?$:{...$,documents:$.documents.map(K=>{const{path:D,...G}=K.source||{};return{...K,source:G}})}}const U=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),Se=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Lt=new Set([".html",".htm",".xhtml"]),Mt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(y,A,$,K={})=>({status:y,body:{error:{type:A,message:$},...K}}),S=y=>({status:200,body:y});function Gt(y,{limit:A=60}={}){ee(y);const $=y.graph||{nodes:[],edges:[]},K=new Set(we($,{limit:A}).map(m=>m.id)),D=new Map(we($,{limit:A}).map(m=>[m.id,m.weight])),G=$.nodes.filter(m=>m.kind==="entity"?K.has(m.id)||m.type==="person"||m.type==="role":m.kind!=="chunk").slice(0,A*6),F=new Set(G.map(m=>m.id)),z=$.edges.filter(m=>F.has(m.from)&&F.has(m.to)),v=m=>m.kind==="holds"||m.kind==="member"||m.kind==="has",H=[...z.filter(v),...z.filter(m=>!v(m))].slice(0,A*20),C=gt($).map(m=>({...m,members:m.members.filter(X=>F.has(X))})).filter(m=>m.members.length>=2).slice(0,24);return{nodes:G.map(m=>({id:m.id,kind:m.kind,label:m.label,count:m.count,...m.type?{type:m.type}:{},...m.doc?{doc:m.doc}:{},...D.has(m.id)?{weight:D.get(m.id)}:{}})),edges:H,communities:C,total:{nodes:$.nodes.length,edges:$.edges.length}}}const $e=Object.freeze({".pdf":"application/pdf",".txt":"text/plain; charset=utf-8",".md":"text/plain; charset=utf-8",".csv":"text/plain; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"});function qt({store:y,extract:A=null,embedded:$=null,cfg:K={},rerank:D=null,read:G=null,completer:F=null,log:z=()=>{},now:v=()=>Date.now(),home:H=Ne.homedir(),team:C=()=>null,remoteCards:m=null,reveal:X=null,confined:xe=()=>!1}={}){const N=()=>{const e=Kt(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||jt("embed")||""},ne=(e="passage")=>{const n=N();if(!$||!n)return null;const d=$.health("embed",n);return d.state!=="ready"&&d.state!=="loading"&&!d.installed?($.embed(n,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await $.embed(n,l,{kind:e})).vectors},Te=typeof D=="function"?D:null,se=new Set;function ue(e){!e||se.has(e.id)||e.embed==="off"||!ne("passage")||Xe(e)&&(se.add(e.id),I(e).then(n=>{n&&(y.save(e),z(`[kb] ${e.id}: ${n} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>se.delete(e.id)))}async function I(e,{late:n=()=>!1}={}){const d=ne("passage");if(!d)return 0;try{return await He(e,d,{model:N(),late:n})}catch(l){return z(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function Oe(e,n,d=""){const l=Pt(e,n);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=_t(e);if(/\.x?html?$/i.test(n)||/html/i.test(l.label||"")){const s=$t(r);return{type:"html",pages:te(s.markdown).map((x,T)=>({page:T+1,text:x})),title:s.title,links:s.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
2
+ `).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(n);return{type:l.label||"text",pages:te(r).map((s,x)=>({page:x+1,text:s})),title:f?f[1].trim():"",links:k?xt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const i=A(),o=await i.open(e,{name:n,hint:d}),u=[];for(let r=1;r<=o.pages;r+=1){let f="";try{f=String((await i.page(o.hash,r)).text||"")}catch(k){z(`[kb] ${n} p.${r}: ${k.message}`)}u.push({page:r,text:f,...o.labels?.[r-1]?{label:o.labels[r-1]}:{}})}return{type:o.type,pages:u,title:o.title||"",hash:o.hash,scanned:!!o.scanned,markdown:!!o.markdown,labels:o.labels||[]}}async function V(e,n,{name:d,hint:l="",title:i="",source:o={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const s=await Oe(n,d,l),x=Ot(s.pages.map(c=>c.text).join(`
3
+ `));if(k&&x){const c=e.docs.find(a=>a.textHash===x&&a.id!==r);if(c)return{duplicateOf:c}}const T=o.path&&s.links?.length?Tt(o.path,s.links,{root:f||Ie(o.path)}):[],t=ie(e,{id:r,title:i||s.title||W(d),pages:s.pages,source:{kind:o.kind||"bytes",name:d,...o},hash:s.hash||"",type:s.type,reach:u,now:v,links:T,textHash:x,markdownHeadings:!!s.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...s.scanned?{scanned:!0}:{}}}function _e(e,n){const d=Z(e).toLowerCase();return!Se.has(d)&&!Mt.has(d)?!1:n?.length?n.some(l=>{const i=String(l).toLowerCase().replace(/^\*/,"");return d===(i.startsWith(".")?i:`.${i}`)||e.toLowerCase().endsWith(i)}):!0}function fe(e,{recursive:n=!0,include:d=null}={}){const l=At(e,{home:H,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const i=me(Fe(e.replace(/^~(?=$|\/)/,H))),o=[],u=[];let r=0;const f=(x,T)=>{if(o.length>=U.files)return u.push({path:T,why:`stopped at ${U.files} files`}),!1;if(ve(x))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ae(x)}catch{return!0}const c=Z(x).toLowerCase(),a=Se.has(c)||Lt.has(c)?le:U.textBytes;return t.size>a?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>U.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,o.push({full:x,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ae(i).isDirectory())return f(i,W(i)),{root:i,files:o,skipped:u,single:!0};const s=(x,T,t)=>{if(t>U.depth)return!0;let c=[];try{c=Be(x,{withFileTypes:!0}).sort((a,h)=>a.name.localeCompare(h.name))}catch{return!0}for(const a of c){const h=a.name;if(h.startsWith(".")&&a.isDirectory())continue;const w=De(x,h),p=T?`${T}/${h}`:h;if(a.isDirectory()){if(Et.has(h)||!n)continue;try{if(!me(w).startsWith(i)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(w,p,t+1))return!1;continue}if(!(!a.isFile()&&!a.isSymbolicLink())){if(ve(w)){u.push({path:p,why:"withheld (a credential store)"});continue}if(_e(h,d)&&!f(w,p))return!1}}return!0};return s(i,"",0),{root:i,files:o,skipped:u}}async function Ee(e,{path:n,recursive:d=!0,include:l=null,title:i=""}){const{files:o,skipped:u,single:r}=fe(n,{recursive:d,include:l}),f=[];for(const k of o)try{const s=await V(e,oe(k.full),{name:W(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?i:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Pe(e,{path:n,include:d=null,rebuild:l=!1},{progress:i=null}={}){const{root:o,files:u,skipped:r}=fe(n,{recursive:!0,include:d}),f=vt(e,o,{include:d});if(l){for(const p of Object.values(f.files))p?.id&&q(e,p.id,{now:v});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,O]of Object.entries(f.files))O?.dupOf&&!k.has(O.dupOf)&&delete f.files[p];const s=yt({known:St(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});i&&(i.total=s.add.length+s.change.length,i.done=0);const x=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){q(e,p,{now:v});for(const[O,E]of Object.entries(f.files))E.id===p&&(delete f.files[O],T.push(O.startsWith(`${o}/`)?O.slice(o.length+1):O))}const t=[],c=[],a=[],h=p=>String(p||"").startsWith(`${o}/`)?p.slice(o.length+1):p,w=async(p,O)=>{if(i?.cancel)return;await new Promise(_=>setImmediate(_));const E=x.get(p),j=wt(p);try{const _=await V(e,oe(p),{name:W(p),source:{kind:"file",path:p},reach:"internal",id:j,root:o,dedupe:!0});_.duplicateOf?(e.docs.some(R=>R.id===j)&&q(e,j,{now:v}),f.files[p]={id:j,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},a.push({path:E.rel,of:h(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:j,size:E.size,mtime:E.mtime},O.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}i&&(i.done+=1)};for(const p of s.add)await w(p,t);for(const p of s.change)await w(p.path,c);return f.syncedAt=v(),f.lastSync={at:f.syncedAt,added:t.length,changed:c.length,removed:T.length,same:s.same,duplicates:a.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:a.slice(0,20)},{root:o,added:t,changed:c,removed:T,same:s.same,duplicates:a,skipped:r}}async function Ae(e,{url:n,title:d=""}){if(!G)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await G().read({url:n,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const i=String(l.body.markdown||l.body.text||"");if(!i.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const o=te(i).map((r,f)=>({page:f+1,text:r})),u=ie(e,{title:d||l.body.title||n,pages:o,source:{kind:"url",url:l.body.url||n,name:l.body.title||""},type:"html",reach:"web",now:v});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function je(e,n,{admin:d=!1}={}){const l=v();let i=[],o=[];if(n.kind==="bytes"){const r=Buffer.from(n.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>le)return g(413,"too_large",`kb: ${r.length} bytes is over the ${le}-byte limit`);try{i.push(await V(e,r,{name:n.name,hint:n.type||"",title:n.title,reach:n.reach}))}catch(f){return Y(f)}}else if(n.kind==="path"){if(!d)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:i,skipped:o}=await Ee(e,n))}catch(r){return Y(r)}}else if(n.kind==="url")try{i.push(await Ae(e,n))}catch(r){return Y(r)}else if(n.kind==="text"){const r=te(n.text).map((k,s)=>({page:s+1,text:k})),f=ie(e,{title:n.title||n.name,pages:r,source:{kind:"text",name:n.name},type:"text",reach:n.reach,now:v});i.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=i.length?await I(e):0;return y.save(e),S({added:i,skipped:o,embedded:u,kb:P(e,d),ms:v()-l})}function Y(e){const n=e?.code||"";return n==="refused"?g(403,"refused",`kb: ${e.message}`):n==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):n==="too_large"?g(413,"too_large",`kb: ${e.message}`):n==="read_failed"||n==="empty"?g(502,"read_failed",`kb: ${e.message}`):n==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ke=e=>e.vectors?.model&&e.vectors.model!==N()?null:ne("query"),re=(e,n)=>Ue(e,n.query,{limit:n.limit,hops:n.hops,docs:n.docs||null,queries:n.queries||[],...n.filters?{filters:n.filters}:{},embed:Ke(e),rerank:n.rerank===!1?null:Te,now:v}),Le=(e,n)=>e.docs.find(d=>d.id===n)?.title||n,pe=(e,n)=>{const d=ce(e,n);if(!d)return null;const l=d.kind==="note"?"Note":Le(e,d.doc);return{...d,title:l,cite:d.kind==="note"?`[note ${d.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${d.page}]`}};function Me(e,n){ee(e);const d=n.node.replace(/^chunk:/,""),l=(/#\d+$/.test(d)&&ce(e,d)?{id:`chunk:${d}`,kind:"chunk",label:d}:null)||ke(e.graph,n.node);if(!l)return S({node:null,neighbours:[],message:`no node named "${n.node}"`});const i=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},o=Qe(e,l.id,{limit:Math.min(8,n.limit||6),...n.query?{query:n.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:qe(e.graph,l.id,{hops:n.hops,kinds:n.kinds||null,limit:n.limit}),passages:o.passages,next:o.next};if(n.to){const r=ke(e.graph,n.to);u.to=n.to,u.path=r?(et(e.graph,l.id,r.id)||[]).map(i):null,r&&!u.path.length&&(u.path=null)}return S(u)}async function Ge(e,n,{admin:d=!1}={}){if(n.model&&!d)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=n.model&&typeof F=="function"?F(n.model):null,i=P(e,d),o=await Ze(n.question,{search:async(u,r)=>{const f=await re(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||n.docs||null});return f&&Array.isArray(f.results)?{...f,results:f.results.map(k=>({...k,kb:e.id}))}:f},outline:async u=>u?ye(e.chunks,{doc:u}):e.outline,read:async u=>{const r=pe(e,u);return r&&{...r,kb:e.id}},complete:l,kbName:e.name,docs:i.documents,previous:n.previous||null,answer:n.answer||"",ask:n.ask!==!1,now:v});return S({attachment:o.attachment,read:o.read,hits:o.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:o.queries,verdict:o.verdict,rounds:o.rounds,ask:o.ask,how:o.how,frame:{whole:o.frame.whole,docs:o.frame.docs},ms:o.ms})}const L=new Map;function he(e,n){const d=P(e,n),l=e.chunks.length?e.chunks.filter(o=>o.form||o.label).length/e.chunks.length:1,i=n?(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0,...o.lastSync?{lastSync:{at:o.lastSync.at,added:o.lastSync.added,changed:o.lastSync.changed,removed:o.lastSync.removed,skipped:o.lastSync.skipped}}:{}})):(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0}));return mt({...d,coverage:d.chunks?Math.round(d.vectors/d.chunks*100):0,placed:l,sources:i,...L.has(e.id)?{syncing:(({done:o,total:u})=>({done:o,total:u}))(L.get(e.id).progress)}:{}},{outline:e.outline,team:C(e.id),now:v()})}async function ze({method:e="GET",pathname:n="",query:d=new URLSearchParams,body:l=null,admin:i=!1,agent:o="",local:u=!0}={}){const r=nt(n);if(!r)return g(404,"not_found",`no route ${n}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ht.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:i,agent:String(o||d.get("agent")||"").trim().toLowerCase()},k=t=>{try{return{value:t()}}catch(c){return{res:g(400,"invalid_request",c.message)}}};if(!r.id){if(e==="GET"&&d.get("view")==="card"){const t=[];for(const{manifest:a}of y.list()){if(!de({access:a.access},f))continue;const h=y.load(a.id);h&&t.push(he(h,i))}const c=i&&typeof m=="function"?await m({admin:i}).catch(a=>[{gateway:"remote",error:a.message}]):[];return S({cards:t,...c.length?{remote:c}:{}})}if(e==="GET")return S({kbs:y.list().filter(({manifest:t})=>de({access:t.access},f)).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=k(()=>st(l||{}));if(t.res)return t.res;const c=t.value;if(c.id&&y.load(c.id))return S({kb:P(y.load(c.id),i),existed:!0});const a=be({id:c.id,name:c.name,embed:c.embed,now:v});return y.save(a),{status:201,body:{kb:P(a,i)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!i)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(C(r.id))return J(r.id);const t=k(()=>ut(l||{}));if(t.res)return t.res;const c=t.value,a=L.get(r.id);if(a)return{status:202,body:{running:!0,progress:{...a.progress},kb:a.base?P(a.base,i):null}};let h=y.load(r.id);const w=!h;h||(h=be({id:r.id,name:c.name||W(String(c.path).replace(/[\\/]+$/,""))||r.id,now:v}),y.save(h));const p=v(),O={done:0,total:0},E=(async()=>{const b=await Pe(h,c,{progress:O});if(O.cancel)return{cancelled:!0};const M=b.added.length+b.changed.length+b.removed.length,B=b.added.length||b.changed.length?await I(h):0;return(M||w)&&y.save(h),{folder:b.root,added:b.added,changed:b.changed,removed:b.removed,same:b.same,duplicates:b.duplicates,skipped:b.skipped,embedded:B,made:w,kb:P(h,i),ms:v()-p}})();L.set(r.id,{progress:O,base:h}),E.catch(b=>z(`[kb] ${r.id}: sync failed — ${b?.message||b}`)).finally(()=>L.delete(r.id));const j=c.waitMs??5e3;if(j===0)return{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}};let _=null;const R=new Promise(b=>{_=setTimeout(()=>b(null),j)});let Q;try{Q=await Promise.race([E,R])}catch(b){return clearTimeout(_),Y(b)}return clearTimeout(_),Q?S(Q):{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}}}const s=y.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const x=C(s.id)?.role==="replica",T=!!C(s.id);if(!de(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){L.has(s.id)||ue(s);const t=P(s,i),c=i?(s.sources||[]).map(a=>({kind:a.kind,path:a.path,files:Object.keys(a.files||{}).length,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:a.lastSync}:{}})):void 0;return S({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:y.sizeOf(s.id),dir:i?y.dirOf(s.id):void 0,...c?.length?{sources:c}:{},...L.has(s.id)?{syncing:(({done:a,total:h})=>({done:a,total:h}))(L.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!i)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=L.get(s.id);return t&&(t.progress.cancel=!0),y.remove(s.id),S({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>rt(l||{}));return t.res?t.res:je(s,t.value,{admin:i})}if(e==="DELETE"&&r.rest)return i?q(s,r.rest,{now:v})?(y.save(s),S({ok:!0,kb:P(s,i)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const t=Number(d.get("page"))||1,c=Ye(s,r.rest,t);return c?S(c):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return S({documents:P(s,i).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=pe(s,r.rest);return t?S(t):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){ee(s);const t=d.get("doc");return S({outline:t?ye(s.chunks,{doc:t}):s.outline})}break}case"search":{if(e==="POST"){const t=k(()=>ot(l||{}));if(t.res)return t.res;const c=v(),a=await re(s,t.value);return ue(s),S({...a,ms:v()-c})}break}case"research":{if(e==="POST"){const t=k(()=>at(l||{}));return t.res?t.res:Ge(s,t.value,{admin:i})}break}case"graph":{if(e==="GET")return S(Gt(s,{limit:pt(d.get("limit"))}));if(e==="POST"){const t=k(()=>it(l||{}));return t.res?t.res:Me(s,t.value)}break}case"report":{if(e==="GET")return ee(s),{status:200,text:tt(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return S({notes:s.notes});if(x&&e==="POST")return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>ct(l||{}));if(t.res)return t.res;const c=t.value,a=c.status==="accepted"&&i?"accepted":"proposed",h=Re(s,{text:c.text,cites:c.cites||[],by:c.by||(i?"user":"agent"),status:a,now:v});return await I(s),y.save(s),{status:201,body:{note:h}}}if(e==="POST"&&r.rest){if(!i)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=k(()=>dt(l||{}));if(t.res)return t.res;const c=t.value,a=We(s,r.rest,c.status,{now:v});return a?(y.save(s),S({note:a,removed:c.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return S({access:s.access});if(x&&e==="POST")return J(s.id);if(e==="POST"){if(!i)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>lt(l||{}));if(t.res)return t.res;const c=Je(s,t.value,{now:v});return y.save(s),S({access:c})}break}case"pages":{if(e!=="GET")break;const t=d.get("doc")||s.docs[0]?.id,c=s.docs.find(a=>a.id===t);return c?S(bt(s.chunks,c)):g(404,"not_found",`kb: no document ${t||""}`)}case"view":{if(e!=="GET")break;const t=d.get("original");if(t){const b=s.docs.find(Ce=>Ce.id===t),M=b?.source?.kind==="file"?String(b.source.path||""):"",B=$e[Z(M).toLowerCase()];if(!M||!B)return g(404,"not_found","kb: no original on this machine for that document");let ge;try{ge=oe(M)}catch{return g(404,"not_found","kb: the original is no longer where it was read")}return{status:200,text:ge,contentType:B,headers:{"content-security-policy":"sandbox","x-content-type-options":"nosniff"}}}const c=d.get("passage")||"",a=c&&ce(s,c);if(!a)return g(404,"not_found",`kb: no passage ${c.slice(0,80)}`);const h=s.docs.find(b=>b.id===a.doc)||{id:a.doc,title:a.doc},w=a.page||1,p=s.chunks.filter(b=>b.doc===a.doc&&(b.page||1)<=w&&(b.pageEnd||b.page||1)>=w),O=b=>{const M=s.chunks.find(B=>B.doc===a.doc&&(B.page||1)===b);return M?`?passage=${encodeURIComponent(M.id)}`:""},E=h.source?.kind==="file"?String(h.source.path||""):"",j=Z(E).toLowerCase(),_=String(a.text||"").replace(/\s+/g," ").trim().split(" ").slice(0,6).join(" "),R=h.source?.kind==="url"&&/^https?:\/\//.test(h.source.url||"")?`${h.source.url}#:~:text=${encodeURIComponent(_)}`:$e[j]?`?original=${encodeURIComponent(h.id)}${j===".pdf"?`#page=${w}`:""}`:"";return{status:200,text:kt({base:s.name||s.id,doc:{title:h.title,pages:h.pages,original:R},page:w,label:a.label||"",passages:p.map(b=>({id:b.id,text:b.text,section:b.section?String(b.section).split(" › ").slice(-2).join(" › "):""})),cited:a.id,prev:w>1?O(w-1):"",next:O(w+1)}),contentType:"text/html; charset=utf-8",headers:{"content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}}}case"reveal":{if(e!=="POST")break;if(!i)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(xe())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(C(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof X!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>ft(l||{}));if(t.res)return t.res;const c=t.value;let a="",h="file";if(c.doc){const w=s.docs.find(p=>p.id===c.doc);if(!w)return g(404,"not_found",`kb: no document ${c.doc}`);a=w.source?.path||"",a||(a=y.dirOf(s.id),h="index")}else if(c.source!=null){const w=(s.sources||[])[c.source];if(!w?.path)return g(404,"not_found",`kb: no kept folder ${c.source}`);a=w.path,h="folder"}else{const w=(s.sources||[]).find(p=>p.path);a=w?.path||y.dirOf(s.id),h=w?"folder":"index"}try{ae(a)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await X(a,{folder:h!=="file"})}catch(w){return g(502,"reveal_failed",`kb: the file manager did not open — ${w.message}`)}return S({ok:!0,revealed:h})}case"embed":{if(e==="POST"){const t=N(),c=$&&t?$.health("embed",t):{state:"off"},a=await I(s);return a&&y.save(s),S({embedded:a,vectors:s.vectors.by.size,model:s.vectors.model||t,dims:s.vectors.dims,state:c.state,...c.progress?{progress:c.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${n} is not a route`)}function J(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:ze,store:y,embedModel:N,cardOf:he,addBytes:(e,n,d)=>V(e,n,d),embedAll:e=>I(e),searchBase:(e,n)=>re(e,n)}}export{U as KB_WALK_LIMITS,qt as createKbService,P as kbStatusFor,Gt as wholeGraph};
package/src/server.js CHANGED
@@ -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:oe.get(n),after:m}});const h=oe.watch(n,w=>{w.seq==null?l(w):w.seq>m&&(m=w.seq,l(w))});for(const w of oe.eventsSince(n,m))m=w.seq,l(w);const f=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});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(go||=rn({store:e,notify:Ge}),await nn(r,o,{pathname:i,api:go,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.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:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.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:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.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:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=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: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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=$s(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 As(s,f=>R.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.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"&&r.method==="POST"){let e;try{e=JSON.parse((await k(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&&!L(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(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),K=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.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})}),fe=await K.json().catch(()=>({}));return K.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.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,f=await fn(n,{store:R,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gn(n,f,{size:R.size,newest:R.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(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 be().handle({method:r.method,pathname:i,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Da]});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 k(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=Ss({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>gs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:L(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 k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*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 X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8"}),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:R.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.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"&&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:R.size,bytes:R.bytes,newest:R.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({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=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Us))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Wn((re,xe)=>Vn(T,{salt:re,iterations:xe})):null,K=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Kn(Qn,re.blob.compression):null;return Fn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:K});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,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(!Q)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=Q.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=Q.deleteOf(l);for(const m of Ae)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});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(go||=rn({store:e,notify:Ge}),await nn(r,o,{pathname:i,api:go,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.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:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.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:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.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:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=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: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 k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=$s(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 As(s,f=>R.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.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"&&r.method==="POST"){let e;try{e=JSON.parse((await k(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&&!L(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(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),K=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.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})}),fe=await K.json().catch(()=>({}));return K.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.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,f=await fn(n,{store:R,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gn(n,f,{size:R.size,newest:R.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(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 be().handle({method:r.method,pathname:i,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Da]});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 k(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=Ss({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>gs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:L(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 k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*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 X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(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:R.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.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"&&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:R.size,bytes:R.bytes,newest:R.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({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=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Us))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Wn((re,xe)=>Vn(T,{salt:re,iterations:xe})):null,K=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Kn(Qn,re.blob.compression):null;return Fn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:K});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,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(!Q)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=Q.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=Q.deleteOf(l);for(const m of Ae)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:Q.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await k(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:Gn(m?.source))===ko,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${ko}" is this gateway's own log`})),d=Ln(Q,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:Q.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 Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=jn(Q.all());return a(o,200,{ok:!0,stats:e,year:zn(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=So(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=Q.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=>_t(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=So(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.152.1";export{o as VERSION};
1
+ const o="0.153.0";export{o as VERSION};