@chatpanel/gateway 0.143.2 → 0.144.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/extract/engine.js +2 -2
- package/src/extract/handler.js +1 -1
- package/src/extract/pdf.js +1 -1
- package/src/extract/service.js +2 -2
- package/src/extract/worker.js +1 -1
- package/src/kb.js +1 -1
- 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.144.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.478.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/extract/engine.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createHash as f}from"node:crypto";import{paginateText as
|
|
1
|
+
import{createHash as f}from"node:crypto";import{paginateText as p,EXTRACT_TYPES as m}from"../extract-capability.js";import{pdfPages as g}from"./pdf.js";import{docxPages as h}from"./docx.js";import{xlsxPages as w,pptxPages as b,odfPages as y}from"./office-xml.js";const B="chatpanel-extract",T=[["pdf",[37,80,68,70,45]],["zip",[80,75,3,4]]],c={docx:"docx",xlsx:"xlsx",pptx:"pptx",odt:"odt",ods:"ods",odp:"odp",epub:"epub"},d={md:"md",markdown:"md",txt:"txt",text:"txt",csv:"csv",html:"html",htm:"html",json:"txt",xml:"txt",log:"txt"};function l(r){const e=/\.([a-z0-9]{1,8})$/i.exec(String(r||""));return e?e[1].toLowerCase():""}function v(r,{name:e="",hint:s=""}={}){const n=r.subarray(0,8);for(const[t,u]of T)if(u.every((i,x)=>n[x]===i)){if(t!=="zip")return t;const i=l(e);return c[i]?c[i]:c[s]?s:E(r)||"zip"}const o=l(e);if(d[o])return d[o];if(m.includes(s)&&s!=="pdf")return s;const a=r.subarray(0,4096);for(let t=0;t<a.length;t+=1)if(a[t]===0)return"binary";return"txt"}function E(r){const e=Buffer.from(r.subarray(0,4096)).toString("latin1");return e.includes("word/")?"docx":e.includes("xl/")?"xlsx":e.includes("ppt/")?"pptx":e.includes("mimetypeapplication/vnd.oasis.opendocument.text")?"odt":e.includes("mimetypeapplication/vnd.oasis.opendocument.spreadsheet")?"ods":e.includes("mimetypeapplication/vnd.oasis.opendocument.presentation")?"odp":""}function P(r){return f("sha256").update(r).digest("hex")}async function C(r,{name:e="",hint:s=""}={}){const n=r instanceof Uint8Array?r:new Uint8Array(r),o=v(n,{name:e,hint:s}),a={hash:P(n),type:o,title:""};switch(o){case"pdf":{const t=await g(n);return{...a,title:t.title,pages:t.pages,scanned:t.scanned,markdown:!!t.markdown,labels:t.labels||[],outline:t.outline||[]}}case"docx":{const t=await h(n);return{...a,title:t.title,pages:p(t.markdown)}}case"xlsx":return{...a,pages:await w(n)};case"pptx":return{...a,pages:await b(n)};case"odt":case"ods":case"odp":{const t=await y(n,o);return{...a,pages:o==="odt"?p(t.text):t.pages}}case"md":case"txt":case"csv":case"html":{let t=Buffer.from(n).toString("utf8");return o==="html"&&(t=S(t)),{...a,pages:p(t)}}default:{const t=new Error(`extract: no reader for ${o==="binary"?"this file type":o}${e?` (${e})`:""}`);throw t.code="unsupported",t}}}function S(r){return String(r).replace(/<(script|style|noscript)\b[\s\S]*?<\/\1>/gi," ").replace(/<(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\b[^>]*>/gi,`
|
|
2
2
|
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/[ \t]+/g," ").replace(/\n[ \t]+/g,`
|
|
3
3
|
`).replace(/\n{3,}/g,`
|
|
4
4
|
|
|
5
|
-
`).trim()}export{
|
|
5
|
+
`).trim()}export{B as PROVIDER_ID,P as hashOf,C as openDocument,v as typeOf};
|
package/src/extract/handler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateExtractRequest as w,validateExtractContextRequest as
|
|
1
|
+
import{validateExtractRequest as w,validateExtractContextRequest as b,MAX_DOCUMENT_BYTES as m}from"../extract-capability.js";import{documentContext as x,documentBudget as _}from"@chatpanel/events/document-context.js";import{isSmallWindow as k}from"@chatpanel/events/context-window.js";import{PROVIDER_ID as h}from"./engine.js";function E(p){const a=p.status();return{id:"extract",route:"/v1/extract",providers:[h],default:h,types:["pdf","docx","xlsx","pptx","odt","ods","odp","md","txt","csv","html"],maxBytes:m,requirements:{egress:"none",deterministic:!0},stats:{opens:a.stats.opens,pages:a.stats.pages,msPerMBp50:a.stats.msPerMBp50},runtime:{name:"worker",state:a.running?"ready":"idle",sandbox:a.sandbox}}}async function B(p,{service:a}={}){let e;try{e=w(p)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}const s=(r,t,n,o={})=>({status:r,body:{error:{message:n,type:t},...o}});try{if(e.kind==="page"){const n=a.known(e.hash);if(!n)return s(404,"unknown_document","that document is not open here — send its bytes again");if(e.page>n.pages)return s(400,"invalid_request",`page must be 1–${n.pages}`);const o=await a.page(e.hash,e.page);return{status:200,body:{hash:e.hash,type:o.type,pages:o.pages,page:e.page,text:o.text,title:n.title||"",provider:h,ms:o.ms}}}const r=Buffer.from(e.data,"base64");if(!r.length)return s(400,"invalid_request","extract: data decoded to nothing");if(r.length>m)return s(413,"too_large",`extract: ${r.length} bytes is over the ${m}-byte limit`);if(e.budgetMs!=null){const n=a.predictMs(r.length);if(n!=null&&n>e.budgetMs)return{status:503,body:{error:{message:`predicted ${n} ms, over the ${e.budgetMs} ms budget`,type:"over_budget"},predictedMs:n}}}const t=await a.open(r,{name:e.name,hint:e.type||""});return{status:200,body:{hash:t.hash,type:t.type,pages:t.pages,title:t.title||"",scanned:!!t.scanned,provider:h,ms:t.ms,...t.markdown?{markdown:!0}:{},...t.labels?{labels:t.labels}:{},...t.outline?{outline:t.outline}:{}}}}catch(r){const t=r?.code||"extract_error";return t==="unsupported"?s(415,"unsupported",r.message):t==="unknown_document"?s(404,"unknown_document",r.message):t==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):t==="invalid_request"?s(400,"invalid_request",r.message):s(500,"extract_error",r?.message||String(r))}}async function C(p,{service:a}={}){let e;try{e=b(p)}catch(t){return{status:400,body:{error:{message:t.message,type:"invalid_request"}}}}const s=(t,n,o)=>({status:t,body:{error:{message:o,type:n}}}),r=Date.now();try{const t=[],n=new Map;for(const[d,u]of e.documents.entries()){let c;if(u.hash){const i=a.known(u.hash);if(!i)return s(404,"unknown_document",`documents[${d}]: that document is not open here — send its bytes again`);c={hash:u.hash,pages:i.pages,title:i.title||""}}else{const i=Buffer.from(u.data,"base64");if(!i.length)return s(400,"invalid_request",`documents[${d}]: data decoded to nothing`);if(i.length>m)return s(413,"too_large",`documents[${d}]: ${i.length} bytes is over the ${m}-byte limit`);c=await a.open(i,{name:u.name,hint:u.type||""})}const g=`doc-${d+1}`,f=u.name||c.title||g;t.push({id:g,kind:"path",path:`/${f}`,title:f,isDir:!1,pages:c.pages,hash:c.hash}),n.set(g,{title:f,pages:c.pages,page:async i=>(await a.page(c.hash,i)).text||""})}const o=e.window?k(e.window):!0,y=e.budgetChars||_({window:e.window||4096,small:o}),l=await x({question:e.question,documents:t,open:async d=>n.get(d.id)||null,budgetChars:y});return{status:200,body:{attachment:l.attachment,read:l.read.map(d=>({...d,hash:t.find(u=>u.id===d.id)?.hash||""})),skipped:l.skipped,how:l.how,budgetChars:y,provider:h,ms:Date.now()-r}}}catch(t){const n=t?.code||"extract_error";return n==="unsupported"?s(415,"unsupported",t.message):n==="unknown_document"?s(404,"unknown_document",t.message):n==="timeout"?s(504,"extract_timeout","the document took too long to parse and the worker was restarted"):n==="invalid_request"?s(400,"invalid_request",t.message):s(500,"extract_error",t?.message||String(t))}}export{E as extractCapabilityEntry,B as handleExtract,C as handleExtractContext};
|
package/src/extract/pdf.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{linesFromItems as P,looksScanned as k}from"@chatpanel/events/pdf-layout.js";import{structurePages as F}from"@chatpanel/events/pdf-structure.js";let g=null;function S(){return g||(g=Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"),import("pdfjs-dist/legacy/build/pdf.worker.mjs")]).then(([t,s])=>(globalThis.pdfjsWorker||=s,t)).catch(t=>{throw g=null,t})),g}const b=1500;async function D(t,{maxPages:s=b}={}){const i=(await S()).getDocument({data:new Uint8Array(t),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),a=await i.promise;try{const n=await a.getMetadata().catch(()=>null),o=a.numPages,r=[],u=[],f=[];for(let e=1;e<=Math.min(o,s);e+=1){const c=await a.getPage(e);try{const y=await c.getTextContent(),d=c.getViewport({scale:1});r.push(P(y.items)),u.push(d.width),f.push(d.height)}finally{c.cleanup()}}const h=await x(a).catch(()=>[]),m=F(r,{pageWidths:u,pageHeights:f,outline:h}),l=m.pages.map(e=>e.text),w=n?.info||{};return{title:String(w.Title||"").trim(),pages:l,labels:m.pages.map(e=>e.label),outline:h,markdown:!0,truncatedPages:o>l.length?o-l.length:0,scanned:k(l.map((e,c)=>({page:c+1,text:e})))}}finally{await i.destroy().catch(()=>{})}}async function x(t){const s=[],p=async(i,a)=>{for(const n of i||[]){if(s.length>=400)return;let o=0;try{const r=typeof n.dest=="string"?await t.getDestination(n.dest):n.dest;Array.isArray(r)&&r[0]&&(o=await t.getPageIndex(r[0])+1)}catch{}s.push({title:String(n.title||"").trim(),page:o,level:a}),a<2&&n.items?.length&&await p(n.items,a+1)}};return await p(await t.getOutline(),1),s.filter(i=>i.title)}export{b as PDF_MAX_PAGES,D as pdfPages};
|
package/src/extract/service.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)})}return{async open(t,{name:n="",hint:r=""}={}){const o=Date.now(),p=Buffer.isBuffer(t)?t.toString("base64"):Buffer.from(t).toString("base64"),e=await b({op:"open",name:n,hint:r,data:p},
|
|
1
|
+
import{spawn as k}from"node:child_process";import{createInterface as E}from"node:readline";import{tmpdir as _}from"node:os";import T from"node:path";import{fileURLToPath as I}from"node:url";const D=600*1e3,v=12e4,L=1e4;function j(){const d=process.execPath,f=T.basename(d).toLowerCase(),g=f.startsWith("node")||f.startsWith("bun"),h=I(new URL("../../bin/chatpanel-gateway.js",import.meta.url));return{program:d,args:[...g?[h]:[],"--extract-worker"]}}function J({wrap:d=null,idleMs:f=D,cacheDir:g=T.join(_(),"chatpanel-extract"),launch:h=j,onLog:B=()=>{}}={}){let a=null,w={layer:"none",reason:"not started"},O=0;const l=new Map;let c=null;const m=new Map,i={opens:0,msPerMB:[],pages:0};function M(){c&&clearTimeout(c),c=setTimeout(()=>x("idle"),f),c.unref&&c.unref()}function y(t){for(const[,n]of l)clearTimeout(n.timer),n.reject(Object.assign(new Error(t),{code:"worker_gone"}));l.clear()}async function S(){if(a)return a;const{program:t,args:n}=h();let r={bin:t,argv:n,opts:{stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_OPTIONS:""}},record:{layer:"none",reason:"no sandbox runner in this gateway"}};if(typeof d=="function")try{r=await d(r.bin,r.argv,r.opts,{engine:"extract",cwd:g})}catch(e){r.record={layer:"none",reason:`sandbox: ${e?.message||e}`}}w=r.record||w,a=k(r.bin,r.argv,{...r.opts,stdio:["pipe","pipe","pipe"]});const o=a;return E({input:o.stdout,crlfDelay:1/0}).on("line",e=>{let s;try{s=JSON.parse(e)}catch{return}const u=l.get(s?.id);u&&(l.delete(s.id),clearTimeout(u.timer),s.ok?u.resolve(s):u.reject(Object.assign(new Error(s.error||"extract failed"),{code:s.code||"extract_error"})))}),o.stderr.on("data",e=>B(String(e).trim())),o.on("exit",(e,s)=>{a===o&&(a=null),m.clear(),y(`extract worker exited (${s||e})`)}),M(),o}function x(t="stopped"){c&&(clearTimeout(c),c=null);const n=a;if(a=null,m.clear(),n){try{n.stdin.end()}catch{}setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},3e3).unref?.()}y(`extract worker ${t}`)}async function b(t,n){const r=await S(),o=++O;return M(),new Promise((p,e)=>{const s=setTimeout(()=>{l.delete(o),e(Object.assign(new Error("extract timed out"),{code:"timeout"})),x("timed out")},n);l.set(o,{resolve:p,reject:e,timer:s}),r.stdin.write(`${JSON.stringify({id:o,...t})}
|
|
2
|
+
`)})}return{async open(t,{name:n="",hint:r=""}={}){const o=Date.now(),p=Buffer.isBuffer(t)?t.toString("base64"):Buffer.from(t).toString("base64"),e=await b({op:"open",name:n,hint:r,data:p},v),s=Date.now()-o,u=Math.max(.05,p.length*.75/(1024*1024));i.opens+=1,i.msPerMB.push(s/u),i.msPerMB.length>50&&i.msPerMB.shift();const P={...e.markdown?{markdown:!0}:{},...e.labels?{labels:e.labels}:{},...e.outline?{outline:e.outline}:{}};return m.set(e.hash,{type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,...P,at:Date.now()}),{hash:e.hash,type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,...P,ms:s}},async page(t,n){const r=Date.now(),o=await b({op:"page",hash:t,page:n},L);return i.pages+=1,{text:o.text,pages:o.pages,type:o.type,ms:Date.now()-r}},known:t=>m.get(t)||null,predictMs(t){if(!i.msPerMB.length)return null;const n=[...i.msPerMB].sort((o,p)=>o-p),r=n[Math.floor(n.length/2)];return Math.round(r*Math.max(.05,t/(1024*1024)))},status(){const t=[...i.msPerMB].sort((n,r)=>n-r);return{running:!!a,pid:a?.pid||null,sandbox:w,open:m.size,stats:{opens:i.opens,pages:i.pages,msPerMBp50:t.length?Math.round(t[Math.floor(t.length/2)]):null}}},stop:x}}export{D as IDLE_MS,J as createExtractService,j as workerLaunch};
|
package/src/extract/worker.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createInterface as c}from"node:readline";import{openDocument as
|
|
1
|
+
import{createInterface as c}from"node:readline";import{openDocument as l}from"./engine.js";const u=24,p=64*1024*1024,s=new Map;function h(n){const o=n.pages.reduce((e,t)=>e+t.length,0);s.delete(n.hash),s.set(n.hash,{...n,chars:o});let r=[...s.values()].reduce((e,t)=>e+t.chars,0);for(;s.size>u||r>p&&s.size>1;){const[e,t]=s.entries().next().value;s.delete(e),r-=t.chars}}async function d(n){const o=n?.id??null,r=(e,t)=>({id:o,ok:!1,code:e,error:t});try{if(n.op==="open"){const e=Buffer.from(String(n.data||""),"base64");if(!e.length)return r("invalid_request","no bytes");const t=await l(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),{name:n.name,hint:n.hint});return h(t),{id:o,ok:!0,hash:t.hash,type:t.type,title:t.title||"",pages:t.pages.length,scanned:!!t.scanned,...t.markdown?{markdown:!0}:{},...t.labels?.some(Boolean)?{labels:t.labels}:{},...t.outline?.length?{outline:t.outline}:{}}}if(n.op==="page"){const e=s.get(String(n.hash||""));if(!e)return r("unknown_document","not open here — send the bytes again");const t=Number(n.page);return!Number.isInteger(t)||t<1||t>e.pages.length?r("invalid_request",`page must be 1–${e.pages.length}`):(s.delete(e.hash),s.set(e.hash,e),{id:o,ok:!0,text:e.pages[t-1],pages:e.pages.length,type:e.type})}return n.op==="status"?{id:o,ok:!0,docs:s.size,pid:process.pid}:r("invalid_request",`unknown op ${n.op}`)}catch(e){return r(e?.code==="unsupported"?"unsupported":"extract_error",e?.message||String(e))}}function f({input:n=process.stdin,output:o=process.stdout}={}){try{process.title="chatpanel-extract"}catch{}const r=c({input:n,crlfDelay:1/0});let e=Promise.resolve();r.on("line",t=>{if(!t.trim())return;let a;try{a=JSON.parse(t)}catch{o.write(`${JSON.stringify({id:null,ok:!1,code:"invalid_request",error:"not JSON"})}
|
|
2
2
|
`);return}e=e.then(()=>d(a)).then(i=>{o.write(`${JSON.stringify(i)}
|
|
3
3
|
`)})}),r.on("close",()=>process.exit(0))}process.argv[1]&&/worker\.js$/.test(process.argv[1])&&!process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED&&f();export{f as runExtractWorker};
|
package/src/kb.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{readFileSync as te,statSync as se,readdirSync as xe,realpathSync as ne}from"node:fs";import{join as $e,basename as z,extname as re,resolve as Te,dirname as Oe}from"node:path";import _e from"node:os";import{createKb as ae,addDocument as R,removeDocument as G,addNote as Ee,setNoteStatus as Pe,searchKb as Ke,embedMissing as ze,kbStatus as T,readPage as Me,chunkById as je,refreshKb as U,setKbAccess as Ae,kbMayUse as ie}from"@chatpanel/events/kb-index.js";import{kbResearch as De}from"@chatpanel/events/kb-research.js";import{neighbours as Fe,pathBetween as Le,resolveNode as oe,graphReport as Ge}from"@chatpanel/events/kb-graph.js";import{outlineOf as ce}from"@chatpanel/events/kb-chunk.js";import{routeKb as Be,validateKbCreate as Ne,validateKbAdd as Ce,validateKbSearch as Ie,validateKbResearch as We,validateKbGraph as Re,validateKbNote as Ue,validateKbNoteStatus as Xe,validateKbAccess as He,validateKbSync as Ve}from"@chatpanel/events/kb-capability.js";import{planFolderSync as Ye,folderDocId as Je,folderSource as Qe,knownFiles as Ze}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as qe,markdownLinks as et,resolveLinks as tt,visibleTextHash as st,decodeText as nt}from"@chatpanel/events/kb-html.js";import{secretReason as de,SKIP_DIR_NAMES as rt,sniffType as at,checkAttachablePath as it}from"@chatpanel/events/attached-paths.js";import{paginateText as B,MAX_DOCUMENT_BYTES as X}from"./extract-capability.js";import{defaultEmbeddedModel as ot}from"./embedded-models.js";import{primaryProvider as ct}from"./capability-config.js";const M=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),le=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),dt=new Set([".html",".htm",".xhtml"]),lt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(b,j,E,A={})=>({status:b,body:{error:{type:j,message:E},...A}}),y=b=>({status:200,body:b});function Tt({store:b,extract:j=null,embedded:E=null,cfg:A={},rerank:H=null,read:V=null,completer:Y=null,log:D=()=>{},now:k=()=>Date.now(),home:J=_e.homedir()}={}){const F=()=>{const e=ct(A.capabilities?.embed,"embed",{destinations:A.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||ot("embed")||""},N=(e="passage")=>{const s=F();if(!E||!s)return null;const c=E.health("embed",s);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?(E.embed(s,["warm"],{kind:e}).catch(()=>{}),null):async d=>(await E.embed(s,d,{kind:e})).vectors},ue=typeof H=="function"?H:null,C=new Set;function Q(e){!e||C.has(e.id)||e.embed==="off"||!N("passage")||e.vectors.by.size>=e.chunks.length||(C.add(e.id),K(e).then(s=>{s&&(b.save(e),D(`[kb] ${e.id}: ${s} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>C.delete(e.id)))}async function K(e,{late:s=()=>!1}={}){const c=N("passage");if(!c)return 0;try{return await ze(e,c,{model:F(),late:s})}catch(d){return D(`[kb] ${e.id}: embedding failed — ${d.message}`),0}}async function fe(e,s,c=""){const d=at(e,s);if(d.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(d.text){const u=nt(e);if(/\.x?html?$/i.test(s)||/html/i.test(d.label||"")){const t=qe(u);return{type:"html",pages:B(t.markdown).map((o,f)=>({page:f+1,text:o})),title:t.title,links:t.links,markdown:!0}}const l=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(u.split(`
|
|
2
|
-
`).find(t=>t.trim())||""),r=/\.(md|markdown)$/i.test(s);return{type:d.label||"text",pages:B(u).map((t,o)=>({page:o+1,text:t})),title:l?l[1].trim():"",links:r?et(u):[],markdown:r}}if(d.group!=="document")throw Object.assign(new Error(`${d.label||"binary"} is not a document`),{code:"unsupported"});if(!j)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=j(),i=await a.open(e,{name:s,hint:c}),n=[];for(let u=1;u<=i.pages;u+=1){let l="";try{l=String((await a.page(i.hash,u)).text||"")}catch(r){D(`[kb] ${s} p.${u}: ${r.message}`)}n.push({page:u,text:l})}return{type:i.type,pages:n,title:i.title||"",hash:i.hash,scanned:!!i.scanned}}async function I(e,s,{name:c,hint:d="",title:a="",source:i={},reach:n="",id:u="",root:l="",dedupe:r=!1}){const t=await fe(s,c,d),o=st(t.pages.map(w=>w.text).join(`
|
|
2
|
+
`).find(t=>t.trim())||""),r=/\.(md|markdown)$/i.test(s);return{type:d.label||"text",pages:B(u).map((t,o)=>({page:o+1,text:t})),title:l?l[1].trim():"",links:r?et(u):[],markdown:r}}if(d.group!=="document")throw Object.assign(new Error(`${d.label||"binary"} is not a document`),{code:"unsupported"});if(!j)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const a=j(),i=await a.open(e,{name:s,hint:c}),n=[];for(let u=1;u<=i.pages;u+=1){let l="";try{l=String((await a.page(i.hash,u)).text||"")}catch(r){D(`[kb] ${s} p.${u}: ${r.message}`)}n.push({page:u,text:l})}return{type:i.type,pages:n,title:i.title||"",hash:i.hash,scanned:!!i.scanned,markdown:!!i.markdown,labels:i.labels||[]}}async function I(e,s,{name:c,hint:d="",title:a="",source:i={},reach:n="",id:u="",root:l="",dedupe:r=!1}){const t=await fe(s,c,d),o=st(t.pages.map(w=>w.text).join(`
|
|
3
3
|
`));if(r&&o){const w=e.docs.find(v=>v.textHash===o&&v.id!==u);if(w)return{duplicateOf:w}}const f=i.path&&t.links?.length?tt(i.path,t.links,{root:l||Oe(i.path)}):[],h=R(e,{id:u,title:a||t.title||z(c),pages:t.pages,source:{kind:i.kind||"bytes",name:c,...i},hash:t.hash||"",type:t.type,reach:n,now:k,links:f,textHash:o,markdownHeadings:!!t.markdown});return{id:h.doc.id,title:h.doc.title,pages:h.doc.pages,chunks:h.doc.chunks,replaced:h.replaced,...t.scanned?{scanned:!0}:{}}}function pe(e,s){const c=re(e).toLowerCase();return!le.has(c)&&!lt.has(c)?!1:s?.length?s.some(d=>{const a=String(d).toLowerCase().replace(/^\*/,"");return c===(a.startsWith(".")?a:`.${a}`)||e.toLowerCase().endsWith(a)}):!0}function Z(e,{recursive:s=!0,include:c=null}={}){const d=it(e,{home:J,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const a=ne(Te(e.replace(/^~(?=$|\/)/,J))),i=[],n=[];let u=0;const l=(o,f)=>{if(i.length>=M.files)return n.push({path:f,why:`stopped at ${M.files} files`}),!1;if(de(o))return n.push({path:f,why:"withheld (a credential store)"}),!0;let h;try{h=se(o)}catch{return!0}const w=re(o).toLowerCase(),v=le.has(w)||dt.has(w)?X:M.textBytes;return h.size>v?(n.push({path:f,why:`too large (${Math.round(h.size/1048576)} MB)`}),!0):u+h.size>M.bytes?(n.push({path:f,why:"stopped: the folder is past the size limit"}),!1):(u+=h.size,i.push({full:o,rel:f,size:h.size,mtime:Math.floor(h.mtimeMs)}),!0)};if(!se(a).isDirectory())return l(a,z(a)),{root:a,files:i,skipped:n,single:!0};const t=(o,f,h)=>{if(h>M.depth)return!0;let w=[];try{w=xe(o,{withFileTypes:!0}).sort((v,S)=>v.name.localeCompare(S.name))}catch{return!0}for(const v of w){const S=v.name;if(S.startsWith(".")&&v.isDirectory())continue;const O=$e(o,S),p=f?`${f}/${S}`:S;if(v.isDirectory()){if(rt.has(S)||!s)continue;try{if(!ne(O).startsWith(a)){n.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!t(O,p,h+1))return!1;continue}if(!(!v.isFile()&&!v.isSymbolicLink())){if(de(O)){n.push({path:p,why:"withheld (a credential store)"});continue}if(pe(S,c)&&!l(O,p))return!1}}return!0};return t(a,"",0),{root:a,files:i,skipped:n}}async function he(e,{path:s,recursive:c=!0,include:d=null,title:a=""}){const{files:i,skipped:n,single:u}=Z(s,{recursive:c,include:d}),l=[];for(const r of i)try{const t=await I(e,te(r.full),{name:z(r.full),title:l.length===0&&(u||!r.rel.includes("/"))?a:"",source:{kind:"file",path:r.full},reach:"internal"});l.push({...t,path:r.rel})}catch(t){n.push({path:r.rel,why:t.message})}return{added:l,skipped:n}}async function me(e,{path:s,include:c=null,rebuild:d=!1},{progress:a=null}={}){const{root:i,files:n,skipped:u}=Z(s,{recursive:!0,include:c}),l=Qe(e,i,{include:c});if(d){for(const p of Object.values(l.files))p?.id&&G(e,p.id,{now:k});l.files={}}const r=new Set(n.map(p=>p.full));for(const[p,x]of Object.entries(l.files))x?.dupOf&&!r.has(x.dupOf)&&delete l.files[p];const t=Ye({known:Ze(l),listing:n.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});a&&(a.total=t.add.length+t.change.length,a.done=0);const o=new Map(n.map(p=>[p.full,p])),f=[];for(const p of t.remove){G(e,p,{now:k});for(const[x,$]of Object.entries(l.files))$.id===p&&(delete l.files[x],f.push(x.startsWith(`${i}/`)?x.slice(i.length+1):x))}const h=[],w=[],v=[],S=p=>String(p||"").startsWith(`${i}/`)?p.slice(i.length+1):p,O=async(p,x)=>{if(a?.cancel)return;await new Promise(m=>setImmediate(m));const $=o.get(p),_=Je(p);try{const m=await I(e,te(p),{name:z(p),source:{kind:"file",path:p},reach:"internal",id:_,root:i,dedupe:!0});m.duplicateOf?(e.docs.some(W=>W.id===_)&&G(e,_,{now:k}),l.files[p]={id:_,size:$.size,mtime:$.mtime,dupOf:m.duplicateOf.source?.path||m.duplicateOf.id},v.push({path:$.rel,of:S(m.duplicateOf.source?.path||m.duplicateOf.title)})):(l.files[p]={id:_,size:$.size,mtime:$.mtime},x.push({...m,path:$.rel}))}catch(m){u.push({path:$.rel,why:m.message})}a&&(a.done+=1)};for(const p of t.add)await O(p,h);for(const p of t.change)await O(p.path,w);return l.syncedAt=k(),l.lastSync={at:l.syncedAt,added:h.length,changed:w.length,removed:f.length,same:t.same,duplicates:v.length,skipped:u.length,skippedSample:u.slice(0,20),duplicateSample:v.slice(0,20)},{root:i,added:h,changed:w,removed:f,same:t.same,duplicates:v,skipped:u}}async function ge(e,{url:s,title:c=""}){if(!V)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const d=await V().read({url:s,format:"markdown"});if(d.status!==200)throw Object.assign(new Error(d.body?.error?.message||`read failed (${d.status})`),{code:"read_failed"});const a=String(d.body.markdown||d.body.text||"");if(!a.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const i=B(a).map((u,l)=>({page:l+1,text:u})),n=R(e,{title:c||d.body.title||s,pages:i,source:{kind:"url",url:d.body.url||s,name:d.body.title||""},type:"html",reach:"web",now:k});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced}}async function be(e,s,{admin:c=!1}={}){const d=k();let a=[],i=[];if(s.kind==="bytes"){const u=Buffer.from(s.data,"base64");if(!u.length)return g(400,"invalid_request","kb: data decoded to nothing");if(u.length>X)return g(413,"too_large",`kb: ${u.length} bytes is over the ${X}-byte limit`);try{a.push(await I(e,u,{name:s.name,hint:s.type||"",title:s.title,reach:s.reach}))}catch(l){return L(l)}}else if(s.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:a,skipped:i}=await he(e,s))}catch(u){return L(u)}}else if(s.kind==="url")try{a.push(await ge(e,s))}catch(u){return L(u)}else if(s.kind==="text"){const u=B(s.text).map((r,t)=>({page:t+1,text:r})),l=R(e,{title:s.title||s.name,pages:u,source:{kind:"text",name:s.name},type:"text",reach:s.reach,now:k});a.push({id:l.doc.id,title:l.doc.title,pages:l.doc.pages,chunks:l.doc.chunks,replaced:l.replaced})}const n=a.length?await K(e):0;return b.save(e),y({added:a,skipped:i,embedded:n,kb:T(e),ms:k()-d})}function L(e){const s=e?.code||"";return s==="refused"?g(403,"refused",`kb: ${e.message}`):s==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):s==="too_large"?g(413,"too_large",`kb: ${e.message}`):s==="read_failed"||s==="empty"?g(502,"read_failed",`kb: ${e.message}`):s==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const q=(e,s)=>Ke(e,s.query,{limit:s.limit,hops:s.hops,docs:s.docs||null,queries:s.queries||[],embed:N("query"),rerank:s.rerank===!1?null:ue,now:k}),ke=(e,s)=>e.docs.find(c=>c.id===s)?.title||s,ee=(e,s)=>{const c=je(e,s);if(!c)return null;const d=c.kind==="note"?"Note":ke(e,c.doc);return{...c,title:d,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${d.replace(/[[\]]/g,"")} p.${c.page}]`}};function ye(e,s){U(e);const c=oe(e.graph,s.node);if(!c)return y({node:null,neighbours:[],message:`no node named "${s.node}"`});const d=i=>{const n=e.graph.nodes.find(u=>u.id===i);return{id:i,label:n?.label||i.replace(/^chunk:/,"passage "),kind:n?.kind||"chunk"}},a={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Fe(e.graph,c.id,{hops:s.hops,kinds:s.kinds||null,limit:s.limit})};if(s.to){const i=oe(e.graph,s.to);a.to=s.to,a.path=i?(Le(e.graph,c.id,i.id)||[]).map(d):null,i&&!a.path.length&&(a.path=null)}return y(a)}async function we(e,s,{admin:c=!1}={}){if(s.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const d=s.model&&typeof Y=="function"?Y(s.model):null,a=T(e),i=await De(s.question,{search:(n,u)=>q(e,{query:n,limit:u.limit||10,hops:u.hops??1,docs:u.docs||s.docs||null}),outline:async n=>n?ce(e.chunks,{doc:n}):e.outline,read:async n=>ee(e,n),complete:d,kbName:e.name,docs:a.documents,previous:s.previous||null,answer:s.answer||"",ask:s.ask!==!1,now:k});return y({attachment:i.attachment,read:i.read,hits:i.hits.map(n=>({id:n.id,doc:n.doc,title:n.title,page:n.page,section:n.section,cite:n.cite,lanes:n.lanes,via:n.via})),queries:i.queries,verdict:i.verdict,rounds:i.rounds,ask:i.ask,how:i.how,frame:{whole:i.frame.whole,docs:i.frame.docs},ms:i.ms})}const P=new Map;async function ve({method:e="GET",pathname:s="",query:c=new URLSearchParams,body:d=null,admin:a=!1,agent:i=""}={}){const n=Be(s);if(!n)return g(404,"not_found",`no route ${s}`);if(n.bad)return g(400,"invalid_request",`kb: "${n.bad}" is not a valid id or route`);const u={admin:a,agent:String(i||c.get("agent")||"").trim().toLowerCase()},l=t=>{try{return{value:t()}}catch(o){return{res:g(400,"invalid_request",o.message)}}};if(!n.id){if(e==="GET")return y({kbs:b.list().filter(({manifest:t})=>ie({access:t.access},u)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=l(()=>Ne(d||{}));if(t.res)return t.res;const o=t.value;if(o.id&&b.load(o.id))return y({kb:T(b.load(o.id)),existed:!0});const f=ae({id:o.id,name:o.name,embed:o.embed,now:k});return b.save(f),{status:201,body:{kb:T(f)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(n.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!a)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");const t=l(()=>Ve(d||{}));if(t.res)return t.res;const o=t.value,f=P.get(n.id);if(f)return{status:202,body:{running:!0,progress:{...f.progress},kb:f.base?T(f.base):null}};let h=b.load(n.id);const w=!h;h||(h=ae({id:n.id,name:o.name||z(String(o.path).replace(/[\\/]+$/,""))||n.id,now:k}),b.save(h));const v=k(),S={done:0,total:0},O=(async()=>{const m=await me(h,o,{progress:S});if(S.cancel)return{cancelled:!0};const W=m.added.length+m.changed.length+m.removed.length,Se=m.added.length||m.changed.length?await K(h):0;return(W||w)&&b.save(h),{folder:m.root,added:m.added,changed:m.changed,removed:m.removed,same:m.same,duplicates:m.duplicates,skipped:m.skipped,embedded:Se,made:w,kb:T(h),ms:k()-v}})();P.set(n.id,{progress:S,base:h}),O.catch(m=>D(`[kb] ${n.id}: sync failed — ${m?.message||m}`)).finally(()=>P.delete(n.id));const p=o.waitMs??5e3;if(p===0)return{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}};let x=null;const $=new Promise(m=>{x=setTimeout(()=>m(null),p)});let _;try{_=await Promise.race([O,$])}catch(m){return clearTimeout(x),L(m)}return clearTimeout(x),_?y(_):{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}}}const r=b.load(n.id);if(!r)return g(404,"not_found",`kb: no knowledge base ${n.id} — POST /v1/kb to create one`);if(!ie(r,u))return g(404,"not_found",`kb: no knowledge base ${n.id} for ${u.agent||"this caller"} — the owner can grant it (POST /v1/kb/${n.id}/access)`);if(!n.sub){if(e==="GET"){P.has(r.id)||Q(r);const t=T(r),o=a?(r.sources||[]).map(f=>({kind:f.kind,path:f.path,files:Object.keys(f.files||{}).length,syncedAt:f.syncedAt||0,...f.lastSync?{lastSync:f.lastSync}:{}})):void 0;return y({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:b.sizeOf(r.id),dir:a?b.dirOf(r.id):void 0,...o?.length?{sources:o}:{},...P.has(r.id)?{syncing:(({done:f,total:h})=>({done:f,total:h}))(P.get(r.id).progress)}:{}}})}if(e==="DELETE"){if(!a)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=P.get(r.id);return t&&(t.progress.cancel=!0),b.remove(r.id),y({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(n.sub){case"documents":{if(e==="POST"&&!n.rest){const t=l(()=>Ce(d||{}));return t.res?t.res:be(r,t.value,{admin:a})}if(e==="DELETE"&&n.rest)return a?G(r,n.rest,{now:k})?(b.save(r),y({ok:!0,kb:T(r)})):g(404,"not_found",`kb: no document ${n.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&n.rest){const t=Number(c.get("page"))||1,o=Me(r,n.rest,t);return o?y(o):g(404,"not_found",`kb: no document ${n.rest}`)}if(e==="GET")return y({documents:T(r).documents});break}case"passages":{if(e==="GET"&&n.rest){const t=ee(r,n.rest);return t?y(t):g(404,"not_found",`kb: no passage ${n.rest}`)}break}case"outline":{if(e==="GET"){U(r);const t=c.get("doc");return y({outline:t?ce(r.chunks,{doc:t}):r.outline})}break}case"search":{if(e==="POST"){const t=l(()=>Ie(d||{}));if(t.res)return t.res;const o=k(),f=await q(r,t.value);return Q(r),y({...f,ms:k()-o})}break}case"research":{if(e==="POST"){const t=l(()=>We(d||{}));return t.res?t.res:we(r,t.value,{admin:a})}break}case"graph":{if(e==="POST"){const t=l(()=>Re(d||{}));return t.res?t.res:ye(r,t.value)}break}case"report":{if(e==="GET")return U(r),{status:200,text:Ge(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return y({notes:r.notes});if(e==="POST"&&!n.rest){const t=l(()=>Ue(d||{}));if(t.res)return t.res;const o=t.value,f=o.status==="accepted"&&a?"accepted":"proposed",h=Ee(r,{text:o.text,cites:o.cites||[],by:o.by||(a?"user":"agent"),status:f,now:k});return await K(r),b.save(r),{status:201,body:{note:h}}}if(e==="POST"&&n.rest){if(!a)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=l(()=>Xe(d||{}));if(t.res)return t.res;const o=t.value,f=Pe(r,n.rest,o.status,{now:k});return f?(b.save(r),y({note:f,removed:o.status==="removed"})):g(404,"not_found",`kb: no note ${n.rest}`)}break}case"access":{if(e==="GET")return y({access:r.access});if(e==="POST"){if(!a)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=l(()=>He(d||{}));if(t.res)return t.res;const o=Ae(r,t.value,{now:k});return b.save(r),y({access:o})}break}case"embed":{if(e==="POST"){const t=F(),o=E&&t?E.health("embed",t):{state:"off"},f=await K(r);return f&&b.save(r),y({embedded:f,vectors:r.vectors.by.size,model:r.vectors.model||t,dims:r.vectors.dims,state:o.state,...o.progress?{progress:o.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${s} is not a route`)}return{handle:ve,store:b,embedModel:F}}export{M as KB_WALK_LIMITS,Tt as createKbService};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.144.0";export{o as VERSION};
|