@chatpanel/gateway 0.144.1 → 0.147.1

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