@chatpanel/gateway 0.152.1 → 0.153.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 +2 -2
- package/src/context.js +1 -1
- package/src/kb-bucket-sync.js +1 -1
- package/src/kb.js +3 -3
- package/src/server.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.153.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": {
|
|
@@ -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.502.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateContextRequest as
|
|
1
|
+
import{validateContextRequest as z,searchContext as D,CONTEXT_FEDERATED_HEADER as H}from"@chatpanel/events/context-api.js";import{kbContextProvider as U,webContextProvider as R,bedrockContextProvider as W,gatewayContextProvider as N,patchContextProviders as X,viewContextProviders as J,sourcesOfProvider as M}from"@chatpanel/events/context-providers.js";import{gatewayKbClient as Q}from"@chatpanel/events/kb-tool.js";import{buildApiRequest as V,readApiResponse as Y}from"@chatpanel/events/search-api.js";import{bucketLocationKey as q}from"@chatpanel/events/kb-bucket.js";const Z=Object.freeze({allowLoopback:!1,allowPrivate:!1}),s=(c,v,g)=>({status:c,body:{error:{type:v,message:g}}}),w=c=>({status:200,body:c});function ie({cfg:c,kb:v,search:g=null,apiEngines:T=()=>[],redact:S=null,rerank:O=null,fetchFn:y=fetch,persist:j=()=>{},buckets:m=null,syncWaitMs:I=2e3,profiles:b=null,now:P=()=>Date.now(),log:_=()=>{}}={}){const A=()=>(Array.isArray(c.context?.providers)?c.context.providers:[]).filter(n=>n&&n.enabled!==!1);async function K(n){const t=async(r,o,d)=>{const u=await v().handle({method:r,pathname:o.split("?")[0],query:new URLSearchParams(o.split("?")[1]||""),body:d,admin:n.admin,agent:n.agent});if(u.status>=400)throw new Error(u.body?.error?.message||`kb ${u.status}`);return u.body};return((await t("GET","/v1/kb")).kbs||[]).map(r=>({id:r.id,name:r.name,client:Q({call:t,kbId:r.id})}))}function h(n,{federated:t=!1}={}){const e=[U({bases:()=>K(n)})];typeof g=="function"&&e.push(R({id:"*",search:g,name:"web"}));for(const r of T().filter(o=>o.enabled!==!1)){const o=r.api.id;e.push(R({id:o,name:r.api.name,search:async(d,{limit:u,signal:k})=>{const f=V(r.api,{q:d,limit:u,vars:r.vars||{}}),a=await y(f.url,{method:f.method,headers:f.headers,body:f.body??void 0,signal:k,maxRedirects:0,policy:Z});if(!a.ok)throw new Error(`${r.api.name} ${a.status}`);return{results:Y(r.api,await a.json(),{limit:u}).map(l=>({...l,engine:`api:${o}`}))}}}))}if(!n.admin)return e;for(const r of A())try{r.kind==="bedrock"?e.push(W({id:r.id,name:r.name,region:r.region,knowledgeBaseId:r.knowledgeBaseId,credentials:r.credentials?.profile&&b?()=>b.keys(r.credentials.profile):{accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,...r.sessionToken?{sessionToken:r.sessionToken}:{}},fetch:(o,d)=>y(o,{...d,maxRedirects:0}),now:P})):r.kind==="gateway"&&!t&&e.push(N({id:r.id,name:r.name,url:r.url,token:r.token||"",trusted:r.trusted===!0,fetch:(o,d)=>y(o,{...d,maxRedirects:0})}))}catch(o){_(`[context] ${r.id}: not usable — ${o.message}`)}return e}async function C(n,t,{federated:e=!1,signal:r=null}={}){let o;try{o=z(n||{})}catch(u){return s(400,"invalid_request",u.message)}const d=await D({...o,providers:h(t,{federated:e}),redact:S,rerank:o.rerank?O:null,signal:r,now:P});if(!t.admin)for(const[u,k]of Object.entries(d.providers))k.error==="not configured"&&/^(bedrock|gw)/.test(u)&&(k.error="needs the gateway token");return w({query:o.query,...d})}function E(n){const t=[{id:"kb",type:"kb",source:"kb:*",name:"Knowledge bases on this gateway",configured:!0,enabled:!0,remote:!1},...typeof g=="function"?[{id:"web",type:"web",source:"web",name:"Web search (this gateway’s engines)",configured:!0,enabled:!0,remote:!0}]:[],...T().map(e=>({id:`web:${e.api.id}`,type:"web",source:`web:${e.api.id}`,name:e.api.name,configured:e.enabled!==!1,enabled:e.enabled!==!1,remote:!0,host:e.api.host}))];if(!n.admin)return t;for(const e of J(c.context?.providers||[])){const r=(c.context?.providers||[]).find(d=>d.id===e.id),o=e.kind==="bucket"&&m?m.teamOf(e.kbId||e.id):null;t.push({...e,type:e.kind==="gateway"?"gw":e.kind==="bucket"?"kb":e.kind,source:M(r)[0],configured:!0,remote:e.kind!=="bucket",...o?{team:o}:{}})}return t}async function B(n){if(n.kind==="bucket")return m?m.test(n):{ok:!1,error:"no bucket client here"};if(n.kind==="gateway")try{const t=await y(`${n.url}/v1/kb`,{headers:n.token?{authorization:`Bearer ${n.token}`}:{},maxRedirects:0,signal:AbortSignal.timeout(8e3)}),e=await t.json().catch(()=>({}));return t.ok?{ok:!0,bases:(e.kbs||[]).length}:{ok:!1,status:t.status,error:e?.error?.message||e?.error||`HTTP ${t.status}`}}catch(t){return{ok:!1,error:t.message}}if(n.kind==="bedrock"){const t=h({admin:!0}).find(e=>e.type==="bedrock"&&e.id===n.id);if(!t)return{ok:!1,error:"not usable — check its region, id and keys"};try{return{ok:!0,results:(await t.retrieve("test",{limit:1,signal:AbortSignal.timeout(8e3)})).length}}catch(e){return{ok:!1,error:e.message}}}return{ok:!1,error:"nothing to test"}}async function G(){const n=A().filter(t=>t.kind==="gateway");return Promise.all(n.map(async t=>{try{const e=await y(`${t.url}/v1/kb?view=card`,{headers:{[H]:"1",...t.token?{authorization:`Bearer ${t.token}`}:{}},maxRedirects:0,signal:AbortSignal.timeout(5e3)}),r=await e.json().catch(()=>({}));return e.ok?{gateway:t.name||t.id,id:t.id,host:(()=>{try{return new URL(t.url).host}catch{return""}})(),cards:(r.cards||[]).map(o=>({...o,kind:"remote",gateway:t.name||t.id,gatewayId:t.id,reveal:!1}))}:{gateway:t.name||t.id,id:t.id,error:r?.error?.message||`HTTP ${e.status}`}}catch(e){return{gateway:t.name||t.id,id:t.id,error:e.message}}}))}async function L({method:n="GET",pathname:t="",body:e=null,admin:r=!1,agent:o="",federated:d=!1,signal:u=null}={}){const k={admin:r,agent:o};if(t==="/v1/context")return n!=="POST"?s(405,"method_not_allowed","context: POST"):C(e,k,{federated:d,signal:u});if(t==="/v1/context/profiles")return n!=="GET"?s(405,"method_not_allowed","context: GET"):r?w({profiles:b?b.list():[]}):s(403,"forbidden","context: listing profiles needs the gateway token or the extension origin");if(t==="/v1/context/providers"){if(n==="GET")return w({providers:E(k)});if(n==="POST"){if(!r)return s(403,"forbidden","context: changing providers needs the gateway token or the extension origin");const a=Array.isArray(e)?e:e?.providers;let l;try{l=X(c.context?.providers||[],a)}catch(i){return s(400,"invalid_request",i.message)}const x=(c.context?.providers||[]).filter(i=>i?.kind==="bucket"&&(()=>{const p=l.find($=>$.id===i.id);return!p||p.kind!=="bucket"||q(p)!==q(i)})());c.context={...c.context||{},providers:l};try{j()}catch(i){return s(500,"persist_failed",`context: could not save — ${i.message}`)}for(const i of x)try{await m?.forget(i)}catch(p){_(`[team] ${i.id}: the old copy was not removed — ${p.message}`)}return m?.restart(),w({providers:E(k)})}return s(405,"method_not_allowed","context: GET or POST")}const f=/^\/v1\/context\/providers\/([a-z0-9][a-z0-9_-]{0,39})\/(test|sync|upload)$/.exec(t);if(f&&n==="POST"){if(!r)return s(403,"forbidden","context: needs the gateway token or the extension origin");const a=(c.context?.providers||[]).find(i=>i.id===f[1]);if(!a)return s(404,"not_found",`context: no provider ${f[1]}`);if(f[2]==="test")return w(await B(a));if(a.kind!=="bucket"||!m)return s(400,"invalid_request",`context: ${f[2]} is for a team bucket`);if(f[2]==="sync"){const i=m.run(a),p=await Promise.race([i,new Promise($=>{setTimeout($,I,null).unref?.()})]);return w(p||{ok:!0,running:!0})}const l=String(e?.name||"").replace(/\\/g,"/").replace(/^\/+/,"");if(!l||l.includes("..")||l.startsWith(".")||l.length>300)return s(400,"invalid_request","context: upload needs a file name (no .., not hidden)");const x=typeof e?.data=="string"?Buffer.from(e.data,"base64"):null;if(!x?.length)return s(400,"invalid_request","context: upload needs data (base64)");try{await m.upload(a,l,x)}catch(i){return s(502,"bucket_failed",i.message)}return a.role==="builder"&&m.run(a),w({ok:!0,key:`${a.prefix||""}${l}`,building:a.role==="builder"})}return s(404,"not_found",`no route ${t}`)}return{handle:L,remoteCards:G,providersFor:h,context:C}}export{ie as createContextService};
|
package/src/kb-bucket-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as le,mkdirSync as W,readFileSync as q,writeFileSync as ue,readdirSync as pe,rmSync as fe,renameSync as he}from"node:fs";import{join as A,basename as me}from"node:path";import be from"node:os";import{createHash as ye}from"node:crypto";import{bucketClient as ve,indexKey as $,isDocumentKey as ge,bucketDocId as ke,splitIndexParts as we,validateRevision as M,planReplicaSync as Ae,assembleReplica as $e,makeLease as Se,leaseState as Oe,replicaFreshness as je,bucketWhere as De,sha256Hex as G,KB_REVISION_FORMAT as Ie}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as xe}from"@chatpanel/events/kb-folder-sync.js";import{createKb as Ne,removeDocument as Be,serializeKb as Re,deserializeKb as Te}from"@chatpanel/events/kb-index.js";import{graphReport as Fe}from"@chatpanel/events/kb-graph.js";const ze=new TextEncoder,Me=r=>typeof r=="string"?ze.encode(r):r instanceof Uint8Array?r:new Uint8Array(r.buffer,r.byteOffset,r.byteLength),Q=(r,S)=>{const I=`${r}.tmp-${process.pid}`;ue(I,S,{mode:384}),he(I,r)},Ee=(r={},S=be.hostname())=>typeof r.builderName=="string"&&r.builderName.trim()?r.builderName.trim().slice(0,60):`gateway-${ye("sha256").update(String(S)).digest("hex").slice(0,8)}`;function Ve({store:r,kb:S,entries:I=()=>[],fetchFn:X,now:u=()=>Date.now(),log:x=()=>{},holder:Y=null,version:Z="",subtle:E=null,profiles:ee=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"),te=e=>A(r.dirOf(e),"parts"),B=e=>ve(e,{fetch:X,now:u,subtle:E,profiles:ee});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 se=(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 ie(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=te(t.kbId);W(h,{recursive:!0,mode:448});const j=m=>le(A(h,m)),l=Ae({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=$e(a,n=>new Uint8Array(q(A(h,n))));m.manifest={...m.manifest,id:t.kbId};const d=Te(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 pe(h))z.has(n)||fe(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 ne(e){const t=R(e),i=B(e),c=Y||Ee(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(Oe(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(Se({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=Ne({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:re}=await i.list(e.prefix||""),H=re.filter(s=>ge(e,s.key)).map(s=>({path:s.key,size:s.size,mtime:s.mtime,etag:s.etag})),oe=Object.entries(b.files).map(([s,o])=>({path:s,id:o.id,size:o.size,etag:o.etag})),f=xe({known:oe,listing:H}),k=[];for(const s of f.remove){Be(n,s,{now:u});for(const[o,p]of Object.entries(b.files))p.id===s&&delete b.files[o]}const ae=new Map(H.map(s=>[s.path,s]));for(const s of[...f.add,...f.change.map(o=>o.path)]){const o=ae.get(s);try{const p=await i.get(s);if(p.status!==200)throw new Error(`not readable (${p.status})`);const y=ke(s);await z.addBytes(n,Buffer.from(p.bytes),{name:me(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=Re(n),U=we(w),ce=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=Me(s),_=await G(y,E),V=`objects/${_}.${o}`;return ce.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 de=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=de.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:Ie,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(Fe(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"?ne(e):ie(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),se(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:De(t),freshness:je({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{Ee as builderName,Ve as createBucketSync};
|
|
1
|
+
import{existsSync as fe,mkdirSync as X,readFileSync as P,writeFileSync as me,readdirSync as be,rmSync as ge,renameSync as ve}from"node:fs";import{join as O,basename as ye}from"node:path";import ke from"node:os";import{createHash as we}from"node:crypto";import{bucketClient as $e,indexKey as D,isDocumentKey as Ae,bucketDocId as Se,splitIndexParts as Oe,validateRevision as U,planReplicaSync as De,assembleReplica as je,makeLease as Ie,leaseState as xe,replicaFreshness as Re,bucketWhere as Y,sha256Hex as C,KB_REVISION_FORMAT as Ne}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as Te}from"@chatpanel/events/kb-folder-sync.js";import{createKb as Be,removeDocument as Fe,serializeKb as ze,deserializeKb as Me}from"@chatpanel/events/kb-index.js";import{graphReport as Je}from"@chatpanel/events/kb-graph.js";const Ee=new TextEncoder,Z=r=>typeof r=="string"?Ee.encode(r):r instanceof Uint8Array?r:new Uint8Array(r.buffer,r.byteOffset,r.byteLength),ee=(r,g)=>{const $=`${r}.tmp-${process.pid}`;me($,g,{mode:384}),ve($,r)},Ke=(r={},g=ke.hostname())=>typeof r.builderName=="string"&&r.builderName.trim()?r.builderName.trim().slice(0,60):`gateway-${we("sha256").update(String(g)).digest("hex").slice(0,8)}`,Ue=(r={},g=Date.now())=>r.error?{at:g,error:String(r.error).slice(0,300)}:{at:g,...r.revision?{revision:r.revision}:{},...r.published!=null?{published:!!r.published}:{},...r.upToDate?{upToDate:!0}:{},skipped:(r.skipped||[]).length,...(r.skipped||[]).length?{skippedSample:r.skipped.slice(0,3).map(({path:$,why:_})=>({path:$,why:String(_).slice(0,200)}))}:{}};function Ge({store:r,kb:g,entries:$=()=>[],fetchFn:_,now:l=()=>Date.now(),log:j=()=>{},holder:te=null,version:se="",subtle:R=null,profiles:ie=null}={}){const N=new Map,T=new Map,A=new Map,B=e=>e.kbId||e.id,L=e=>O(r.dirOf(e),"team.json"),re=e=>O(r.dirOf(e),"parts"),F=e=>$e(e,{fetch:_,now:l,subtle:R,profiles:ie});function z(e){if(N.has(e.id))return N.get(e.id);let t={kbId:B(e),role:e.role,revision:0,rev:null,syncedAt:0,checkedAt:0,error:"",updating:!1,remoteRevision:0,behindDocs:0,etag:""};try{const s=JSON.parse(P(L(B(e)),"utf8"));s?.provider===e.id&&(t={...t,...s.state,rev:s.state?.rev?U(s.state.rev):null,updating:!1})}catch{}return N.set(e.id,t),t}const ne=(e,t)=>{try{X(r.dirOf(t.kbId),{recursive:!0,mode:448}),ee(L(t.kbId),JSON.stringify({provider:e.id,state:{...t,updating:!1}}))}catch(s){j(`[team] ${e.id}: state not saved — ${s.message}`)}};async function oe(e){const t=z(e),s=F(e),o=await s.get(D(e,"revision.json"),{etag:t.rev?t.etag:""});if(t.checkedAt=l(),o.status===304)return t.error="",t.remoteRevision=t.revision,t.behindDocs=0,{upToDate:!0};if(o.status===404)throw new Error("no index has been published to this bucket yet — a builder has not run");const a=U(JSON.parse(new TextDecoder().decode(o.bytes)));t.remoteRevision=a.revision;const f=re(t.kbId);X(f,{recursive:!0,mode:448});const I=m=>fe(O(f,m)),p=De({current:t.rev,next:a,have:I});if(p.upToDate)return t.etag=o.etag,t.error="",t.behindDocs=0,{upToDate:!0};t.behindDocs=p.added+p.changed+p.removed,t.updating=!0;try{for(const n of p.fetch){const k=await s.get(D(e,n.file));if(k.status!==200)throw new Error(`part ${n.file} is missing from the bucket (${k.status})`);if(await C(k.bytes,R)!==n.hash)throw new Error(`part ${n.file} does not match its hash — not used`);ee(O(f,n.hash),k.bytes)}const m=je(a,n=>new Uint8Array(P(O(f,n))));m.manifest={...m.manifest,id:t.kbId};const c=Me(m);r.save(c);const E=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 be(f))E.has(n)||ge(O(f,n),{force:!0});return Object.assign(t,{rev:a,revision:a.revision,builtAt:a.builtAt,builtBy:a.builder.name,etag:o.etag,syncedAt:l(),error:"",behindDocs:0}),j(`[team] ${e.id}: revision ${a.revision} (${p.added} added, ${p.changed} changed, ${p.removed} removed; ${p.fetch.length} parts, ${p.bytes} bytes)`),{revision:a.revision,...p,fetch:p.fetch.length}}finally{t.updating=!1}}async function ae(e){const t=z(e),s=F(e),o=te||Ke(e),a=`${o}#${process.pid}`,f=D(e,"lease.json"),I=await s.get(f).then(m=>m.status===200?JSON.parse(new TextDecoder().decode(m.bytes)):null).catch(()=>null);if(xe(I,{holder:a,now:l()})==="held")throw new Error(`another builder (${I.holder}) is building until ${new Date(I.until).toISOString()}`);await s.put(f,JSON.stringify(Ie({holder:a,now:l()})),{contentType:"application/json"});const p=await s.get(f);if(p.status!==200||JSON.parse(new TextDecoder().decode(p.bytes)).holder!==a)throw new Error("another builder took the lease at the same moment — this one stands aside");try{const m=await s.get(D(e,"revision.json")),c=m.status===200?U(JSON.parse(new TextDecoder().decode(m.bytes))):null,E=g();let n=r.load(t.kbId);n||(n=Be({id:t.kbId,name:e.name||e.bucket,now:l}));const k=`s3://${e.bucket}/${e.prefix||""}`;Array.isArray(n.sources)||(n.sources=[]);let b=n.sources.find(i=>i.kind==="bucket"&&i.path===k);b||(b={kind:"bucket",path:k,files:{},syncedAt:0},n.sources.push(b));const{objects:ce}=await s.list(e.prefix||""),V=ce.filter(i=>Ae(e,i.key)).map(i=>({path:i.key,size:i.size,mtime:i.mtime,etag:i.etag})),de=Object.entries(b.files).map(([i,d])=>({path:i,id:d.id,size:d.size,etag:d.etag})),u=Te({known:de,listing:V}),v=[];for(const i of u.remove){Fe(n,i,{now:l});for(const[d,h]of Object.entries(b.files))h.id===i&&delete b.files[d]}const le=new Map(V.map(i=>[i.path,i])),W=[...u.add,...u.change.map(i=>i.path)];t.progress={done:0,total:W.length};for(const i of W){const d=le.get(i);try{const h=await s.get(i);if(h.status!==200)throw new Error(`not readable (${h.status})`);const y=Se(i);await E.addBytes(n,Buffer.from(h.bytes),{name:ye(i),source:{kind:"bucket",name:i},id:y,reach:"internal"}),b.files[i]={id:y,size:d.size,etag:d.etag,mtime:d.mtime}}catch(h){v.push({path:i,why:h.message})}t.progress.done+=1}b.syncedAt=l(),b.lastSync={at:b.syncedAt,added:u.add.length,changed:u.change.length,removed:u.remove.length,same:u.same,skipped:v.length,skippedSample:v.slice(0,20)},await E.embedAll(n),r.save(n);const S=ze(n),K=Oe(S),ue=u.add.length+u.change.length-v.length+u.remove.length;if(c&&ue===0&&await C(Z(K.notes),R)===c.notes.hash)return Object.assign(t,{revision:c.revision,rev:c,builtAt:c.builtAt,builtBy:c.builder.name,syncedAt:l(),error:""}),{published:!1,revision:c.revision,...u,skipped:v};const pe=new Set(c?[c.manifest,c.notes,...c.report?[c.report]:[],...c.docs.flatMap(i=>[i.chunksFile,i.vectorsFile].filter(Boolean))].map(i=>i.hash):[]),x=async(i,d,h)=>{const y=Z(i),H=await C(y,R),Q=`objects/${H}.${d}`;return pe.has(H)||await s.put(D(e,Q),y,{contentType:h}),{file:Q,hash:H,bytes:y.length}},q=await x(K.manifest,"json","application/json");if(c&&c.manifest.hash===q.hash)return Object.assign(t,{revision:c.revision,rev:c,builtAt:c.builtAt,builtBy:c.builder.name,syncedAt:l(),error:""}),{published:!1,revision:c.revision,...u,skipped:v};const he=new Map(Object.entries(b.files).map(([i,d])=>[d.id,{key:i,...d}])),G=[];for(const i of K.docs){const d=S.manifest.docs.find(y=>y.id===i.id)||{},h=he.get(i.id)||{key:d.source?.name||i.id,etag:"",size:0};G.push({id:i.id,key:h.key,etag:h.etag||"",size:h.size||0,title:d.title||h.key,type:d.type||"",pages:d.pages||0,chunks:i.count,chunksFile:await x(i.chunks,"jsonl","application/x-ndjson"),...i.vectors?{vectorsFile:await x(new Uint8Array(i.vectors.buffer,i.vectors.byteOffset,i.vectors.byteLength),"f32","application/octet-stream")}:{}})}const w=U({format:Ne,kind:"chap-kb-index",kb:{id:t.kbId,name:n.name},revision:(c?.revision||0)+1,builtAt:l(),builder:{name:o,version:se},embed:S.vectors.dims?{model:S.vectors.model,recipe:S.vectors.recipe,dims:S.vectors.dims}:null,manifest:q,notes:await x(K.notes,"json","application/json"),report:await x(Je(n),"md","text/markdown"),docs:G});return await s.put(D(e,"revision.json"),JSON.stringify(w),{contentType:"application/json"}),Object.assign(t,{rev:w,revision:w.revision,builtAt:w.builtAt,builtBy:o,syncedAt:l(),checkedAt:l(),remoteRevision:w.revision,error:""}),j(`[team] ${e.id}: published revision ${w.revision} (${u.add.length} added, ${u.change.length} changed, ${u.remove.length} removed, ${v.length} skipped)`),{published:!0,revision:w.revision,...u,skipped:v}}finally{await s.del(f).catch(()=>{})}}function M(e){if(A.has(e.id))return A.get(e.id);const t=z(e);t.role=e.role;const s=(e.role==="builder"?ae(e):oe(e)).then(o=>(t.error="",o)).catch(o=>(t.error=String(o?.message||o).slice(0,300),t.checkedAt=l(),j(`[team] ${e.id}: ${t.error}`),{error:t.error})).then(o=>(t.lastRun=Ue(o,l()),o)).finally(()=>{t.progress=null,A.delete(e.id),ne(e,t)});return A.set(e.id,s),s}const J=()=>($()||[]).filter(e=>e?.kind==="bucket"&&e.enabled!==!1);return{run:M,runById:e=>{const t=J().find(s=>s.id===e);return t?M(t):Promise.resolve({error:`no bucket source ${e}`})},test:e=>F(e).test(),upload:(e,t,s)=>F(e).put(`${e.prefix||""}${String(t).replace(/^\/+/,"")}`,s),teamOf(e){const t=J().find(f=>B(f)===e);if(!t)return null;const s=z(t),o=A.has(t.id),a=Re({revision:s.revision,remoteRevision:s.remoteRevision,syncedAt:s.syncedAt,checkedAt:s.checkedAt,error:s.error,updating:o,behindDocs:s.behindDocs,now:l()});return o&&s.progress?.total&&(a.label=`Indexing ${s.progress.done} of ${s.progress.total} document${s.progress.total===1?"":"s"}…`),{role:t.role,provider:t.id,revision:s.revision,builtAt:s.builtAt||0,...s.builtBy?{builtBy:s.builtBy}:{},syncedAt:s.syncedAt,where:Y(t),freshness:a,...o&&s.progress?{progress:{...s.progress}}:{},...s.lastRun?{lastRun:s.lastRun}:{}}},start(){for(const e of J()){if(T.has(e.id))continue;const t=setInterval(()=>{const o=J().find(a=>a.id===e.id);o&&M(o)},Math.max(1,e.pollMinutes||5)*6e4);t.unref?.(),T.set(e.id,t),setTimeout(()=>M(e),2e3).unref?.()}},stop(){for(const e of T.values())clearInterval(e);T.clear()},restart(){this.stop(),this.start()},async forget(e){await A.get(e.id)?.catch(()=>{}),N.delete(e.id);const t=B(e);let s=null;try{s=JSON.parse(P(L(t),"utf8"))?.provider}catch{}return s!==e.id?!1:(r.remove(t),j(`[team] ${e.id}: the copy of ${Y(e).bucket}/${e.prefix||""} on this computer is removed (its source moved or was removed)`),!0)}}}export{Ke as builderName,Ge as createBucketSync,Ue as lastRunOf};
|
package/src/kb.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(
|
|
3
|
-
`));if(k&&$){const i=e.docs.find(d=>d.textHash===$&&d.id!==r);if(i)return{duplicateOf:i}}const T=a.path&&s.links?.length?vt(a.path,s.links,{root:f||De(a.path)}):[],n=se(e,{id:r,title:o||s.title||C(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:y,links:T,textHash:$,markdownHeadings:!!s.markdown});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced,...s.scanned?{scanned:!0}:{}}}function $e(e,t){const c=fe(e).toLowerCase();return!ye.has(c)&&!At.has(c)?!1:t?.length?t.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function ie(e,{recursive:t=!0,include:c=null}={}){const l=xt(e,{home:W,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=ue(Be(e.replace(/^~(?=$|\/)/,W))),a=[],u=[];let r=0;const f=($,T)=>{if(a.length>=I.files)return u.push({path:T,why:`stopped at ${I.files} files`}),!1;if(ke($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let n;try{n=ne($)}catch{return!0}const i=fe($).toLowerCase(),d=ye.has(i)||Pt.has(i)?ae:I.textBytes;return n.size>d?(u.push({path:T,why:`too large (${Math.round(n.size/1048576)} MB)`}),!0):r+n.size>I.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=n.size,a.push({full:$,rel:T,size:n.size,mtime:Math.floor(n.mtimeMs)}),!0)};if(!ne(o).isDirectory())return f(o,C(o)),{root:o,files:a,skipped:u,single:!0};const s=($,T,n)=>{if(n>I.depth)return!0;let i=[];try{i=je($,{withFileTypes:!0}).sort((d,m)=>d.name.localeCompare(m.name))}catch{return!0}for(const d of i){const m=d.name;if(m.startsWith(".")&&d.isDirectory())continue;const v=ze($,m),p=T?`${T}/${m}`:m;if(d.isDirectory()){if(Ot.has(m)||!t)continue;try{if(!ue(v).startsWith(o)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(v,p,n+1))return!1;continue}if(!(!d.isFile()&&!d.isSymbolicLink())){if(ke(v)){u.push({path:p,why:"withheld (a credential store)"});continue}if($e(m,c)&&!f(v,p))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function Oe(e,{path:t,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=ie(t,{recursive:c,include:l}),f=[];for(const k of a)try{const s=await U(e,le(k.full),{name:C(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Te(e,{path:t,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=ie(t,{recursive:!0,include:c}),f=bt(e,a,{include:c});if(l){for(const p of Object.values(f.files))p?.id&&V(e,p.id,{now:y});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,x]of Object.entries(f.files))x?.dupOf&&!k.has(x.dupOf)&&delete f.files[p];const s=gt({known:kt(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const $=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){V(e,p,{now:y});for(const[x,E]of Object.entries(f.files))E.id===p&&(delete f.files[x],T.push(x.startsWith(`${a}/`)?x.slice(a.length+1):x))}const n=[],i=[],d=[],m=p=>String(p||"").startsWith(`${a}/`)?p.slice(a.length+1):p,v=async(p,x)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(p),G=mt(p);try{const _=await U(e,le(p),{name:C(p),source:{kind:"file",path:p},reach:"internal",id:G,root:a,dedupe:!0});_.duplicateOf?(e.docs.some(ee=>ee.id===G)&&V(e,G,{now:y}),f.files[p]={id:G,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},d.push({path:E.rel,of:m(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:G,size:E.size,mtime:E.mtime},x.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const p of s.add)await v(p,n);for(const p of s.change)await v(p.path,i);return f.syncedAt=y(),f.lastSync={at:f.syncedAt,added:n.length,changed:i.length,removed:T.length,same:s.same,duplicates:d.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:d.slice(0,20)},{root:a,added:n,changed:i,removed:T,same:s.same,duplicates:d,skipped:r}}async function xe(e,{url:t,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().read({url:t,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=J(o).map((r,f)=>({page:f+1,text:r})),u=se(e,{title:c||l.body.title||t,pages:a,source:{kind:"url",url:l.body.url||t,name:l.body.title||""},type:"html",reach:"web",now:y});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function _e(e,t,{admin:c=!1}={}){const l=y();let o=[],a=[];if(t.kind==="bytes"){const r=Buffer.from(t.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>ae)return g(413,"too_large",`kb: ${r.length} bytes is over the ${ae}-byte limit`);try{o.push(await U(e,r,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(f){return X(f)}}else if(t.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:o,skipped:a}=await Oe(e,t))}catch(r){return X(r)}}else if(t.kind==="url")try{o.push(await xe(e,t))}catch(r){return X(r)}else if(t.kind==="text"){const r=J(t.text).map((k,s)=>({page:s+1,text:k})),f=se(e,{title:t.title||t.name,pages:r,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:y});o.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=o.length?await F(e):0;return b.save(e),w({added:o,skipped:a,embedded:u,kb:P(e,c),ms:y()-l})}function X(e){const t=e?.code||"";return t==="refused"?g(403,"refused",`kb: ${e.message}`):t==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):t==="too_large"?g(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?g(502,"read_failed",`kb: ${e.message}`):t==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ee=e=>e.vectors?.model&&e.vectors.model!==N()?null:Q("query"),q=(e,t)=>Ie(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],...t.filters?{filters:t.filters}:{},embed:Ee(e),rerank:t.rerank===!1?null:ve,now:y}),Pe=(e,t)=>e.docs.find(c=>c.id===t)?.title||t,ce=(e,t)=>{const c=he(e,t);if(!c)return null;const l=c.kind==="note"?"Note":Pe(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Ae(e,t){Y(e);const c=t.node.replace(/^chunk:/,""),l=(/#\d+$/.test(c)&&he(e,c)?{id:`chunk:${c}`,kind:"chunk",label:c}:null)||ge(e.graph,t.node);if(!l)return w({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},a=Ve(e,l.id,{limit:Math.min(8,t.limit||6),...t.query?{query:t.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:Je(e.graph,l.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit}),passages:a.passages,next:a.next};if(t.to){const r=ge(e.graph,t.to);u.to=t.to,u.path=r?(Qe(e.graph,l.id,r.id)||[]).map(o):null,r&&!u.path.length&&(u.path=null)}return w(u)}async function Ke(e,t,{admin:c=!1}={}){if(t.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=t.model&&typeof D=="function"?D(t.model):null,o=P(e,c),a=await Ye(t.question,{search:(u,r)=>q(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||t.docs||null}),outline:async u=>u?me(e.chunks,{doc:u}):e.outline,read:async u=>ce(e,u),complete:l,kbName:e.name,docs:o.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:y});return w({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function de(e,t){const c=P(e,t),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=t?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return pt({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:z(e.id),now:y()})}async function Me({method:e="GET",pathname:t="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=qe(t);if(!r)return g(404,"not_found",`no route ${t}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ut.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=n=>{try{return{value:n()}}catch(i){return{res:g(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const n=[];for(const{manifest:d}of b.list()){if(!re({access:d.access},f))continue;const m=b.load(d.id);m&&n.push(de(m,o))}const i=o&&typeof h=="function"?await h({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return w({cards:n,...i.length?{remote:i}:{}})}if(e==="GET")return w({kbs:b.list().filter(({manifest:n})=>re({access:n.access},f)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=k(()=>et(l||{}));if(n.res)return n.res;const i=n.value;if(i.id&&b.load(i.id))return w({kb:P(b.load(i.id),o),existed:!0});const d=pe({id:i.id,name:i.name,embed:i.embed,now:y});return b.save(d),{status:201,body:{kb:P(d,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(z(r.id))return H(r.id);const n=k(()=>ct(l||{}));if(n.res)return n.res;const i=n.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let m=b.load(r.id);const v=!m;m||(m=pe({id:r.id,name:i.name||C(String(i.path).replace(/[\\/]+$/,""))||r.id,now:y}),b.save(m));const p=y(),x={done:0,total:0},E=(async()=>{const O=await Te(m,i,{progress:x});if(x.cancel)return{cancelled:!0};const Ge=O.added.length+O.changed.length+O.removed.length,Le=O.added.length||O.changed.length?await F(m):0;return(Ge||v)&&b.save(m),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Le,made:v,kb:P(m,o),ms:y()-p}})();M.set(r.id,{progress:x,base:m}),E.catch(O=>j(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const G=i.waitMs??5e3;if(G===0)return{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}};let _=null;const ee=new Promise(O=>{_=setTimeout(()=>O(null),G)});let te;try{te=await Promise.race([E,ee])}catch(O){return clearTimeout(_),X(O)}return clearTimeout(_),te?w(te):{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}}}const s=b.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=z(s.id)?.role==="replica",T=!!z(s.id);if(!re(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||oe(s);const n=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return w({kb:{...n,coverage:n.chunks?Math.round(n.vectors/n.chunks*100):0,bytes:b.sizeOf(s.id),dir:o?b.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:m})=>({done:d,total:m}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const n=M.get(s.id);return n&&(n.progress.cancel=!0),b.remove(s.id),w({ok:!0,...n?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>tt(l||{}));return n.res?n.res:_e(s,n.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?V(s,r.rest,{now:y})?(b.save(s),w({ok:!0,kb:P(s,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const n=Number(c.get("page"))||1,i=Xe(s,r.rest,n);return i?w(i):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return w({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const n=ce(s,r.rest);return n?w(n):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){Y(s);const n=c.get("doc");return w({outline:n?me(s.chunks,{doc:n}):s.outline})}break}case"search":{if(e==="POST"){const n=k(()=>nt(l||{}));if(n.res)return n.res;const i=y(),d=await q(s,n.value);return oe(s),w({...d,ms:y()-i})}break}case"research":{if(e==="POST"){const n=k(()=>st(l||{}));return n.res?n.res:Ke(s,n.value,{admin:o})}break}case"graph":{if(e==="GET")return w(Kt(s,{limit:lt(c.get("limit"))}));if(e==="POST"){const n=k(()=>rt(l||{}));return n.res?n.res:Ae(s,n.value)}break}case"report":{if(e==="GET")return Y(s),{status:200,text:Ze(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return w({notes:s.notes});if($&&e==="POST")return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>at(l||{}));if(n.res)return n.res;const i=n.value,d=i.status==="accepted"&&o?"accepted":"proposed",m=Ne(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:y});return await F(s),b.save(s),{status:201,body:{note:m}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=k(()=>ot(l||{}));if(n.res)return n.res;const i=n.value,d=Ce(s,r.rest,i.status,{now:y});return d?(b.save(s),w({note:d,removed:i.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return w({access:s.access});if($&&e==="POST")return H(s.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=k(()=>it(l||{}));if(n.res)return n.res;const i=He(s,n.value,{now:y});return b.save(s),w({access:i})}break}case"pages":{if(e!=="GET")break;const n=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===n);return i?w(ht(s.chunks,i)):g(404,"not_found",`kb: no document ${n||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(we())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(z(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof R!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const n=k(()=>dt(l||{}));if(n.res)return n.res;const i=n.value;let d="",m="file";if(i.doc){const v=s.docs.find(p=>p.id===i.doc);if(!v)return g(404,"not_found",`kb: no document ${i.doc}`);d=v.source?.path||"",d||(d=b.dirOf(s.id),m="index")}else if(i.source!=null){const v=(s.sources||[])[i.source];if(!v?.path)return g(404,"not_found",`kb: no kept folder ${i.source}`);d=v.path,m="folder"}else{const v=(s.sources||[]).find(p=>p.path);d=v?.path||b.dirOf(s.id),m=v?"folder":"index"}try{ne(d)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await R(d,{folder:m!=="file"})}catch(v){return g(502,"reveal_failed",`kb: the file manager did not open — ${v.message}`)}return w({ok:!0,revealed:m})}case"embed":{if(e==="POST"){const n=N(),i=S&&n?S.health("embed",n):{state:"off"},d=await F(s);return d&&b.save(s),w({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||n,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}function H(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:Me,store:b,embedModel:N,cardOf:de,addBytes:(e,t,c)=>U(e,t,c),embedAll:e=>F(e),searchBase:(e,t)=>q(e,t)}}export{I as KB_WALK_LIMITS,Vt as createKbService,P as kbStatusFor,Kt as wholeGraph};
|
|
1
|
+
import{readFileSync as oe,statSync as ae,readdirSync as Be,realpathSync as me}from"node:fs";import{join as De,basename as W,extname as Z,resolve as Fe,dirname as Ie}from"node:path";import Ne from"node:os";import{createKb as be,addDocument as ie,removeDocument as q,addNote as Re,setNoteStatus as We,searchKb as Ue,embedMissing as He,kbNeedsVectors as Xe,kbStatus as Ve,readPage as Ye,chunkById as ce,refreshKb as ee,setKbAccess as Je,kbMayUse as de,graphWalk as Qe}from"@chatpanel/events/kb-index.js";import{kbResearch as Ze}from"@chatpanel/events/kb-research.js";import{neighbours as qe,pathBetween as et,resolveNode as ke,graphReport as tt}from"@chatpanel/events/kb-graph.js";import{outlineOf as ye}from"@chatpanel/events/kb-chunk.js";import{routeKb as nt,validateKbCreate as st,validateKbAdd as rt,validateKbSearch as ot,validateKbResearch as at,validateKbGraph as it,validateKbNote as ct,validateKbNoteStatus as dt,validateKbAccess as lt,validateKbSync as ut,validateKbReveal as ft,kbGraphLimit as pt,KB_LOCAL_ACTIONS as ht}from"@chatpanel/events/kb-capability.js";import{communities as gt,topEntities as we}from"@chatpanel/events/kb-graph.js";import{kbCard as mt,pageStrip as bt}from"@chatpanel/events/kb-view.js";import{passagePageHtml as kt}from"@chatpanel/events/kb-cite.js";import{planFolderSync as yt,folderDocId as wt,folderSource as vt,knownFiles as St}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as $t,markdownLinks as xt,resolveLinks as Tt,visibleTextHash as Ot,decodeText as _t}from"@chatpanel/events/kb-html.js";import{secretReason as ve,SKIP_DIR_NAMES as Et,sniffType as Pt,checkAttachablePath as At}from"@chatpanel/events/attached-paths.js";import{paginateText as te,MAX_DOCUMENT_BYTES as le}from"./extract-capability.js";import{defaultEmbeddedModel as jt}from"./embedded-models.js";import{primaryProvider as Kt}from"./capability-config.js";function P(y,A){const $=Ve(y);return A?$:{...$,documents:$.documents.map(K=>{const{path:D,...G}=K.source||{};return{...K,source:G}})}}const U=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),Se=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Lt=new Set([".html",".htm",".xhtml"]),Mt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(y,A,$,K={})=>({status:y,body:{error:{type:A,message:$},...K}}),S=y=>({status:200,body:y});function Gt(y,{limit:A=60}={}){ee(y);const $=y.graph||{nodes:[],edges:[]},K=new Set(we($,{limit:A}).map(m=>m.id)),D=new Map(we($,{limit:A}).map(m=>[m.id,m.weight])),G=$.nodes.filter(m=>m.kind==="entity"?K.has(m.id)||m.type==="person"||m.type==="role":m.kind!=="chunk").slice(0,A*6),F=new Set(G.map(m=>m.id)),z=$.edges.filter(m=>F.has(m.from)&&F.has(m.to)),v=m=>m.kind==="holds"||m.kind==="member"||m.kind==="has",H=[...z.filter(v),...z.filter(m=>!v(m))].slice(0,A*20),C=gt($).map(m=>({...m,members:m.members.filter(X=>F.has(X))})).filter(m=>m.members.length>=2).slice(0,24);return{nodes:G.map(m=>({id:m.id,kind:m.kind,label:m.label,count:m.count,...m.type?{type:m.type}:{},...m.doc?{doc:m.doc}:{},...D.has(m.id)?{weight:D.get(m.id)}:{}})),edges:H,communities:C,total:{nodes:$.nodes.length,edges:$.edges.length}}}const $e=Object.freeze({".pdf":"application/pdf",".txt":"text/plain; charset=utf-8",".md":"text/plain; charset=utf-8",".csv":"text/plain; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"});function qt({store:y,extract:A=null,embedded:$=null,cfg:K={},rerank:D=null,read:G=null,completer:F=null,log:z=()=>{},now:v=()=>Date.now(),home:H=Ne.homedir(),team:C=()=>null,remoteCards:m=null,reveal:X=null,confined:xe=()=>!1}={}){const N=()=>{const e=Kt(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||jt("embed")||""},ne=(e="passage")=>{const n=N();if(!$||!n)return null;const d=$.health("embed",n);return d.state!=="ready"&&d.state!=="loading"&&!d.installed?($.embed(n,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await $.embed(n,l,{kind:e})).vectors},Te=typeof D=="function"?D:null,se=new Set;function ue(e){!e||se.has(e.id)||e.embed==="off"||!ne("passage")||Xe(e)&&(se.add(e.id),I(e).then(n=>{n&&(y.save(e),z(`[kb] ${e.id}: ${n} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>se.delete(e.id)))}async function I(e,{late:n=()=>!1}={}){const d=ne("passage");if(!d)return 0;try{return await He(e,d,{model:N(),late:n})}catch(l){return z(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function Oe(e,n,d=""){const l=Pt(e,n);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=_t(e);if(/\.x?html?$/i.test(n)||/html/i.test(l.label||"")){const s=$t(r);return{type:"html",pages:te(s.markdown).map((x,T)=>({page:T+1,text:x})),title:s.title,links:s.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
|
|
2
|
+
`).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(n);return{type:l.label||"text",pages:te(r).map((s,x)=>({page:x+1,text:s})),title:f?f[1].trim():"",links:k?xt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const i=A(),o=await i.open(e,{name:n,hint:d}),u=[];for(let r=1;r<=o.pages;r+=1){let f="";try{f=String((await i.page(o.hash,r)).text||"")}catch(k){z(`[kb] ${n} p.${r}: ${k.message}`)}u.push({page:r,text:f,...o.labels?.[r-1]?{label:o.labels[r-1]}:{}})}return{type:o.type,pages:u,title:o.title||"",hash:o.hash,scanned:!!o.scanned,markdown:!!o.markdown,labels:o.labels||[]}}async function V(e,n,{name:d,hint:l="",title:i="",source:o={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const s=await Oe(n,d,l),x=Ot(s.pages.map(c=>c.text).join(`
|
|
3
|
+
`));if(k&&x){const c=e.docs.find(a=>a.textHash===x&&a.id!==r);if(c)return{duplicateOf:c}}const T=o.path&&s.links?.length?Tt(o.path,s.links,{root:f||Ie(o.path)}):[],t=ie(e,{id:r,title:i||s.title||W(d),pages:s.pages,source:{kind:o.kind||"bytes",name:d,...o},hash:s.hash||"",type:s.type,reach:u,now:v,links:T,textHash:x,markdownHeadings:!!s.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...s.scanned?{scanned:!0}:{}}}function _e(e,n){const d=Z(e).toLowerCase();return!Se.has(d)&&!Mt.has(d)?!1:n?.length?n.some(l=>{const i=String(l).toLowerCase().replace(/^\*/,"");return d===(i.startsWith(".")?i:`.${i}`)||e.toLowerCase().endsWith(i)}):!0}function fe(e,{recursive:n=!0,include:d=null}={}){const l=At(e,{home:H,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const i=me(Fe(e.replace(/^~(?=$|\/)/,H))),o=[],u=[];let r=0;const f=(x,T)=>{if(o.length>=U.files)return u.push({path:T,why:`stopped at ${U.files} files`}),!1;if(ve(x))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ae(x)}catch{return!0}const c=Z(x).toLowerCase(),a=Se.has(c)||Lt.has(c)?le:U.textBytes;return t.size>a?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>U.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,o.push({full:x,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ae(i).isDirectory())return f(i,W(i)),{root:i,files:o,skipped:u,single:!0};const s=(x,T,t)=>{if(t>U.depth)return!0;let c=[];try{c=Be(x,{withFileTypes:!0}).sort((a,h)=>a.name.localeCompare(h.name))}catch{return!0}for(const a of c){const h=a.name;if(h.startsWith(".")&&a.isDirectory())continue;const w=De(x,h),p=T?`${T}/${h}`:h;if(a.isDirectory()){if(Et.has(h)||!n)continue;try{if(!me(w).startsWith(i)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(w,p,t+1))return!1;continue}if(!(!a.isFile()&&!a.isSymbolicLink())){if(ve(w)){u.push({path:p,why:"withheld (a credential store)"});continue}if(_e(h,d)&&!f(w,p))return!1}}return!0};return s(i,"",0),{root:i,files:o,skipped:u}}async function Ee(e,{path:n,recursive:d=!0,include:l=null,title:i=""}){const{files:o,skipped:u,single:r}=fe(n,{recursive:d,include:l}),f=[];for(const k of o)try{const s=await V(e,oe(k.full),{name:W(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?i:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Pe(e,{path:n,include:d=null,rebuild:l=!1},{progress:i=null}={}){const{root:o,files:u,skipped:r}=fe(n,{recursive:!0,include:d}),f=vt(e,o,{include:d});if(l){for(const p of Object.values(f.files))p?.id&&q(e,p.id,{now:v});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,O]of Object.entries(f.files))O?.dupOf&&!k.has(O.dupOf)&&delete f.files[p];const s=yt({known:St(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});i&&(i.total=s.add.length+s.change.length,i.done=0);const x=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){q(e,p,{now:v});for(const[O,E]of Object.entries(f.files))E.id===p&&(delete f.files[O],T.push(O.startsWith(`${o}/`)?O.slice(o.length+1):O))}const t=[],c=[],a=[],h=p=>String(p||"").startsWith(`${o}/`)?p.slice(o.length+1):p,w=async(p,O)=>{if(i?.cancel)return;await new Promise(_=>setImmediate(_));const E=x.get(p),j=wt(p);try{const _=await V(e,oe(p),{name:W(p),source:{kind:"file",path:p},reach:"internal",id:j,root:o,dedupe:!0});_.duplicateOf?(e.docs.some(R=>R.id===j)&&q(e,j,{now:v}),f.files[p]={id:j,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},a.push({path:E.rel,of:h(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:j,size:E.size,mtime:E.mtime},O.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}i&&(i.done+=1)};for(const p of s.add)await w(p,t);for(const p of s.change)await w(p.path,c);return f.syncedAt=v(),f.lastSync={at:f.syncedAt,added:t.length,changed:c.length,removed:T.length,same:s.same,duplicates:a.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:a.slice(0,20)},{root:o,added:t,changed:c,removed:T,same:s.same,duplicates:a,skipped:r}}async function Ae(e,{url:n,title:d=""}){if(!G)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await G().read({url:n,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const i=String(l.body.markdown||l.body.text||"");if(!i.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const o=te(i).map((r,f)=>({page:f+1,text:r})),u=ie(e,{title:d||l.body.title||n,pages:o,source:{kind:"url",url:l.body.url||n,name:l.body.title||""},type:"html",reach:"web",now:v});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function je(e,n,{admin:d=!1}={}){const l=v();let i=[],o=[];if(n.kind==="bytes"){const r=Buffer.from(n.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>le)return g(413,"too_large",`kb: ${r.length} bytes is over the ${le}-byte limit`);try{i.push(await V(e,r,{name:n.name,hint:n.type||"",title:n.title,reach:n.reach}))}catch(f){return Y(f)}}else if(n.kind==="path"){if(!d)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:i,skipped:o}=await Ee(e,n))}catch(r){return Y(r)}}else if(n.kind==="url")try{i.push(await Ae(e,n))}catch(r){return Y(r)}else if(n.kind==="text"){const r=te(n.text).map((k,s)=>({page:s+1,text:k})),f=ie(e,{title:n.title||n.name,pages:r,source:{kind:"text",name:n.name},type:"text",reach:n.reach,now:v});i.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=i.length?await I(e):0;return y.save(e),S({added:i,skipped:o,embedded:u,kb:P(e,d),ms:v()-l})}function Y(e){const n=e?.code||"";return n==="refused"?g(403,"refused",`kb: ${e.message}`):n==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):n==="too_large"?g(413,"too_large",`kb: ${e.message}`):n==="read_failed"||n==="empty"?g(502,"read_failed",`kb: ${e.message}`):n==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ke=e=>e.vectors?.model&&e.vectors.model!==N()?null:ne("query"),re=(e,n)=>Ue(e,n.query,{limit:n.limit,hops:n.hops,docs:n.docs||null,queries:n.queries||[],...n.filters?{filters:n.filters}:{},embed:Ke(e),rerank:n.rerank===!1?null:Te,now:v}),Le=(e,n)=>e.docs.find(d=>d.id===n)?.title||n,pe=(e,n)=>{const d=ce(e,n);if(!d)return null;const l=d.kind==="note"?"Note":Le(e,d.doc);return{...d,title:l,cite:d.kind==="note"?`[note ${d.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${d.page}]`}};function Me(e,n){ee(e);const d=n.node.replace(/^chunk:/,""),l=(/#\d+$/.test(d)&&ce(e,d)?{id:`chunk:${d}`,kind:"chunk",label:d}:null)||ke(e.graph,n.node);if(!l)return S({node:null,neighbours:[],message:`no node named "${n.node}"`});const i=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},o=Qe(e,l.id,{limit:Math.min(8,n.limit||6),...n.query?{query:n.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:qe(e.graph,l.id,{hops:n.hops,kinds:n.kinds||null,limit:n.limit}),passages:o.passages,next:o.next};if(n.to){const r=ke(e.graph,n.to);u.to=n.to,u.path=r?(et(e.graph,l.id,r.id)||[]).map(i):null,r&&!u.path.length&&(u.path=null)}return S(u)}async function Ge(e,n,{admin:d=!1}={}){if(n.model&&!d)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=n.model&&typeof F=="function"?F(n.model):null,i=P(e,d),o=await Ze(n.question,{search:async(u,r)=>{const f=await re(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||n.docs||null});return f&&Array.isArray(f.results)?{...f,results:f.results.map(k=>({...k,kb:e.id}))}:f},outline:async u=>u?ye(e.chunks,{doc:u}):e.outline,read:async u=>{const r=pe(e,u);return r&&{...r,kb:e.id}},complete:l,kbName:e.name,docs:i.documents,previous:n.previous||null,answer:n.answer||"",ask:n.ask!==!1,now:v});return S({attachment:o.attachment,read:o.read,hits:o.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:o.queries,verdict:o.verdict,rounds:o.rounds,ask:o.ask,how:o.how,frame:{whole:o.frame.whole,docs:o.frame.docs},ms:o.ms})}const L=new Map;function he(e,n){const d=P(e,n),l=e.chunks.length?e.chunks.filter(o=>o.form||o.label).length/e.chunks.length:1,i=n?(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0,...o.lastSync?{lastSync:{at:o.lastSync.at,added:o.lastSync.added,changed:o.lastSync.changed,removed:o.lastSync.removed,skipped:o.lastSync.skipped}}:{}})):(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0}));return mt({...d,coverage:d.chunks?Math.round(d.vectors/d.chunks*100):0,placed:l,sources:i,...L.has(e.id)?{syncing:(({done:o,total:u})=>({done:o,total:u}))(L.get(e.id).progress)}:{}},{outline:e.outline,team:C(e.id),now:v()})}async function ze({method:e="GET",pathname:n="",query:d=new URLSearchParams,body:l=null,admin:i=!1,agent:o="",local:u=!0}={}){const r=nt(n);if(!r)return g(404,"not_found",`no route ${n}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ht.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:i,agent:String(o||d.get("agent")||"").trim().toLowerCase()},k=t=>{try{return{value:t()}}catch(c){return{res:g(400,"invalid_request",c.message)}}};if(!r.id){if(e==="GET"&&d.get("view")==="card"){const t=[];for(const{manifest:a}of y.list()){if(!de({access:a.access},f))continue;const h=y.load(a.id);h&&t.push(he(h,i))}const c=i&&typeof m=="function"?await m({admin:i}).catch(a=>[{gateway:"remote",error:a.message}]):[];return S({cards:t,...c.length?{remote:c}:{}})}if(e==="GET")return S({kbs:y.list().filter(({manifest:t})=>de({access:t.access},f)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=k(()=>st(l||{}));if(t.res)return t.res;const c=t.value;if(c.id&&y.load(c.id))return S({kb:P(y.load(c.id),i),existed:!0});const a=be({id:c.id,name:c.name,embed:c.embed,now:v});return y.save(a),{status:201,body:{kb:P(a,i)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!i)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(C(r.id))return J(r.id);const t=k(()=>ut(l||{}));if(t.res)return t.res;const c=t.value,a=L.get(r.id);if(a)return{status:202,body:{running:!0,progress:{...a.progress},kb:a.base?P(a.base,i):null}};let h=y.load(r.id);const w=!h;h||(h=be({id:r.id,name:c.name||W(String(c.path).replace(/[\\/]+$/,""))||r.id,now:v}),y.save(h));const p=v(),O={done:0,total:0},E=(async()=>{const b=await Pe(h,c,{progress:O});if(O.cancel)return{cancelled:!0};const M=b.added.length+b.changed.length+b.removed.length,B=b.added.length||b.changed.length?await I(h):0;return(M||w)&&y.save(h),{folder:b.root,added:b.added,changed:b.changed,removed:b.removed,same:b.same,duplicates:b.duplicates,skipped:b.skipped,embedded:B,made:w,kb:P(h,i),ms:v()-p}})();L.set(r.id,{progress:O,base:h}),E.catch(b=>z(`[kb] ${r.id}: sync failed — ${b?.message||b}`)).finally(()=>L.delete(r.id));const j=c.waitMs??5e3;if(j===0)return{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}};let _=null;const R=new Promise(b=>{_=setTimeout(()=>b(null),j)});let Q;try{Q=await Promise.race([E,R])}catch(b){return clearTimeout(_),Y(b)}return clearTimeout(_),Q?S(Q):{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}}}const s=y.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const x=C(s.id)?.role==="replica",T=!!C(s.id);if(!de(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){L.has(s.id)||ue(s);const t=P(s,i),c=i?(s.sources||[]).map(a=>({kind:a.kind,path:a.path,files:Object.keys(a.files||{}).length,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:a.lastSync}:{}})):void 0;return S({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:y.sizeOf(s.id),dir:i?y.dirOf(s.id):void 0,...c?.length?{sources:c}:{},...L.has(s.id)?{syncing:(({done:a,total:h})=>({done:a,total:h}))(L.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!i)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=L.get(s.id);return t&&(t.progress.cancel=!0),y.remove(s.id),S({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>rt(l||{}));return t.res?t.res:je(s,t.value,{admin:i})}if(e==="DELETE"&&r.rest)return i?q(s,r.rest,{now:v})?(y.save(s),S({ok:!0,kb:P(s,i)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const t=Number(d.get("page"))||1,c=Ye(s,r.rest,t);return c?S(c):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return S({documents:P(s,i).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=pe(s,r.rest);return t?S(t):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){ee(s);const t=d.get("doc");return S({outline:t?ye(s.chunks,{doc:t}):s.outline})}break}case"search":{if(e==="POST"){const t=k(()=>ot(l||{}));if(t.res)return t.res;const c=v(),a=await re(s,t.value);return ue(s),S({...a,ms:v()-c})}break}case"research":{if(e==="POST"){const t=k(()=>at(l||{}));return t.res?t.res:Ge(s,t.value,{admin:i})}break}case"graph":{if(e==="GET")return S(Gt(s,{limit:pt(d.get("limit"))}));if(e==="POST"){const t=k(()=>it(l||{}));return t.res?t.res:Me(s,t.value)}break}case"report":{if(e==="GET")return ee(s),{status:200,text:tt(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return S({notes:s.notes});if(x&&e==="POST")return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>ct(l||{}));if(t.res)return t.res;const c=t.value,a=c.status==="accepted"&&i?"accepted":"proposed",h=Re(s,{text:c.text,cites:c.cites||[],by:c.by||(i?"user":"agent"),status:a,now:v});return await I(s),y.save(s),{status:201,body:{note:h}}}if(e==="POST"&&r.rest){if(!i)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=k(()=>dt(l||{}));if(t.res)return t.res;const c=t.value,a=We(s,r.rest,c.status,{now:v});return a?(y.save(s),S({note:a,removed:c.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return S({access:s.access});if(x&&e==="POST")return J(s.id);if(e==="POST"){if(!i)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>lt(l||{}));if(t.res)return t.res;const c=Je(s,t.value,{now:v});return y.save(s),S({access:c})}break}case"pages":{if(e!=="GET")break;const t=d.get("doc")||s.docs[0]?.id,c=s.docs.find(a=>a.id===t);return c?S(bt(s.chunks,c)):g(404,"not_found",`kb: no document ${t||""}`)}case"view":{if(e!=="GET")break;const t=d.get("original");if(t){const b=s.docs.find(Ce=>Ce.id===t),M=b?.source?.kind==="file"?String(b.source.path||""):"",B=$e[Z(M).toLowerCase()];if(!M||!B)return g(404,"not_found","kb: no original on this machine for that document");let ge;try{ge=oe(M)}catch{return g(404,"not_found","kb: the original is no longer where it was read")}return{status:200,text:ge,contentType:B,headers:{"content-security-policy":"sandbox","x-content-type-options":"nosniff"}}}const c=d.get("passage")||"",a=c&&ce(s,c);if(!a)return g(404,"not_found",`kb: no passage ${c.slice(0,80)}`);const h=s.docs.find(b=>b.id===a.doc)||{id:a.doc,title:a.doc},w=a.page||1,p=s.chunks.filter(b=>b.doc===a.doc&&(b.page||1)<=w&&(b.pageEnd||b.page||1)>=w),O=b=>{const M=s.chunks.find(B=>B.doc===a.doc&&(B.page||1)===b);return M?`?passage=${encodeURIComponent(M.id)}`:""},E=h.source?.kind==="file"?String(h.source.path||""):"",j=Z(E).toLowerCase(),_=String(a.text||"").replace(/\s+/g," ").trim().split(" ").slice(0,6).join(" "),R=h.source?.kind==="url"&&/^https?:\/\//.test(h.source.url||"")?`${h.source.url}#:~:text=${encodeURIComponent(_)}`:$e[j]?`?original=${encodeURIComponent(h.id)}${j===".pdf"?`#page=${w}`:""}`:"";return{status:200,text:kt({base:s.name||s.id,doc:{title:h.title,pages:h.pages,original:R},page:w,label:a.label||"",passages:p.map(b=>({id:b.id,text:b.text,section:b.section?String(b.section).split(" › ").slice(-2).join(" › "):""})),cited:a.id,prev:w>1?O(w-1):"",next:O(w+1)}),contentType:"text/html; charset=utf-8",headers:{"content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}}}case"reveal":{if(e!=="POST")break;if(!i)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(xe())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(C(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof X!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>ft(l||{}));if(t.res)return t.res;const c=t.value;let a="",h="file";if(c.doc){const w=s.docs.find(p=>p.id===c.doc);if(!w)return g(404,"not_found",`kb: no document ${c.doc}`);a=w.source?.path||"",a||(a=y.dirOf(s.id),h="index")}else if(c.source!=null){const w=(s.sources||[])[c.source];if(!w?.path)return g(404,"not_found",`kb: no kept folder ${c.source}`);a=w.path,h="folder"}else{const w=(s.sources||[]).find(p=>p.path);a=w?.path||y.dirOf(s.id),h=w?"folder":"index"}try{ae(a)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await X(a,{folder:h!=="file"})}catch(w){return g(502,"reveal_failed",`kb: the file manager did not open — ${w.message}`)}return S({ok:!0,revealed:h})}case"embed":{if(e==="POST"){const t=N(),c=$&&t?$.health("embed",t):{state:"off"},a=await I(s);return a&&y.save(s),S({embedded:a,vectors:s.vectors.by.size,model:s.vectors.model||t,dims:s.vectors.dims,state:c.state,...c.progress?{progress:c.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${n} is not a route`)}function J(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:ze,store:y,embedModel:N,cardOf:he,addBytes:(e,n,d)=>V(e,n,d),embedAll:e=>I(e),searchBase:(e,n)=>re(e,n)}}export{U as KB_WALK_LIMITS,qt as createKbService,P as kbStatusFor,Gt as wholeGraph};
|
package/src/server.js
CHANGED
|
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
|
38
38
|
|
|
39
39
|
`),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:oe.get(n),after:m}});const h=oe.watch(n,w=>{w.seq==null?l(w):w.seq>m&&(m=w.seq,l(w))});for(const w of oe.eventsSince(n,m))m=w.seq,l(w);const f=setInterval(()=>{try{o.write(`: keep-alive
|
|
40
40
|
|
|
41
|
-
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=R.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});if(go||=rn({store:e,notify:Ge}),await nn(r,o,{pathname:i,api:go,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:ye.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=$s(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await As(s,f=>R.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!L(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),K=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),fe=await K.json().catch(()=>({}));return K.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await fn(n,{store:R,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gn(n,f,{size:R.size,newest:R.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await be().handle({method:r.method,pathname:i,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Da]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await k(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ss({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>gs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:L(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8"}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Us))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Wn((re,xe)=>Vn(T,{salt:re,iterations:xe})):null,K=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Kn(Qn,re.blob.compression):null;return Fn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:K});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ae)try{m.write(`event: deleted
|
|
41
|
+
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=R.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});if(go||=rn({store:e,notify:Ge}),await nn(r,o,{pathname:i,api:go,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:ye.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=$s(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await As(s,f=>R.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!L(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),K=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),fe=await K.json().catch(()=>({}));return K.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await fn(n,{store:R,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gn(n,f,{size:R.size,newest:R.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await be().handle({method:r.method,pathname:i,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Da]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await k(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ss({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>gs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:L(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Us))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Wn((re,xe)=>Vn(T,{salt:re,iterations:xe})):null,K=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Kn(Qn,re.blob.compression):null;return Fn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:K});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ae)try{m.write(`event: deleted
|
|
42
42
|
data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
|
|
43
43
|
|
|
44
44
|
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:Q.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:Gn(m?.source))===ko,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${ko}" is this gateway's own log`})),d=Ln(Q,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=jn(Q.all());return a(o,200,{ok:!0,stats:e,year:zn(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=So(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=Q.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>_t(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=So(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.153.2";export{o as VERSION};
|