@chatpanel/gateway 0.144.1 → 0.147.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +2 -2
- package/src/configstore.js +1 -1
- package/src/context.js +1 -0
- package/src/egress.js +2 -2
- package/src/extract/pdf.js +1 -1
- package/src/kb-bucket-sync.js +1 -0
- package/src/kb-store.js +2 -2
- package/src/kb.js +3 -3
- package/src/mcp.js +23 -22
- package/src/reveal.js +1 -0
- package/src/server.js +32 -32
- package/src/version.js +1 -1
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.147.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.485.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{patchApis as $,viewApis as H}from"./retrieval/search-apis.js";import{writeFileSync as B,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as z,EMBEDDED_IDS as D,isEmbeddedModel as K}from"./embedded-models.js";import{capabilityList as g,isProviderList as O,listProblems as W,primaryProvider as Y,storedShape as _}from"./capability-config.js";import{normalizeRegistries as Z,REGISTRY_KINDS as Q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as E}from"@chatpanel/pii";import{normalizeGrant as x}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as N,parseWrapperTemplate as V}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as k}from"@chatpanel/events/policy.js";const p=["open","allowlist","off"],T=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0")),m=e=>Object.assign(new Error(e),{code:"SHAPE"}),L=/^[A-Za-z0-9][\w.-]{0,63}$/,ee=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function oe(e,{strict:r=!1}={}){const o={};if(!e||typeof e!="object"||Array.isArray(e))return o;for(const[i,t]of Object.entries(e))if(t!=null)try{if(!L.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const n=x(t);ee(n)||(o[i]=n)}catch(n){if(r)throw m(`sandbox.agents.${i}: ${n.message}`)}return o}function f(e={},{strict:r=!1}={}){const o=e&&typeof e=="object"?e:{};if(r&&o.mode!==void 0&&!p.includes(o.mode))throw m(`sandbox.mode must be one of ${p.join(", ")} — got ${JSON.stringify(o.mode)}`);const i=p.includes(o.mode)?o.mode:"open";if(r&&o.reads!==void 0&&!A.includes(o.reads))throw m(`sandbox.reads must be one of ${A.join(", ")} — got ${JSON.stringify(o.reads)}`);const t=A.includes(o.reads)?o.reads:A[0];if(r&&o.required!==void 0&&typeof o.required!="boolean")throw m(`sandbox.required must be true or false — got ${JSON.stringify(o.required)}`);if(r&&o.required===!0&&o.mode==="off")throw m("the sandbox cannot be required while it is off — choose open or allowlist first");const n=o.required===!0&&i!=="off";if(r&&o.runtime!==void 0&&!N.includes(o.runtime))throw m(`sandbox.runtime must be one of ${N.join(", ")} — got ${JSON.stringify(o.runtime)}`);const s=N.includes(o.runtime)?o.runtime:"srt";let d="";if(o.command!==void 0&&String(Array.isArray(o.command)?o.command.join(""):o.command).trim())try{V(o.command),d=Array.isArray(o.command)?JSON.stringify(o.command):String(o.command).trim()}catch(l){if(r)throw m(`sandbox.command: ${l.message.replace(/^sandbox command: /,"")}`);d=""}const a=typeof o.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(o.image.trim())?o.image.trim():"";if(r&&o.image!==void 0&&String(o.image).trim()&&!a)throw m("sandbox.image must be an image reference (registry/name:tag)");const u=["podman","docker"].includes(o.engine)?o.engine:"";if(r&&s==="command"&&!d)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(r&&s==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:y}=x({hosts:o.hosts??[]}),b=oe(o.agents,{strict:r});return{mode:i,reads:t,required:n,runtime:s,command:d,image:a,engine:u,hosts:y,write:T(o.write),denyRead:T(o.denyRead),...Object.keys(b).length?{agents:b}:{}}}const re=["off","0","false"],S=e=>String(e||"").split(",").map(r=>r.trim()).filter(Boolean),v=(...e)=>[...new Set(e.flat())];function c(e=process.env){const r=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return A.includes(r)?r:""}function w(e=process.env){const r=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return r?re.includes(r)?{mode:"off"}:p.includes(r)?{mode:r}:{unknown:r}:{}}function ce(e,r=process.env){const o=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!p.includes(i.mode)&&o.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${p.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[a,u]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!L.test(a))throw new Error("not an agent id");x(u)}catch(y){o.push(`sandbox.agents.${a} in the config is not valid and is ignored — ${y.message}`)}const t=w(r),n=f(i).mode;t.unknown&&o.push(`CHATPANEL_SANDBOX="${t.unknown}" in this process's environment is not one of ${p.join(", ")} — ignored; the config's "${n}" applies`),t.mode&&t.mode!==n&&o.push(`the sandbox mode is "${t.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${n}"; Settings › Runtime cannot change it while that variable is set`);const s=c(r),d=f(i).reads;return s&&s!==d&&o.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${d}"; Settings › Runtime cannot change it while that variable is set`),o}function we(e,r=process.env,o=null){const i=f(e?.sandbox),{sandbox:t}=k(i,o);Array.isArray(t.command)&&(t.command=JSON.stringify(t.command));const n=w(r);let s={};try{const a=JSON.parse(r.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(s=a)}catch{}const d={...s,...t.agents||{}};return{CHATPANEL_SANDBOX:o?.sandbox?.mode||n.mode||t.mode,CHATPANEL_SANDBOX_RUNTIME:t.runtime,CHATPANEL_SANDBOX_COMMAND:t.command||"",CHATPANEL_SANDBOX_IMAGE:t.image||"",CHATPANEL_SANDBOX_ENGINE:t.engine||"",CHATPANEL_SANDBOX_READS:o?.sandbox?.reads||c(r)||t.reads,CHATPANEL_SANDBOX_REQUIRED:t.required==="policy"?"policy":String(r.CHATPANEL_SANDBOX_REQUIRED||"")||(t.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:v(t.hosts,S(r.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:v(t.write,S(r.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:v(t.denyRead,S(r.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(d).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(d)}:{}}}function h(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||G(q.homedir(),".chatpanel","gateway.config.json")}function ge(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function P(e,r,o){o?e.capabilities[r]=o:delete e.capabilities[r]}function R(e,r,o,i){if(o.provider==="endpoint")return(typeof o.endpoint!="string"||!/^[\w.:-]{1,80}$/.test(o.endpoint))&&i(`capabilities.${e}: an endpoint provider names its endpoint`),(typeof o.model!="string"||!o.model.trim()||o.model.length>200)&&i(`capabilities.${e}: an endpoint provider names its model`),(typeof o.adapter!="string"||!/^[a-z-]{2,40}$/.test(o.adapter))&&i(`capabilities.${e}: an endpoint provider names its adapter`),{provider:"endpoint",endpoint:o.endpoint,model:o.model.trim(),adapter:o.adapter,...typeof o.id=="string"&&o.id?{id:o.id}:{},...typeof o.label=="string"&&o.label.length<=160?{label:o.label}:{},...typeof o.redact=="boolean"?{redact:o.redact}:{},...typeof o.voice=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(o.voice)?{voice:o.voice}:{}};if(o.provider==="embedded")return D.includes(e)&&o.model!=null?(K(e,o.model)||i(`capabilities.${e}.model must be one of ${z[e].map(n=>n.id).join(", ")}`),{provider:"embedded",model:o.model}):{provider:"embedded"};if(o.provider==="none"&&D.includes(e))return{provider:"none"};const t={...r};if("url"in o){const n=String(o.url||"").trim();n&&E(n);const s=d=>{try{return new URL(d).origin}catch{return d}};r.url&&n&&s(r.url)!==s(n)&&typeof o.token!="string"&&delete t.token,t.url=n}return typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(t.adapter=o.adapter),typeof o.model=="string"&&(t.model=o.model.trim()),typeof o.token=="string"&&(t.token=o.token),typeof o.calibrated=="boolean"&&(t.calibrated=o.calibrated),typeof o.redact=="boolean"&&(t.redact=o.redact),t.url?(t.provider="remote",delete t.service,delete t.hasToken,t):null}const j=e=>{const{token:r,...o}=e||{};return{...o,hasToken:!!r}};function Ee(e,r=h()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===h({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);M(U(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};B(r,JSON.stringify(o,null,2),{mode:384});try{X(r,384)}catch{}}function xe(e,{proUnlocked:r=!1,policy:o=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:t,...n}=i;return{...n,hasKey:!!t}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:t}=k(f(e.sandbox),o);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...w().mode?{envMode:w().mode}:{},...c()?{envReads:c()}:{},...t.length?{locked:t,lockedBy:o?.org?.name||"your organisation"}:{}}})(),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:H(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,t])=>[i,O(t)?{...t,providers:t.providers.map(j)}:j(t)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:F(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function Ne(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function ie(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const I=["default","acceptEdits","bypassPermissions"];function Se(e,r={}){const o=e?.bridge||{};return{...I.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function ve(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=ie(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(d=>typeof d=="string"&&d):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const d=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;d&&(t.apiKey=d)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;n&&(t.service=n),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(t.fromEndpoint=!0);const s=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return s&&(t.endpointId=s),t}).filter((i,t,n)=>!i.endpointId||n.findIndex(s=>s.endpointId===i.endpointId)===t)}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),I.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"){const o=f(e.sandbox),i={...o,...r.sandbox};r.sandbox.agents&&typeof r.sandbox.agents=="object"&&!Array.isArray(r.sandbox.agents)&&(i.agents={...o.agents||{},...r.sandbox.agents}),e.sandbox=f(i,{strict:!0})}if(r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&E(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=Z(r.registries),i={...e.registries||{}};for(const t of Q)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&E(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}"apis"in r.search&&(e.search.apis=$(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=J(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};const o=i=>{const t=new Error(i);throw t.code="SHAPE",t};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const t=r.capabilities[i];if(t===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!(!t||typeof t!="object")){if(O(t)){const n=W(i,t);n.length&&o(n[0]);const s=g(e.capabilities[i],i).providers,d=[];for(const a of t.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=s.find(C=>C.service===a.service);l&&d.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},y=(typeof a.id=="string"?s.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?s.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,y,a,o);b&&d.push(typeof a.id=="string"?{...b,id:a.id}:b)}P(e,i,_({mode:t.mode??g(e.capabilities[i],i).mode,providers:d},i))}else{const n=g(e.capabilities[i],i),s=R(i,n.providers[0]||{},t,o);P(e,i,_({mode:n.mode,providers:s?[s,...n.providers.slice(1)]:n.providers.slice(1)},i))}if(i==="detect"){const n=Y(e.capabilities[i],i);n?.url&&n.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{I as PERMISSION_MODES,p as SANDBOX_MODES,ve as applyConfigPatch,Ne as applyNerModelSelection,Se as bridgeAgentOptions,h as configPath,ie as isSelfDestination,f as normalizeSandboxConfig,Ee as persistConfig,xe as publicConfig,ge as registryChildEnv,we as sandboxEnvFor,w as sandboxModeFromEnv,ce as sandboxProblems,c as sandboxReadsFromEnv};
|
|
1
|
+
import{patchApis as $,viewApis as H}from"./retrieval/search-apis.js";import{writeFileSync as B,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as z,EMBEDDED_IDS as D,isEmbeddedModel as K}from"./embedded-models.js";import{capabilityList as x,isProviderList as O,listProblems as W,primaryProvider as Y,storedShape as _}from"./capability-config.js";import{normalizeRegistries as Z,REGISTRY_KINDS as Q}from"@chatpanel/events/registries.js";import{viewContextProviders as V}from"@chatpanel/events/context-providers.js";import{assertEndpointUrl as E}from"@chatpanel/pii";import{normalizeGrant as g}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as N,parseWrapperTemplate as ee}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as k}from"@chatpanel/events/policy.js";const p=["open","allowlist","off"],T=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0")),m=e=>Object.assign(new Error(e),{code:"SHAPE"}),L=/^[A-Za-z0-9][\w.-]{0,63}$/,oe=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function re(e,{strict:r=!1}={}){const o={};if(!e||typeof e!="object"||Array.isArray(e))return o;for(const[i,t]of Object.entries(e))if(t!=null)try{if(!L.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const n=g(t);oe(n)||(o[i]=n)}catch(n){if(r)throw m(`sandbox.agents.${i}: ${n.message}`)}return o}function y(e={},{strict:r=!1}={}){const o=e&&typeof e=="object"?e:{};if(r&&o.mode!==void 0&&!p.includes(o.mode))throw m(`sandbox.mode must be one of ${p.join(", ")} — got ${JSON.stringify(o.mode)}`);const i=p.includes(o.mode)?o.mode:"open";if(r&&o.reads!==void 0&&!A.includes(o.reads))throw m(`sandbox.reads must be one of ${A.join(", ")} — got ${JSON.stringify(o.reads)}`);const t=A.includes(o.reads)?o.reads:A[0];if(r&&o.required!==void 0&&typeof o.required!="boolean")throw m(`sandbox.required must be true or false — got ${JSON.stringify(o.required)}`);if(r&&o.required===!0&&o.mode==="off")throw m("the sandbox cannot be required while it is off — choose open or allowlist first");const n=o.required===!0&&i!=="off";if(r&&o.runtime!==void 0&&!N.includes(o.runtime))throw m(`sandbox.runtime must be one of ${N.join(", ")} — got ${JSON.stringify(o.runtime)}`);const s=N.includes(o.runtime)?o.runtime:"srt";let d="";if(o.command!==void 0&&String(Array.isArray(o.command)?o.command.join(""):o.command).trim())try{ee(o.command),d=Array.isArray(o.command)?JSON.stringify(o.command):String(o.command).trim()}catch(l){if(r)throw m(`sandbox.command: ${l.message.replace(/^sandbox command: /,"")}`);d=""}const a=typeof o.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(o.image.trim())?o.image.trim():"";if(r&&o.image!==void 0&&String(o.image).trim()&&!a)throw m("sandbox.image must be an image reference (registry/name:tag)");const u=["podman","docker"].includes(o.engine)?o.engine:"";if(r&&s==="command"&&!d)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(r&&s==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:f}=g({hosts:o.hosts??[]}),b=re(o.agents,{strict:r});return{mode:i,reads:t,required:n,runtime:s,command:d,image:a,engine:u,hosts:f,write:T(o.write),denyRead:T(o.denyRead),...Object.keys(b).length?{agents:b}:{}}}const ie=["off","0","false"],S=e=>String(e||"").split(",").map(r=>r.trim()).filter(Boolean),v=(...e)=>[...new Set(e.flat())];function c(e=process.env){const r=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return A.includes(r)?r:""}function w(e=process.env){const r=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return r?ie.includes(r)?{mode:"off"}:p.includes(r)?{mode:r}:{unknown:r}:{}}function xe(e,r=process.env){const o=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!p.includes(i.mode)&&o.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${p.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[a,u]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!L.test(a))throw new Error("not an agent id");g(u)}catch(f){o.push(`sandbox.agents.${a} in the config is not valid and is ignored — ${f.message}`)}const t=w(r),n=y(i).mode;t.unknown&&o.push(`CHATPANEL_SANDBOX="${t.unknown}" in this process's environment is not one of ${p.join(", ")} — ignored; the config's "${n}" applies`),t.mode&&t.mode!==n&&o.push(`the sandbox mode is "${t.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${n}"; Settings › Runtime cannot change it while that variable is set`);const s=c(r),d=y(i).reads;return s&&s!==d&&o.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${d}"; Settings › Runtime cannot change it while that variable is set`),o}function Ee(e,r=process.env,o=null){const i=y(e?.sandbox),{sandbox:t}=k(i,o);Array.isArray(t.command)&&(t.command=JSON.stringify(t.command));const n=w(r);let s={};try{const a=JSON.parse(r.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(s=a)}catch{}const d={...s,...t.agents||{}};return{CHATPANEL_SANDBOX:o?.sandbox?.mode||n.mode||t.mode,CHATPANEL_SANDBOX_RUNTIME:t.runtime,CHATPANEL_SANDBOX_COMMAND:t.command||"",CHATPANEL_SANDBOX_IMAGE:t.image||"",CHATPANEL_SANDBOX_ENGINE:t.engine||"",CHATPANEL_SANDBOX_READS:o?.sandbox?.reads||c(r)||t.reads,CHATPANEL_SANDBOX_REQUIRED:t.required==="policy"?"policy":String(r.CHATPANEL_SANDBOX_REQUIRED||"")||(t.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:v(t.hosts,S(r.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:v(t.write,S(r.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:v(t.denyRead,S(r.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(d).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(d)}:{}}}function P(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||G(q.homedir(),".chatpanel","gateway.config.json")}function ge(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function h(e,r,o){o?e.capabilities[r]=o:delete e.capabilities[r]}function R(e,r,o,i){if(o.provider==="endpoint")return(typeof o.endpoint!="string"||!/^[\w.:-]{1,80}$/.test(o.endpoint))&&i(`capabilities.${e}: an endpoint provider names its endpoint`),(typeof o.model!="string"||!o.model.trim()||o.model.length>200)&&i(`capabilities.${e}: an endpoint provider names its model`),(typeof o.adapter!="string"||!/^[a-z-]{2,40}$/.test(o.adapter))&&i(`capabilities.${e}: an endpoint provider names its adapter`),{provider:"endpoint",endpoint:o.endpoint,model:o.model.trim(),adapter:o.adapter,...typeof o.id=="string"&&o.id?{id:o.id}:{},...typeof o.label=="string"&&o.label.length<=160?{label:o.label}:{},...typeof o.redact=="boolean"?{redact:o.redact}:{},...typeof o.voice=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(o.voice)?{voice:o.voice}:{}};if(o.provider==="embedded")return D.includes(e)&&o.model!=null?(K(e,o.model)||i(`capabilities.${e}.model must be one of ${z[e].map(n=>n.id).join(", ")}`),{provider:"embedded",model:o.model}):{provider:"embedded"};if(o.provider==="none"&&D.includes(e))return{provider:"none"};const t={...r};if("url"in o){const n=String(o.url||"").trim();n&&E(n);const s=d=>{try{return new URL(d).origin}catch{return d}};r.url&&n&&s(r.url)!==s(n)&&typeof o.token!="string"&&delete t.token,t.url=n}return typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(t.adapter=o.adapter),typeof o.model=="string"&&(t.model=o.model.trim()),typeof o.token=="string"&&(t.token=o.token),typeof o.calibrated=="boolean"&&(t.calibrated=o.calibrated),typeof o.redact=="boolean"&&(t.redact=o.redact),t.url?(t.provider="remote",delete t.service,delete t.hasToken,t):null}const j=e=>{const{token:r,...o}=e||{};return{...o,hasToken:!!r}};function Ne(e,r=P()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===P({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);M(U(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls,...e.context?{context:e.context}:{}};B(r,JSON.stringify(o,null,2),{mode:384});try{X(r,384)}catch{}}function Se(e,{proUnlocked:r=!1,policy:o=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:t,...n}=i;return{...n,hasKey:!!t}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:t}=k(y(e.sandbox),o);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...w().mode?{envMode:w().mode}:{},...c()?{envReads:c()}:{},...t.length?{locked:t,lockedBy:o?.org?.name||"your organisation"}:{}}})(),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:H(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,t])=>[i,O(t)?{...t,providers:t.providers.map(j)}:j(t)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:F(e)},context:{providers:V(e.context?.providers)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function ve(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function te(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const C=["default","acceptEdits","bypassPermissions"];function De(e,r={}){const o=e?.bridge||{};return{...C.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function Oe(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=te(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(d=>typeof d=="string"&&d):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const d=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;d&&(t.apiKey=d)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;n&&(t.service=n),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(t.fromEndpoint=!0);const s=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return s&&(t.endpointId=s),t}).filter((i,t,n)=>!i.endpointId||n.findIndex(s=>s.endpointId===i.endpointId)===t)}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),C.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"){const o=y(e.sandbox),i={...o,...r.sandbox};r.sandbox.agents&&typeof r.sandbox.agents=="object"&&!Array.isArray(r.sandbox.agents)&&(i.agents={...o.agents||{},...r.sandbox.agents}),e.sandbox=y(i,{strict:!0})}if(r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&E(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=Z(r.registries),i={...e.registries||{}};for(const t of Q)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&E(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}"apis"in r.search&&(e.search.apis=$(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=J(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};const o=i=>{const t=new Error(i);throw t.code="SHAPE",t};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const t=r.capabilities[i];if(t===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!(!t||typeof t!="object")){if(O(t)){const n=W(i,t);n.length&&o(n[0]);const s=x(e.capabilities[i],i).providers,d=[];for(const a of t.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=s.find(I=>I.service===a.service);l&&d.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},f=(typeof a.id=="string"?s.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?s.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,f,a,o);b&&d.push(typeof a.id=="string"?{...b,id:a.id}:b)}h(e,i,_({mode:t.mode??x(e.capabilities[i],i).mode,providers:d},i))}else{const n=x(e.capabilities[i],i),s=R(i,n.providers[0]||{},t,o);h(e,i,_({mode:n.mode,providers:s?[s,...n.providers.slice(1)]:n.providers.slice(1)},i))}if(i==="detect"){const n=Y(e.capabilities[i],i);n?.url&&n.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{C as PERMISSION_MODES,p as SANDBOX_MODES,Oe as applyConfigPatch,ve as applyNerModelSelection,De as bridgeAgentOptions,P as configPath,te as isSelfDestination,y as normalizeSandboxConfig,Ne as persistConfig,Se as publicConfig,ge as registryChildEnv,Ee as sandboxEnvFor,w as sandboxModeFromEnv,xe as sandboxProblems,c as sandboxReadsFromEnv};
|
package/src/context.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{validateContextRequest as j,searchContext as B,CONTEXT_FEDERATED_HEADER as K}from"@chatpanel/events/context-api.js";import{kbContextProvider as z,webContextProvider as _,bedrockContextProvider as L,gatewayContextProvider as D,patchContextProviders as G,viewContextProviders as H,sourcesOfProvider as U}from"@chatpanel/events/context-providers.js";import{gatewayKbClient as W}from"@chatpanel/events/kb-tool.js";import{buildApiRequest as N,readApiResponse as X}from"@chatpanel/events/search-api.js";const J=Object.freeze({allowLoopback:!1,allowPrivate:!1}),d=(c,y,g)=>({status:c,body:{error:{type:y,message:g}}}),p=c=>({status:200,body:c});function Z({cfg:c,kb:y,search:g=null,apiEngines:x=()=>[],redact:A=null,rerank:C=null,fetchFn:w=fetch,persist:R=()=>{},buckets:f=null,now:h=()=>Date.now(),log:q=()=>{}}={}){const $=()=>(Array.isArray(c.context?.providers)?c.context.providers:[]).filter(n=>n&&n.enabled!==!1);async function E(n){const t=async(r,o,i)=>{const s=await y().handle({method:r,pathname:o.split("?")[0],query:new URLSearchParams(o.split("?")[1]||""),body:i,admin:n.admin,agent:n.agent});if(s.status>=400)throw new Error(s.body?.error?.message||`kb ${s.status}`);return s.body};return((await t("GET","/v1/kb")).kbs||[]).map(r=>({id:r.id,name:r.name,client:W({call:t,kbId:r.id})}))}function b(n,{federated:t=!1}={}){const e=[z({bases:()=>E(n)})];typeof g=="function"&&e.push(_({id:"*",search:g,name:"web"}));for(const r of x().filter(o=>o.enabled!==!1)){const o=r.api.id;e.push(_({id:o,name:r.api.name,search:async(i,{limit:s,signal:m})=>{const u=N(r.api,{q:i,limit:s,vars:r.vars||{}}),a=await w(u.url,{method:u.method,headers:u.headers,body:u.body??void 0,signal:m,maxRedirects:0,policy:J});if(!a.ok)throw new Error(`${r.api.name} ${a.status}`);return{results:X(r.api,await a.json(),{limit:s}).map(l=>({...l,engine:`api:${o}`}))}}}))}if(!n.admin)return e;for(const r of $())try{r.kind==="bedrock"?e.push(L({id:r.id,name:r.name,region:r.region,knowledgeBaseId:r.knowledgeBaseId,credentials:{accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,...r.sessionToken?{sessionToken:r.sessionToken}:{}},fetch:(o,i)=>w(o,{...i,maxRedirects:0}),now:h})):r.kind==="gateway"&&!t&&e.push(D({id:r.id,name:r.name,url:r.url,token:r.token||"",trusted:r.trusted===!0,fetch:(o,i)=>w(o,{...i,maxRedirects:0})}))}catch(o){q(`[context] ${r.id}: not usable — ${o.message}`)}return e}async function T(n,t,{federated:e=!1,signal:r=null}={}){let o;try{o=j(n||{})}catch(s){return d(400,"invalid_request",s.message)}const i=await B({...o,providers:b(t,{federated:e}),redact:A,rerank:o.rerank?C:null,signal:r,now:h});if(!t.admin)for(const[s,m]of Object.entries(i.providers))m.error==="not configured"&&/^(bedrock|gw)/.test(s)&&(m.error="needs the gateway token");return p({query:o.query,...i})}function P(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}]:[],...x().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 H(c.context?.providers||[])){const r=(c.context?.providers||[]).find(i=>i.id===e.id),o=e.kind==="bucket"&&f?f.teamOf(e.kbId||e.id):null;t.push({...e,type:e.kind==="gateway"?"gw":e.kind==="bucket"?"kb":e.kind,source:U(r)[0],configured:!0,remote:e.kind!=="bucket",...o?{team:o}:{}})}return t}async function S(n){if(n.kind==="bucket")return f?f.test(n):{ok:!1,error:"no bucket client here"};if(n.kind==="gateway")try{const t=await w(`${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=b({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 O(){const n=$().filter(t=>t.kind==="gateway");return Promise.all(n.map(async t=>{try{const e=await w(`${t.url}/v1/kb?view=card`,{headers:{[K]:"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 I({method:n="GET",pathname:t="",body:e=null,admin:r=!1,agent:o="",federated:i=!1,signal:s=null}={}){const m={admin:r,agent:o};if(t==="/v1/context")return n!=="POST"?d(405,"method_not_allowed","context: POST"):T(e,m,{federated:i,signal:s});if(t==="/v1/context/providers"){if(n==="GET")return p({providers:P(m)});if(n==="POST"){if(!r)return d(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=G(c.context?.providers||[],a)}catch(k){return d(400,"invalid_request",k.message)}c.context={...c.context||{},providers:l};try{R()}catch(k){return d(500,"persist_failed",`context: could not save — ${k.message}`)}return f?.restart(),p({providers:P(m)})}return d(405,"method_not_allowed","context: GET or POST")}const u=/^\/v1\/context\/providers\/([a-z0-9][a-z0-9_-]{0,39})\/(test|sync|upload)$/.exec(t);if(u&&n==="POST"){if(!r)return d(403,"forbidden","context: needs the gateway token or the extension origin");const a=(c.context?.providers||[]).find(v=>v.id===u[1]);if(!a)return d(404,"not_found",`context: no provider ${u[1]}`);if(u[2]==="test")return p(await S(a));if(a.kind!=="bucket"||!f)return d(400,"invalid_request",`context: ${u[2]} is for a team bucket`);if(u[2]==="sync")return p(await f.run(a));const l=String(e?.name||"").replace(/\\/g,"/").replace(/^\/+/,"");if(!l||l.includes("..")||l.startsWith(".")||l.length>300)return d(400,"invalid_request","context: upload needs a file name (no .., not hidden)");const k=typeof e?.data=="string"?Buffer.from(e.data,"base64"):null;if(!k?.length)return d(400,"invalid_request","context: upload needs data (base64)");try{await f.upload(a,l,k)}catch(v){return d(502,"bucket_failed",v.message)}return a.role==="builder"&&f.run(a),p({ok:!0,key:`${a.prefix||""}${l}`,building:a.role==="builder"})}return d(404,"not_found",`no route ${t}`)}return{handle:I,remoteCards:O,providersFor:b,context:T}}export{Z as createContextService};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const P=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=P}={}){const t=new Map;return{record(a){const r=y(a);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((a,r)=>a.local===r.local?r.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let b=null;function O(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=A();let r=t;a.setGate=l=>{r=l},a.blocked=[];const u=l=>{let i=null;try{i=y(l),a.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:w(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;a.blocked.includes(o)||a.blocked.push(o);const n=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return n.code="EGRESS_POLICY",n},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=a,e===globalThis&&(b=a),a}function x(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function T(e={},t=process.env,a=process.platform,r=process.arch){const u=[],s=(n,p,{when:d="always",off:m=null,local:v=!1,data:k=""}={})=>{n&&u.push({host:n,purpose:p,when:d,off:m,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),e.runtime?.services?.llama?.build!=="system"&&(s("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),s("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),s("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:L(e.link||{}).relay;if(c){const n=new URL(c).host;s(n,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let n=l;try{n=new URL(l).host}catch{}s(n,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(n)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const n of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(n.api.host,`web search: ${n.api.name} (search API${n.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${n.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let n=e.read.remote.url;try{n=new URL(e.read.remote.url).host}catch{}s(n,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(n)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[n,p]of Object.entries(i))for(const d of S(e.capabilities?.[n],n,{destinations:e.destinations||[]}).providers){if(!d?.url||d.provider==="embedded")continue;let m=d.url;try{m=new URL(d.url).host}catch{}s(m,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${n}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${n} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(m)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[n,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:w(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of e.destinations||[])n?.baseUrl&&s(f(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:w(f(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const n=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function _(e,{ledger:t=x(),version:a="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=T(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(n=>n.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:a,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function q(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const a of e.link.partners||[]){const r=a.lastSeen?new Date(a.lastSeen).toISOString():"never";t.push(` partner:${a.partner} scopes: ${a.scopes.join(", ")||"none"} agents: ${a.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${a.route||"?"}${a.host?` via ${a.host}`:""} · last seen ${r}${a.online?" (online)":""}`),a.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${a.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${a.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,r])=>r===!0?a:`${a}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
-
`)}export{A as createEgressLedger,
|
|
1
|
+
import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const x=()=>new Date().toISOString();function y(e){try{const a=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),n=a.protocol.replace(":","");return{host:a.hostname,port:a.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const m=e=>{const a=String(e||"").toLowerCase();return a==="localhost"||a.endsWith(".localhost")||a==="::1"||a==="[::1]"?!0:g(a,{allowLoopback:!1,allowPrivate:!1})&&!g(a,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=x}={}){const a=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const p=`${r.scheme}://${r.host}:${r.port}`,o=e(),u=a.get(p);if(u){u.count+=1,u.lastAt=o;return}a.set(p,{host:r.host,port:r.port,scheme:r.scheme,local:m(r.host),count:1,firstAt:o,lastAt:o})},snapshot(){return[...a.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){a.clear()}}}let b=null;function N(e=globalThis,{allow:a=null}={}){if(e.__chatpanelEgress)return a&&e.__chatpanelEgress.setGate(a),e.__chatpanelEgress;const n=A();let r=a;n.setGate=c=>{r=c},n.blocked=[];const p=c=>{let i=null;try{i=y(c),n.record(c)}catch{}if(!r||!i?.host)return null;let l=!0;try{l=r(`${i.scheme}://${i.host}:${i.port}`,{local:m(i.host)})}catch{l=!0}if(l)return null;const s=`${i.host}:${i.port}`;n.blocked.includes(s)||n.blocked.push(s);const t=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return t.code="EGRESS_POLICY",t},o=e.fetch;typeof o=="function"&&(e.fetch=function(i,l){const s=p(i);return s?Promise.reject(s):o.call(this,i,l)});const u=e.WebSocket;return typeof u=="function"&&(e.WebSocket=new Proxy(u,{construct(c,i,l){const s=p(i[0]);if(s)throw s;return Reflect.construct(c,i,l)}})),e.__chatpanelEgress=n,e===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function w(e){try{return new URL(e).host}catch{return String(e||"")}}function R(e={},a=process.env,n=process.platform,r=process.arch){const p=[],o=(t,d,{when:h="always",off:f=null,local:v=!1,data:k=""}={})=>{t&&p.push({host:t,purpose:d,when:h,off:f,local:v,data:k})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),o("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),e.runtime?.services?.llama?.build!=="system"&&(o("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),o("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),o("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),o("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),a.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&r==="arm64"&&o("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const u=e.link?.enabled===!1?null:L(e.link||{}).relay;if(u){const t=new URL(u).host;o(t,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=e.search?.searxng?.url||"";if(c){let t=c;try{t=new URL(c).host}catch{}o(t,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(t)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const t of E(e).filter(d=>d.kind==="api"&&d.enabled!==!1))o(t.api.host,`web search: ${t.api.name} (search API${t.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${t.api.id}", enabled: false }]`,data:"the same query"})}for(const t of Array.isArray(e.context?.providers)?e.context.providers:[]){if(!t||t.enabled===!1)continue;const d=`context.providers: [{ id: "${t.id}", enabled: false }] (Settings › Knowledge › Sources)`;if(t.kind==="bedrock"&&t.region)o(`bedrock-agent-runtime.${t.region}.amazonaws.com`,`knowledge: your AWS Bedrock knowledge base "${t.name||t.id}" (Retrieve)`,{when:"a context search names it (bedrock:"+t.id+") — from a client holding the gateway token",off:d,data:"the search query with emails, cards, keys and dictionary terms removed; signed with the AWS keys you gave it"});else if(t.kind==="gateway"&&t.url){let h=t.url;try{h=new URL(t.url).host}catch{}o(h,`knowledge: the ChatPanel gateway "${t.name||t.id}" you configured (its /v1/context and /v1/kb)`,{when:"a context search names it (gw:"+t.id+"), and the knowledge library lists its bases",off:d,data:t.trusted?"the search query AS TYPED — you marked this gateway as your own (trusted)":"the search query with emails, cards, keys and dictionary terms removed; the token you gave it",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(h)})}else if(t.kind==="bucket"&&t.endpoint){let h=t.endpoint;try{const f=new URL(t.endpoint);h=t.addressing==="virtual"?`${t.bucket}.${f.host}`:f.host}catch{}o(h,`knowledge: the team base "${t.name||t.id}" kept in your ${t.provider||"S3-compatible"} bucket ${t.bucket}/${t.prefix||""}`,{when:t.role==="builder"?`every ${t.pollMinutes||5} min: list the documents, read the new and changed ones, publish the index`:`every ${t.pollMinutes||5} min: is a newer index published? then fetch only what changed`,off:d,data:t.role==="builder"?"the index of the documents in that bucket (passages, vectors, the report), written back beside them; the keys you gave it":"nothing of yours — reads of the published index; the keys you gave it",local:/^(localhost|127\.|\[::1\])/.test(h)})}}if(e.read?.remote?.url){let t=e.read.remote.url;try{t=new URL(e.read.remote.url).host}catch{}o(t,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(t)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[t,d]of Object.entries(i))for(const h of S(e.capabilities?.[t],t,{destinations:e.destinations||[]}).providers){if(!h?.url||h.provider==="embedded")continue;let f=h.url;try{f=new URL(h.url).host}catch{}o(f,`${d.what}${h.service?` (the ${h.service} container, started under Settings › Runtime)`:` (${h.adapter} at the address you configured)`}`,{when:`a client calls /v1/${t}`,off:h.service?`stop the ${h.service} service under Settings › Runtime`:`capabilities.${t} = null`,data:`${d.data}${h.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}a.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[t,d]of Object.entries(e.upstreams||{}))d?.baseUrl&&o(w(d.baseUrl),`model upstream "${t}" — chat requests (after redaction) go here`,{when:`a request addressed to ${t}`,off:`upstreams.${t}.baseUrl`,local:m(w(d.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const t of e.destinations||[])t?.baseUrl&&o(w(t.baseUrl),`destination "${t.id||t.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${t.id||"it"}`,off:"destinations[]",local:m(w(t.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(w(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(w(e.ner.url).split(":")[0]),data:"the text being redacted"});const l=e.tts||{};if(l.provider==="openai"||l.provider==="elevenlabs"){const t=l.remote?.baseUrl?w(l.remote.baseUrl):l.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(t,`remote read-aloud voice (${l.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:l.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const s=e.bridge?.url||"http://127.0.0.1:4319";return o(w(s),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),p}function O(e,{ledger:a=P(),version:n="",startedAt:r=null,env:p=process.env,managed:o=null,certificates:u=null,linkPartners:c=null,confined:i=null}={}){const l=R(e,p);for(const s of c||[])!s.host||s.route!=="link"&&s.route!=="relay"||l.some(t=>t.host===s.host)||l.push({host:s.host,purpose:`ChatPanel Link: the relay partner "${s.partner?.name||s.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${s.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...u?{certificates:u}:{},...i?{confined:i}:{},...o?{managed:o,blocked:a?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:a?a.snapshot():[],declared:l,...c?{link:{partners:c.map(s=>({id:s.id,partner:s.partner?.name||s.name,scopes:s.scopes||[],route:s.route||null,host:s.host||null,...s.folder?{folder:s.folder}:{},pairedAt:s.pairedAt||null,lastSeen:s.lastSeen||null,online:!!s.online}))}}:{}}}function _(e){const a=[];a.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&a.push(`observed since ${e.since}`),a.push(""),a.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||a.push(" (none yet)");for(const n of e.observed||[])a.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);a.push(""),a.push("DECLARED — hosts this configuration allows, and why");for(const n of e.declared||[])a.push(` ${n.local?"[local] ":""}${n.host}`),a.push(` ${n.purpose}`),a.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&a.push(` sends: ${n.data}`);if(e.certificates){const n=e.certificates;a.push(""),a.push("CERTIFICATES — whose word is taken that a server is who it says"),a.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),a.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(a.push(""),a.push("CONFINEMENT — what this process itself can reach on this computer"),a.push(` ${$(e.confined)}`),e.confined.on&&a.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){a.push(""),a.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||a.push(" (none — no partner can reach this gateway until you pair one)");for(const n of e.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";a.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),a.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&a.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),a.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return e.managed&&(a.push(""),a.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),a.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),a.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),a.push(""),a.push(`Scope: ${e.scope}`),a.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),a.join(`
|
|
2
|
+
`)}export{A as createEgressLedger,R as declaredEgress,O as egressAudit,P as egressLedger,_ as formatAudit,N as installEgressLedger};
|
package/src/extract/pdf.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{linesFromItems as
|
|
1
|
+
import{linesFromItems as A,looksScanned as M}from"@chatpanel/events/pdf-layout.js";import{structurePages as j}from"@chatpanel/events/pdf-structure.js";import{execFile as F}from"node:child_process";import{mkdtempSync as _,writeFileSync as k,rmSync as O,existsSync as E}from"node:fs";import{tmpdir as C,homedir as H}from"node:os";import x from"node:path";import{APPLE_HELPER as N,appleHelperDirs as v}from"../apple-model.js";function D(e){const o=(e||[]).map(n=>Math.abs(Number(n?.transform?.[3])||0)).filter(n=>n>0).sort((n,r)=>n-r);if(!o.length)return e||[];const a=o[Math.floor(o.length/2)];return e.map(n=>{const r=n.transform||[],t=Math.abs(Number(r[3])||0);return!t||Math.abs(t-a)>a*.3?n:{...n,transform:[a,0,0,a,r[4],r[5]],height:a}})}const L=20;function R({home:e=H(),platform:o=process.platform,dirs:a=null,run:n=F,env:r=process.env}={}){if(o!=="darwin"||r.CHATPANEL_OCR==="off")return null;const t=(a||v({home:e})).map(c=>x.join(c,N)).find(c=>E(c));return t?async(c,l)=>{const f=_(x.join(C(),"chap-ocr-")),g=x.join(f,"doc.pdf");try{k(g,c,{mode:384});const w=await new Promise((p,y)=>n(t,["ocr",g,"--pages",l.join(",")],{timeout:6e4+l.length*5e3,maxBuffer:64*1024*1024},(d,m)=>d?y(d):p(m))),h=JSON.parse(String(w||"{}"));return new Map((h.pages||[]).map(p=>[p.page,Array.isArray(p.items)?p.items:[]]))}finally{O(f,{recursive:!0,force:!0})}}:null}let S=null;function T(){return S||(S=Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"),import("pdfjs-dist/legacy/build/pdf.worker.mjs")]).then(([e,o])=>(globalThis.pdfjsWorker||=o,e)).catch(e=>{throw S=null,e})),S}const z=1500;async function q(e,{maxPages:o=z,ocr:a=R()}={}){const r=(await T()).getDocument({data:new Uint8Array(e),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),t=await r.promise;try{const c=await t.getMetadata().catch(()=>null),l=t.numPages,f=[],g=[],w=[];for(let s=1;s<=Math.min(l,o);s+=1){const i=await t.getPage(s);try{const u=await i.getTextContent(),P=i.getViewport({scale:1});f.push(A(u.items)),g.push(P.width),w.push(P.height)}finally{i.cleanup()}}const h=f.map((s,i)=>s.reduce((u,P)=>u+String(P.text||"").trim().length,0)<L?i+1:0).filter(Boolean),p=[];if(h.length&&typeof a=="function")try{const s=await a(e,h);for(const i of h){const u=s?.get?.(i);u?.length&&(f[i-1]=A(D(u)),p.push(i))}}catch{}const y=await I(t).catch(()=>[]),d=j(f,{pageWidths:g,pageHeights:w,outline:y}),m=d.pages.map(s=>s.text),b=c?.info||{};return{title:String(b.Title||"").trim(),pages:m,labels:d.pages.map(s=>s.label),outline:y,markdown:!0,truncatedPages:l>m.length?l-m.length:0,...p.length?{ocrPages:p}:{},scanned:M(m.map((s,i)=>({page:i+1,text:s})))}}finally{await r.destroy().catch(()=>{})}}async function I(e){const o=[],a=async(n,r)=>{for(const t of n||[]){if(o.length>=400)return;let c=0;try{const l=typeof t.dest=="string"?await e.getDestination(t.dest):t.dest;Array.isArray(l)&&l[0]&&(c=await e.getPageIndex(l[0])+1)}catch{}o.push({title:String(t.title||"").trim(),page:c,level:r}),r<2&&t.items?.length&&await a(t.items,r+1)}};return await a(await e.getOutline(),1),o.filter(n=>n.title)}export{L as OCR_MIN_CHARS,z as PDF_MAX_PAGES,D as evenOcrSizes,R as macOcr,q as pdfPages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as ce,mkdirSync as W,readFileSync as q,writeFileSync as de,readdirSync as le,rmSync as ue,renameSync as pe}from"node:fs";import{join as w,basename as fe}from"node:path";import he from"node:os";import{bucketClient as me,indexKey as A,isDocumentKey as be,bucketDocId as ye,splitIndexParts as ve,validateRevision as z,planReplicaSync as ge,assembleReplica as ke,makeLease as we,leaseState as Ae,replicaFreshness as $e,bucketWhere as Se,sha256Hex as G,KB_REVISION_FORMAT as Oe}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as je}from"@chatpanel/events/kb-folder-sync.js";import{createKb as De,removeDocument as Ie,serializeKb as Be,deserializeKb as Re}from"@chatpanel/events/kb-index.js";import{graphReport as Te}from"@chatpanel/events/kb-graph.js";const xe=new TextEncoder,Fe=l=>typeof l=="string"?xe.encode(l):l instanceof Uint8Array?l:new Uint8Array(l.buffer,l.byteOffset,l.byteLength),Q=(l,M)=>{const O=`${l}.tmp-${process.pid}`;de(O,M,{mode:384}),pe(O,l)};function _e({store:l,kb:M,entries:O=()=>[],fetchFn:X,now:f=()=>Date.now(),log:j=()=>{},holder:N=`${he.hostname()}`,version:Y="",subtle:E=null}={}){const J=new Map,D=new Map,$=new Map,K=e=>e.kbId||e.id,L=e=>w(l.dirOf(e),"team.json"),Z=e=>w(l.dirOf(e),"parts"),I=e=>me(e,{fetch:X,now:f,subtle:E});function B(e){if(J.has(e.id))return J.get(e.id);let t={kbId:K(e),role:e.role,revision:0,rev:null,syncedAt:0,checkedAt:0,error:"",updating:!1,remoteRevision:0,behindDocs:0,etag:""};try{const i=JSON.parse(q(L(K(e)),"utf8"));i?.provider===e.id&&(t={...t,...i.state,rev:i.state?.rev?z(i.state.rev):null,updating:!1})}catch{}return J.set(e.id,t),t}const ee=(e,t)=>{try{W(l.dirOf(t.kbId),{recursive:!0,mode:448}),Q(L(t.kbId),JSON.stringify({provider:e.id,state:{...t,updating:!1}}))}catch(i){j(`[team] ${e.id}: state not saved — ${i.message}`)}};async function te(e){const t=B(e),i=I(e),a=await i.get(A(e,"revision.json"),{etag:t.rev?t.etag:""});if(t.checkedAt=f(),a.status===304)return t.error="",t.remoteRevision=t.revision,t.behindDocs=0,{upToDate:!0};if(a.status===404)throw new Error("no index has been published to this bucket yet — a builder has not run");const n=z(JSON.parse(new TextDecoder().decode(a.bytes)));t.remoteRevision=n.revision;const b=Z(t.kbId);W(b,{recursive:!0,mode:448});const x=o=>ce(w(b,o)),c=ge({current:t.rev,next:n,have:x});if(c.upToDate)return t.etag=a.etag,t.error="",t.behindDocs=0,{upToDate:!0};t.behindDocs=c.added+c.changed+c.removed,t.updating=!0;try{for(const d of c.fetch){const u=await i.get(A(e,d.file));if(u.status!==200)throw new Error(`part ${d.file} is missing from the bucket (${u.status})`);if(await G(u.bytes,E)!==d.hash)throw new Error(`part ${d.file} does not match its hash — not used`);Q(w(b,d.hash),u.bytes)}const o=ke(n,d=>new Uint8Array(q(w(b,d))));o.manifest={...o.manifest,id:t.kbId};const F=Re(o);l.save(F);const p=new Set([n.manifest,n.notes,...n.report?[n.report]:[],...n.docs.flatMap(d=>[d.chunksFile,d.vectorsFile].filter(Boolean))].map(d=>d.hash));for(const d of le(b))p.has(d)||ue(w(b,d),{force:!0});return Object.assign(t,{rev:n,revision:n.revision,builtAt:n.builtAt,builtBy:n.builder.name,etag:a.etag,syncedAt:f(),error:"",behindDocs:0}),j(`[team] ${e.id}: revision ${n.revision} (${c.added} added, ${c.changed} changed, ${c.removed} removed; ${c.fetch.length} parts, ${c.bytes} bytes)`),{revision:n.revision,...c,fetch:c.fetch.length}}finally{t.updating=!1}}async function se(e){const t=B(e),i=I(e),a=`${N}#${process.pid}`,n=A(e,"lease.json"),b=await i.get(n).then(c=>c.status===200?JSON.parse(new TextDecoder().decode(c.bytes)):null).catch(()=>null);if(Ae(b,{holder:a,now:f()})==="held")throw new Error(`another builder (${b.holder}) is building until ${new Date(b.until).toISOString()}`);await i.put(n,JSON.stringify(we({holder:a,now:f()})),{contentType:"application/json"});const x=await i.get(n);if(x.status!==200||JSON.parse(new TextDecoder().decode(x.bytes)).holder!==a)throw new Error("another builder took the lease at the same moment — this one stands aside");try{const c=await i.get(A(e,"revision.json")),o=c.status===200?z(JSON.parse(new TextDecoder().decode(c.bytes))):null,F=M();let p=l.load(t.kbId);p||(p=De({id:t.kbId,name:e.name||e.bucket,now:f}));const d=`s3://${e.bucket}/${e.prefix||""}`;Array.isArray(p.sources)||(p.sources=[]);let u=p.sources.find(s=>s.kind==="bucket"&&s.path===d);u||(u={kind:"bucket",path:d,files:{},syncedAt:0},p.sources.push(u));const{objects:ie}=await i.list(e.prefix||""),P=ie.filter(s=>be(e,s.key)).map(s=>({path:s.key,size:s.size,mtime:s.mtime,etag:s.etag})),ne=Object.entries(u.files).map(([s,r])=>({path:s,id:r.id,size:r.size,etag:r.etag})),m=je({known:ne,listing:P}),g=[];for(const s of m.remove){Ie(p,s,{now:f});for(const[r,h]of Object.entries(u.files))h.id===s&&delete u.files[r]}const re=new Map(P.map(s=>[s.path,s]));for(const s of[...m.add,...m.change.map(r=>r.path)]){const r=re.get(s);try{const h=await i.get(s);if(h.status!==200)throw new Error(`not readable (${h.status})`);const y=ye(s);await F.addBytes(p,Buffer.from(h.bytes),{name:fe(s),source:{kind:"bucket",name:s},id:y,reach:"internal"}),u.files[s]={id:y,size:r.size,etag:r.etag,mtime:r.mtime}}catch(h){g.push({path:s,why:h.message})}}u.syncedAt=f(),u.lastSync={at:u.syncedAt,added:m.add.length,changed:m.change.length,removed:m.remove.length,same:m.same,skipped:g.length,skippedSample:g.slice(0,20)},await F.embedAll(p),l.save(p);const k=Be(p),U=ve(k),oe=new Set(o?[o.manifest,o.notes,...o.report?[o.report]:[],...o.docs.flatMap(s=>[s.chunksFile,s.vectorsFile].filter(Boolean))].map(s=>s.hash):[]),S=async(s,r,h)=>{const y=Fe(s),_=await G(y,E),V=`objects/${_}.${r}`;return oe.has(_)||await i.put(A(e,V),y,{contentType:h}),{file:V,hash:_,bytes:y.length}},C=await S(U.manifest,"json","application/json");if(o&&o.manifest.hash===C.hash)return Object.assign(t,{revision:o.revision,rev:o,builtAt:o.builtAt,builtBy:o.builder.name,syncedAt:f(),error:""}),{published:!1,revision:o.revision,...m,skipped:g};const ae=new Map(Object.entries(u.files).map(([s,r])=>[r.id,{key:s,...r}])),H=[];for(const s of U.docs){const r=k.manifest.docs.find(y=>y.id===s.id)||{},h=ae.get(s.id)||{key:r.source?.name||s.id,etag:"",size:0};H.push({id:s.id,key:h.key,etag:h.etag||"",size:h.size||0,title:r.title||h.key,type:r.type||"",pages:r.pages||0,chunks:s.count,chunksFile:await S(s.chunks,"jsonl","application/x-ndjson"),...s.vectors?{vectorsFile:await S(new Uint8Array(s.vectors.buffer,s.vectors.byteOffset,s.vectors.byteLength),"f32","application/octet-stream")}:{}})}const v=z({format:Oe,kind:"chap-kb-index",kb:{id:t.kbId,name:p.name},revision:(o?.revision||0)+1,builtAt:f(),builder:{name:N,version:Y},embed:k.vectors.dims?{model:k.vectors.model,recipe:k.vectors.recipe,dims:k.vectors.dims}:null,manifest:C,notes:await S(U.notes,"json","application/json"),report:await S(Te(p),"md","text/markdown"),docs:H});return await i.put(A(e,"revision.json"),JSON.stringify(v),{contentType:"application/json"}),Object.assign(t,{rev:v,revision:v.revision,builtAt:v.builtAt,builtBy:N,syncedAt:f(),checkedAt:f(),remoteRevision:v.revision,error:""}),j(`[team] ${e.id}: published revision ${v.revision} (${m.add.length} added, ${m.change.length} changed, ${m.remove.length} removed, ${g.length} skipped)`),{published:!0,revision:v.revision,...m,skipped:g}}finally{await i.del(n).catch(()=>{})}}function R(e){if($.has(e.id))return $.get(e.id);const t=B(e);t.role=e.role;const i=(e.role==="builder"?se(e):te(e)).then(a=>(t.error="",a)).catch(a=>(t.error=String(a?.message||a).slice(0,300),t.checkedAt=f(),j(`[team] ${e.id}: ${t.error}`),{error:t.error})).finally(()=>{$.delete(e.id),ee(e,t)});return $.set(e.id,i),i}const T=()=>(O()||[]).filter(e=>e?.kind==="bucket"&&e.enabled!==!1);return{run:R,runById:e=>{const t=T().find(i=>i.id===e);return t?R(t):Promise.resolve({error:`no bucket source ${e}`})},test:e=>I(e).test(),upload:(e,t,i)=>I(e).put(`${e.prefix||""}${String(t).replace(/^\/+/,"")}`,i),teamOf(e){const t=T().find(a=>K(a)===e);if(!t)return null;const i=B(t);return{role:t.role,provider:t.id,revision:i.revision,builtAt:i.builtAt||0,...i.builtBy?{builtBy:i.builtBy}:{},syncedAt:i.syncedAt,where:Se(t),freshness:$e({revision:i.revision,remoteRevision:i.remoteRevision,syncedAt:i.syncedAt,checkedAt:i.checkedAt,error:i.error,updating:$.has(t.id),behindDocs:i.behindDocs,now:f()})}},start(){for(const e of T()){if(D.has(e.id))continue;const t=setInterval(()=>{const a=T().find(n=>n.id===e.id);a&&R(a)},Math.max(1,e.pollMinutes||5)*6e4);t.unref?.(),D.set(e.id,t),setTimeout(()=>R(e),2e3).unref?.()}},stop(){for(const e of D.values())clearInterval(e);D.clear()},restart(){this.stop(),this.start()}}}export{_e as createBucketSync};
|
package/src/kb-store.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{mkdirSync as S,readFileSync as a,writeFileSync as w,renameSync as _,existsSync as f,readdirSync as j,rmSync as g,chmodSync as z,statSync as A}from"node:fs";import{join as r}from"node:path";import I from"node:os";import{serializeKb as O,deserializeKb as L,refreshKb as b,KB_LIMITS as x}from"@chatpanel/events/kb-index.js";import{graphReport as E}from"@chatpanel/events/kb-graph.js";import{KB_ID_RE as F}from"@chatpanel/events/kb-capability.js";function T(s=process.env){return s.CHATPANEL_KB_DIR||r(I.homedir(),".chatpanel","kb")}function m(s,l){const o=`${s}.tmp-${process.pid}`;w(o,l,{mode:384}),_(o,s)}function G({root:s=T(),log:l=()=>{}}={}){const o=new Map,u=e=>r(s,e),N=()=>{S(s,{recursive:!0,mode:448});try{z(s,448)}catch{}};function y(){return f(s)?j(s).filter(e=>F.test(e)&&f(r(s,e,"manifest.json"))).sort():[]}function J(){return y().map(e=>{if(o.has(e))return{id:e,manifest:O(o.get(e)).manifest,loaded:!0};try{return{id:e,manifest:JSON.parse(a(r(u(e),"manifest.json"),"utf8")),loaded:!1}}catch{return null}}).filter(Boolean)}function B(e){if(o.has(e))return o.get(e);const t=u(e);if(!f(r(t,"manifest.json")))return null;const n=JSON.parse(a(r(t,"manifest.json"),"utf8")),c=f(r(t,"chunks.jsonl"))?a(r(t,"chunks.jsonl"),"utf8").split(`
|
|
2
|
-
`).filter(Boolean).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(Boolean):[],$=f(r(t,"notes.json"))?JSON.parse(a(r(t,"notes.json"),"utf8")):[];let h=null;if(f(r(t,"vectors.json"))&&f(r(t,"vectors.f32")))try{const i=JSON.parse(a(r(t,"vectors.json"),"utf8")),d=a(r(t,"vectors.f32")),v=new Float32Array(d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength));i.dims>0&&v.length===i.ids.length*i.dims&&(h={model:i.model,dims:i.dims,ids:i.ids,data:v})}catch(i){l(`[kb] ${e}: vectors unreadable, rebuilding — ${i.message}`)}const p=L({manifest:n,chunks:c,notes:$,vectors:h});return b(p),o.set(e,p),p}function K(e){N();const t=u(e.id);S(t,{recursive:!0,mode:448});const n=O(e);if(m(r(t,"manifest.json"),JSON.stringify(n.manifest,null,2)),m(r(t,"chunks.jsonl"),n.chunks.map(c=>JSON.stringify(c)).join(`
|
|
2
|
+
`).filter(Boolean).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(Boolean):[],$=f(r(t,"notes.json"))?JSON.parse(a(r(t,"notes.json"),"utf8")):[];let h=null;if(f(r(t,"vectors.json"))&&f(r(t,"vectors.f32")))try{const i=JSON.parse(a(r(t,"vectors.json"),"utf8")),d=a(r(t,"vectors.f32")),v=new Float32Array(d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength));i.dims>0&&v.length===i.ids.length*i.dims&&(h={model:i.model,recipe:i.recipe||"",dims:i.dims,ids:i.ids,data:v})}catch(i){l(`[kb] ${e}: vectors unreadable, rebuilding — ${i.message}`)}const p=L({manifest:n,chunks:c,notes:$,vectors:h});return b(p),o.set(e,p),p}function K(e){N();const t=u(e.id);S(t,{recursive:!0,mode:448});const n=O(e);if(m(r(t,"manifest.json"),JSON.stringify(n.manifest,null,2)),m(r(t,"chunks.jsonl"),n.chunks.map(c=>JSON.stringify(c)).join(`
|
|
3
3
|
`)+(n.chunks.length?`
|
|
4
|
-
`:"")),m(r(t,"notes.json"),JSON.stringify(n.notes,null,2)),n.vectors.ids.length)m(r(t,"vectors.json"),JSON.stringify({model:n.vectors.model,dims:n.vectors.dims,ids:n.vectors.ids})),m(r(t,"vectors.f32"),Buffer.from(n.vectors.data.buffer,n.vectors.data.byteOffset,n.vectors.data.byteLength));else for(const c of["vectors.json","vectors.f32"])try{g(r(t,c),{force:!0})}catch{}b(e);try{m(r(t,"REPORT.md"),E(e))}catch(c){l(`[kb] ${e.id}: report not written — ${c.message}`)}return o.set(e.id,e),t}function R(e){o.delete(e);const t=u(e);return f(t)?(g(t,{recursive:!0,force:!0}),!0):!1}function k(e){const t=u(e);return f(t)?j(t).reduce((n,c)=>{try{return n+A(r(t,c)).size}catch{return n}},0):0}return{root:s,ids:y,list:J,load:B,save:K,remove:R,sizeOf:k,dirOf:u,loaded:o,limits:x}}export{G as createKbStore,T as kbRoot};
|
|
4
|
+
`:"")),m(r(t,"notes.json"),JSON.stringify(n.notes,null,2)),n.vectors.ids.length)m(r(t,"vectors.json"),JSON.stringify({model:n.vectors.model,recipe:n.vectors.recipe||"",dims:n.vectors.dims,ids:n.vectors.ids})),m(r(t,"vectors.f32"),Buffer.from(n.vectors.data.buffer,n.vectors.data.byteOffset,n.vectors.data.byteLength));else for(const c of["vectors.json","vectors.f32"])try{g(r(t,c),{force:!0})}catch{}b(e);try{m(r(t,"REPORT.md"),E(e))}catch(c){l(`[kb] ${e.id}: report not written — ${c.message}`)}return o.set(e.id,e),t}function R(e){o.delete(e);const t=u(e);return f(t)?(g(t,{recursive:!0,force:!0}),!0):!1}function k(e){const t=u(e);return f(t)?j(t).reduce((n,c)=>{try{return n+A(r(t,c)).size}catch{return n}},0):0}return{root:s,ids:y,list:J,load:B,save:K,remove:R,sizeOf:k,dirOf:u,loaded:o,limits:x}}export{G as createKbStore,T as kbRoot};
|
package/src/kb.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`).find(
|
|
3
|
-
`));if(r&&o){const w=e.docs.find(v=>v.textHash===o&&v.id!==u);if(w)return{duplicateOf:w}}const f=i.path&&t.links?.length?tt(i.path,t.links,{root:l||Oe(i.path)}):[],h=R(e,{id:u,title:a||t.title||z(c),pages:t.pages,source:{kind:i.kind||"bytes",name:c,...i},hash:t.hash||"",type:t.type,reach:n,now:k,links:f,textHash:o,markdownHeadings:!!t.markdown});return{id:h.doc.id,title:h.doc.title,pages:h.doc.pages,chunks:h.doc.chunks,replaced:h.replaced,...t.scanned?{scanned:!0}:{}}}function pe(e,s){const c=re(e).toLowerCase();return!le.has(c)&&!lt.has(c)?!1:s?.length?s.some(d=>{const a=String(d).toLowerCase().replace(/^\*/,"");return c===(a.startsWith(".")?a:`.${a}`)||e.toLowerCase().endsWith(a)}):!0}function Z(e,{recursive:s=!0,include:c=null}={}){const d=it(e,{home:J,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const a=ne(Te(e.replace(/^~(?=$|\/)/,J))),i=[],n=[];let u=0;const l=(o,f)=>{if(i.length>=M.files)return n.push({path:f,why:`stopped at ${M.files} files`}),!1;if(de(o))return n.push({path:f,why:"withheld (a credential store)"}),!0;let h;try{h=se(o)}catch{return!0}const w=re(o).toLowerCase(),v=le.has(w)||dt.has(w)?X:M.textBytes;return h.size>v?(n.push({path:f,why:`too large (${Math.round(h.size/1048576)} MB)`}),!0):u+h.size>M.bytes?(n.push({path:f,why:"stopped: the folder is past the size limit"}),!1):(u+=h.size,i.push({full:o,rel:f,size:h.size,mtime:Math.floor(h.mtimeMs)}),!0)};if(!se(a).isDirectory())return l(a,z(a)),{root:a,files:i,skipped:n,single:!0};const t=(o,f,h)=>{if(h>M.depth)return!0;let w=[];try{w=xe(o,{withFileTypes:!0}).sort((v,S)=>v.name.localeCompare(S.name))}catch{return!0}for(const v of w){const S=v.name;if(S.startsWith(".")&&v.isDirectory())continue;const O=$e(o,S),p=f?`${f}/${S}`:S;if(v.isDirectory()){if(rt.has(S)||!s)continue;try{if(!ne(O).startsWith(a)){n.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!t(O,p,h+1))return!1;continue}if(!(!v.isFile()&&!v.isSymbolicLink())){if(de(O)){n.push({path:p,why:"withheld (a credential store)"});continue}if(pe(S,c)&&!l(O,p))return!1}}return!0};return t(a,"",0),{root:a,files:i,skipped:n}}async function he(e,{path:s,recursive:c=!0,include:d=null,title:a=""}){const{files:i,skipped:n,single:u}=Z(s,{recursive:c,include:d}),l=[];for(const r of i)try{const t=await I(e,te(r.full),{name:z(r.full),title:l.length===0&&(u||!r.rel.includes("/"))?a:"",source:{kind:"file",path:r.full},reach:"internal"});l.push({...t,path:r.rel})}catch(t){n.push({path:r.rel,why:t.message})}return{added:l,skipped:n}}async function me(e,{path:s,include:c=null,rebuild:d=!1},{progress:a=null}={}){const{root:i,files:n,skipped:u}=Z(s,{recursive:!0,include:c}),l=Qe(e,i,{include:c});if(d){for(const p of Object.values(l.files))p?.id&&G(e,p.id,{now:k});l.files={}}const r=new Set(n.map(p=>p.full));for(const[p,x]of Object.entries(l.files))x?.dupOf&&!r.has(x.dupOf)&&delete l.files[p];const t=Ye({known:Ze(l),listing:n.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});a&&(a.total=t.add.length+t.change.length,a.done=0);const o=new Map(n.map(p=>[p.full,p])),f=[];for(const p of t.remove){G(e,p,{now:k});for(const[x,$]of Object.entries(l.files))$.id===p&&(delete l.files[x],f.push(x.startsWith(`${i}/`)?x.slice(i.length+1):x))}const h=[],w=[],v=[],S=p=>String(p||"").startsWith(`${i}/`)?p.slice(i.length+1):p,O=async(p,x)=>{if(a?.cancel)return;await new Promise(m=>setImmediate(m));const $=o.get(p),_=Je(p);try{const m=await I(e,te(p),{name:z(p),source:{kind:"file",path:p},reach:"internal",id:_,root:i,dedupe:!0});m.duplicateOf?(e.docs.some(W=>W.id===_)&&G(e,_,{now:k}),l.files[p]={id:_,size:$.size,mtime:$.mtime,dupOf:m.duplicateOf.source?.path||m.duplicateOf.id},v.push({path:$.rel,of:S(m.duplicateOf.source?.path||m.duplicateOf.title)})):(l.files[p]={id:_,size:$.size,mtime:$.mtime},x.push({...m,path:$.rel}))}catch(m){u.push({path:$.rel,why:m.message})}a&&(a.done+=1)};for(const p of t.add)await O(p,h);for(const p of t.change)await O(p.path,w);return l.syncedAt=k(),l.lastSync={at:l.syncedAt,added:h.length,changed:w.length,removed:f.length,same:t.same,duplicates:v.length,skipped:u.length,skippedSample:u.slice(0,20),duplicateSample:v.slice(0,20)},{root:i,added:h,changed:w,removed:f,same:t.same,duplicates:v,skipped:u}}async function ge(e,{url:s,title:c=""}){if(!V)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const d=await V().read({url:s,format:"markdown"});if(d.status!==200)throw Object.assign(new Error(d.body?.error?.message||`read failed (${d.status})`),{code:"read_failed"});const a=String(d.body.markdown||d.body.text||"");if(!a.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const i=B(a).map((u,l)=>({page:l+1,text:u})),n=R(e,{title:c||d.body.title||s,pages:i,source:{kind:"url",url:d.body.url||s,name:d.body.title||""},type:"html",reach:"web",now:k});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced}}async function be(e,s,{admin:c=!1}={}){const d=k();let a=[],i=[];if(s.kind==="bytes"){const u=Buffer.from(s.data,"base64");if(!u.length)return g(400,"invalid_request","kb: data decoded to nothing");if(u.length>X)return g(413,"too_large",`kb: ${u.length} bytes is over the ${X}-byte limit`);try{a.push(await I(e,u,{name:s.name,hint:s.type||"",title:s.title,reach:s.reach}))}catch(l){return L(l)}}else if(s.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:a,skipped:i}=await he(e,s))}catch(u){return L(u)}}else if(s.kind==="url")try{a.push(await ge(e,s))}catch(u){return L(u)}else if(s.kind==="text"){const u=B(s.text).map((r,t)=>({page:t+1,text:r})),l=R(e,{title:s.title||s.name,pages:u,source:{kind:"text",name:s.name},type:"text",reach:s.reach,now:k});a.push({id:l.doc.id,title:l.doc.title,pages:l.doc.pages,chunks:l.doc.chunks,replaced:l.replaced})}const n=a.length?await K(e):0;return b.save(e),y({added:a,skipped:i,embedded:n,kb:T(e),ms:k()-d})}function L(e){const s=e?.code||"";return s==="refused"?g(403,"refused",`kb: ${e.message}`):s==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):s==="too_large"?g(413,"too_large",`kb: ${e.message}`):s==="read_failed"||s==="empty"?g(502,"read_failed",`kb: ${e.message}`):s==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const q=(e,s)=>Ke(e,s.query,{limit:s.limit,hops:s.hops,docs:s.docs||null,queries:s.queries||[],embed:N("query"),rerank:s.rerank===!1?null:ue,now:k}),ke=(e,s)=>e.docs.find(c=>c.id===s)?.title||s,ee=(e,s)=>{const c=je(e,s);if(!c)return null;const d=c.kind==="note"?"Note":ke(e,c.doc);return{...c,title:d,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${d.replace(/[[\]]/g,"")} p.${c.page}]`}};function ye(e,s){U(e);const c=oe(e.graph,s.node);if(!c)return y({node:null,neighbours:[],message:`no node named "${s.node}"`});const d=i=>{const n=e.graph.nodes.find(u=>u.id===i);return{id:i,label:n?.label||i.replace(/^chunk:/,"passage "),kind:n?.kind||"chunk"}},a={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Fe(e.graph,c.id,{hops:s.hops,kinds:s.kinds||null,limit:s.limit})};if(s.to){const i=oe(e.graph,s.to);a.to=s.to,a.path=i?(Le(e.graph,c.id,i.id)||[]).map(d):null,i&&!a.path.length&&(a.path=null)}return y(a)}async function we(e,s,{admin:c=!1}={}){if(s.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const d=s.model&&typeof Y=="function"?Y(s.model):null,a=T(e),i=await De(s.question,{search:(n,u)=>q(e,{query:n,limit:u.limit||10,hops:u.hops??1,docs:u.docs||s.docs||null}),outline:async n=>n?ce(e.chunks,{doc:n}):e.outline,read:async n=>ee(e,n),complete:d,kbName:e.name,docs:a.documents,previous:s.previous||null,answer:s.answer||"",ask:s.ask!==!1,now:k});return y({attachment:i.attachment,read:i.read,hits:i.hits.map(n=>({id:n.id,doc:n.doc,title:n.title,page:n.page,section:n.section,cite:n.cite,lanes:n.lanes,via:n.via})),queries:i.queries,verdict:i.verdict,rounds:i.rounds,ask:i.ask,how:i.how,frame:{whole:i.frame.whole,docs:i.frame.docs},ms:i.ms})}const P=new Map;async function ve({method:e="GET",pathname:s="",query:c=new URLSearchParams,body:d=null,admin:a=!1,agent:i=""}={}){const n=Be(s);if(!n)return g(404,"not_found",`no route ${s}`);if(n.bad)return g(400,"invalid_request",`kb: "${n.bad}" is not a valid id or route`);const u={admin:a,agent:String(i||c.get("agent")||"").trim().toLowerCase()},l=t=>{try{return{value:t()}}catch(o){return{res:g(400,"invalid_request",o.message)}}};if(!n.id){if(e==="GET")return y({kbs:b.list().filter(({manifest:t})=>ie({access:t.access},u)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=l(()=>Ne(d||{}));if(t.res)return t.res;const o=t.value;if(o.id&&b.load(o.id))return y({kb:T(b.load(o.id)),existed:!0});const f=ae({id:o.id,name:o.name,embed:o.embed,now:k});return b.save(f),{status:201,body:{kb:T(f)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(n.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!a)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");const t=l(()=>Ve(d||{}));if(t.res)return t.res;const o=t.value,f=P.get(n.id);if(f)return{status:202,body:{running:!0,progress:{...f.progress},kb:f.base?T(f.base):null}};let h=b.load(n.id);const w=!h;h||(h=ae({id:n.id,name:o.name||z(String(o.path).replace(/[\\/]+$/,""))||n.id,now:k}),b.save(h));const v=k(),S={done:0,total:0},O=(async()=>{const m=await me(h,o,{progress:S});if(S.cancel)return{cancelled:!0};const W=m.added.length+m.changed.length+m.removed.length,Se=m.added.length||m.changed.length?await K(h):0;return(W||w)&&b.save(h),{folder:m.root,added:m.added,changed:m.changed,removed:m.removed,same:m.same,duplicates:m.duplicates,skipped:m.skipped,embedded:Se,made:w,kb:T(h),ms:k()-v}})();P.set(n.id,{progress:S,base:h}),O.catch(m=>D(`[kb] ${n.id}: sync failed — ${m?.message||m}`)).finally(()=>P.delete(n.id));const p=o.waitMs??5e3;if(p===0)return{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}};let x=null;const $=new Promise(m=>{x=setTimeout(()=>m(null),p)});let _;try{_=await Promise.race([O,$])}catch(m){return clearTimeout(x),L(m)}return clearTimeout(x),_?y(_):{status:202,body:{running:!0,progress:{...S},made:w,kb:T(h)}}}const r=b.load(n.id);if(!r)return g(404,"not_found",`kb: no knowledge base ${n.id} — POST /v1/kb to create one`);if(!ie(r,u))return g(404,"not_found",`kb: no knowledge base ${n.id} for ${u.agent||"this caller"} — the owner can grant it (POST /v1/kb/${n.id}/access)`);if(!n.sub){if(e==="GET"){P.has(r.id)||Q(r);const t=T(r),o=a?(r.sources||[]).map(f=>({kind:f.kind,path:f.path,files:Object.keys(f.files||{}).length,syncedAt:f.syncedAt||0,...f.lastSync?{lastSync:f.lastSync}:{}})):void 0;return y({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:b.sizeOf(r.id),dir:a?b.dirOf(r.id):void 0,...o?.length?{sources:o}:{},...P.has(r.id)?{syncing:(({done:f,total:h})=>({done:f,total:h}))(P.get(r.id).progress)}:{}}})}if(e==="DELETE"){if(!a)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=P.get(r.id);return t&&(t.progress.cancel=!0),b.remove(r.id),y({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(n.sub){case"documents":{if(e==="POST"&&!n.rest){const t=l(()=>Ce(d||{}));return t.res?t.res:be(r,t.value,{admin:a})}if(e==="DELETE"&&n.rest)return a?G(r,n.rest,{now:k})?(b.save(r),y({ok:!0,kb:T(r)})):g(404,"not_found",`kb: no document ${n.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&n.rest){const t=Number(c.get("page"))||1,o=Me(r,n.rest,t);return o?y(o):g(404,"not_found",`kb: no document ${n.rest}`)}if(e==="GET")return y({documents:T(r).documents});break}case"passages":{if(e==="GET"&&n.rest){const t=ee(r,n.rest);return t?y(t):g(404,"not_found",`kb: no passage ${n.rest}`)}break}case"outline":{if(e==="GET"){U(r);const t=c.get("doc");return y({outline:t?ce(r.chunks,{doc:t}):r.outline})}break}case"search":{if(e==="POST"){const t=l(()=>Ie(d||{}));if(t.res)return t.res;const o=k(),f=await q(r,t.value);return Q(r),y({...f,ms:k()-o})}break}case"research":{if(e==="POST"){const t=l(()=>We(d||{}));return t.res?t.res:we(r,t.value,{admin:a})}break}case"graph":{if(e==="POST"){const t=l(()=>Re(d||{}));return t.res?t.res:ye(r,t.value)}break}case"report":{if(e==="GET")return U(r),{status:200,text:Ge(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return y({notes:r.notes});if(e==="POST"&&!n.rest){const t=l(()=>Ue(d||{}));if(t.res)return t.res;const o=t.value,f=o.status==="accepted"&&a?"accepted":"proposed",h=Ee(r,{text:o.text,cites:o.cites||[],by:o.by||(a?"user":"agent"),status:f,now:k});return await K(r),b.save(r),{status:201,body:{note:h}}}if(e==="POST"&&n.rest){if(!a)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=l(()=>Xe(d||{}));if(t.res)return t.res;const o=t.value,f=Pe(r,n.rest,o.status,{now:k});return f?(b.save(r),y({note:f,removed:o.status==="removed"})):g(404,"not_found",`kb: no note ${n.rest}`)}break}case"access":{if(e==="GET")return y({access:r.access});if(e==="POST"){if(!a)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=l(()=>He(d||{}));if(t.res)return t.res;const o=Ae(r,t.value,{now:k});return b.save(r),y({access:o})}break}case"embed":{if(e==="POST"){const t=F(),o=E&&t?E.health("embed",t):{state:"off"},f=await K(r);return f&&b.save(r),y({embedded:f,vectors:r.vectors.by.size,model:r.vectors.model||t,dims:r.vectors.dims,state:o.state,...o.progress?{progress:o.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${s} is not a route`)}return{handle:ve,store:b,embedModel:F}}export{M as KB_WALK_LIMITS,Tt as createKbService};
|
|
1
|
+
import{readFileSync as de,statSync as q,readdirSync as Ge,realpathSync as le}from"node:fs";import{join as Le,basename as I,extname as ue,resolve as je,dirname as ze}from"node:path";import De from"node:os";import{createKb as fe,addDocument as ee,removeDocument as H,addNote as Fe,setNoteStatus as Be,searchKb as Ne,embedMissing as Ce,kbNeedsVectors as Ie,kbStatus as Re,readPage as We,chunkById as Ue,refreshKb as V,setKbAccess as Xe,kbMayUse as te}from"@chatpanel/events/kb-index.js";import{kbResearch as He}from"@chatpanel/events/kb-research.js";import{neighbours as Ve,pathBetween as Ye,resolveNode as pe,graphReport as Je}from"@chatpanel/events/kb-graph.js";import{outlineOf as he}from"@chatpanel/events/kb-chunk.js";import{routeKb as Qe,validateKbCreate as Ze,validateKbAdd as qe,validateKbSearch as et,validateKbResearch as tt,validateKbGraph as nt,validateKbNote as st,validateKbNoteStatus as rt,validateKbAccess as at,validateKbSync as ot,validateKbReveal as it,kbGraphLimit as ct,KB_LOCAL_ACTIONS as dt}from"@chatpanel/events/kb-capability.js";import{communities as lt,topEntities as ge}from"@chatpanel/events/kb-graph.js";import{kbCard as ut,pageStrip as ft}from"@chatpanel/events/kb-view.js";import{planFolderSync as pt,folderDocId as ht,folderSource as gt,knownFiles as mt}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as bt,markdownLinks as kt,resolveLinks as yt,visibleTextHash as wt,decodeText as vt}from"@chatpanel/events/kb-html.js";import{secretReason as me,SKIP_DIR_NAMES as St,sniffType as $t,checkAttachablePath as Ot}from"@chatpanel/events/attached-paths.js";import{paginateText as Y,MAX_DOCUMENT_BYTES as ne}from"./extract-capability.js";import{defaultEmbeddedModel as Tt}from"./embedded-models.js";import{primaryProvider as _t}from"./capability-config.js";function P(m,A){const $=Re(m);return A?$:{...$,documents:$.documents.map(K=>{const{path:j,...L}=K.source||{};return{...K,source:L}})}}const R=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),be=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),xt=new Set([".html",".htm",".xhtml"]),Et=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(m,A,$,K={})=>({status:m,body:{error:{type:A,message:$},...K}}),v=m=>({status:200,body:m});function Pt(m,{limit:A=60}={}){V(m);const $=m.graph||{nodes:[],edges:[]},K=new Set(ge($,{limit:A}).map(b=>b.id)),j=new Map(ge($,{limit:A}).map(b=>[b.id,b.weight])),L=$.nodes.filter(b=>b.kind==="entity"?K.has(b.id):b.kind!=="chunk").slice(0,A*6),z=new Set(L.map(b=>b.id)),D=$.edges.filter(b=>z.has(b.from)&&z.has(b.to)).slice(0,A*20),w=lt($).map(b=>({...b,members:b.members.filter(F=>z.has(F))})).filter(b=>b.members.length>=2).slice(0,24);return{nodes:L.map(b=>({id:b.id,kind:b.kind,label:b.label,count:b.count,...b.doc?{doc:b.doc}:{},...j.has(b.id)?{weight:j.get(b.id)}:{}})),edges:D,communities:w,total:{nodes:$.nodes.length,edges:$.edges.length}}}function Xt({store:m,extract:A=null,embedded:$=null,cfg:K={},rerank:j=null,read:L=null,completer:z=null,log:D=()=>{},now:w=()=>Date.now(),home:b=De.homedir(),team:F=()=>null,remoteCards:se=null,reveal:re=null,confined:ke=()=>!1}={}){const N=()=>{const e=_t(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Tt("embed")||""},J=(e="passage")=>{const t=N();if(!$||!t)return null;const c=$.health("embed",t);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?($.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await $.embed(t,l,{kind:e})).vectors},ye=typeof j=="function"?j:null,Q=new Set;function ae(e){!e||Q.has(e.id)||e.embed==="off"||!J("passage")||Ie(e)&&(Q.add(e.id),B(e).then(t=>{t&&(m.save(e),D(`[kb] ${e.id}: ${t} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>Q.delete(e.id)))}async function B(e,{late:t=()=>!1}={}){const c=J("passage");if(!c)return 0;try{return await Ce(e,c,{model:N(),late:t})}catch(l){return D(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function we(e,t,c=""){const l=$t(e,t);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=vt(e);if(/\.x?html?$/i.test(t)||/html/i.test(l.label||"")){const s=bt(r);return{type:"html",pages:Y(s.markdown).map((S,n)=>({page:n+1,text:S})),title:s.title,links:s.links,markdown:!0}}const p=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
|
|
2
|
+
`).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(t);return{type:l.label||"text",pages:Y(r).map((s,S)=>({page:S+1,text:s})),title:p?p[1].trim():"",links:k?kt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),a=await o.open(e,{name:t,hint:c}),u=[];for(let r=1;r<=a.pages;r+=1){let p="";try{p=String((await o.page(a.hash,r)).text||"")}catch(k){D(`[kb] ${t} p.${r}: ${k.message}`)}u.push({page:r,text:p,...a.labels?.[r-1]?{label:a.labels[r-1]}:{}})}return{type:a.type,pages:u,title:a.title||"",hash:a.hash,scanned:!!a.scanned,markdown:!!a.markdown,labels:a.labels||[]}}async function W(e,t,{name:c,hint:l="",title:o="",source:a={},reach:u="",id:r="",root:p="",dedupe:k=!1}){const s=await we(t,c,l),S=wt(s.pages.map(d=>d.text).join(`
|
|
3
|
+
`));if(k&&S){const d=e.docs.find(h=>h.textHash===S&&h.id!==r);if(d)return{duplicateOf:d}}const n=a.path&&s.links?.length?yt(a.path,s.links,{root:p||ze(a.path)}):[],i=ee(e,{id:r,title:o||s.title||I(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:w,links:n,textHash:S,markdownHeadings:!!s.markdown});return{id:i.doc.id,title:i.doc.title,pages:i.doc.pages,chunks:i.doc.chunks,replaced:i.replaced,...s.scanned?{scanned:!0}:{}}}function ve(e,t){const c=ue(e).toLowerCase();return!be.has(c)&&!Et.has(c)?!1:t?.length?t.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function oe(e,{recursive:t=!0,include:c=null}={}){const l=Ot(e,{home:b,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=le(je(e.replace(/^~(?=$|\/)/,b))),a=[],u=[];let r=0;const p=(S,n)=>{if(a.length>=R.files)return u.push({path:n,why:`stopped at ${R.files} files`}),!1;if(me(S))return u.push({path:n,why:"withheld (a credential store)"}),!0;let i;try{i=q(S)}catch{return!0}const d=ue(S).toLowerCase(),h=be.has(d)||xt.has(d)?ne:R.textBytes;return i.size>h?(u.push({path:n,why:`too large (${Math.round(i.size/1048576)} MB)`}),!0):r+i.size>R.bytes?(u.push({path:n,why:"stopped: the folder is past the size limit"}),!1):(r+=i.size,a.push({full:S,rel:n,size:i.size,mtime:Math.floor(i.mtimeMs)}),!0)};if(!q(o).isDirectory())return p(o,I(o)),{root:o,files:a,skipped:u,single:!0};const s=(S,n,i)=>{if(i>R.depth)return!0;let d=[];try{d=Ge(S,{withFileTypes:!0}).sort((h,y)=>h.name.localeCompare(y.name))}catch{return!0}for(const h of d){const y=h.name;if(y.startsWith(".")&&h.isDirectory())continue;const T=Le(S,y),f=n?`${n}/${y}`:y;if(h.isDirectory()){if(St.has(y)||!t)continue;try{if(!le(T).startsWith(o)){u.push({path:f,why:"links outside the folder"});continue}}catch{continue}if(!s(T,f,i+1))return!1;continue}if(!(!h.isFile()&&!h.isSymbolicLink())){if(me(T)){u.push({path:f,why:"withheld (a credential store)"});continue}if(ve(y,c)&&!p(T,f))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function Se(e,{path:t,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=oe(t,{recursive:c,include:l}),p=[];for(const k of a)try{const s=await W(e,de(k.full),{name:I(k.full),title:p.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});p.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:p,skipped:u}}async function $e(e,{path:t,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=oe(t,{recursive:!0,include:c}),p=gt(e,a,{include:c});if(l){for(const f of Object.values(p.files))f?.id&&H(e,f.id,{now:w});p.files={}}const k=new Set(u.map(f=>f.full));for(const[f,_]of Object.entries(p.files))_?.dupOf&&!k.has(_.dupOf)&&delete p.files[f];const s=pt({known:mt(p),listing:u.map(f=>({path:f.full,size:f.size,mtime:f.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const S=new Map(u.map(f=>[f.full,f])),n=[];for(const f of s.remove){H(e,f,{now:w});for(const[_,x]of Object.entries(p.files))x.id===f&&(delete p.files[_],n.push(_.startsWith(`${a}/`)?_.slice(a.length+1):_))}const i=[],d=[],h=[],y=f=>String(f||"").startsWith(`${a}/`)?f.slice(a.length+1):f,T=async(f,_)=>{if(o?.cancel)return;await new Promise(E=>setImmediate(E));const x=S.get(f),G=ht(f);try{const E=await W(e,de(f),{name:I(f),source:{kind:"file",path:f},reach:"internal",id:G,root:a,dedupe:!0});E.duplicateOf?(e.docs.some(C=>C.id===G)&&H(e,G,{now:w}),p.files[f]={id:G,size:x.size,mtime:x.mtime,dupOf:E.duplicateOf.source?.path||E.duplicateOf.id},h.push({path:x.rel,of:y(E.duplicateOf.source?.path||E.duplicateOf.title)})):(p.files[f]={id:G,size:x.size,mtime:x.mtime},_.push({...E,path:x.rel}))}catch(E){r.push({path:x.rel,why:E.message})}o&&(o.done+=1)};for(const f of s.add)await T(f,i);for(const f of s.change)await T(f.path,d);return p.syncedAt=w(),p.lastSync={at:p.syncedAt,added:i.length,changed:d.length,removed:n.length,same:s.same,duplicates:h.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:h.slice(0,20)},{root:a,added:i,changed:d,removed:n,same:s.same,duplicates:h,skipped:r}}async function Oe(e,{url:t,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().read({url:t,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=Y(o).map((r,p)=>({page:p+1,text:r})),u=ee(e,{title:c||l.body.title||t,pages:a,source:{kind:"url",url:l.body.url||t,name:l.body.title||""},type:"html",reach:"web",now:w});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function Te(e,t,{admin:c=!1}={}){const l=w();let o=[],a=[];if(t.kind==="bytes"){const r=Buffer.from(t.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>ne)return g(413,"too_large",`kb: ${r.length} bytes is over the ${ne}-byte limit`);try{o.push(await W(e,r,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(p){return U(p)}}else if(t.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:o,skipped:a}=await Se(e,t))}catch(r){return U(r)}}else if(t.kind==="url")try{o.push(await Oe(e,t))}catch(r){return U(r)}else if(t.kind==="text"){const r=Y(t.text).map((k,s)=>({page:s+1,text:k})),p=ee(e,{title:t.title||t.name,pages:r,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:w});o.push({id:p.doc.id,title:p.doc.title,pages:p.doc.pages,chunks:p.doc.chunks,replaced:p.replaced})}const u=o.length?await B(e):0;return m.save(e),v({added:o,skipped:a,embedded:u,kb:P(e,c),ms:w()-l})}function U(e){const t=e?.code||"";return t==="refused"?g(403,"refused",`kb: ${e.message}`):t==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):t==="too_large"?g(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?g(502,"read_failed",`kb: ${e.message}`):t==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const _e=e=>e.vectors?.model&&e.vectors.model!==N()?null:J("query"),Z=(e,t)=>Ne(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],...t.filters?{filters:t.filters}:{},embed:_e(e),rerank:t.rerank===!1?null:ye,now:w}),xe=(e,t)=>e.docs.find(c=>c.id===t)?.title||t,ie=(e,t)=>{const c=Ue(e,t);if(!c)return null;const l=c.kind==="note"?"Note":xe(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Ee(e,t){V(e);const c=pe(e.graph,t.node);if(!c)return v({node:null,neighbours:[],message:`no node named "${t.node}"`});const l=a=>{const u=e.graph.nodes.find(r=>r.id===a);return{id:a,label:u?.label||a.replace(/^chunk:/,"passage "),kind:u?.kind||"chunk"}},o={node:{id:c.id,kind:c.kind,label:c.label},neighbours:Ve(e.graph,c.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const a=pe(e.graph,t.to);o.to=t.to,o.path=a?(Ye(e.graph,c.id,a.id)||[]).map(l):null,a&&!o.path.length&&(o.path=null)}return v(o)}async function Pe(e,t,{admin:c=!1}={}){if(t.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=t.model&&typeof z=="function"?z(t.model):null,o=P(e,c),a=await He(t.question,{search:(u,r)=>Z(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||t.docs||null}),outline:async u=>u?he(e.chunks,{doc:u}):e.outline,read:async u=>ie(e,u),complete:l,kbName:e.name,docs:o.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:w});return v({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function ce(e,t){const c=P(e,t),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=t?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return ut({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:F(e.id),now:w()})}async function Ae({method:e="GET",pathname:t="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=Qe(t);if(!r)return g(404,"not_found",`no route ${t}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(dt.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const p={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=n=>{try{return{value:n()}}catch(i){return{res:g(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const n=[];for(const{manifest:d}of m.list()){if(!te({access:d.access},p))continue;const h=m.load(d.id);h&&n.push(ce(h,o))}const i=o&&typeof se=="function"?await se({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return v({cards:n,...i.length?{remote:i}:{}})}if(e==="GET")return v({kbs:m.list().filter(({manifest:n})=>te({access:n.access},p)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=k(()=>Ze(l||{}));if(n.res)return n.res;const i=n.value;if(i.id&&m.load(i.id))return v({kb:P(m.load(i.id),o),existed:!0});const d=fe({id:i.id,name:i.name,embed:i.embed,now:w});return m.save(d),{status:201,body:{kb:P(d,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(F(r.id)?.role==="replica")return X(r.id);const n=k(()=>ot(l||{}));if(n.res)return n.res;const i=n.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let h=m.load(r.id);const y=!h;h||(h=fe({id:r.id,name:i.name||I(String(i.path).replace(/[\\/]+$/,""))||r.id,now:w}),m.save(h));const T=w(),f={done:0,total:0},_=(async()=>{const O=await $e(h,i,{progress:f});if(f.cancel)return{cancelled:!0};const Ke=O.added.length+O.changed.length+O.removed.length,Me=O.added.length||O.changed.length?await B(h):0;return(Ke||y)&&m.save(h),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Me,made:y,kb:P(h,o),ms:w()-T}})();M.set(r.id,{progress:f,base:h}),_.catch(O=>D(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const x=i.waitMs??5e3;if(x===0)return{status:202,body:{running:!0,progress:{...f},made:y,kb:P(h,o)}};let G=null;const E=new Promise(O=>{G=setTimeout(()=>O(null),x)});let C;try{C=await Promise.race([_,E])}catch(O){return clearTimeout(G),U(O)}return clearTimeout(G),C?v(C):{status:202,body:{running:!0,progress:{...f},made:y,kb:P(h,o)}}}const s=m.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const S=F(s.id)?.role==="replica";if(!te(s,p))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${p.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||ae(s);const n=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return v({kb:{...n,coverage:n.chunks?Math.round(n.vectors/n.chunks*100):0,bytes:m.sizeOf(s.id),dir:o?m.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:h})=>({done:d,total:h}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const n=M.get(s.id);return n&&(n.progress.cancel=!0),m.remove(s.id),v({ok:!0,...n?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(S&&(e==="POST"||e==="DELETE"))return X(s.id);if(e==="POST"&&!r.rest){const n=k(()=>qe(l||{}));return n.res?n.res:Te(s,n.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?H(s,r.rest,{now:w})?(m.save(s),v({ok:!0,kb:P(s,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const n=Number(c.get("page"))||1,i=We(s,r.rest,n);return i?v(i):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return v({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const n=ie(s,r.rest);return n?v(n):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){V(s);const n=c.get("doc");return v({outline:n?he(s.chunks,{doc:n}):s.outline})}break}case"search":{if(e==="POST"){const n=k(()=>et(l||{}));if(n.res)return n.res;const i=w(),d=await Z(s,n.value);return ae(s),v({...d,ms:w()-i})}break}case"research":{if(e==="POST"){const n=k(()=>tt(l||{}));return n.res?n.res:Pe(s,n.value,{admin:o})}break}case"graph":{if(e==="GET")return v(Pt(s,{limit:ct(c.get("limit"))}));if(e==="POST"){const n=k(()=>nt(l||{}));return n.res?n.res:Ee(s,n.value)}break}case"report":{if(e==="GET")return V(s),{status:200,text:Je(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return v({notes:s.notes});if(S&&e==="POST")return X(s.id);if(e==="POST"&&!r.rest){const n=k(()=>st(l||{}));if(n.res)return n.res;const i=n.value,d=i.status==="accepted"&&o?"accepted":"proposed",h=Fe(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:w});return await B(s),m.save(s),{status:201,body:{note:h}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=k(()=>rt(l||{}));if(n.res)return n.res;const i=n.value,d=Be(s,r.rest,i.status,{now:w});return d?(m.save(s),v({note:d,removed:i.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return v({access:s.access});if(S&&e==="POST")return X(s.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=k(()=>at(l||{}));if(n.res)return n.res;const i=Xe(s,n.value,{now:w});return m.save(s),v({access:i})}break}case"pages":{if(e!=="GET")break;const n=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===n);return i?v(ft(s.chunks,i)):g(404,"not_found",`kb: no document ${n||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(ke())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(F(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof re!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const n=k(()=>it(l||{}));if(n.res)return n.res;const i=n.value;let d="",h="file";if(i.doc){const y=s.docs.find(T=>T.id===i.doc);if(!y)return g(404,"not_found",`kb: no document ${i.doc}`);d=y.source?.path||"",d||(d=m.dirOf(s.id),h="index")}else if(i.source!=null){const y=(s.sources||[])[i.source];if(!y?.path)return g(404,"not_found",`kb: no kept folder ${i.source}`);d=y.path,h="folder"}else{const y=(s.sources||[]).find(T=>T.path);d=y?.path||m.dirOf(s.id),h=y?"folder":"index"}try{q(d)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await re(d,{folder:h!=="file"})}catch(y){return g(502,"reveal_failed",`kb: the file manager did not open — ${y.message}`)}return v({ok:!0,revealed:h})}case"embed":{if(e==="POST"){const n=N(),i=$&&n?$.health("embed",n):{state:"off"},d=await B(s);return d&&m.save(s),v({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||n,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}function X(e){return g(409,"read_only",`kb: ${e} is a team base copied from its bucket — add or remove documents in the bucket; the builder publishes the next index`)}return{handle:Ae,store:m,embedModel:N,cardOf:ce,addBytes:(e,t,c)=>W(e,t,c),embedAll:e=>B(e),searchBase:(e,t)=>Z(e,t)}}export{R as KB_WALK_LIMITS,Xt as createKbService,P as kbStatusFor,Pt as wholeGraph};
|