@chatpanel/gateway 0.147.0 → 0.147.2

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.147.0",
3
+ "version": "0.147.2",
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": {
@@ -1,2 +1,3 @@
1
- import{execFile as c}from"node:child_process";import{existsSync as d}from"node:fs";import{delimiter as f,join as u}from"node:path";const p=10*6e4,m=120,h=["on run argv"," activate"," set f to choose folder with prompt (item 1 of argv)"," return POSIX path of f","end run"].join(`
2
- `),g="Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = $env:CHAP_PICK_PROMPT; $d.ShowNewFolderButton = $false; if ($d.ShowDialog() -eq 'OK') { [Console]::Out.Write($d.SelectedPath) }";function y(s,e,{has:n=()=>!0}={}){return s==="darwin"?{file:"/usr/bin/osascript",args:["-e",h,e],cancelled:r=>/-128|User canceled/i.test(String(r?.stderr||r?.message||""))}:s==="win32"?{file:"powershell.exe",args:["-NoProfile","-STA","-Command",g],env:{CHAP_PICK_PROMPT:e},cancelled:()=>!1}:n("zenity")?{file:"zenity",args:["--file-selection","--directory",`--title=${e}`],cancelled:r=>r?.code===1}:n("kdialog")?{file:"kdialog",args:["--getexistingdirectory","~","--title",e],cancelled:r=>r?.code===1}:null}let a=!1;async function C(s={},{platform:e=process.platform,run:n=P,has:r=w}={}){const l=String(s?.prompt||"Choose a folder for Chap to index").replace(/[\r\n\t]+/g," ").trim().slice(0,m)||"Choose a folder",t=y(e,l,{has:r});if(!t)return{status:501,body:{error:{message:"no folder chooser on this system — type the folder's path instead",type:"unsupported"}}};if(a)return{status:409,body:{error:{message:"a folder chooser is already open — finish or cancel it first",type:"conflict"}}};a=!0;try{const o=await n(t.file,t.args,{timeout:p,env:t.env?{...process.env,...t.env}:process.env}),i=String(o||"").replace(/[\r\n]+$/,"").replace(/(.)\/$/,"$1");return{status:200,body:i?{path:i}:{cancelled:!0}}}catch(o){return t.cancelled(o)?{status:200,body:{cancelled:!0}}:{status:502,body:{error:{message:o?.killed?"the folder chooser did not answer in time":`the folder chooser failed: ${String(o?.stderr||o?.message||o).trim().slice(0,200)}`,type:"upstream"}}}}finally{a=!1}}function P(s,e,n){return new Promise((r,l)=>{c(s,e,{...n,maxBuffer:64*1024,windowsHide:!1},(t,o,i)=>{t?(t.stderr=i,l(t)):r(o)})})}function w(s){return String(process.env.PATH||"").split(f).some(e=>!!e&&d(u(e,s)))}export{p as PICK_FOLDER_TIMEOUT_MS,y as chooserFor,C as handlePickFolder};
1
+ import{execFile as d}from"node:child_process";import{existsSync as f}from"node:fs";import{delimiter as u,join as h}from"node:path";const g=10*6e4,m=120,y=["function run(argv) {",' ObjC.import("AppKit");'," const app = $.NSApplication.sharedApplication;"," app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);"," app.activateIgnoringOtherApps(true);"," const p = $.NSOpenPanel.openPanel;"," p.canChooseDirectories = true;"," p.canChooseFiles = false;"," p.allowsMultipleSelection = false;"," p.canCreateDirectories = false;",' p.message = String(argv[0] || "Choose a folder");',' p.prompt = "Choose";',' if (p.runModal !== $.NSModalResponseOK) return "";'," return ObjC.unwrap(p.URLs.objectAtIndex(0).path);","}"].join(`
2
+ `),P=["on run argv"," activate"," set f to choose folder with prompt (item 1 of argv)"," return POSIX path of f","end run"].join(`
3
+ `),S="Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = $env:CHAP_PICK_PROMPT; $d.ShowNewFolderButton = $false; if ($d.ShowDialog() -eq 'OK') { [Console]::Out.Write($d.SelectedPath) }";function w(s,t,{has:n=()=>!0}={}){if(s==="darwin"){const r=i=>/-128|User canceled/i.test(String(i?.stderr||i?.message||""));return{file:"/usr/bin/osascript",args:["-l","JavaScript","-e",y,t],cancelled:r,fallback:{file:"/usr/bin/osascript",args:["-e",P,t],cancelled:r}}}return s==="win32"?{file:"powershell.exe",args:["-NoProfile","-STA","-Command",S],env:{CHAP_PICK_PROMPT:t},cancelled:()=>!1}:n("zenity")?{file:"zenity",args:["--file-selection","--directory",`--title=${t}`],cancelled:r=>r?.code===1}:n("kdialog")?{file:"kdialog",args:["--getexistingdirectory","~","--title",t],cancelled:r=>r?.code===1}:null}let c=!1;async function O(s={},{platform:t=process.platform,run:n=A,has:r=C}={}){const i=String(s?.prompt||"Choose a folder for Chap to index").replace(/[\r\n\t]+/g," ").trim().slice(0,m)||"Choose a folder",e=w(t,i,{has:r});if(!e)return{status:501,body:{error:{message:"no folder chooser on this system — type the folder's path instead",type:"unsupported"}}};if(c)return{status:409,body:{error:{message:"a folder chooser is already open — finish or cancel it first",type:"conflict"}}};c=!0;try{const o={timeout:g,env:e.env?{...process.env,...e.env}:process.env};let a;try{a=await n(e.file,e.args,o)}catch(l){if(!e.fallback||e.cancelled(l)||l?.killed)throw l;a=await n(e.fallback.file,e.fallback.args,o)}const p=String(a||"").replace(/[\r\n]+$/,"").replace(/(.)\/$/,"$1");return{status:200,body:p?{path:p}:{cancelled:!0}}}catch(o){return e.cancelled(o)?{status:200,body:{cancelled:!0}}:{status:502,body:{error:{message:o?.killed?"the folder chooser did not answer in time":`the folder chooser failed: ${String(o?.stderr||o?.message||o).trim().slice(0,200)}`,type:"upstream"}}}}finally{c=!1}}function A(s,t,n){return new Promise((r,i)=>{d(s,t,{...n,maxBuffer:64*1024,windowsHide:!1},(e,o,a)=>{e?(e.stderr=a,i(e)):r(o)})})}function C(s){return String(process.env.PATH||"").split(u).some(t=>!!t&&f(h(t,s)))}export{g as PICK_FOLDER_TIMEOUT_MS,w as chooserFor,O as handlePickFolder};
@@ -1 +1 @@
1
- import{existsSync as ce,mkdirSync as W,readFileSync as q,writeFileSync as de,readdirSync as le,rmSync as ue,renameSync as pe}from"node:fs";import{join as w,basename as fe}from"node:path";import he from"node:os";import{bucketClient as me,indexKey as A,isDocumentKey as be,bucketDocId as ye,splitIndexParts as ve,validateRevision as z,planReplicaSync as ge,assembleReplica as ke,makeLease as we,leaseState as Ae,replicaFreshness as $e,bucketWhere as Se,sha256Hex as G,KB_REVISION_FORMAT as Oe}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as je}from"@chatpanel/events/kb-folder-sync.js";import{createKb as De,removeDocument as Ie,serializeKb as Be,deserializeKb as Re}from"@chatpanel/events/kb-index.js";import{graphReport as Te}from"@chatpanel/events/kb-graph.js";const xe=new TextEncoder,Fe=l=>typeof l=="string"?xe.encode(l):l instanceof Uint8Array?l:new Uint8Array(l.buffer,l.byteOffset,l.byteLength),Q=(l,M)=>{const O=`${l}.tmp-${process.pid}`;de(O,M,{mode:384}),pe(O,l)};function _e({store:l,kb:M,entries:O=()=>[],fetchFn:X,now:f=()=>Date.now(),log:j=()=>{},holder:N=`${he.hostname()}`,version:Y="",subtle:E=null}={}){const J=new Map,D=new Map,$=new Map,K=e=>e.kbId||e.id,L=e=>w(l.dirOf(e),"team.json"),Z=e=>w(l.dirOf(e),"parts"),I=e=>me(e,{fetch:X,now:f,subtle:E});function B(e){if(J.has(e.id))return J.get(e.id);let t={kbId:K(e),role:e.role,revision:0,rev:null,syncedAt:0,checkedAt:0,error:"",updating:!1,remoteRevision:0,behindDocs:0,etag:""};try{const i=JSON.parse(q(L(K(e)),"utf8"));i?.provider===e.id&&(t={...t,...i.state,rev:i.state?.rev?z(i.state.rev):null,updating:!1})}catch{}return J.set(e.id,t),t}const ee=(e,t)=>{try{W(l.dirOf(t.kbId),{recursive:!0,mode:448}),Q(L(t.kbId),JSON.stringify({provider:e.id,state:{...t,updating:!1}}))}catch(i){j(`[team] ${e.id}: state not saved — ${i.message}`)}};async function te(e){const t=B(e),i=I(e),a=await i.get(A(e,"revision.json"),{etag:t.rev?t.etag:""});if(t.checkedAt=f(),a.status===304)return t.error="",t.remoteRevision=t.revision,t.behindDocs=0,{upToDate:!0};if(a.status===404)throw new Error("no index has been published to this bucket yet — a builder has not run");const n=z(JSON.parse(new TextDecoder().decode(a.bytes)));t.remoteRevision=n.revision;const b=Z(t.kbId);W(b,{recursive:!0,mode:448});const x=o=>ce(w(b,o)),c=ge({current:t.rev,next:n,have:x});if(c.upToDate)return t.etag=a.etag,t.error="",t.behindDocs=0,{upToDate:!0};t.behindDocs=c.added+c.changed+c.removed,t.updating=!0;try{for(const d of c.fetch){const u=await i.get(A(e,d.file));if(u.status!==200)throw new Error(`part ${d.file} is missing from the bucket (${u.status})`);if(await G(u.bytes,E)!==d.hash)throw new Error(`part ${d.file} does not match its hash — not used`);Q(w(b,d.hash),u.bytes)}const o=ke(n,d=>new Uint8Array(q(w(b,d))));o.manifest={...o.manifest,id:t.kbId};const F=Re(o);l.save(F);const p=new Set([n.manifest,n.notes,...n.report?[n.report]:[],...n.docs.flatMap(d=>[d.chunksFile,d.vectorsFile].filter(Boolean))].map(d=>d.hash));for(const d of le(b))p.has(d)||ue(w(b,d),{force:!0});return Object.assign(t,{rev:n,revision:n.revision,builtAt:n.builtAt,builtBy:n.builder.name,etag:a.etag,syncedAt:f(),error:"",behindDocs:0}),j(`[team] ${e.id}: revision ${n.revision} (${c.added} added, ${c.changed} changed, ${c.removed} removed; ${c.fetch.length} parts, ${c.bytes} bytes)`),{revision:n.revision,...c,fetch:c.fetch.length}}finally{t.updating=!1}}async function se(e){const t=B(e),i=I(e),a=`${N}#${process.pid}`,n=A(e,"lease.json"),b=await i.get(n).then(c=>c.status===200?JSON.parse(new TextDecoder().decode(c.bytes)):null).catch(()=>null);if(Ae(b,{holder:a,now:f()})==="held")throw new Error(`another builder (${b.holder}) is building until ${new Date(b.until).toISOString()}`);await i.put(n,JSON.stringify(we({holder:a,now:f()})),{contentType:"application/json"});const x=await i.get(n);if(x.status!==200||JSON.parse(new TextDecoder().decode(x.bytes)).holder!==a)throw new Error("another builder took the lease at the same moment — this one stands aside");try{const c=await i.get(A(e,"revision.json")),o=c.status===200?z(JSON.parse(new TextDecoder().decode(c.bytes))):null,F=M();let p=l.load(t.kbId);p||(p=De({id:t.kbId,name:e.name||e.bucket,now:f}));const d=`s3://${e.bucket}/${e.prefix||""}`;Array.isArray(p.sources)||(p.sources=[]);let u=p.sources.find(s=>s.kind==="bucket"&&s.path===d);u||(u={kind:"bucket",path:d,files:{},syncedAt:0},p.sources.push(u));const{objects:ie}=await i.list(e.prefix||""),P=ie.filter(s=>be(e,s.key)).map(s=>({path:s.key,size:s.size,mtime:s.mtime,etag:s.etag})),ne=Object.entries(u.files).map(([s,r])=>({path:s,id:r.id,size:r.size,etag:r.etag})),m=je({known:ne,listing:P}),g=[];for(const s of m.remove){Ie(p,s,{now:f});for(const[r,h]of Object.entries(u.files))h.id===s&&delete u.files[r]}const re=new Map(P.map(s=>[s.path,s]));for(const s of[...m.add,...m.change.map(r=>r.path)]){const r=re.get(s);try{const h=await i.get(s);if(h.status!==200)throw new Error(`not readable (${h.status})`);const y=ye(s);await F.addBytes(p,Buffer.from(h.bytes),{name:fe(s),source:{kind:"bucket",name:s},id:y,reach:"internal"}),u.files[s]={id:y,size:r.size,etag:r.etag,mtime:r.mtime}}catch(h){g.push({path:s,why:h.message})}}u.syncedAt=f(),u.lastSync={at:u.syncedAt,added:m.add.length,changed:m.change.length,removed:m.remove.length,same:m.same,skipped:g.length,skippedSample:g.slice(0,20)},await F.embedAll(p),l.save(p);const k=Be(p),U=ve(k),oe=new Set(o?[o.manifest,o.notes,...o.report?[o.report]:[],...o.docs.flatMap(s=>[s.chunksFile,s.vectorsFile].filter(Boolean))].map(s=>s.hash):[]),S=async(s,r,h)=>{const y=Fe(s),_=await G(y,E),V=`objects/${_}.${r}`;return oe.has(_)||await i.put(A(e,V),y,{contentType:h}),{file:V,hash:_,bytes:y.length}},C=await S(U.manifest,"json","application/json");if(o&&o.manifest.hash===C.hash)return Object.assign(t,{revision:o.revision,rev:o,builtAt:o.builtAt,builtBy:o.builder.name,syncedAt:f(),error:""}),{published:!1,revision:o.revision,...m,skipped:g};const ae=new Map(Object.entries(u.files).map(([s,r])=>[r.id,{key:s,...r}])),H=[];for(const s of U.docs){const r=k.manifest.docs.find(y=>y.id===s.id)||{},h=ae.get(s.id)||{key:r.source?.name||s.id,etag:"",size:0};H.push({id:s.id,key:h.key,etag:h.etag||"",size:h.size||0,title:r.title||h.key,type:r.type||"",pages:r.pages||0,chunks:s.count,chunksFile:await S(s.chunks,"jsonl","application/x-ndjson"),...s.vectors?{vectorsFile:await S(new Uint8Array(s.vectors.buffer,s.vectors.byteOffset,s.vectors.byteLength),"f32","application/octet-stream")}:{}})}const v=z({format:Oe,kind:"chap-kb-index",kb:{id:t.kbId,name:p.name},revision:(o?.revision||0)+1,builtAt:f(),builder:{name:N,version:Y},embed:k.vectors.dims?{model:k.vectors.model,recipe:k.vectors.recipe,dims:k.vectors.dims}:null,manifest:C,notes:await S(U.notes,"json","application/json"),report:await S(Te(p),"md","text/markdown"),docs:H});return await i.put(A(e,"revision.json"),JSON.stringify(v),{contentType:"application/json"}),Object.assign(t,{rev:v,revision:v.revision,builtAt:v.builtAt,builtBy:N,syncedAt:f(),checkedAt:f(),remoteRevision:v.revision,error:""}),j(`[team] ${e.id}: published revision ${v.revision} (${m.add.length} added, ${m.change.length} changed, ${m.remove.length} removed, ${g.length} skipped)`),{published:!0,revision:v.revision,...m,skipped:g}}finally{await i.del(n).catch(()=>{})}}function R(e){if($.has(e.id))return $.get(e.id);const t=B(e);t.role=e.role;const i=(e.role==="builder"?se(e):te(e)).then(a=>(t.error="",a)).catch(a=>(t.error=String(a?.message||a).slice(0,300),t.checkedAt=f(),j(`[team] ${e.id}: ${t.error}`),{error:t.error})).finally(()=>{$.delete(e.id),ee(e,t)});return $.set(e.id,i),i}const T=()=>(O()||[]).filter(e=>e?.kind==="bucket"&&e.enabled!==!1);return{run:R,runById:e=>{const t=T().find(i=>i.id===e);return t?R(t):Promise.resolve({error:`no bucket source ${e}`})},test:e=>I(e).test(),upload:(e,t,i)=>I(e).put(`${e.prefix||""}${String(t).replace(/^\/+/,"")}`,i),teamOf(e){const t=T().find(a=>K(a)===e);if(!t)return null;const i=B(t);return{role:t.role,provider:t.id,revision:i.revision,builtAt:i.builtAt||0,...i.builtBy?{builtBy:i.builtBy}:{},syncedAt:i.syncedAt,where:Se(t),freshness:$e({revision:i.revision,remoteRevision:i.remoteRevision,syncedAt:i.syncedAt,checkedAt:i.checkedAt,error:i.error,updating:$.has(t.id),behindDocs:i.behindDocs,now:f()})}},start(){for(const e of T()){if(D.has(e.id))continue;const t=setInterval(()=>{const a=T().find(n=>n.id===e.id);a&&R(a)},Math.max(1,e.pollMinutes||5)*6e4);t.unref?.(),D.set(e.id,t),setTimeout(()=>R(e),2e3).unref?.()}},stop(){for(const e of D.values())clearInterval(e);D.clear()},restart(){this.stop(),this.start()}}}export{_e as createBucketSync};
1
+ import{existsSync as de,mkdirSync as W,readFileSync as q,writeFileSync as le,readdirSync as ue,rmSync as pe,renameSync as fe}from"node:fs";import{join as A,basename as he}from"node:path";import me from"node:os";import{createHash as be}from"node:crypto";import{bucketClient as ye,indexKey as $,isDocumentKey as ve,bucketDocId as ge,splitIndexParts as ke,validateRevision as M,planReplicaSync as we,assembleReplica as Ae,makeLease as $e,leaseState as Se,replicaFreshness as Oe,bucketWhere as je,sha256Hex as G,KB_REVISION_FORMAT as De}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as Ie}from"@chatpanel/events/kb-folder-sync.js";import{createKb as xe,removeDocument as Ne,serializeKb as Be,deserializeKb as Re}from"@chatpanel/events/kb-index.js";import{graphReport as Te}from"@chatpanel/events/kb-graph.js";const Fe=new TextEncoder,ze=r=>typeof r=="string"?Fe.encode(r):r instanceof Uint8Array?r:new Uint8Array(r.buffer,r.byteOffset,r.byteLength),Q=(r,S)=>{const I=`${r}.tmp-${process.pid}`;le(I,S,{mode:384}),fe(I,r)},Me=(r={},S=me.hostname())=>typeof r.builderName=="string"&&r.builderName.trim()?r.builderName.trim().slice(0,60):`gateway-${be("sha256").update(String(S)).digest("hex").slice(0,8)}`;function Ce({store:r,kb:S,entries:I=()=>[],fetchFn:X,now:u=()=>Date.now(),log:x=()=>{},holder:Y=null,version:Z="",subtle:E=null}={}){const J=new Map,N=new Map,O=new Map,K=e=>e.kbId||e.id,L=e=>A(r.dirOf(e),"team.json"),ee=e=>A(r.dirOf(e),"parts"),B=e=>ye(e,{fetch:X,now:u,subtle:E});function R(e){if(J.has(e.id))return J.get(e.id);let t={kbId:K(e),role:e.role,revision:0,rev:null,syncedAt:0,checkedAt:0,error:"",updating:!1,remoteRevision:0,behindDocs:0,etag:""};try{const i=JSON.parse(q(L(K(e)),"utf8"));i?.provider===e.id&&(t={...t,...i.state,rev:i.state?.rev?M(i.state.rev):null,updating:!1})}catch{}return J.set(e.id,t),t}const te=(e,t)=>{try{W(r.dirOf(t.kbId),{recursive:!0,mode:448}),Q(L(t.kbId),JSON.stringify({provider:e.id,state:{...t,updating:!1}}))}catch(i){x(`[team] ${e.id}: state not saved — ${i.message}`)}};async function se(e){const t=R(e),i=B(e),c=await i.get($(e,"revision.json"),{etag:t.rev?t.etag:""});if(t.checkedAt=u(),c.status===304)return t.error="",t.remoteRevision=t.revision,t.behindDocs=0,{upToDate:!0};if(c.status===404)throw new Error("no index has been published to this bucket yet — a builder has not run");const a=M(JSON.parse(new TextDecoder().decode(c.bytes)));t.remoteRevision=a.revision;const h=ee(t.kbId);W(h,{recursive:!0,mode:448});const j=m=>de(A(h,m)),l=we({current:t.rev,next:a,have:j});if(l.upToDate)return t.etag=c.etag,t.error="",t.behindDocs=0,{upToDate:!0};t.behindDocs=l.added+l.changed+l.removed,t.updating=!0;try{for(const n of l.fetch){const v=await i.get($(e,n.file));if(v.status!==200)throw new Error(`part ${n.file} is missing from the bucket (${v.status})`);if(await G(v.bytes,E)!==n.hash)throw new Error(`part ${n.file} does not match its hash — not used`);Q(A(h,n.hash),v.bytes)}const m=Ae(a,n=>new Uint8Array(q(A(h,n))));m.manifest={...m.manifest,id:t.kbId};const d=Re(m);r.save(d);const z=new Set([a.manifest,a.notes,...a.report?[a.report]:[],...a.docs.flatMap(n=>[n.chunksFile,n.vectorsFile].filter(Boolean))].map(n=>n.hash));for(const n of ue(h))z.has(n)||pe(A(h,n),{force:!0});return Object.assign(t,{rev:a,revision:a.revision,builtAt:a.builtAt,builtBy:a.builder.name,etag:c.etag,syncedAt:u(),error:"",behindDocs:0}),x(`[team] ${e.id}: revision ${a.revision} (${l.added} added, ${l.changed} changed, ${l.removed} removed; ${l.fetch.length} parts, ${l.bytes} bytes)`),{revision:a.revision,...l,fetch:l.fetch.length}}finally{t.updating=!1}}async function ie(e){const t=R(e),i=B(e),c=Y||Me(e),a=`${c}#${process.pid}`,h=$(e,"lease.json"),j=await i.get(h).then(m=>m.status===200?JSON.parse(new TextDecoder().decode(m.bytes)):null).catch(()=>null);if(Se(j,{holder:a,now:u()})==="held")throw new Error(`another builder (${j.holder}) is building until ${new Date(j.until).toISOString()}`);await i.put(h,JSON.stringify($e({holder:a,now:u()})),{contentType:"application/json"});const l=await i.get(h);if(l.status!==200||JSON.parse(new TextDecoder().decode(l.bytes)).holder!==a)throw new Error("another builder took the lease at the same moment — this one stands aside");try{const m=await i.get($(e,"revision.json")),d=m.status===200?M(JSON.parse(new TextDecoder().decode(m.bytes))):null,z=S();let n=r.load(t.kbId);n||(n=xe({id:t.kbId,name:e.name||e.bucket,now:u}));const v=`s3://${e.bucket}/${e.prefix||""}`;Array.isArray(n.sources)||(n.sources=[]);let b=n.sources.find(s=>s.kind==="bucket"&&s.path===v);b||(b={kind:"bucket",path:v,files:{},syncedAt:0},n.sources.push(b));const{objects:ne}=await i.list(e.prefix||""),H=ne.filter(s=>ve(e,s.key)).map(s=>({path:s.key,size:s.size,mtime:s.mtime,etag:s.etag})),re=Object.entries(b.files).map(([s,o])=>({path:s,id:o.id,size:o.size,etag:o.etag})),f=Ie({known:re,listing:H}),k=[];for(const s of f.remove){Ne(n,s,{now:u});for(const[o,p]of Object.entries(b.files))p.id===s&&delete b.files[o]}const oe=new Map(H.map(s=>[s.path,s]));for(const s of[...f.add,...f.change.map(o=>o.path)]){const o=oe.get(s);try{const p=await i.get(s);if(p.status!==200)throw new Error(`not readable (${p.status})`);const y=ge(s);await z.addBytes(n,Buffer.from(p.bytes),{name:he(s),source:{kind:"bucket",name:s},id:y,reach:"internal"}),b.files[s]={id:y,size:o.size,etag:o.etag,mtime:o.mtime}}catch(p){k.push({path:s,why:p.message})}}b.syncedAt=u(),b.lastSync={at:b.syncedAt,added:f.add.length,changed:f.change.length,removed:f.remove.length,same:f.same,skipped:k.length,skippedSample:k.slice(0,20)},await z.embedAll(n),r.save(n);const w=Be(n),U=ke(w),ae=new Set(d?[d.manifest,d.notes,...d.report?[d.report]:[],...d.docs.flatMap(s=>[s.chunksFile,s.vectorsFile].filter(Boolean))].map(s=>s.hash):[]),D=async(s,o,p)=>{const y=ze(s),_=await G(y,E),V=`objects/${_}.${o}`;return ae.has(_)||await i.put($(e,V),y,{contentType:p}),{file:V,hash:_,bytes:y.length}},P=await D(U.manifest,"json","application/json");if(d&&d.manifest.hash===P.hash)return Object.assign(t,{revision:d.revision,rev:d,builtAt:d.builtAt,builtBy:d.builder.name,syncedAt:u(),error:""}),{published:!1,revision:d.revision,...f,skipped:k};const ce=new Map(Object.entries(b.files).map(([s,o])=>[o.id,{key:s,...o}])),C=[];for(const s of U.docs){const o=w.manifest.docs.find(y=>y.id===s.id)||{},p=ce.get(s.id)||{key:o.source?.name||s.id,etag:"",size:0};C.push({id:s.id,key:p.key,etag:p.etag||"",size:p.size||0,title:o.title||p.key,type:o.type||"",pages:o.pages||0,chunks:s.count,chunksFile:await D(s.chunks,"jsonl","application/x-ndjson"),...s.vectors?{vectorsFile:await D(new Uint8Array(s.vectors.buffer,s.vectors.byteOffset,s.vectors.byteLength),"f32","application/octet-stream")}:{}})}const g=M({format:De,kind:"chap-kb-index",kb:{id:t.kbId,name:n.name},revision:(d?.revision||0)+1,builtAt:u(),builder:{name:c,version:Z},embed:w.vectors.dims?{model:w.vectors.model,recipe:w.vectors.recipe,dims:w.vectors.dims}:null,manifest:P,notes:await D(U.notes,"json","application/json"),report:await D(Te(n),"md","text/markdown"),docs:C});return await i.put($(e,"revision.json"),JSON.stringify(g),{contentType:"application/json"}),Object.assign(t,{rev:g,revision:g.revision,builtAt:g.builtAt,builtBy:c,syncedAt:u(),checkedAt:u(),remoteRevision:g.revision,error:""}),x(`[team] ${e.id}: published revision ${g.revision} (${f.add.length} added, ${f.change.length} changed, ${f.remove.length} removed, ${k.length} skipped)`),{published:!0,revision:g.revision,...f,skipped:k}}finally{await i.del(h).catch(()=>{})}}function T(e){if(O.has(e.id))return O.get(e.id);const t=R(e);t.role=e.role;const i=(e.role==="builder"?ie(e):se(e)).then(c=>(t.error="",c)).catch(c=>(t.error=String(c?.message||c).slice(0,300),t.checkedAt=u(),x(`[team] ${e.id}: ${t.error}`),{error:t.error})).finally(()=>{O.delete(e.id),te(e,t)});return O.set(e.id,i),i}const F=()=>(I()||[]).filter(e=>e?.kind==="bucket"&&e.enabled!==!1);return{run:T,runById:e=>{const t=F().find(i=>i.id===e);return t?T(t):Promise.resolve({error:`no bucket source ${e}`})},test:e=>B(e).test(),upload:(e,t,i)=>B(e).put(`${e.prefix||""}${String(t).replace(/^\/+/,"")}`,i),teamOf(e){const t=F().find(c=>K(c)===e);if(!t)return null;const i=R(t);return{role:t.role,provider:t.id,revision:i.revision,builtAt:i.builtAt||0,...i.builtBy?{builtBy:i.builtBy}:{},syncedAt:i.syncedAt,where:je(t),freshness:Oe({revision:i.revision,remoteRevision:i.remoteRevision,syncedAt:i.syncedAt,checkedAt:i.checkedAt,error:i.error,updating:O.has(t.id),behindDocs:i.behindDocs,now:u()})}},start(){for(const e of F()){if(N.has(e.id))continue;const t=setInterval(()=>{const c=F().find(a=>a.id===e.id);c&&T(c)},Math.max(1,e.pollMinutes||5)*6e4);t.unref?.(),N.set(e.id,t),setTimeout(()=>T(e),2e3).unref?.()}},stop(){for(const e of N.values())clearInterval(e);N.clear()},restart(){this.stop(),this.start()}}}export{Me as builderName,Ce as createBucketSync};
package/src/kb.js CHANGED
@@ -1,3 +1,3 @@
1
- import{readFileSync as de,statSync as q,readdirSync as Ge,realpathSync as le}from"node:fs";import{join as Le,basename as I,extname as ue,resolve as je,dirname as ze}from"node:path";import De from"node:os";import{createKb as fe,addDocument as ee,removeDocument as H,addNote as Fe,setNoteStatus as Be,searchKb as Ne,embedMissing as Ce,kbNeedsVectors as Ie,kbStatus as Re,readPage as We,chunkById as Ue,refreshKb as V,setKbAccess as Xe,kbMayUse as te}from"@chatpanel/events/kb-index.js";import{kbResearch as He}from"@chatpanel/events/kb-research.js";import{neighbours as Ve,pathBetween as Ye,resolveNode as pe,graphReport as Je}from"@chatpanel/events/kb-graph.js";import{outlineOf as he}from"@chatpanel/events/kb-chunk.js";import{routeKb as Qe,validateKbCreate as Ze,validateKbAdd as qe,validateKbSearch as et,validateKbResearch as tt,validateKbGraph as nt,validateKbNote as st,validateKbNoteStatus as rt,validateKbAccess as at,validateKbSync as ot,validateKbReveal as it,kbGraphLimit as ct,KB_LOCAL_ACTIONS as dt}from"@chatpanel/events/kb-capability.js";import{communities as lt,topEntities as ge}from"@chatpanel/events/kb-graph.js";import{kbCard as ut,pageStrip as ft}from"@chatpanel/events/kb-view.js";import{planFolderSync as pt,folderDocId as ht,folderSource as gt,knownFiles as mt}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as bt,markdownLinks as kt,resolveLinks as yt,visibleTextHash as wt,decodeText as vt}from"@chatpanel/events/kb-html.js";import{secretReason as me,SKIP_DIR_NAMES as St,sniffType as $t,checkAttachablePath as Ot}from"@chatpanel/events/attached-paths.js";import{paginateText as Y,MAX_DOCUMENT_BYTES as ne}from"./extract-capability.js";import{defaultEmbeddedModel as Tt}from"./embedded-models.js";import{primaryProvider as _t}from"./capability-config.js";function P(m,A){const $=Re(m);return A?$:{...$,documents:$.documents.map(K=>{const{path:j,...L}=K.source||{};return{...K,source:L}})}}const R=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),be=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),xt=new Set([".html",".htm",".xhtml"]),Et=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(m,A,$,K={})=>({status:m,body:{error:{type:A,message:$},...K}}),v=m=>({status:200,body:m});function Pt(m,{limit:A=60}={}){V(m);const $=m.graph||{nodes:[],edges:[]},K=new Set(ge($,{limit:A}).map(b=>b.id)),j=new Map(ge($,{limit:A}).map(b=>[b.id,b.weight])),L=$.nodes.filter(b=>b.kind==="entity"?K.has(b.id):b.kind!=="chunk").slice(0,A*6),z=new Set(L.map(b=>b.id)),D=$.edges.filter(b=>z.has(b.from)&&z.has(b.to)).slice(0,A*20),w=lt($).map(b=>({...b,members:b.members.filter(F=>z.has(F))})).filter(b=>b.members.length>=2).slice(0,24);return{nodes:L.map(b=>({id:b.id,kind:b.kind,label:b.label,count:b.count,...b.doc?{doc:b.doc}:{},...j.has(b.id)?{weight:j.get(b.id)}:{}})),edges:D,communities:w,total:{nodes:$.nodes.length,edges:$.edges.length}}}function Xt({store:m,extract:A=null,embedded:$=null,cfg:K={},rerank:j=null,read:L=null,completer:z=null,log:D=()=>{},now:w=()=>Date.now(),home:b=De.homedir(),team:F=()=>null,remoteCards:se=null,reveal:re=null,confined:ke=()=>!1}={}){const N=()=>{const e=_t(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Tt("embed")||""},J=(e="passage")=>{const t=N();if(!$||!t)return null;const c=$.health("embed",t);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?($.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await $.embed(t,l,{kind:e})).vectors},ye=typeof j=="function"?j:null,Q=new Set;function ae(e){!e||Q.has(e.id)||e.embed==="off"||!J("passage")||Ie(e)&&(Q.add(e.id),B(e).then(t=>{t&&(m.save(e),D(`[kb] ${e.id}: ${t} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>Q.delete(e.id)))}async function B(e,{late:t=()=>!1}={}){const c=J("passage");if(!c)return 0;try{return await Ce(e,c,{model:N(),late:t})}catch(l){return D(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function we(e,t,c=""){const l=$t(e,t);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=vt(e);if(/\.x?html?$/i.test(t)||/html/i.test(l.label||"")){const s=bt(r);return{type:"html",pages:Y(s.markdown).map((S,n)=>({page:n+1,text:S})),title:s.title,links:s.links,markdown:!0}}const p=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
2
- `).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(t);return{type:l.label||"text",pages:Y(r).map((s,S)=>({page:S+1,text:s})),title:p?p[1].trim():"",links:k?kt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),a=await o.open(e,{name:t,hint:c}),u=[];for(let r=1;r<=a.pages;r+=1){let p="";try{p=String((await o.page(a.hash,r)).text||"")}catch(k){D(`[kb] ${t} p.${r}: ${k.message}`)}u.push({page:r,text:p,...a.labels?.[r-1]?{label:a.labels[r-1]}:{}})}return{type:a.type,pages:u,title:a.title||"",hash:a.hash,scanned:!!a.scanned,markdown:!!a.markdown,labels:a.labels||[]}}async function W(e,t,{name:c,hint:l="",title:o="",source:a={},reach:u="",id:r="",root:p="",dedupe:k=!1}){const s=await we(t,c,l),S=wt(s.pages.map(d=>d.text).join(`
3
- `));if(k&&S){const d=e.docs.find(h=>h.textHash===S&&h.id!==r);if(d)return{duplicateOf:d}}const n=a.path&&s.links?.length?yt(a.path,s.links,{root:p||ze(a.path)}):[],i=ee(e,{id:r,title:o||s.title||I(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:w,links:n,textHash:S,markdownHeadings:!!s.markdown});return{id:i.doc.id,title:i.doc.title,pages:i.doc.pages,chunks:i.doc.chunks,replaced:i.replaced,...s.scanned?{scanned:!0}:{}}}function ve(e,t){const c=ue(e).toLowerCase();return!be.has(c)&&!Et.has(c)?!1:t?.length?t.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function oe(e,{recursive:t=!0,include:c=null}={}){const l=Ot(e,{home:b,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=le(je(e.replace(/^~(?=$|\/)/,b))),a=[],u=[];let r=0;const p=(S,n)=>{if(a.length>=R.files)return u.push({path:n,why:`stopped at ${R.files} files`}),!1;if(me(S))return u.push({path:n,why:"withheld (a credential store)"}),!0;let i;try{i=q(S)}catch{return!0}const d=ue(S).toLowerCase(),h=be.has(d)||xt.has(d)?ne:R.textBytes;return i.size>h?(u.push({path:n,why:`too large (${Math.round(i.size/1048576)} MB)`}),!0):r+i.size>R.bytes?(u.push({path:n,why:"stopped: the folder is past the size limit"}),!1):(r+=i.size,a.push({full:S,rel:n,size:i.size,mtime:Math.floor(i.mtimeMs)}),!0)};if(!q(o).isDirectory())return p(o,I(o)),{root:o,files:a,skipped:u,single:!0};const s=(S,n,i)=>{if(i>R.depth)return!0;let d=[];try{d=Ge(S,{withFileTypes:!0}).sort((h,y)=>h.name.localeCompare(y.name))}catch{return!0}for(const h of d){const y=h.name;if(y.startsWith(".")&&h.isDirectory())continue;const T=Le(S,y),f=n?`${n}/${y}`:y;if(h.isDirectory()){if(St.has(y)||!t)continue;try{if(!le(T).startsWith(o)){u.push({path:f,why:"links outside the folder"});continue}}catch{continue}if(!s(T,f,i+1))return!1;continue}if(!(!h.isFile()&&!h.isSymbolicLink())){if(me(T)){u.push({path:f,why:"withheld (a credential store)"});continue}if(ve(y,c)&&!p(T,f))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function Se(e,{path:t,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=oe(t,{recursive:c,include:l}),p=[];for(const k of a)try{const s=await W(e,de(k.full),{name:I(k.full),title:p.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});p.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:p,skipped:u}}async function $e(e,{path:t,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=oe(t,{recursive:!0,include:c}),p=gt(e,a,{include:c});if(l){for(const f of Object.values(p.files))f?.id&&H(e,f.id,{now:w});p.files={}}const k=new Set(u.map(f=>f.full));for(const[f,_]of Object.entries(p.files))_?.dupOf&&!k.has(_.dupOf)&&delete p.files[f];const s=pt({known:mt(p),listing:u.map(f=>({path:f.full,size:f.size,mtime:f.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const S=new Map(u.map(f=>[f.full,f])),n=[];for(const f of s.remove){H(e,f,{now:w});for(const[_,x]of Object.entries(p.files))x.id===f&&(delete p.files[_],n.push(_.startsWith(`${a}/`)?_.slice(a.length+1):_))}const i=[],d=[],h=[],y=f=>String(f||"").startsWith(`${a}/`)?f.slice(a.length+1):f,T=async(f,_)=>{if(o?.cancel)return;await new Promise(E=>setImmediate(E));const x=S.get(f),G=ht(f);try{const E=await W(e,de(f),{name:I(f),source:{kind:"file",path:f},reach:"internal",id:G,root:a,dedupe:!0});E.duplicateOf?(e.docs.some(C=>C.id===G)&&H(e,G,{now:w}),p.files[f]={id:G,size:x.size,mtime:x.mtime,dupOf:E.duplicateOf.source?.path||E.duplicateOf.id},h.push({path:x.rel,of:y(E.duplicateOf.source?.path||E.duplicateOf.title)})):(p.files[f]={id:G,size:x.size,mtime:x.mtime},_.push({...E,path:x.rel}))}catch(E){r.push({path:x.rel,why:E.message})}o&&(o.done+=1)};for(const f of s.add)await T(f,i);for(const f of s.change)await T(f.path,d);return p.syncedAt=w(),p.lastSync={at:p.syncedAt,added:i.length,changed:d.length,removed:n.length,same:s.same,duplicates:h.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:h.slice(0,20)},{root:a,added:i,changed:d,removed:n,same:s.same,duplicates:h,skipped:r}}async function Oe(e,{url:t,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().read({url:t,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=Y(o).map((r,p)=>({page:p+1,text:r})),u=ee(e,{title:c||l.body.title||t,pages:a,source:{kind:"url",url:l.body.url||t,name:l.body.title||""},type:"html",reach:"web",now:w});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function Te(e,t,{admin:c=!1}={}){const l=w();let o=[],a=[];if(t.kind==="bytes"){const r=Buffer.from(t.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>ne)return g(413,"too_large",`kb: ${r.length} bytes is over the ${ne}-byte limit`);try{o.push(await W(e,r,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(p){return U(p)}}else if(t.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:o,skipped:a}=await Se(e,t))}catch(r){return U(r)}}else if(t.kind==="url")try{o.push(await Oe(e,t))}catch(r){return U(r)}else if(t.kind==="text"){const r=Y(t.text).map((k,s)=>({page:s+1,text:k})),p=ee(e,{title:t.title||t.name,pages:r,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:w});o.push({id:p.doc.id,title:p.doc.title,pages:p.doc.pages,chunks:p.doc.chunks,replaced:p.replaced})}const u=o.length?await B(e):0;return m.save(e),v({added:o,skipped:a,embedded:u,kb:P(e,c),ms:w()-l})}function U(e){const t=e?.code||"";return t==="refused"?g(403,"refused",`kb: ${e.message}`):t==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):t==="too_large"?g(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?g(502,"read_failed",`kb: ${e.message}`):t==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const _e=e=>e.vectors?.model&&e.vectors.model!==N()?null:J("query"),Z=(e,t)=>Ne(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],...t.filters?{filters:t.filters}:{},embed:_e(e),rerank:t.rerank===!1?null:ye,now:w}),xe=(e,t)=>e.docs.find(c=>c.id===t)?.title||t,ie=(e,t)=>{const c=Ue(e,t);if(!c)return null;const l=c.kind==="note"?"Note":xe(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Ee(e,t){V(e);const c=pe(e.graph,t.node);if(!c)return v({node:null,neighbours:[],message:`no node named "${t.node}"`});const l=a=>{const u=e.graph.nodes.find(r=>r.id===a);return{id:a,label:u?.label||a.replace(/^chunk:/,"passage "),kind:u?.kind||"chunk"}},o={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Ve(e.graph,c.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const a=pe(e.graph,t.to);o.to=t.to,o.path=a?(Ye(e.graph,c.id,a.id)||[]).map(l):null,a&&!o.path.length&&(o.path=null)}return v(o)}async function Pe(e,t,{admin:c=!1}={}){if(t.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=t.model&&typeof z=="function"?z(t.model):null,o=P(e,c),a=await He(t.question,{search:(u,r)=>Z(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||t.docs||null}),outline:async u=>u?he(e.chunks,{doc:u}):e.outline,read:async u=>ie(e,u),complete:l,kbName:e.name,docs:o.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:w});return v({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function ce(e,t){const c=P(e,t),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=t?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return ut({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:F(e.id),now:w()})}async function Ae({method:e="GET",pathname:t="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=Qe(t);if(!r)return g(404,"not_found",`no route ${t}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(dt.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 p={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=n=>{try{return{value:n()}}catch(i){return{res:g(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const n=[];for(const{manifest:d}of m.list()){if(!te({access:d.access},p))continue;const h=m.load(d.id);h&&n.push(ce(h,o))}const i=o&&typeof se=="function"?await se({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return v({cards:n,...i.length?{remote:i}:{}})}if(e==="GET")return v({kbs:m.list().filter(({manifest:n})=>te({access:n.access},p)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=k(()=>Ze(l||{}));if(n.res)return n.res;const i=n.value;if(i.id&&m.load(i.id))return v({kb:P(m.load(i.id),o),existed:!0});const d=fe({id:i.id,name:i.name,embed:i.embed,now:w});return m.save(d),{status:201,body:{kb:P(d,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(F(r.id)?.role==="replica")return X(r.id);const n=k(()=>ot(l||{}));if(n.res)return n.res;const i=n.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let h=m.load(r.id);const y=!h;h||(h=fe({id:r.id,name:i.name||I(String(i.path).replace(/[\\/]+$/,""))||r.id,now:w}),m.save(h));const T=w(),f={done:0,total:0},_=(async()=>{const O=await $e(h,i,{progress:f});if(f.cancel)return{cancelled:!0};const Ke=O.added.length+O.changed.length+O.removed.length,Me=O.added.length||O.changed.length?await B(h):0;return(Ke||y)&&m.save(h),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Me,made:y,kb:P(h,o),ms:w()-T}})();M.set(r.id,{progress:f,base:h}),_.catch(O=>D(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const x=i.waitMs??5e3;if(x===0)return{status:202,body:{running:!0,progress:{...f},made:y,kb:P(h,o)}};let G=null;const E=new Promise(O=>{G=setTimeout(()=>O(null),x)});let C;try{C=await Promise.race([_,E])}catch(O){return clearTimeout(G),U(O)}return clearTimeout(G),C?v(C):{status:202,body:{running:!0,progress:{...f},made:y,kb:P(h,o)}}}const s=m.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const S=F(s.id)?.role==="replica";if(!te(s,p))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${p.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||ae(s);const n=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return v({kb:{...n,coverage:n.chunks?Math.round(n.vectors/n.chunks*100):0,bytes:m.sizeOf(s.id),dir:o?m.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:h})=>({done:d,total:h}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const n=M.get(s.id);return n&&(n.progress.cancel=!0),m.remove(s.id),v({ok:!0,...n?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(S&&(e==="POST"||e==="DELETE"))return X(s.id);if(e==="POST"&&!r.rest){const n=k(()=>qe(l||{}));return n.res?n.res:Te(s,n.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?H(s,r.rest,{now:w})?(m.save(s),v({ok:!0,kb:P(s,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const n=Number(c.get("page"))||1,i=We(s,r.rest,n);return i?v(i):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return v({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const n=ie(s,r.rest);return n?v(n):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){V(s);const n=c.get("doc");return v({outline:n?he(s.chunks,{doc:n}):s.outline})}break}case"search":{if(e==="POST"){const n=k(()=>et(l||{}));if(n.res)return n.res;const i=w(),d=await Z(s,n.value);return ae(s),v({...d,ms:w()-i})}break}case"research":{if(e==="POST"){const n=k(()=>tt(l||{}));return n.res?n.res:Pe(s,n.value,{admin:o})}break}case"graph":{if(e==="GET")return v(Pt(s,{limit:ct(c.get("limit"))}));if(e==="POST"){const n=k(()=>nt(l||{}));return n.res?n.res:Ee(s,n.value)}break}case"report":{if(e==="GET")return V(s),{status:200,text:Je(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return v({notes:s.notes});if(S&&e==="POST")return X(s.id);if(e==="POST"&&!r.rest){const n=k(()=>st(l||{}));if(n.res)return n.res;const i=n.value,d=i.status==="accepted"&&o?"accepted":"proposed",h=Fe(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:w});return await B(s),m.save(s),{status:201,body:{note:h}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=k(()=>rt(l||{}));if(n.res)return n.res;const i=n.value,d=Be(s,r.rest,i.status,{now:w});return d?(m.save(s),v({note:d,removed:i.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return v({access:s.access});if(S&&e==="POST")return X(s.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=k(()=>at(l||{}));if(n.res)return n.res;const i=Xe(s,n.value,{now:w});return m.save(s),v({access:i})}break}case"pages":{if(e!=="GET")break;const n=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===n);return i?v(ft(s.chunks,i)):g(404,"not_found",`kb: no document ${n||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(ke())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(F(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 re!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const n=k(()=>it(l||{}));if(n.res)return n.res;const i=n.value;let d="",h="file";if(i.doc){const y=s.docs.find(T=>T.id===i.doc);if(!y)return g(404,"not_found",`kb: no document ${i.doc}`);d=y.source?.path||"",d||(d=m.dirOf(s.id),h="index")}else if(i.source!=null){const y=(s.sources||[])[i.source];if(!y?.path)return g(404,"not_found",`kb: no kept folder ${i.source}`);d=y.path,h="folder"}else{const y=(s.sources||[]).find(T=>T.path);d=y?.path||m.dirOf(s.id),h=y?"folder":"index"}try{q(d)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await re(d,{folder:h!=="file"})}catch(y){return g(502,"reveal_failed",`kb: the file manager did not open — ${y.message}`)}return v({ok:!0,revealed:h})}case"embed":{if(e==="POST"){const n=N(),i=$&&n?$.health("embed",n):{state:"off"},d=await B(s);return d&&m.save(s),v({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||n,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}function X(e){return g(409,"read_only",`kb: ${e} is a team base copied from its bucket — add or remove documents in the bucket; the builder publishes the next index`)}return{handle:Ae,store:m,embedModel:N,cardOf:ce,addBytes:(e,t,c)=>W(e,t,c),embedAll:e=>B(e),searchBase:(e,t)=>Z(e,t)}}export{R as KB_WALK_LIMITS,Xt as createKbService,P as kbStatusFor,Pt as wholeGraph};
1
+ import{readFileSync as le,statSync as ee,readdirSync as Le,realpathSync as ue}from"node:fs";import{join as je,basename as C,extname as fe,resolve as ze,dirname as Be}from"node:path";import De from"node:os";import{createKb as pe,addDocument as te,removeDocument as X,addNote as Fe,setNoteStatus as Ne,searchKb as Ce,embedMissing as Ie,kbNeedsVectors as Re,kbStatus as We,readPage as Ue,chunkById as Xe,refreshKb as H,setKbAccess as He,kbMayUse as ne}from"@chatpanel/events/kb-index.js";import{kbResearch as Ve}from"@chatpanel/events/kb-research.js";import{neighbours as Ye,pathBetween as Je,resolveNode as he,graphReport as Qe}from"@chatpanel/events/kb-graph.js";import{outlineOf as ge}from"@chatpanel/events/kb-chunk.js";import{routeKb as Ze,validateKbCreate as qe,validateKbAdd as et,validateKbSearch as tt,validateKbResearch as nt,validateKbGraph as st,validateKbNote as rt,validateKbNoteStatus as at,validateKbAccess as ot,validateKbSync as it,validateKbReveal as ct,kbGraphLimit as dt,KB_LOCAL_ACTIONS as lt}from"@chatpanel/events/kb-capability.js";import{communities as ut,topEntities as me}from"@chatpanel/events/kb-graph.js";import{kbCard as ft,pageStrip as pt}from"@chatpanel/events/kb-view.js";import{planFolderSync as ht,folderDocId as gt,folderSource as mt,knownFiles as bt}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as kt,markdownLinks as yt,resolveLinks as wt,visibleTextHash as vt,decodeText as St}from"@chatpanel/events/kb-html.js";import{secretReason as be,SKIP_DIR_NAMES as $t,sniffType as Ot,checkAttachablePath as Tt}from"@chatpanel/events/attached-paths.js";import{paginateText as V,MAX_DOCUMENT_BYTES as se}from"./extract-capability.js";import{defaultEmbeddedModel as xt}from"./embedded-models.js";import{primaryProvider as _t}from"./capability-config.js";function P(m,A){const S=We(m);return A?S:{...S,documents:S.documents.map(K=>{const{path:z,...L}=K.source||{};return{...K,source:L}})}}const I=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),ke=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Et=new Set([".html",".htm",".xhtml"]),Pt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),h=(m,A,S,K={})=>({status:m,body:{error:{type:A,message:S},...K}}),w=m=>({status:200,body:m});function At(m,{limit:A=60}={}){H(m);const S=m.graph||{nodes:[],edges:[]},K=new Set(me(S,{limit:A}).map(b=>b.id)),z=new Map(me(S,{limit:A}).map(b=>[b.id,b.weight])),L=S.nodes.filter(b=>b.kind==="entity"?K.has(b.id):b.kind!=="chunk").slice(0,A*6),B=new Set(L.map(b=>b.id)),D=S.edges.filter(b=>B.has(b.from)&&B.has(b.to)).slice(0,A*20),y=ut(S).map(b=>({...b,members:b.members.filter(j=>B.has(j))})).filter(b=>b.members.length>=2).slice(0,24);return{nodes:L.map(b=>({id:b.id,kind:b.kind,label:b.label,count:b.count,...b.doc?{doc:b.doc}:{},...z.has(b.id)?{weight:z.get(b.id)}:{}})),edges:D,communities:y,total:{nodes:S.nodes.length,edges:S.edges.length}}}function Ht({store:m,extract:A=null,embedded:S=null,cfg:K={},rerank:z=null,read:L=null,completer:B=null,log:D=()=>{},now:y=()=>Date.now(),home:b=De.homedir(),team:j=()=>null,remoteCards:re=null,reveal:ae=null,confined:ye=()=>!1}={}){const N=()=>{const e=_t(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||xt("embed")||""},Y=(e="passage")=>{const n=N();if(!S||!n)return null;const c=S.health("embed",n);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?(S.embed(n,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await S.embed(n,l,{kind:e})).vectors},we=typeof z=="function"?z:null,J=new Set;function oe(e){!e||J.has(e.id)||e.embed==="off"||!Y("passage")||Re(e)&&(J.add(e.id),F(e).then(n=>{n&&(m.save(e),D(`[kb] ${e.id}: ${n} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>J.delete(e.id)))}async function F(e,{late:n=()=>!1}={}){const c=Y("passage");if(!c)return 0;try{return await Ie(e,c,{model:N(),late:n})}catch(l){return D(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function ve(e,n,c=""){const l=Ot(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=St(e);if(/\.x?html?$/i.test(n)||/html/i.test(l.label||"")){const s=kt(r);return{type:"html",pages:V(s.markdown).map(($,T)=>({page:T+1,text:$})),title:s.title,links:s.links,markdown:!0}}const p=/^\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:V(r).map((s,$)=>({page:$+1,text:s})),title:p?p[1].trim():"",links:k?yt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),a=await o.open(e,{name:n,hint:c}),u=[];for(let r=1;r<=a.pages;r+=1){let p="";try{p=String((await o.page(a.hash,r)).text||"")}catch(k){D(`[kb] ${n} p.${r}: ${k.message}`)}u.push({page:r,text:p,...a.labels?.[r-1]?{label:a.labels[r-1]}:{}})}return{type:a.type,pages:u,title:a.title||"",hash:a.hash,scanned:!!a.scanned,markdown:!!a.markdown,labels:a.labels||[]}}async function R(e,n,{name:c,hint:l="",title:o="",source:a={},reach:u="",id:r="",root:p="",dedupe:k=!1}){const s=await ve(n,c,l),$=vt(s.pages.map(i=>i.text).join(`
3
+ `));if(k&&$){const i=e.docs.find(d=>d.textHash===$&&d.id!==r);if(i)return{duplicateOf:i}}const T=a.path&&s.links?.length?wt(a.path,s.links,{root:p||Be(a.path)}):[],t=te(e,{id:r,title:o||s.title||C(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:y,links:T,textHash:$,markdownHeadings:!!s.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...s.scanned?{scanned:!0}:{}}}function Se(e,n){const c=fe(e).toLowerCase();return!ke.has(c)&&!Pt.has(c)?!1:n?.length?n.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function ie(e,{recursive:n=!0,include:c=null}={}){const l=Tt(e,{home:b,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=ue(ze(e.replace(/^~(?=$|\/)/,b))),a=[],u=[];let r=0;const p=($,T)=>{if(a.length>=I.files)return u.push({path:T,why:`stopped at ${I.files} files`}),!1;if(be($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ee($)}catch{return!0}const i=fe($).toLowerCase(),d=ke.has(i)||Et.has(i)?se:I.textBytes;return t.size>d?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>I.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,a.push({full:$,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ee(o).isDirectory())return p(o,C(o)),{root:o,files:a,skipped:u,single:!0};const s=($,T,t)=>{if(t>I.depth)return!0;let i=[];try{i=Le($,{withFileTypes:!0}).sort((d,g)=>d.name.localeCompare(g.name))}catch{return!0}for(const d of i){const g=d.name;if(g.startsWith(".")&&d.isDirectory())continue;const v=je($,g),f=T?`${T}/${g}`:g;if(d.isDirectory()){if($t.has(g)||!n)continue;try{if(!ue(v).startsWith(o)){u.push({path:f,why:"links outside the folder"});continue}}catch{continue}if(!s(v,f,t+1))return!1;continue}if(!(!d.isFile()&&!d.isSymbolicLink())){if(be(v)){u.push({path:f,why:"withheld (a credential store)"});continue}if(Se(g,c)&&!p(v,f))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function $e(e,{path:n,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=ie(n,{recursive:c,include:l}),p=[];for(const k of a)try{const s=await R(e,le(k.full),{name:C(k.full),title:p.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});p.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:p,skipped:u}}async function Oe(e,{path:n,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=ie(n,{recursive:!0,include:c}),p=mt(e,a,{include:c});if(l){for(const f of Object.values(p.files))f?.id&&X(e,f.id,{now:y});p.files={}}const k=new Set(u.map(f=>f.full));for(const[f,x]of Object.entries(p.files))x?.dupOf&&!k.has(x.dupOf)&&delete p.files[f];const s=ht({known:bt(p),listing:u.map(f=>({path:f.full,size:f.size,mtime:f.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const $=new Map(u.map(f=>[f.full,f])),T=[];for(const f of s.remove){X(e,f,{now:y});for(const[x,E]of Object.entries(p.files))E.id===f&&(delete p.files[x],T.push(x.startsWith(`${a}/`)?x.slice(a.length+1):x))}const t=[],i=[],d=[],g=f=>String(f||"").startsWith(`${a}/`)?f.slice(a.length+1):f,v=async(f,x)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(f),G=gt(f);try{const _=await R(e,le(f),{name:C(f),source:{kind:"file",path:f},reach:"internal",id:G,root:a,dedupe:!0});_.duplicateOf?(e.docs.some(Z=>Z.id===G)&&X(e,G,{now:y}),p.files[f]={id:G,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},d.push({path:E.rel,of:g(_.duplicateOf.source?.path||_.duplicateOf.title)})):(p.files[f]={id:G,size:E.size,mtime:E.mtime},x.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const f of s.add)await v(f,t);for(const f of s.change)await v(f.path,i);return p.syncedAt=y(),p.lastSync={at:p.syncedAt,added:t.length,changed:i.length,removed:T.length,same:s.same,duplicates:d.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:d.slice(0,20)},{root:a,added:t,changed:i,removed:T,same:s.same,duplicates:d,skipped:r}}async function Te(e,{url:n,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().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 o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=V(o).map((r,p)=>({page:p+1,text:r})),u=te(e,{title:c||l.body.title||n,pages:a,source:{kind:"url",url:l.body.url||n,name:l.body.title||""},type:"html",reach:"web",now:y});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function xe(e,n,{admin:c=!1}={}){const l=y();let o=[],a=[];if(n.kind==="bytes"){const r=Buffer.from(n.data,"base64");if(!r.length)return h(400,"invalid_request","kb: data decoded to nothing");if(r.length>se)return h(413,"too_large",`kb: ${r.length} bytes is over the ${se}-byte limit`);try{o.push(await R(e,r,{name:n.name,hint:n.type||"",title:n.title,reach:n.reach}))}catch(p){return W(p)}}else if(n.kind==="path"){if(!c)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:o,skipped:a}=await $e(e,n))}catch(r){return W(r)}}else if(n.kind==="url")try{o.push(await Te(e,n))}catch(r){return W(r)}else if(n.kind==="text"){const r=V(n.text).map((k,s)=>({page:s+1,text:k})),p=te(e,{title:n.title||n.name,pages:r,source:{kind:"text",name:n.name},type:"text",reach:n.reach,now:y});o.push({id:p.doc.id,title:p.doc.title,pages:p.doc.pages,chunks:p.doc.chunks,replaced:p.replaced})}const u=o.length?await F(e):0;return m.save(e),w({added:o,skipped:a,embedded:u,kb:P(e,c),ms:y()-l})}function W(e){const n=e?.code||"";return n==="refused"?h(403,"refused",`kb: ${e.message}`):n==="unsupported"?h(415,"unsupported",`kb: ${e.message}`):n==="too_large"?h(413,"too_large",`kb: ${e.message}`):n==="read_failed"||n==="empty"?h(502,"read_failed",`kb: ${e.message}`):n==="timeout"?h(504,"extract_timeout","kb: the document took too long to parse"):h(500,"kb_error",`kb: ${e?.message||e}`)}const _e=e=>e.vectors?.model&&e.vectors.model!==N()?null:Y("query"),Q=(e,n)=>Ce(e,n.query,{limit:n.limit,hops:n.hops,docs:n.docs||null,queries:n.queries||[],...n.filters?{filters:n.filters}:{},embed:_e(e),rerank:n.rerank===!1?null:we,now:y}),Ee=(e,n)=>e.docs.find(c=>c.id===n)?.title||n,ce=(e,n)=>{const c=Xe(e,n);if(!c)return null;const l=c.kind==="note"?"Note":Ee(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Pe(e,n){H(e);const c=he(e.graph,n.node);if(!c)return w({node:null,neighbours:[],message:`no node named "${n.node}"`});const l=a=>{const u=e.graph.nodes.find(r=>r.id===a);return{id:a,label:u?.label||a.replace(/^chunk:/,"passage "),kind:u?.kind||"chunk"}},o={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Ye(e.graph,c.id,{hops:n.hops,kinds:n.kinds||null,limit:n.limit})};if(n.to){const a=he(e.graph,n.to);o.to=n.to,o.path=a?(Je(e.graph,c.id,a.id)||[]).map(l):null,a&&!o.path.length&&(o.path=null)}return w(o)}async function Ae(e,n,{admin:c=!1}={}){if(n.model&&!c)return h(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=n.model&&typeof B=="function"?B(n.model):null,o=P(e,c),a=await Ve(n.question,{search:(u,r)=>Q(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||n.docs||null}),outline:async u=>u?ge(e.chunks,{doc:u}):e.outline,read:async u=>ce(e,u),complete:l,kbName:e.name,docs:o.documents,previous:n.previous||null,answer:n.answer||"",ask:n.ask!==!1,now:y});return w({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function de(e,n){const c=P(e,n),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=n?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return ft({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:j(e.id),now:y()})}async function Ke({method:e="GET",pathname:n="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=Ze(n);if(!r)return h(404,"not_found",`no route ${n}`);if(r.bad)return h(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(lt.includes(r.sub)&&!u)return h(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const p={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=t=>{try{return{value:t()}}catch(i){return{res:h(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const t=[];for(const{manifest:d}of m.list()){if(!ne({access:d.access},p))continue;const g=m.load(d.id);g&&t.push(de(g,o))}const i=o&&typeof re=="function"?await re({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return w({cards:t,...i.length?{remote:i}:{}})}if(e==="GET")return w({kbs:m.list().filter(({manifest:t})=>ne({access:t.access},p)).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(()=>qe(l||{}));if(t.res)return t.res;const i=t.value;if(i.id&&m.load(i.id))return w({kb:P(m.load(i.id),o),existed:!0});const d=pe({id:i.id,name:i.name,embed:i.embed,now:y});return m.save(d),{status:201,body:{kb:P(d,o)}}}return h(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return h(405,"method_not_allowed","kb: sync is POST");if(!o)return h(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(j(r.id))return U(r.id);const t=k(()=>it(l||{}));if(t.res)return t.res;const i=t.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let g=m.load(r.id);const v=!g;g||(g=pe({id:r.id,name:i.name||C(String(i.path).replace(/[\\/]+$/,""))||r.id,now:y}),m.save(g));const f=y(),x={done:0,total:0},E=(async()=>{const O=await Oe(g,i,{progress:x});if(x.cancel)return{cancelled:!0};const Me=O.added.length+O.changed.length+O.removed.length,Ge=O.added.length||O.changed.length?await F(g):0;return(Me||v)&&m.save(g),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Ge,made:v,kb:P(g,o),ms:y()-f}})();M.set(r.id,{progress:x,base:g}),E.catch(O=>D(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const G=i.waitMs??5e3;if(G===0)return{status:202,body:{running:!0,progress:{...x},made:v,kb:P(g,o)}};let _=null;const Z=new Promise(O=>{_=setTimeout(()=>O(null),G)});let q;try{q=await Promise.race([E,Z])}catch(O){return clearTimeout(_),W(O)}return clearTimeout(_),q?w(q):{status:202,body:{running:!0,progress:{...x},made:v,kb:P(g,o)}}}const s=m.load(r.id);if(!s)return h(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=j(s.id)?.role==="replica",T=!!j(s.id);if(!ne(s,p))return h(404,"not_found",`kb: no knowledge base ${r.id} for ${p.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||oe(s);const t=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return w({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:m.sizeOf(s.id),dir:o?m.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:g})=>({done:d,total:g}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return h(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=M.get(s.id);return t&&(t.progress.cancel=!0),m.remove(s.id),w({ok:!0,...t?{stoppedSync:!0}:{}})}return h(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return U(s.id);if(e==="POST"&&!r.rest){const t=k(()=>et(l||{}));return t.res?t.res:xe(s,t.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?X(s,r.rest,{now:y})?(m.save(s),w({ok:!0,kb:P(s,o)})):h(404,"not_found",`kb: no document ${r.rest}`):h(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const t=Number(c.get("page"))||1,i=Ue(s,r.rest,t);return i?w(i):h(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return w({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=ce(s,r.rest);return t?w(t):h(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){H(s);const t=c.get("doc");return w({outline:t?ge(s.chunks,{doc:t}):s.outline})}break}case"search":{if(e==="POST"){const t=k(()=>tt(l||{}));if(t.res)return t.res;const i=y(),d=await Q(s,t.value);return oe(s),w({...d,ms:y()-i})}break}case"research":{if(e==="POST"){const t=k(()=>nt(l||{}));return t.res?t.res:Ae(s,t.value,{admin:o})}break}case"graph":{if(e==="GET")return w(At(s,{limit:dt(c.get("limit"))}));if(e==="POST"){const t=k(()=>st(l||{}));return t.res?t.res:Pe(s,t.value)}break}case"report":{if(e==="GET")return H(s),{status:200,text:Qe(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return w({notes:s.notes});if($&&e==="POST")return U(s.id);if(e==="POST"&&!r.rest){const t=k(()=>rt(l||{}));if(t.res)return t.res;const i=t.value,d=i.status==="accepted"&&o?"accepted":"proposed",g=Fe(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:y});return await F(s),m.save(s),{status:201,body:{note:g}}}if(e==="POST"&&r.rest){if(!o)return h(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=k(()=>at(l||{}));if(t.res)return t.res;const i=t.value,d=Ne(s,r.rest,i.status,{now:y});return d?(m.save(s),w({note:d,removed:i.status==="removed"})):h(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return w({access:s.access});if($&&e==="POST")return U(s.id);if(e==="POST"){if(!o)return h(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>ot(l||{}));if(t.res)return t.res;const i=He(s,t.value,{now:y});return m.save(s),w({access:i})}break}case"pages":{if(e!=="GET")break;const t=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===t);return i?w(pt(s.chunks,i)):h(404,"not_found",`kb: no document ${t||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return h(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(ye())return h(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(j(s.id))return h(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof ae!="function")return h(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>ct(l||{}));if(t.res)return t.res;const i=t.value;let d="",g="file";if(i.doc){const v=s.docs.find(f=>f.id===i.doc);if(!v)return h(404,"not_found",`kb: no document ${i.doc}`);d=v.source?.path||"",d||(d=m.dirOf(s.id),g="index")}else if(i.source!=null){const v=(s.sources||[])[i.source];if(!v?.path)return h(404,"not_found",`kb: no kept folder ${i.source}`);d=v.path,g="folder"}else{const v=(s.sources||[]).find(f=>f.path);d=v?.path||m.dirOf(s.id),g=v?"folder":"index"}try{ee(d)}catch{return h(410,"gone","kb: not found on disk — refresh the base")}try{await ae(d,{folder:g!=="file"})}catch(v){return h(502,"reveal_failed",`kb: the file manager did not open — ${v.message}`)}return w({ok:!0,revealed:g})}case"embed":{if(e==="POST"){const t=N(),i=S&&t?S.health("embed",t):{state:"off"},d=await F(s);return d&&m.save(s),w({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||t,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return h(405,"method_not_allowed",`kb: ${e} ${n} is not a route`)}function U(e){return h(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:Ke,store:m,embedModel:N,cardOf:de,addBytes:(e,n,c)=>R(e,n,c),embedAll:e=>F(e),searchBase:(e,n)=>Q(e,n)}}export{I as KB_WALK_LIMITS,Ht as createKbService,P as kbStatusFor,At as wholeGraph};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.147.0";export{o as VERSION};
1
+ const o="0.147.2";export{o as VERSION};