@chatpanel/gateway 0.141.0 → 0.142.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 +2 -2
- package/src/kb.js +2 -2
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.142.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.
|
|
27
|
+
"@chatpanel/events": "^0.470.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,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`).find(r=>r.trim())||"");return{type:o.label||"text",pages:M(i).map((r,n)=>({page:n+1,text:r})),title:d?d[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!_)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const c=_(),u=await c.open(e,{name:t,hint:a}),s=[];for(let i=1;i<=u.pages;i+=1){let d="";try{d=String((await c.page(u.hash,i)).text||"")}catch(r){R(`[kb] ${t} p.${i}: ${r.message}`)}s.push({page:i,text:d})}return{type:u.type,pages:s,title:u.title||"",hash:u.hash,scanned:!!u.scanned}}async function U(e,t,{name:a,hint:o="",title:c="",source:u={},reach:s=""}){const i=await se(t,a,o),d=j(e,{title:c||i.title||L(a),pages:i.pages,source:{kind:u.kind||"bytes",name:a,...u},hash:i.hash||"",type:i.type,reach:s,now:g});return{id:d.doc.id,title:d.doc.title,pages:d.doc.pages,chunks:d.doc.chunks,replaced:d.replaced,...i.scanned?{scanned:!0}:{}}}function re(e,t){const a=Q(e).toLowerCase();return!te.has(a)&&!Ie.has(a)?!1:t?.length?t.some(o=>{const c=String(o).toLowerCase().replace(/^\*/,"");return a===(c.startsWith(".")?c:`.${c}`)||e.toLowerCase().endsWith(c)}):!0}async function ae(e,{path:t,recursive:a=!0,include:o=null,title:c=""}){const u=Fe(t,{home:W,cwd:process.cwd()});if(!u.ok)throw Object.assign(new Error(u.reason||"that path cannot be attached"),{code:"refused"});const s=J(ge(t.replace(/^~(?=$|\/)/,W))),i=[],d=[];let r=0,n=0;const l=async(y,b)=>{if(r>=T.files)return d.push({path:b,why:`stopped at ${T.files} files`}),!1;if(ee(y))return d.push({path:b,why:"withheld (a credential store)"}),!0;let x;try{x=H(y)}catch{return!0}const w=Q(y).toLowerCase(),k=te.has(w)?N:T.textBytes;if(x.size>k)return d.push({path:b,why:`too large (${Math.round(x.size/1048576)} MB)`}),!0;if(n+x.size>T.bytes)return d.push({path:b,why:"stopped: the folder is past the size limit"}),!1;r+=1,n+=x.size;try{const $=await U(e,pe(y),{name:L(y),title:i.length===0&&!b.includes("/")?c:"",source:{kind:"file",path:y},reach:"internal"});i.push({...$,path:b})}catch($){d.push({path:b,why:$.message})}return!0};if(!H(s).isDirectory())return await l(s,L(s)),{added:i,skipped:d};const K=async(y,b,G)=>{if(G>T.depth)return!0;let x=[];try{x=fe(y,{withFileTypes:!0}).sort((w,k)=>w.name.localeCompare(k.name))}catch{return!0}for(const w of x){const k=w.name;if(k.startsWith(".")&&w.isDirectory())continue;const $=he(y,k),P=b?`${b}/${k}`:k;if(w.isDirectory()){if(Ce.has(k)||!a)continue;try{if(!J($).startsWith(s)){d.push({path:P,why:"links outside the folder"});continue}}catch{continue}if(!await K($,P,G+1))return!1;continue}if(!(!w.isFile()&&!w.isSymbolicLink())){if(ee($)){d.push({path:P,why:"withheld (a credential store)"});continue}if(re(k,o)&&!await l($,P))return!1}}return!0};return await K(s,"",0),{added:i,skipped:d}}async function oe(e,{url:t,title:a=""}){if(!z)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await z().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const c=String(o.body.markdown||o.body.text||"");if(!c.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const u=M(c).map((i,d)=>({page:d+1,text:i})),s=j(e,{title:a||o.body.title||t,pages:u,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:g});return{id:s.doc.id,title:s.doc.title,pages:s.doc.pages,chunks:s.doc.chunks,replaced:s.replaced}}async function ie(e,t,{admin:a=!1}={}){const o=g();let c=[],u=[];if(t.kind==="bytes"){const i=Buffer.from(t.data,"base64");if(!i.length)return p(400,"invalid_request","kb: data decoded to nothing");if(i.length>N)return p(413,"too_large",`kb: ${i.length} bytes is over the ${N}-byte limit`);try{c.push(await U(e,i,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(d){return B(d)}}else if(t.kind==="path"){if(!a)return p(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:c,skipped:u}=await ae(e,t))}catch(i){return B(i)}}else if(t.kind==="url")try{c.push(await oe(e,t))}catch(i){return B(i)}else if(t.kind==="text"){const i=M(t.text).map((r,n)=>({page:n+1,text:r})),d=j(e,{title:t.title||t.name,pages:i,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:g});c.push({id:d.doc.id,title:d.doc.title,pages:d.doc.pages,chunks:d.doc.chunks,replaced:d.replaced})}const s=c.length?await D(e):0;return f.save(e),h({added:c,skipped:u,embedded:s,kb:S(e),ms:g()-o})}function B(e){const t=e?.code||"";return t==="refused"?p(403,"refused",`kb: ${e.message}`):t==="unsupported"?p(415,"unsupported",`kb: ${e.message}`):t==="too_large"?p(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?p(502,"read_failed",`kb: ${e.message}`):t==="timeout"?p(504,"extract_timeout","kb: the document took too long to parse"):p(500,"kb_error",`kb: ${e?.message||e}`)}const X=(e,t)=>ve(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:I("query"),rerank:t.rerank===!1?null:ne,now:g}),ce=(e,t)=>e.docs.find(a=>a.id===t)?.title||t,Y=(e,t)=>{const a=Se(e,t);if(!a)return null;const o=a.kind==="note"?"Note":ce(e,a.doc);return{...a,title:o,cite:a.kind==="note"?`[note ${a.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${a.page}]`}};function de(e,t){A(e);const a=Z(e.graph,t.node);if(!a)return h({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=u=>{const s=e.graph.nodes.find(i=>i.id===u);return{id:u,label:s?.label||u.replace(/^chunk:/,"passage "),kind:s?.kind||"chunk"}},c={node:{id:a.id,kind:a.kind,label:a.label},neighbours:Ee(e.graph,a.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const u=Z(e.graph,t.to);c.to=t.to,c.path=u?(Oe(e.graph,a.id,u.id)||[]).map(o):null,u&&!c.path.length&&(c.path=null)}return h(c)}async function ue(e,t,{admin:a=!1}={}){if(t.model&&!a)return p(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof F=="function"?F(t.model):null,c=S(e),u=await _e(t.question,{search:(s,i)=>X(e,{query:s,limit:i.limit||10,hops:i.hops??1,docs:i.docs||t.docs||null}),outline:async s=>s?q(e.chunks,{doc:s}):e.outline,read:async s=>Y(e,s),complete:o,kbName:e.name,docs:c.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:g});return h({attachment:u.attachment,read:u.read,hits:u.hits.map(s=>({id:s.id,doc:s.doc,title:s.title,page:s.page,section:s.section,cite:s.cite,lanes:s.lanes,via:s.via})),queries:u.queries,verdict:u.verdict,rounds:u.rounds,ask:u.ask,how:u.how,frame:{whole:u.frame.whole,docs:u.frame.docs},ms:u.ms})}async function le({method:e="GET",pathname:t="",query:a=new URLSearchParams,body:o=null,admin:c=!1,agent:u=""}={}){const s=Pe(t);if(!s)return p(404,"not_found",`no route ${t}`);if(s.bad)return p(400,"invalid_request",`kb: "${s.bad}" is not a valid id or route`);const i={admin:c,agent:String(u||a.get("agent")||"").trim().toLowerCase()},d=n=>{try{return{value:n()}}catch(l){return{res:p(400,"invalid_request",l.message)}}};if(!s.id){if(e==="GET")return h({kbs:f.list().filter(({manifest:n})=>V({access:n.access},i)).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=d(()=>De(o||{}));if(n.res)return n.res;const l=n.value;if(l.id&&f.load(l.id))return h({kb:S(f.load(l.id)),existed:!0});const m=be({id:l.id,name:l.name,embed:l.embed,now:g});return f.save(m),{status:201,body:{kb:S(m)}}}return p(405,"method_not_allowed",`kb: ${e} is not allowed here`)}const r=f.load(s.id);if(!r)return p(404,"not_found",`kb: no knowledge base ${s.id} — POST /v1/kb to create one`);if(!V(r,i))return p(404,"not_found",`kb: no knowledge base ${s.id} for ${i.agent||"this caller"} — the owner can grant it (POST /v1/kb/${s.id}/access)`);if(!s.sub)return e==="GET"?h({kb:{...S(r),bytes:f.sizeOf(r.id),dir:c?f.dirOf(r.id):void 0}}):e==="DELETE"?c?(f.remove(r.id),h({ok:!0})):p(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):p(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(s.sub){case"documents":{if(e==="POST"&&!s.rest){const n=d(()=>Be(o||{}));return n.res?n.res:ie(r,n.value,{admin:c})}if(e==="DELETE"&&s.rest)return c?ke(r,s.rest,{now:g})?(f.save(r),h({ok:!0,kb:S(r)})):p(404,"not_found",`kb: no document ${s.rest}`):p(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&s.rest){const n=Number(a.get("page"))||1,l=$e(r,s.rest,n);return l?h(l):p(404,"not_found",`kb: no document ${s.rest}`)}if(e==="GET")return h({documents:S(r).documents});break}case"passages":{if(e==="GET"&&s.rest){const n=Y(r,s.rest);return n?h(n):p(404,"not_found",`kb: no passage ${s.rest}`)}break}case"outline":{if(e==="GET"){A(r);const n=a.get("doc");return h({outline:n?q(r.chunks,{doc:n}):r.outline})}break}case"search":{if(e==="POST"){const n=d(()=>Ge(o||{}));return n.res?n.res:h(await X(r,n.value))}break}case"research":{if(e==="POST"){const n=d(()=>Le(o||{}));return n.res?n.res:ue(r,n.value,{admin:c})}break}case"graph":{if(e==="POST"){const n=d(()=>je(o||{}));return n.res?n.res:de(r,n.value)}break}case"report":{if(e==="GET")return A(r),{status:200,text:Ke(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return h({notes:r.notes});if(e==="POST"&&!s.rest){const n=d(()=>Ae(o||{}));if(n.res)return n.res;const l=n.value,m=l.status==="accepted"&&c?"accepted":"proposed",K=ye(r,{text:l.text,cites:l.cites||[],by:l.by||(c?"user":"agent"),status:m,now:g});return await D(r),f.save(r),{status:201,body:{note:K}}}if(e==="POST"&&s.rest){if(!c)return p(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=d(()=>Me(o||{}));if(n.res)return n.res;const l=n.value,m=we(r,s.rest,l.status,{now:g});return m?(f.save(r),h({note:m,removed:l.status==="removed"})):p(404,"not_found",`kb: no note ${s.rest}`)}break}case"access":{if(e==="GET")return h({access:r.access});if(e==="POST"){if(!c)return p(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=d(()=>Ne(o||{}));if(n.res)return n.res;const l=Te(r,n.value,{now:g});return f.save(r),h({access:l})}break}case"embed":{if(e==="POST"){const n=O(),l=v&&n?v.health("embed",n):{state:"off"},m=await D(r);return m&&f.save(r),h({embedded:m,vectors:r.vectors.by.size,model:r.vectors.model||n,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return p(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:le,store:f,embedModel:O}}export{T as KB_WALK_LIMITS,st as createKbService};
|
|
1
|
+
import{readFileSync as X,statSync as Y,readdirSync as he,realpathSync as H}from"node:fs";import{join as me,basename as _,extname as J,resolve as ge}from"node:path";import be from"node:os";import{createKb as Q,addDocument as M,removeDocument as V,addNote as ke,setNoteStatus as ye,searchKb as we,embedMissing as ve,kbStatus as S,readPage as xe,chunkById as Se,refreshKb as F,setKbAccess as $e,kbMayUse as Z}from"@chatpanel/events/kb-index.js";import{kbResearch as _e}from"@chatpanel/events/kb-research.js";import{neighbours as Te,pathBetween as Ee,resolveNode as q,graphReport as Oe}from"@chatpanel/events/kb-graph.js";import{outlineOf as ee}from"@chatpanel/events/kb-chunk.js";import{routeKb as Pe,validateKbCreate as Ke,validateKbAdd as ze,validateKbSearch as De,validateKbResearch as Me,validateKbGraph as Fe,validateKbNote as je,validateKbNoteStatus as Ae,validateKbAccess as Be,validateKbSync as Ge}from"@chatpanel/events/kb-capability.js";import{planFolderSync as Le,folderDocId as Ne,folderSource as Ce,knownFiles as Re}from"@chatpanel/events/kb-folder-sync.js";import{secretReason as te,SKIP_DIR_NAMES as We,sniffType as Ie,checkAttachablePath as Ue}from"@chatpanel/events/attached-paths.js";import{paginateText as j,MAX_DOCUMENT_BYTES as A}from"./extract-capability.js";import{defaultEmbeddedModel as Xe}from"./embedded-models.js";import{primaryProvider as Ye}from"./capability-config.js";const T=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),ne=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),He=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),h=(g,E,x,O={})=>({status:g,body:{error:{type:E,message:x},...O}}),b=g=>({status:200,body:g});function ct({store:g,extract:E=null,embedded:x=null,cfg:O={},rerank:B=null,read:G=null,completer:L=null,log:N=()=>{},now:k=()=>Date.now(),home:C=be.homedir()}={}){const P=()=>{const e=Ye(O.capabilities?.embed,"embed",{destinations:O.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Xe("embed")||""},R=(e="passage")=>{const t=P();if(!x||!t)return null;const i=x.health("embed",t);return i.state!=="ready"&&!i.installed?(x.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async o=>(await x.embed(t,o,{kind:e})).vectors},se=typeof B=="function"?B:null;async function K(e,{late:t=()=>!1}={}){const i=R("passage");if(!i)return 0;try{return await ve(e,i,{model:P(),late:t})}catch(o){return N(`[kb] ${e.id}: embedding failed — ${o.message}`),0}}async function re(e,t,i=""){const o=Ie(e,t);if(o.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(o.text){const d=Buffer.from(e).toString("utf8"),u=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(d.split(`
|
|
2
|
+
`).find(r=>r.trim())||"");return{type:o.label||"text",pages:j(d).map((r,s)=>({page:s+1,text:r})),title:u?u[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!E)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=E(),c=await a.open(e,{name:t,hint:i}),n=[];for(let d=1;d<=c.pages;d+=1){let u="";try{u=String((await a.page(c.hash,d)).text||"")}catch(r){N(`[kb] ${t} p.${d}: ${r.message}`)}n.push({page:d,text:u})}return{type:c.type,pages:n,title:c.title||"",hash:c.hash,scanned:!!c.scanned}}async function D(e,t,{name:i,hint:o="",title:a="",source:c={},reach:n="",id:d=""}){const u=await re(t,i,o),r=M(e,{id:d,title:a||u.title||_(i),pages:u.pages,source:{kind:c.kind||"bytes",name:i,...c},hash:u.hash||"",type:u.type,reach:n,now:k});return{id:r.doc.id,title:r.doc.title,pages:r.doc.pages,chunks:r.doc.chunks,replaced:r.replaced,...u.scanned?{scanned:!0}:{}}}function ae(e,t){const i=J(e).toLowerCase();return!ne.has(i)&&!He.has(i)?!1:t?.length?t.some(o=>{const a=String(o).toLowerCase().replace(/^\*/,"");return i===(a.startsWith(".")?a:`.${a}`)||e.toLowerCase().endsWith(a)}):!0}function W(e,{recursive:t=!0,include:i=null}={}){const o=Ue(e,{home:C,cwd:process.cwd()});if(!o.ok)throw Object.assign(new Error(o.reason||"that path cannot be attached"),{code:"refused"});const a=H(ge(e.replace(/^~(?=$|\/)/,C))),c=[],n=[];let d=0;const u=(l,p)=>{if(c.length>=T.files)return n.push({path:p,why:`stopped at ${T.files} files`}),!1;if(te(l))return n.push({path:p,why:"withheld (a credential store)"}),!0;let f;try{f=Y(l)}catch{return!0}const y=ne.has(J(l).toLowerCase())?A:T.textBytes;return f.size>y?(n.push({path:p,why:`too large (${Math.round(f.size/1048576)} MB)`}),!0):d+f.size>T.bytes?(n.push({path:p,why:"stopped: the folder is past the size limit"}),!1):(d+=f.size,c.push({full:l,rel:p,size:f.size,mtime:Math.floor(f.mtimeMs)}),!0)};if(!Y(a).isDirectory())return u(a,_(a)),{root:a,files:c,skipped:n,single:!0};const s=(l,p,f)=>{if(f>T.depth)return!0;let y=[];try{y=he(l,{withFileTypes:!0}).sort((m,w)=>m.name.localeCompare(w.name))}catch{return!0}for(const m of y){const w=m.name;if(w.startsWith(".")&&m.isDirectory())continue;const v=me(l,w),$=p?`${p}/${w}`:w;if(m.isDirectory()){if(We.has(w)||!t)continue;try{if(!H(v).startsWith(a)){n.push({path:$,why:"links outside the folder"});continue}}catch{continue}if(!s(v,$,f+1))return!1;continue}if(!(!m.isFile()&&!m.isSymbolicLink())){if(te(v)){n.push({path:$,why:"withheld (a credential store)"});continue}if(ae(w,i)&&!u(v,$))return!1}}return!0};return s(a,"",0),{root:a,files:c,skipped:n}}async function oe(e,{path:t,recursive:i=!0,include:o=null,title:a=""}){const{files:c,skipped:n,single:d}=W(t,{recursive:i,include:o}),u=[];for(const r of c)try{const s=await D(e,X(r.full),{name:_(r.full),title:u.length===0&&(d||!r.rel.includes("/"))?a:"",source:{kind:"file",path:r.full},reach:"internal"});u.push({...s,path:r.rel})}catch(s){n.push({path:r.rel,why:s.message})}return{added:u,skipped:n}}async function ie(e,{path:t,include:i=null}){const{root:o,files:a,skipped:c}=W(t,{recursive:!0,include:i}),n=Ce(e,o,{include:i}),d=Le({known:Re(n),listing:a.map(f=>({path:f.full,size:f.size,mtime:f.mtime}))}),u=new Map(a.map(f=>[f.full,f])),r=[];for(const f of d.remove){V(e,f,{now:k});for(const[y,m]of Object.entries(n.files))m.id===f&&(delete n.files[y],r.push(y.startsWith(`${o}/`)?y.slice(o.length+1):y))}const s=[],l=[],p=async(f,y)=>{const m=u.get(f),w=Ne(f);try{const v=await D(e,X(f),{name:_(f),source:{kind:"file",path:f},reach:"internal",id:w});n.files[f]={id:w,size:m.size,mtime:m.mtime},y.push({...v,path:m.rel})}catch(v){c.push({path:m.rel,why:v.message})}};for(const f of d.add)await p(f,s);for(const f of d.change)await p(f.path,l);return n.syncedAt=k(),{root:o,added:s,changed:l,removed:r,same:d.same,skipped:c}}async function ce(e,{url:t,title:i=""}){if(!G)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await G().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const a=String(o.body.markdown||o.body.text||"");if(!a.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const c=j(a).map((d,u)=>({page:u+1,text:d})),n=M(e,{title:i||o.body.title||t,pages:c,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:k});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced}}async function de(e,t,{admin:i=!1}={}){const o=k();let a=[],c=[];if(t.kind==="bytes"){const d=Buffer.from(t.data,"base64");if(!d.length)return h(400,"invalid_request","kb: data decoded to nothing");if(d.length>A)return h(413,"too_large",`kb: ${d.length} bytes is over the ${A}-byte limit`);try{a.push(await D(e,d,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(u){return z(u)}}else if(t.kind==="path"){if(!i)return h(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:a,skipped:c}=await oe(e,t))}catch(d){return z(d)}}else if(t.kind==="url")try{a.push(await ce(e,t))}catch(d){return z(d)}else if(t.kind==="text"){const d=j(t.text).map((r,s)=>({page:s+1,text:r})),u=M(e,{title:t.title||t.name,pages:d,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:k});a.push({id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced})}const n=a.length?await K(e):0;return g.save(e),b({added:a,skipped:c,embedded:n,kb:S(e),ms:k()-o})}function z(e){const t=e?.code||"";return t==="refused"?h(403,"refused",`kb: ${e.message}`):t==="unsupported"?h(415,"unsupported",`kb: ${e.message}`):t==="too_large"?h(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?h(502,"read_failed",`kb: ${e.message}`):t==="timeout"?h(504,"extract_timeout","kb: the document took too long to parse"):h(500,"kb_error",`kb: ${e?.message||e}`)}const I=(e,t)=>we(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:R("query"),rerank:t.rerank===!1?null:se,now:k}),ue=(e,t)=>e.docs.find(i=>i.id===t)?.title||t,U=(e,t)=>{const i=Se(e,t);if(!i)return null;const o=i.kind==="note"?"Note":ue(e,i.doc);return{...i,title:o,cite:i.kind==="note"?`[note ${i.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${i.page}]`}};function le(e,t){F(e);const i=q(e.graph,t.node);if(!i)return b({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=c=>{const n=e.graph.nodes.find(d=>d.id===c);return{id:c,label:n?.label||c.replace(/^chunk:/,"passage "),kind:n?.kind||"chunk"}},a={node:{id:i.id,kind:i.kind,label:i.label},neighbours:Te(e.graph,i.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const c=q(e.graph,t.to);a.to=t.to,a.path=c?(Ee(e.graph,i.id,c.id)||[]).map(o):null,c&&!a.path.length&&(a.path=null)}return b(a)}async function fe(e,t,{admin:i=!1}={}){if(t.model&&!i)return h(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof L=="function"?L(t.model):null,a=S(e),c=await _e(t.question,{search:(n,d)=>I(e,{query:n,limit:d.limit||10,hops:d.hops??1,docs:d.docs||t.docs||null}),outline:async n=>n?ee(e.chunks,{doc:n}):e.outline,read:async n=>U(e,n),complete:o,kbName:e.name,docs:a.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:k});return b({attachment:c.attachment,read:c.read,hits:c.hits.map(n=>({id:n.id,doc:n.doc,title:n.title,page:n.page,section:n.section,cite:n.cite,lanes:n.lanes,via:n.via})),queries:c.queries,verdict:c.verdict,rounds:c.rounds,ask:c.ask,how:c.how,frame:{whole:c.frame.whole,docs:c.frame.docs},ms:c.ms})}async function pe({method:e="GET",pathname:t="",query:i=new URLSearchParams,body:o=null,admin:a=!1,agent:c=""}={}){const n=Pe(t);if(!n)return h(404,"not_found",`no route ${t}`);if(n.bad)return h(400,"invalid_request",`kb: "${n.bad}" is not a valid id or route`);const d={admin:a,agent:String(c||i.get("agent")||"").trim().toLowerCase()},u=s=>{try{return{value:s()}}catch(l){return{res:h(400,"invalid_request",l.message)}}};if(!n.id){if(e==="GET")return b({kbs:g.list().filter(({manifest:s})=>Z({access:s.access},d)).map(({manifest:s})=>({id:s.id,name:s.name,docs:(s.docs||[]).length,updatedAt:s.updatedAt,vectors:s.vectors?.count||0,model:s.vectors?.model||"",access:s.access||{agents:"all"}}))});if(e==="POST"){const s=u(()=>Ke(o||{}));if(s.res)return s.res;const l=s.value;if(l.id&&g.load(l.id))return b({kb:S(g.load(l.id)),existed:!0});const p=Q({id:l.id,name:l.name,embed:l.embed,now:k});return g.save(p),{status:201,body:{kb:S(p)}}}return h(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(n.sub==="sync"){if(e!=="POST")return h(405,"method_not_allowed","kb: sync is POST");if(!a)return h(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");const s=u(()=>Ge(o||{}));if(s.res)return s.res;const l=s.value;let p=g.load(n.id);const f=!p;p||(p=Q({id:n.id,name:l.name||_(String(l.path).replace(/[\\/]+$/,""))||n.id,now:k}));const y=k();let m;try{m=await ie(p,l)}catch($){return z($)}const w=m.added.length+m.changed.length+m.removed.length,v=m.added.length||m.changed.length?await K(p):0;return(w||f)&&g.save(p),b({folder:m.root,added:m.added,changed:m.changed,removed:m.removed,same:m.same,skipped:m.skipped,embedded:v,made:f,kb:S(p),ms:k()-y})}const r=g.load(n.id);if(!r)return h(404,"not_found",`kb: no knowledge base ${n.id} — POST /v1/kb to create one`);if(!Z(r,d))return h(404,"not_found",`kb: no knowledge base ${n.id} for ${d.agent||"this caller"} — the owner can grant it (POST /v1/kb/${n.id}/access)`);if(!n.sub)return e==="GET"?b({kb:{...S(r),bytes:g.sizeOf(r.id),dir:a?g.dirOf(r.id):void 0}}):e==="DELETE"?a?(g.remove(r.id),b({ok:!0})):h(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):h(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(n.sub){case"documents":{if(e==="POST"&&!n.rest){const s=u(()=>ze(o||{}));return s.res?s.res:de(r,s.value,{admin:a})}if(e==="DELETE"&&n.rest)return a?V(r,n.rest,{now:k})?(g.save(r),b({ok:!0,kb:S(r)})):h(404,"not_found",`kb: no document ${n.rest}`):h(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&n.rest){const s=Number(i.get("page"))||1,l=xe(r,n.rest,s);return l?b(l):h(404,"not_found",`kb: no document ${n.rest}`)}if(e==="GET")return b({documents:S(r).documents});break}case"passages":{if(e==="GET"&&n.rest){const s=U(r,n.rest);return s?b(s):h(404,"not_found",`kb: no passage ${n.rest}`)}break}case"outline":{if(e==="GET"){F(r);const s=i.get("doc");return b({outline:s?ee(r.chunks,{doc:s}):r.outline})}break}case"search":{if(e==="POST"){const s=u(()=>De(o||{}));return s.res?s.res:b(await I(r,s.value))}break}case"research":{if(e==="POST"){const s=u(()=>Me(o||{}));return s.res?s.res:fe(r,s.value,{admin:a})}break}case"graph":{if(e==="POST"){const s=u(()=>Fe(o||{}));return s.res?s.res:le(r,s.value)}break}case"report":{if(e==="GET")return F(r),{status:200,text:Oe(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return b({notes:r.notes});if(e==="POST"&&!n.rest){const s=u(()=>je(o||{}));if(s.res)return s.res;const l=s.value,p=l.status==="accepted"&&a?"accepted":"proposed",f=ke(r,{text:l.text,cites:l.cites||[],by:l.by||(a?"user":"agent"),status:p,now:k});return await K(r),g.save(r),{status:201,body:{note:f}}}if(e==="POST"&&n.rest){if(!a)return h(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const s=u(()=>Ae(o||{}));if(s.res)return s.res;const l=s.value,p=ye(r,n.rest,l.status,{now:k});return p?(g.save(r),b({note:p,removed:l.status==="removed"})):h(404,"not_found",`kb: no note ${n.rest}`)}break}case"access":{if(e==="GET")return b({access:r.access});if(e==="POST"){if(!a)return h(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const s=u(()=>Be(o||{}));if(s.res)return s.res;const l=$e(r,s.value,{now:k});return g.save(r),b({access:l})}break}case"embed":{if(e==="POST"){const s=P(),l=x&&s?x.health("embed",s):{state:"off"},p=await K(r);return p&&g.save(r),b({embedded:p,vectors:r.vectors.by.size,model:r.vectors.model||s,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return h(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:pe,store:g,embedModel:P}}export{T as KB_WALK_LIMITS,ct as createKbService};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.142.0";export{o as VERSION};
|