@chatpanel/gateway 0.154.5 → 0.155.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.154.5",
3
+ "version": "0.155.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.506.0",
27
+ "@chatpanel/events": "^0.507.2",
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 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};
1
+ import{readFileSync as oe,statSync as ie,readdirSync as Ce,realpathSync as me}from"node:fs";import{join as De,basename as U,extname as Z,resolve as Fe,dirname as Ne}from"node:path";import Re from"node:os";import{createKb as be,addDocument as ae,removeDocument as q,addNote as We,setNoteStatus as Ue,searchKb as He,embedMissing as Xe,kbNeedsVectors as Ve,kbStatus as Ye,readPage as Je,chunkById as ce,refreshKb as ee,setKbAccess as Qe,kbMayUse as de,graphWalk as Ze}from"@chatpanel/events/kb-index.js";import{kbResearch as qe}from"@chatpanel/events/kb-research.js";import{neighbours as et,pathBetween as tt,resolveNode as ke,graphReport as nt}from"@chatpanel/events/kb-graph.js";import{outlineOf as ye}from"@chatpanel/events/kb-chunk.js";import{validateKbInstructions as st,setKbInstructions as rt,normalizeKbInstructions as we,kbInstructionsBlock as ot}from"@chatpanel/events/kb-instructions.js";import{routeKb as it,validateKbCreate as at,validateKbAdd as ct,validateKbSearch as dt,validateKbResearch as lt,validateKbGraph as ut,validateKbNote as ft,validateKbNoteStatus as pt,validateKbAccess as ht,validateKbSync as gt,validateKbReveal as mt,kbGraphLimit as bt,KB_LOCAL_ACTIONS as kt}from"@chatpanel/events/kb-capability.js";import{communities as yt,topEntities as ve}from"@chatpanel/events/kb-graph.js";import{kbCard as wt,pageStrip as vt}from"@chatpanel/events/kb-view.js";import{passagePageHtml as St}from"@chatpanel/events/kb-cite.js";import{planFolderSync as $t,folderDocId as xt,folderSource as Tt,knownFiles as Ot}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as _t,markdownLinks as Et,resolveLinks as Pt,visibleTextHash as At,decodeText as jt}from"@chatpanel/events/kb-html.js";import{secretReason as Se,SKIP_DIR_NAMES as Kt,sniffType as It,checkAttachablePath as Lt}from"@chatpanel/events/attached-paths.js";import{paginateText as te,MAX_DOCUMENT_BYTES as le}from"./extract-capability.js";import{defaultEmbeddedModel as Mt}from"./embedded-models.js";import{primaryProvider as Gt}from"./capability-config.js";function P(y,A){const x=Ye(y);return A?x:{...x,documents:x.documents.map(K=>{const{path:C,...M}=K.source||{};return{...K,source:M}})}}const H=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),$e=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),zt=new Set([".html",".htm",".xhtml"]),Bt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(y,A,x,K={})=>({status:y,body:{error:{type:A,message:x},...K}}),S=y=>({status:200,body:y});function Ct(y,{limit:A=60}={}){ee(y);const x=y.graph||{nodes:[],edges:[]},K=new Set(ve(x,{limit:A}).map(m=>m.id)),C=new Map(ve(x,{limit:A}).map(m=>[m.id,m.weight])),M=x.nodes.filter(m=>m.kind==="entity"?K.has(m.id)||m.type==="person"||m.type==="role":m.kind!=="chunk").slice(0,A*6),D=new Set(M.map(m=>m.id)),G=x.edges.filter(m=>D.has(m.from)&&D.has(m.to)),v=m=>m.kind==="holds"||m.kind==="member"||m.kind==="has",X=[...G.filter(v),...G.filter(m=>!v(m))].slice(0,A*20),z=yt(x).map(m=>({...m,members:m.members.filter(V=>D.has(V))})).filter(m=>m.members.length>=2).slice(0,24);return{nodes:M.map(m=>({id:m.id,kind:m.kind,label:m.label,count:m.count,...m.type?{type:m.type}:{},...m.doc?{doc:m.doc}:{},...C.has(m.id)?{weight:C.get(m.id)}:{}})),edges:X,communities:z,total:{nodes:x.nodes.length,edges:x.edges.length}}}const xe=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 rn({store:y,extract:A=null,embedded:x=null,cfg:K={},rerank:C=null,read:M=null,completer:D=null,log:G=()=>{},now:v=()=>Date.now(),home:X=Re.homedir(),team:z=()=>null,remoteCards:m=null,reveal:V=null,confined:Te=()=>!1}={}){const N=()=>{const e=Gt(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Mt("embed")||""},ne=(e="passage")=>{const s=N();if(!x||!s)return null;const d=x.health("embed",s);return d.state!=="ready"&&d.state!=="loading"&&!d.installed?(x.embed(s,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await x.embed(s,l,{kind:e})).vectors},Oe=typeof C=="function"?C:null,se=new Set;function ue(e){!e||se.has(e.id)||e.embed==="off"||!ne("passage")||Ve(e)&&(se.add(e.id),F(e).then(s=>{s&&(y.save(e),G(`[kb] ${e.id}: ${s} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>se.delete(e.id)))}async function F(e,{late:s=()=>!1}={}){const d=ne("passage");if(!d)return 0;try{return await Xe(e,d,{model:N(),late:s})}catch(l){return G(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function _e(e,s,d=""){const l=It(e,s);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=jt(e);if(/\.x?html?$/i.test(s)||/html/i.test(l.label||"")){const n=_t(r);return{type:"html",pages:te(n.markdown).map(($,T)=>({page:T+1,text:$})),title:n.title,links:n.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
2
+ `).find(n=>n.trim())||""),k=/\.(md|markdown)$/i.test(s);return{type:l.label||"text",pages:te(r).map((n,$)=>({page:$+1,text:n})),title:f?f[1].trim():"",links:k?Et(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(),i=await o.open(e,{name:s,hint:d}),u=[];for(let r=1;r<=i.pages;r+=1){let f="";try{f=String((await o.page(i.hash,r)).text||"")}catch(k){G(`[kb] ${s} p.${r}: ${k.message}`)}u.push({page:r,text:f,...i.labels?.[r-1]?{label:i.labels[r-1]}:{}})}return{type:i.type,pages:u,title:i.title||"",hash:i.hash,scanned:!!i.scanned,markdown:!!i.markdown,labels:i.labels||[]}}async function Y(e,s,{name:d,hint:l="",title:o="",source:i={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const n=await _e(s,d,l),$=At(n.pages.map(c=>c.text).join(`
3
+ `));if(k&&$){const c=e.docs.find(a=>a.textHash===$&&a.id!==r);if(c)return{duplicateOf:c}}const T=i.path&&n.links?.length?Pt(i.path,n.links,{root:f||Ne(i.path)}):[],t=ae(e,{id:r,title:o||n.title||U(d),pages:n.pages,source:{kind:i.kind||"bytes",name:d,...i},hash:n.hash||"",type:n.type,reach:u,now:v,links:T,textHash:$,markdownHeadings:!!n.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...n.scanned?{scanned:!0}:{}}}function Ee(e,s){const d=Z(e).toLowerCase();return!$e.has(d)&&!Bt.has(d)?!1:s?.length?s.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return d===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function fe(e,{recursive:s=!0,include:d=null}={}){const l=Lt(e,{home:X,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=me(Fe(e.replace(/^~(?=$|\/)/,X))),i=[],u=[];let r=0;const f=($,T)=>{if(i.length>=H.files)return u.push({path:T,why:`stopped at ${H.files} files`}),!1;if(Se($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ie($)}catch{return!0}const c=Z($).toLowerCase(),a=$e.has(c)||zt.has(c)?le:H.textBytes;return t.size>a?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>H.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,i.push({full:$,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ie(o).isDirectory())return f(o,U(o)),{root:o,files:i,skipped:u,single:!0};const n=($,T,t)=>{if(t>H.depth)return!0;let c=[];try{c=Ce($,{withFileTypes:!0}).sort((a,p)=>a.name.localeCompare(p.name))}catch{return!0}for(const a of c){const p=a.name;if(p.startsWith(".")&&a.isDirectory())continue;const w=De($,p),h=T?`${T}/${p}`:p;if(a.isDirectory()){if(Kt.has(p)||!s)continue;try{if(!me(w).startsWith(o)){u.push({path:h,why:"links outside the folder"});continue}}catch{continue}if(!n(w,h,t+1))return!1;continue}if(!(!a.isFile()&&!a.isSymbolicLink())){if(Se(w)){u.push({path:h,why:"withheld (a credential store)"});continue}if(Ee(p,d)&&!f(w,h))return!1}}return!0};return n(o,"",0),{root:o,files:i,skipped:u}}async function Pe(e,{path:s,recursive:d=!0,include:l=null,title:o=""}){const{files:i,skipped:u,single:r}=fe(s,{recursive:d,include:l}),f=[];for(const k of i)try{const n=await Y(e,oe(k.full),{name:U(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...n,path:k.rel})}catch(n){u.push({path:k.rel,why:n.message})}return{added:f,skipped:u}}async function Ae(e,{path:s,include:d=null,rebuild:l=!1},{progress:o=null}={}){const{root:i,files:u,skipped:r}=fe(s,{recursive:!0,include:d}),f=Tt(e,i,{include:d});if(l){for(const h of Object.values(f.files))h?.id&&q(e,h.id,{now:v});f.files={}}const k=new Set(u.map(h=>h.full));for(const[h,O]of Object.entries(f.files))O?.dupOf&&!k.has(O.dupOf)&&delete f.files[h];const n=$t({known:Ot(f),listing:u.map(h=>({path:h.full,size:h.size,mtime:h.mtime}))});o&&(o.total=n.add.length+n.change.length,o.done=0);const $=new Map(u.map(h=>[h.full,h])),T=[];for(const h of n.remove){q(e,h,{now:v});for(const[O,E]of Object.entries(f.files))E.id===h&&(delete f.files[O],T.push(O.startsWith(`${i}/`)?O.slice(i.length+1):O))}const t=[],c=[],a=[],p=h=>String(h||"").startsWith(`${i}/`)?h.slice(i.length+1):h,w=async(h,O)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(h),j=xt(h);try{const _=await Y(e,oe(h),{name:U(h),source:{kind:"file",path:h},reach:"internal",id:j,root:i,dedupe:!0});_.duplicateOf?(e.docs.some(W=>W.id===j)&&q(e,j,{now:v}),f.files[h]={id:j,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},a.push({path:E.rel,of:p(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[h]={id:j,size:E.size,mtime:E.mtime},O.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const h of n.add)await w(h,t);for(const h of n.change)await w(h.path,c);return f.syncedAt=v(),f.lastSync={at:f.syncedAt,added:t.length,changed:c.length,removed:T.length,same:n.same,duplicates:a.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:a.slice(0,20)},{root:i,added:t,changed:c,removed:T,same:n.same,duplicates:a,skipped:r}}async function je(e,{url:s,title:d=""}){if(!M)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await M().read({url:s,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 i=te(o).map((r,f)=>({page:f+1,text:r})),u=ae(e,{title:d||l.body.title||s,pages:i,source:{kind:"url",url:l.body.url||s,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 Ke(e,s,{admin:d=!1}={}){const l=v();let o=[],i=[];if(s.kind==="bytes"){const r=Buffer.from(s.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{o.push(await Y(e,r,{name:s.name,hint:s.type||"",title:s.title,reach:s.reach}))}catch(f){return J(f)}}else if(s.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:o,skipped:i}=await Pe(e,s))}catch(r){return J(r)}}else if(s.kind==="url")try{o.push(await je(e,s))}catch(r){return J(r)}else if(s.kind==="text"){const r=te(s.text).map((k,n)=>({page:n+1,text:k})),f=ae(e,{title:s.title||s.name,pages:r,source:{kind:"text",name:s.name},type:"text",reach:s.reach,now:v});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 y.save(e),S({added:o,skipped:i,embedded:u,kb:P(e,d),ms:v()-l})}function J(e){const s=e?.code||"";return s==="refused"?g(403,"refused",`kb: ${e.message}`):s==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):s==="too_large"?g(413,"too_large",`kb: ${e.message}`):s==="read_failed"||s==="empty"?g(502,"read_failed",`kb: ${e.message}`):s==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ie=e=>e.vectors?.model&&e.vectors.model!==N()?null:ne("query"),re=(e,s)=>He(e,s.query,{limit:s.limit,hops:s.hops,docs:s.docs||null,queries:s.queries||[],...s.filters?{filters:s.filters}:{},embed:Ie(e),rerank:s.rerank===!1?null:Oe,now:v}),Le=(e,s)=>e.docs.find(d=>d.id===s)?.title||s,pe=(e,s)=>{const d=ce(e,s);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,s){ee(e);const d=s.node.replace(/^chunk:/,""),l=(/#\d+$/.test(d)&&ce(e,d)?{id:`chunk:${d}`,kind:"chunk",label:d}:null)||ke(e.graph,s.node);if(!l)return S({node:null,neighbours:[],message:`no node named "${s.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"}},i=Ze(e,l.id,{limit:Math.min(8,s.limit||6),...s.query?{query:s.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:et(e.graph,l.id,{hops:s.hops,kinds:s.kinds||null,limit:s.limit}),passages:i.passages,next:i.next};if(s.to){const r=ke(e.graph,s.to);u.to=s.to,u.path=r?(tt(e.graph,l.id,r.id)||[]).map(o):null,r&&!u.path.length&&(u.path=null)}return S(u)}async function Ge(e,s,{admin:d=!1}={}){if(s.model&&!d)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=s.model&&typeof D=="function"?D(s.model):null,o=P(e,d),i=await qe(s.question,{search:async(u,r)=>{const f=await re(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||s.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:o.documents,previous:s.previous||null,answer:s.answer||"",ask:s.ask!==!1,now:v,instructions:ot([{name:e.name,instructions:e.instructions}])});return S({attachment:i.attachment,read:i.read,hits:i.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:i.queries,verdict:i.verdict,rounds:i.rounds,ask:i.ask,how:i.how,frame:{whole:i.frame.whole,docs:i.frame.docs},ms:i.ms})}const I=new Map;function he(e,s){const d=P(e,s),l=e.chunks.length?e.chunks.filter(i=>i.form||i.label).length/e.chunks.length:1,o=s?(e.sources||[]).map(i=>({kind:i.kind,syncedAt:i.syncedAt||0,...i.lastSync?{lastSync:{at:i.lastSync.at,added:i.lastSync.added,changed:i.lastSync.changed,removed:i.lastSync.removed,skipped:i.lastSync.skipped}}:{}})):(e.sources||[]).map(i=>({kind:i.kind,syncedAt:i.syncedAt||0}));return wt({...d,coverage:d.chunks?Math.round(d.vectors/d.chunks*100):0,placed:l,sources:o,...I.has(e.id)?{syncing:(({done:i,total:u})=>({done:i,total:u}))(I.get(e.id).progress)}:{}},{outline:e.outline,team:z(e.id),now:v()})}async function ze({method:e="GET",pathname:s="",query:d=new URLSearchParams,body:l=null,admin:o=!1,agent:i="",local:u=!0}={}){const r=it(s);if(!r)return g(404,"not_found",`no route ${s}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(kt.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(i||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 p=y.load(a.id);p&&t.push(he(p,o))}const c=o&&typeof m=="function"?await m({admin:o}).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(()=>at(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),o),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,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 R(r.id);const t=k(()=>gt(l||{}));if(t.res)return t.res;const c=t.value,a=I.get(r.id);if(a)return{status:202,body:{running:!0,progress:{...a.progress},kb:a.base?P(a.base,o):null}};let p=y.load(r.id);const w=!p;p||(p=be({id:r.id,name:c.name||U(String(c.path).replace(/[\\/]+$/,""))||r.id,now:v}),y.save(p));const h=v(),O={done:0,total:0},E=(async()=>{const b=await Ae(p,c,{progress:O});if(O.cancel)return{cancelled:!0};const L=b.added.length+b.changed.length+b.removed.length,B=b.added.length||b.changed.length?await F(p):0;return(L||w)&&y.save(p),{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(p,o),ms:v()-h}})();I.set(r.id,{progress:O,base:p}),E.catch(b=>G(`[kb] ${r.id}: sync failed — ${b?.message||b}`)).finally(()=>I.delete(r.id));const j=c.waitMs??5e3;if(j===0)return{status:202,body:{running:!0,progress:{...O},made:w,kb:P(p,o)}};let _=null;const W=new Promise(b=>{_=setTimeout(()=>b(null),j)});let Q;try{Q=await Promise.race([E,W])}catch(b){return clearTimeout(_),J(b)}return clearTimeout(_),Q?S(Q):{status:202,body:{running:!0,progress:{...O},made:w,kb:P(p,o)}}}const n=y.load(r.id);if(!n)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=z(n.id)?.role==="replica",T=!!z(n.id);if(!de(n,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"){I.has(n.id)||ue(n);const t=P(n,o),c=o?(n.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,canInstruct:o&&!$,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:y.sizeOf(n.id),dir:o?y.dirOf(n.id):void 0,...c?.length?{sources:c}:{},...I.has(n.id)?{syncing:(({done:a,total:p})=>({done:a,total:p}))(I.get(n.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=I.get(n.id);return t&&(t.progress.cancel=!0),y.remove(n.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 R(n.id);if(e==="POST"&&!r.rest){const t=k(()=>ct(l||{}));return t.res?t.res:Ke(n,t.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?q(n,r.rest,{now:v})?(y.save(n),S({ok:!0,kb:P(n,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 t=Number(d.get("page"))||1,c=Je(n,r.rest,t);return c?S(c):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return S({documents:P(n,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=pe(n,r.rest);return t?S(t):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){ee(n);const t=d.get("doc");return S({outline:t?ye(n.chunks,{doc:t}):n.outline})}break}case"search":{if(e==="POST"){const t=k(()=>dt(l||{}));if(t.res)return t.res;const c=v(),a=await re(n,t.value);ue(n);const p=we(n.instructions);return S({...a,...p?.text?{instructions:p}:{},ms:v()-c})}break}case"research":{if(e==="POST"){const t=k(()=>lt(l||{}));return t.res?t.res:Ge(n,t.value,{admin:o})}break}case"graph":{if(e==="GET")return S(Ct(n,{limit:bt(d.get("limit"))}));if(e==="POST"){const t=k(()=>ut(l||{}));return t.res?t.res:Me(n,t.value)}break}case"report":{if(e==="GET")return ee(n),{status:200,text:nt(n),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return S({notes:n.notes});if($&&e==="POST")return R(n.id);if(e==="POST"&&!r.rest){const t=k(()=>ft(l||{}));if(t.res)return t.res;const c=t.value,a=c.status==="accepted"&&o?"accepted":"proposed",p=We(n,{text:c.text,cites:c.cites||[],by:c.by||(o?"user":"agent"),status:a,now:v});return await F(n),y.save(n),{status:201,body:{note:p}}}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 t=k(()=>pt(l||{}));if(t.res)return t.res;const c=t.value,a=Ue(n,r.rest,c.status,{now:v});return a?(y.save(n),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:n.access});if($&&e==="POST")return R(n.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>ht(l||{}));if(t.res)return t.res;const c=Qe(n,t.value,{now:v});return y.save(n),S({access:c})}break}case"instructions":{if(e==="GET")return S({instructions:we(n.instructions),canInstruct:o&&!$});if(e==="POST"){if($)return R(n.id);if(!o)return g(403,"forbidden","kb: setting a base's instructions needs the gateway token or the extension origin");const t=k(()=>st(l||{}));if(t.res)return t.res;const c=rt(n,t.value,{now:v});return y.save(n),S({instructions:c})}break}case"pages":{if(e!=="GET")break;const t=d.get("doc")||n.docs[0]?.id,c=n.docs.find(a=>a.id===t);return c?S(vt(n.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=n.docs.find(Be=>Be.id===t),L=b?.source?.kind==="file"?String(b.source.path||""):"",B=xe[Z(L).toLowerCase()];if(!L||!B)return g(404,"not_found","kb: no original on this machine for that document");let ge;try{ge=oe(L)}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(n,c);if(!a)return g(404,"not_found",`kb: no passage ${c.slice(0,80)}`);const p=n.docs.find(b=>b.id===a.doc)||{id:a.doc,title:a.doc},w=a.page||1,h=n.chunks.filter(b=>b.doc===a.doc&&(b.page||1)<=w&&(b.pageEnd||b.page||1)>=w),O=b=>{const L=n.chunks.find(B=>B.doc===a.doc&&(B.page||1)===b);return L?`?passage=${encodeURIComponent(L.id)}`:""},E=p.source?.kind==="file"?String(p.source.path||""):"",j=Z(E).toLowerCase(),_=String(a.text||"").replace(/\s+/g," ").trim().split(" ").slice(0,6).join(" "),W=p.source?.kind==="url"&&/^https?:\/\//.test(p.source.url||"")?`${p.source.url}#:~:text=${encodeURIComponent(_)}`:xe[j]?`?original=${encodeURIComponent(p.id)}${j===".pdf"?`#page=${w}`:""}`:"";return{status:200,text:St({base:n.name||n.id,doc:{title:p.title,pages:p.pages,original:W},page:w,label:a.label||"",passages:h.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(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(Te())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(z(n.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 V!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>mt(l||{}));if(t.res)return t.res;const c=t.value;let a="",p="file";if(c.doc){const w=n.docs.find(h=>h.id===c.doc);if(!w)return g(404,"not_found",`kb: no document ${c.doc}`);a=w.source?.path||"",a||(a=y.dirOf(n.id),p="index")}else if(c.source!=null){const w=(n.sources||[])[c.source];if(!w?.path)return g(404,"not_found",`kb: no kept folder ${c.source}`);a=w.path,p="folder"}else{const w=(n.sources||[]).find(h=>h.path);a=w?.path||y.dirOf(n.id),p=w?"folder":"index"}try{ie(a)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await V(a,{folder:p!=="file"})}catch(w){return g(502,"reveal_failed",`kb: the file manager did not open — ${w.message}`)}return S({ok:!0,revealed:p})}case"embed":{if(e==="POST"){const t=N(),c=x&&t?x.health("embed",t):{state:"off"},a=await F(n);return a&&y.save(n),S({embedded:a,vectors:n.vectors.by.size,model:n.vectors.model||t,dims:n.vectors.dims,state:c.state,...c.progress?{progress:c.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${s} is not a route`)}function R(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,s,d)=>Y(e,s,d),embedAll:e=>F(e),searchBase:(e,s)=>re(e,s)}}export{H as KB_WALK_LIMITS,rn as createKbService,P as kbStatusFor,Ct as wholeGraph};
package/src/mcp.js CHANGED
@@ -35,7 +35,10 @@ Then retry. History tools work without the bridge. [${r.message}]`}const t=o.ski
35
35
  `)+`
36
36
 
37
37
  Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let o;try{o=await $(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(t){return`Could not open "${e.name}": ${t.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),t=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await $(`/skills/${o}/file/${t}`)}catch(a){return`Could not read ${e.path}: ${a.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}if(n.startsWith("kb_"))return re(n,e);if(n==="search_context")return oe(e);throw new Error(`unknown tool: ${n}`)}async function re(n,e={}){const s=String(e.kb||"").trim(),i=s?`/v1/kb/${encodeURIComponent(s)}`:"",c={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},o=(t,r)=>d(t,{method:"POST",headers:{"content-type":"application/json",...c},body:JSON.stringify(r)});if(n==="kb_list"){const r=(await d("/v1/kb",{headers:c})).kbs||[];return r.length?[`${r.length} knowledge base${r.length===1?"":"s"}:`,...r.map(a=>`- ${a.id}: ${a.name} — ${a.docs} document${a.docs===1?"":"s"}${a.vectors?`, ${a.vectors} vectors`:""}`),"","kb_report <id> for the map, kb_search <id> for a question."].join(`
38
- `):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!s)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${i}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return M(t)}if(n==="kb_read"){if(e.id)try{const t=await d(`${i}/passages/${encodeURIComponent(String(e.id))}`,{headers:c});return`${t.cite||t.id}${t.section?` §${t.section}`:""}
38
+ `):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!s)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${i}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return`${t.instructions?.text?`Instructions from the administrator of this base — follow them when answering from it:
39
+ ${t.instructions.text}
40
+
41
+ `:""}${M(t)}`}if(n==="kb_read"){if(e.id)try{const t=await d(`${i}/passages/${encodeURIComponent(String(e.id))}`,{headers:c});return`${t.cite||t.id}${t.section?` §${t.section}`:""}
39
42
  ${t.text}`}catch(t){return`No passage ${e.id}: ${t.message}. Search first; passage ids look like "d3f2a1b4c5d6#12".`}if(e.doc)try{const t=await d(`${i}/documents/${encodeURIComponent(String(e.doc))}?page=${Number(e.page)||1}`,{headers:c});return`${t.title} — page ${t.page} of ${t.pages}${t.page<t.pages?` (next: ${t.page+1})`:" (last page)"}
40
43
  ${t.text||"(no text on this page — an image or a scan)"}`}catch(t){return`No document ${e.doc}: ${t.message}. kb_status lists the ids.`}return"kb_read needs a passage id, or a document id with a page."}if(n==="kb_outline"){const[t,r]=await Promise.all([d(`${i}/outline${e.doc?`?doc=${encodeURIComponent(String(e.doc))}`:""}`,{headers:c}),d(i,{headers:c})]);return U(t.outline||[],r.kb)}if(n==="kb_graph")return D(await o(`${i}/graph`,{node:String(e.node||""),hops:Math.max(1,Math.min(3,Number(e.hops)||1)),...e.to?{to:String(e.to)}:{},...typeof e.query=="string"&&e.query.trim()?{query:e.query}:{}}));if(n==="kb_status")return H((await d(i,{headers:c})).kb);if(n==="kb_report"){const t=await fetch(`${f()}${i}/report`,{headers:c});if(!t.ok)throw new Error(`the gateway returned HTTP ${t.status} for the report`);return t.text()}if(n==="kb_note"){const r=(await o(`${i}/notes`,{text:String(e.text||""),cites:Array.isArray(e.cites)?e.cites.map(String):[]})).note||{};return`Noted (${r.status||"proposed"} — the user can accept it in ChatPanel): ${r.text}${r.cites?.length?` — cites ${r.cites.join(", ")}`:""}`}throw new Error(`unknown tool: ${n}`)}async function oe(n={}){const e={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},s={...Array.isArray(n.pages)&&n.pages.length?{pages:n.pages.slice(0,2).map(Number)}:{},...n.section?{section:String(n.section)}:{},...n.form?{form:String(n.form)}:{}},i=await d("/v1/context",{method:"POST",headers:{"content-type":"application/json",...e},body:JSON.stringify({query:String(n.query||""),sources:Array.isArray(n.sources)&&n.sources.length?n.sources.map(String):["kb:*"],...Object.keys(s).length?{filters:s}:{},max_tokens:Math.max(200,Math.min(2e4,Number(n.max_tokens)||4e3))})}),c=Object.entries(i.providers||{}).filter(([,o])=>o.error).map(([o,t])=>`${o}: ${t.error}`);return[B(i),...c.length?["",`Not searched — ${c.join("; ")}`]:[]].join(`
41
44
  `)}async function ie(n){const{id:e,method:s,params:i}=n||{},c=t=>({jsonrpc:"2.0",id:e,result:t}),o=(t,r)=>({jsonrpc:"2.0",id:e,error:{code:t,message:r}});try{switch(s){case"initialize":{m=i?.clientInfo?.name||m;const t=await X(),r=T(S()).some(a=>a.name==="delegate_task")?`
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.154.5";export{o as VERSION};
1
+ const o="0.155.0";export{o as VERSION};