@chatpanel/gateway 0.147.2 → 0.152.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/cloud-profiles.js +1 -0
- package/src/configstore.js +1 -1
- package/src/context.js +1 -1
- package/src/destinations-service.js +1 -0
- package/src/egress.js +1 -1
- package/src/embedded-models.js +1 -1
- package/src/kb-bucket-sync.js +1 -1
- package/src/kb.js +3 -3
- package/src/mcp.js +6 -6
- package/src/server.js +29 -29
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.152.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.495.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as x,existsSync as b}from"node:fs";import{createPrivateKey as O,createSign as C}from"node:crypto";import{join as k}from"node:path";import m from"node:os";function w(n){const o={};let c=null;for(const _ of String(n||"").split(/\r?\n/)){const f=_.trim();if(!f||f.startsWith("#")||f.startsWith(";"))continue;const y=/^\[([^\]]+)\]$/.exec(f);if(y){c=y[1].trim(),o[c]=o[c]||{};continue}const p=/^([^=]+?)\s*=\s*(.*)$/.exec(f);p&&c&&(o[c][p[1].trim().toLowerCase()]=p[2].trim())}return o}function E(n){try{const o=JSON.parse(Buffer.from(String(n).split(".")[1]||"","base64url").toString("utf8"));return Number(o.exp)>0?Number(o.exp)*1e3:0}catch{return 0}}const u=(n,o)=>{try{return n.existsSync(o)?n.readFileSync(o,"utf8"):""}catch{return""}},h=/^[\w.-]{1,64}$/;function I({home:n=m.homedir(),env:o=process.env}={}){return{awsCredentials:o.AWS_SHARED_CREDENTIALS_FILE||k(n,".aws","credentials"),awsConfig:o.AWS_CONFIG_FILE||k(n,".aws","config"),oci:o.OCI_CLI_CONFIG_FILE||k(n,".oci","config")}}function W({home:n=m.homedir(),env:o=process.env,fs:c={readFileSync:x,existsSync:b},now:_=()=>Date.now()}={}){const f=I({home:n,env:o}),y=e=>String(e||"").replace(/^~(?=$|\/)/,n),p=()=>{const e=w(u(c,f.awsCredentials)),s=w(u(c,f.awsConfig)),t=i=>s[i==="default"?"default":`profile ${i}`]||s[i]||{},r=new Set([...Object.keys(e),...Object.keys(s).map(i=>i.replace(/^profile\s+/,""))].filter(i=>h.test(i)&&i!=="sso-session"&&!i.startsWith("sso-session ")&&!i.startsWith("services ")));return{creds:e,confOf:t,names:[...r]}},d=e=>{const{creds:s,confOf:t}=p();return{...t(e),...s[e]||{}}},g=e=>e.aws_access_key_id&&e.aws_secret_access_key?"":e.sso_session||e.sso_start_url?"signs in with SSO — not supported here yet":e.credential_process?"uses credential_process — not supported here yet":e.role_arn?"assumes a role — not supported here yet":"has no access key",S=e=>e.endpoint_url||"";return{paths:f,list(){const e=[];for(const t of p().names.sort()){const r=d(t),i=g(r);e.push({from:"aws",name:t,...r.region?{region:r.region}:{},...S(r)?{endpoint:S(r)}:{},usable:!i,...i?{why:i}:{}})}const s=w(u(c,f.oci));for(const t of Object.keys(s).filter(r=>h.test(r)).sort()){const r=s[t],i=!!r.security_token_file;let a=i?r.key_file?"":"is missing key_file":r.tenancy&&r.user&&r.fingerprint&&r.key_file?"":"is missing tenancy, user, fingerprint or key_file",l=0;if(i&&!a){const $=u(c,y(r.security_token_file)).trim();l=E($),$?l&&l<_()&&(a=`its session expired — refresh it: oci session refresh --profile ${t}`):a="its session token file cannot be read"}e.push({from:"oci",name:t,...r.region?{region:r.region}:{},...i?{session:!0}:{},...l?{expires:l}:{},usable:!a,...a?{why:a}:{}})}return e.filter(t=>t.usable||t.why)},async keys(e){if(!h.test(String(e||"")))throw new Error("profile: a profile name");const s=d(e),t=g(s);if(t)throw new Error(`profile "${e}" ${t==="has no access key"&&!p().names.includes(e)?"is not in the shared credentials file":t}`);return{accessKeyId:s.aws_access_key_id,secretAccessKey:s.aws_secret_access_key,...s.aws_session_token?{sessionToken:s.aws_session_token}:{}}},async ociAuth(e){if(!h.test(String(e||"")))throw new Error("profile: a profile name");const s=w(u(c,f.oci))[e];if(!s)throw new Error(`profile "${e}" is not in ${f.oci}`);let t;if(s.security_token_file){if(!s.key_file)throw new Error(`profile "${e}" is missing key_file`);const a=u(c,y(s.security_token_file)).trim();if(!a)throw new Error(`profile "${e}": its session token file cannot be read`);const l=E(a);if(l&&l<_())throw new Error(`profile "${e}": the session expired — refresh it: oci session refresh --profile ${e}`);t="ST$"+a}else{if(!(s.tenancy&&s.user&&s.fingerprint&&s.key_file))throw new Error(`profile "${e}" is missing tenancy, user, fingerprint or key_file`);t=`${s.tenancy}/${s.user}/${s.fingerprint}`}const r=u(c,y(s.key_file));if(!r)throw new Error(`profile "${e}": its key file cannot be read`);const i=O({key:r,...s.pass_phrase?{passphrase:s.pass_phrase}:{}});return{keyId:t,region:s.region||"",sign:async a=>C("RSA-SHA256").update(a).sign(i,"base64")}}}}export{W as createCloudProfiles,w as parseIni,I as profilePaths,E as tokenExpiry};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{patchApis as $,viewApis as H}from"./retrieval/search-apis.js";import{writeFileSync as B,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as z,EMBEDDED_IDS as D,isEmbeddedModel as K}from"./embedded-models.js";import{capabilityList as 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};
|
|
1
|
+
import{carriedKey as $}from"@chatpanel/events/destinations.js";import{patchApis as H,viewApis as B}from"./retrieval/search-apis.js";import{writeFileSync as M,mkdirSync as X,chmodSync as G}from"node:fs";import{join as U,dirname as q}from"node:path";import F from"node:os";import{usage as J}from"./freegate.js";import{applyFusionsPatch as z}from"./fusions.js";import{EMBEDDED_MODELS as W,EMBEDDED_IDS as D,isEmbeddedModel as Y}from"./embedded-models.js";import{capabilityList as x,isProviderList as O,listProblems as K,primaryProvider as Z,storedShape as _}from"./capability-config.js";import{normalizeRegistries as Q,REGISTRY_KINDS as V}from"@chatpanel/events/registries.js";import{viewContextProviders as ee}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 oe}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}$/,re=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function ie(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);re(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{oe(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}=g({hosts:o.hosts??[]}),b=ie(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 te=["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?te.includes(r)?{mode:"off"}:p.includes(r)?{mode:r}:{unknown:r}:{}}function ge(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(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 Ne(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 P(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||U(F.homedir(),".chatpanel","gateway.config.json")}function Se(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?(Y(e,o.model)||i(`capabilities.${e}.model must be one of ${W[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 ve(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`);X(q(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}:{}};M(r,JSON.stringify(o,null,2),{mode:384});try{G(r,384)}catch{}}function De(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:B(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:J(e)},context:{providers:ee(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 Oe(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function ne(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 _e(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 ke(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=ne(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=$(o.get(i.id),{type:"api",baseUrl:t.baseUrl,apiKey:i.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=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=Q(r.registries),i={...e.registries||{}};for(const t of V)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=H(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=z(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=K(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}},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)}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=Z(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,ke as applyConfigPatch,Oe as applyNerModelSelection,_e as bridgeAgentOptions,P as configPath,ne as isSelfDestination,f as normalizeSandboxConfig,ve as persistConfig,De as publicConfig,Se as registryChildEnv,Ne as sandboxEnvFor,w as sandboxModeFromEnv,ge as sandboxProblems,c as sandboxReadsFromEnv};
|
package/src/context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateContextRequest as
|
|
1
|
+
import{validateContextRequest as B,searchContext as G,CONTEXT_FEDERATED_HEADER as K}from"@chatpanel/events/context-api.js";import{kbContextProvider as z,webContextProvider as A,bedrockContextProvider as L,gatewayContextProvider as D,patchContextProviders as H,viewContextProviders as U,sourcesOfProvider as W}from"@chatpanel/events/context-providers.js";import{gatewayKbClient as N}from"@chatpanel/events/kb-tool.js";import{buildApiRequest as X,readApiResponse as J}from"@chatpanel/events/search-api.js";const M=Object.freeze({allowLoopback:!1,allowPrivate:!1}),i=(c,b,g)=>({status:c,body:{error:{type:b,message:g}}}),m=c=>({status:200,body:c});function F({cfg:c,kb:b,search:g=null,apiEngines:h=()=>[],redact:C=null,rerank:E=null,fetchFn:w=fetch,persist:R=()=>{},buckets:f=null,profiles:y=null,now:T=()=>Date.now(),log:q=()=>{}}={}){const $=()=>(Array.isArray(c.context?.providers)?c.context.providers:[]).filter(n=>n&&n.enabled!==!1);async function S(n){const t=async(r,o,s)=>{const d=await b().handle({method:r,pathname:o.split("?")[0],query:new URLSearchParams(o.split("?")[1]||""),body:s,admin:n.admin,agent:n.agent});if(d.status>=400)throw new Error(d.body?.error?.message||`kb ${d.status}`);return d.body};return((await t("GET","/v1/kb")).kbs||[]).map(r=>({id:r.id,name:r.name,client:N({call:t,kbId:r.id})}))}function x(n,{federated:t=!1}={}){const e=[z({bases:()=>S(n)})];typeof g=="function"&&e.push(A({id:"*",search:g,name:"web"}));for(const r of h().filter(o=>o.enabled!==!1)){const o=r.api.id;e.push(A({id:o,name:r.api.name,search:async(s,{limit:d,signal:k})=>{const u=X(r.api,{q:s,limit:d,vars:r.vars||{}}),a=await w(u.url,{method:u.method,headers:u.headers,body:u.body??void 0,signal:k,maxRedirects:0,policy:M});if(!a.ok)throw new Error(`${r.api.name} ${a.status}`);return{results:J(r.api,await a.json(),{limit:d}).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:r.credentials?.profile&&y?()=>y.keys(r.credentials.profile):{accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,...r.sessionToken?{sessionToken:r.sessionToken}:{}},fetch:(o,s)=>w(o,{...s,maxRedirects:0}),now:T})):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,s)=>w(o,{...s,maxRedirects:0})}))}catch(o){q(`[context] ${r.id}: not usable — ${o.message}`)}return e}async function P(n,t,{federated:e=!1,signal:r=null}={}){let o;try{o=B(n||{})}catch(d){return i(400,"invalid_request",d.message)}const s=await G({...o,providers:x(t,{federated:e}),redact:C,rerank:o.rerank?E:null,signal:r,now:T});if(!t.admin)for(const[d,k]of Object.entries(s.providers))k.error==="not configured"&&/^(bedrock|gw)/.test(d)&&(k.error="needs the gateway token");return m({query:o.query,...s})}function _(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}]:[],...h().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 U(c.context?.providers||[])){const r=(c.context?.providers||[]).find(s=>s.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:W(r)[0],configured:!0,remote:e.kind!=="bucket",...o?{team:o}:{}})}return t}async function O(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=x({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 I(){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 j({method:n="GET",pathname:t="",body:e=null,admin:r=!1,agent:o="",federated:s=!1,signal:d=null}={}){const k={admin:r,agent:o};if(t==="/v1/context")return n!=="POST"?i(405,"method_not_allowed","context: POST"):P(e,k,{federated:s,signal:d});if(t==="/v1/context/profiles")return n!=="GET"?i(405,"method_not_allowed","context: GET"):r?m({profiles:y?y.list():[]}):i(403,"forbidden","context: listing profiles needs the gateway token or the extension origin");if(t==="/v1/context/providers"){if(n==="GET")return m({providers:_(k)});if(n==="POST"){if(!r)return i(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=H(c.context?.providers||[],a)}catch(p){return i(400,"invalid_request",p.message)}c.context={...c.context||{},providers:l};try{R()}catch(p){return i(500,"persist_failed",`context: could not save — ${p.message}`)}return f?.restart(),m({providers:_(k)})}return i(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 i(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 i(404,"not_found",`context: no provider ${u[1]}`);if(u[2]==="test")return m(await O(a));if(a.kind!=="bucket"||!f)return i(400,"invalid_request",`context: ${u[2]} is for a team bucket`);if(u[2]==="sync")return m(await f.run(a));const l=String(e?.name||"").replace(/\\/g,"/").replace(/^\/+/,"");if(!l||l.includes("..")||l.startsWith(".")||l.length>300)return i(400,"invalid_request","context: upload needs a file name (no .., not hidden)");const p=typeof e?.data=="string"?Buffer.from(e.data,"base64"):null;if(!p?.length)return i(400,"invalid_request","context: upload needs data (base64)");try{await f.upload(a,l,p)}catch(v){return i(502,"bucket_failed",v.message)}return a.role==="builder"&&f.run(a),m({ok:!0,key:`${a.prefix||""}${l}`,building:a.role==="builder"})}return i(404,"not_found",`no route ${t}`)}return{handle:j,remoteCards:I,providersFor:x,context:P}}export{F as createContextService};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{editDestinations as w,destinationView as c}from"@chatpanel/events/destinations.js";function k({cfg:r,apply:f,persist:y,isSelf:p=()=>!1}={}){const i=(n,u,a="invalid_request")=>({status:n,body:{error:{message:u,type:a}}}),o=()=>Array.isArray(r.destinations)?r.destinations:[];return{handle({method:n,pathname:u,body:a=null,admin:h=!1}={}){if(!h)return i(403,"destinations: the gateway token or the paired extension is needed — they say where turns go and hold keys","forbidden");const l=/^\/v1\/destinations(?:\/([^/]+))?\/?$/.exec(u);if(!l)return i(404,"destinations: no such route","not_found");let e=null;if(l[1])try{e=decodeURIComponent(l[1])}catch{return i(400,"destinations: the name in the path is not valid")}if(n==="GET"&&!e)return{status:200,body:{destinations:o().map(c)}};if(n==="GET"){const d=o().find(v=>v.id===e);return d?{status:200,body:{destination:c(d)}}:i(404,`no destination called "${e.slice(0,60)}"`,"not_found")}let s;if(n==="DELETE"&&e)s={action:"delete",id:e};else if(n==="POST"&&!e)s={action:"put",destination:a||{}};else if(n==="PUT"&&e)s={action:"put",id:e,destination:{id:e,...a||{}}};else return i(405,`destinations: ${n} is not allowed here`,"method_not_allowed");const t=w(o(),s);if(!t.ok)return i(t.status||400,t.error,t.status===404?"not_found":t.status===409?"conflict":"invalid_request");if(t.destination&&p(t.destination))return i(400,`"${t.destination.baseUrl}" is this gateway — a destination there would send every turn back to itself`);if(f(r,{destinations:t.list}),y(),s.action==="delete")return{status:200,body:{deleted:e}};const b=o().find(d=>d.id===t.destination.id)||t.destination;return{status:n==="POST"?201:200,body:{destination:c(b),keyDropped:t.keyDropped}}}}}export{k as createDestinationsService};
|
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 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(`
|
|
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(t){try{const a=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.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 w=t=>{const a=String(t||"").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:t=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=t(),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:w(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(t=globalThis,{allow:a=null}={}){if(t.__chatpanelEgress)return a&&t.__chatpanelEgress.setGate(a),t.__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:w(i.host)})}catch{l=!0}if(l)return null;const s=`${i.host}:${i.port}`;n.blocked.includes(s)||n.blocked.push(s);const e=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return e.code="EGRESS_POLICY",e},o=t.fetch;typeof o=="function"&&(t.fetch=function(i,l){const s=p(i);return s?Promise.reject(s):o.call(this,i,l)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(c,i,l){const s=p(i[0]);if(s)throw s;return Reflect.construct(c,i,l)}})),t.__chatpanelEgress=n,t===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function m(t){try{return new URL(t).host}catch{return String(t||"")}}function R(t={},a=process.env,n=process.platform,r=process.arch){const p=[],o=(e,d,{when:h="always",off:f=null,local:v=!1,data:k=""}={})=>{e&&p.push({host:e,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"}),t.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=t.link?.enabled===!1?null:L(t.link||{}).relay;if(u){const e=new URL(u).host;o(e,"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=t.search?.searxng?.url||"";if(c){let e=c;try{e=new URL(c).host}catch{}o(e,"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(e)})}if(t.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 e of E(t).filter(d=>d.kind==="api"&&d.enabled!==!1))o(e.api.host,`web search: ${e.api.name} (search API${e.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: "${e.api.id}", enabled: false }]`,data:"the same query"})}for(const e of Array.isArray(t.context?.providers)?t.context.providers:[]){if(!e||e.enabled===!1)continue;const d=`context.providers: [{ id: "${e.id}", enabled: false }] (Settings › Knowledge › Sources)`;if(e.kind==="bedrock"&&e.region)o(`bedrock-agent-runtime.${e.region}.amazonaws.com`,`knowledge: your AWS Bedrock knowledge base "${e.name||e.id}" (Retrieve)`,{when:"a context search names it (bedrock:"+e.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(e.kind==="gateway"&&e.url){let h=e.url;try{h=new URL(e.url).host}catch{}o(h,`knowledge: the ChatPanel gateway "${e.name||e.id}" you configured (its /v1/context and /v1/kb)`,{when:"a context search names it (gw:"+e.id+"), and the knowledge library lists its bases",off:d,data:e.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(e.kind==="bucket"&&e.endpoint){let h=e.endpoint;try{const f=new URL(e.endpoint);h=e.addressing==="virtual"?`${e.bucket}.${f.host}`:f.host}catch{}o(h,`knowledge: the team base "${e.name||e.id}" kept in your ${e.provider||"S3-compatible"} bucket ${e.bucket}/${e.prefix||""}`,{when:e.role==="builder"?`every ${e.pollMinutes||5} min: list the documents, read the new and changed ones, publish the index`:`every ${e.pollMinutes||5} min: is a newer index published? then fetch only what changed`,off:d,data:`${e.role==="builder"?"the index of the documents in that bucket (passages, vectors, the report), written back beside them":"nothing of yours — reads of the published index"}; ${e.credentials?.profile?`signed with your ${e.credentials.from==="oci"?"OCI config":"shared credentials"} profile "${e.credentials.profile}" (read from the file at each call)`:"the keys you gave it"}`,local:/^(localhost|127\.|\[::1\])/.test(h)})}}if(t.read?.remote?.url){let e=t.read.remote.url;try{e=new URL(t.read.remote.url).host}catch{}o(e,"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(e)})}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[e,d]of Object.entries(i))for(const h of S(t.capabilities?.[e],e,{destinations:t.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/${e}`,off:h.service?`stop the ${h.service} service under Settings › Runtime`:`capabilities.${e} = 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[e,d]of Object.entries(t.upstreams||{}))d?.baseUrl&&o(m(d.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:w(m(d.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&o(m(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:w(m(e.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"}),t.ner?.url&&o(m(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(m(t.ner.url).split(":")[0]),data:"the text being redacted"});const l=t.tts||{};if(l.provider==="openai"||l.provider==="elevenlabs"){const e=l.remote?.baseUrl?m(l.remote.baseUrl):l.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(e,`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"&&t.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=t.bridge?.url||"http://127.0.0.1:4319";return o(m(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(t,{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(t,p);for(const s of c||[])!s.host||s.route!=="link"&&s.route!=="relay"||l.some(e=>e.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 _(t){const a=[];a.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&a.push(`observed since ${t.since}`),a.push(""),a.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||a.push(" (none yet)");for(const n of t.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 t.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(t.certificates){const n=t.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(t.confined&&(a.push(""),a.push("CONFINEMENT — what this process itself can reach on this computer"),a.push(` ${$(t.confined)}`),t.confined.on&&a.push(" checked at start: home folder listed "+(t.confined.homeListed?"YES":"no")+" · home folder written "+(t.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(t.confined.fenceWritten?"YES":"no")+" · own folder written "+(t.confined.stateWritten?"yes":"NO"))),t.link){a.push(""),a.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),t.link.partners?.length||a.push(" (none — no partner can reach this gateway until you pair one)");for(const n of t.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 t.managed&&(a.push(""),a.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),a.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),a.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),a.push(""),a.push(`Scope: ${t.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
2
|
`)}export{A as createEgressLedger,R as declaredEgress,O as egressAudit,P as egressLedger,_ as formatAudit,N as installEgressLedger};
|
package/src/embedded-models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const a=Object.freeze({rerank:Object.freeze([Object.freeze({id:"Xenova/ms-marco-TinyBERT-L-2-v2",label:"TinyBERT L-2",mb:5,languages:"English",note:"lightest — the default"}),Object.freeze({id:"jinaai/jina-reranker-v1-tiny-en",label:"Jina reranker v1 tiny",mb:34,languages:"English",note:"a little sharper, still light"}),Object.freeze({id:"Xenova/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",mb:24,languages:"English",note:"sharper on direct questions; ~0.4 s CPU per search"}),Object.freeze({id:"Alibaba-NLP/gte-reranker-modernbert-base",label:"GTE reranker ModernBERT base",mb:154,languages:"English",note:"most accurate; ~1.7 s CPU per search"}),Object.freeze({id:"Xenova/bge-reranker-base",label:"BGE reranker base",mb:289,languages:"100+ languages",note:"multilingual; ~1 GB while loaded"})]),decide:Object.freeze([Object.freeze({id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot",mb:147,languages:"English",note:"the default"})]),embed:Object.freeze([Object.freeze({id:"Xenova/multilingual-e5-small",label:"Multilingual E5 small",mb:118,dims:384,languages:"100+ languages",note:"the default"}),Object.freeze({id:"Xenova/all-MiniLM-L6-v2",label:"MiniLM L6 v2",mb:23,dims:384,languages:"English",note:"lighter, English only"})])}),r=Object.freeze(Object.keys(a)),t=e=>a[e]?.[0]?.id||null,i=(e,l)=>!!a[e]?.some(n=>n.id===l);export{r as EMBEDDED_IDS,a as EMBEDDED_MODELS,t as defaultEmbeddedModel,i as isEmbeddedModel};
|
package/src/kb-bucket-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as le,mkdirSync as W,readFileSync as q,writeFileSync as ue,readdirSync as pe,rmSync as fe,renameSync as he}from"node:fs";import{join as A,basename as me}from"node:path";import be from"node:os";import{createHash as ye}from"node:crypto";import{bucketClient as ve,indexKey as $,isDocumentKey as ge,bucketDocId as ke,splitIndexParts as we,validateRevision as M,planReplicaSync as Ae,assembleReplica as $e,makeLease as Se,leaseState as Oe,replicaFreshness as je,bucketWhere as De,sha256Hex as G,KB_REVISION_FORMAT as Ie}from"@chatpanel/events/kb-bucket.js";import{planFolderSync as xe}from"@chatpanel/events/kb-folder-sync.js";import{createKb as Ne,removeDocument as Be,serializeKb as Re,deserializeKb as Te}from"@chatpanel/events/kb-index.js";import{graphReport as Fe}from"@chatpanel/events/kb-graph.js";const ze=new TextEncoder,Me=r=>typeof r=="string"?ze.encode(r):r instanceof Uint8Array?r:new Uint8Array(r.buffer,r.byteOffset,r.byteLength),Q=(r,S)=>{const I=`${r}.tmp-${process.pid}`;ue(I,S,{mode:384}),he(I,r)},Ee=(r={},S=be.hostname())=>typeof r.builderName=="string"&&r.builderName.trim()?r.builderName.trim().slice(0,60):`gateway-${ye("sha256").update(String(S)).digest("hex").slice(0,8)}`;function Ve({store:r,kb:S,entries:I=()=>[],fetchFn:X,now:u=()=>Date.now(),log:x=()=>{},holder:Y=null,version:Z="",subtle:E=null,profiles:ee=null}={}){const J=new Map,N=new Map,O=new Map,K=e=>e.kbId||e.id,L=e=>A(r.dirOf(e),"team.json"),te=e=>A(r.dirOf(e),"parts"),B=e=>ve(e,{fetch:X,now:u,subtle:E,profiles:ee});function R(e){if(J.has(e.id))return J.get(e.id);let t={kbId:K(e),role:e.role,revision:0,rev:null,syncedAt:0,checkedAt:0,error:"",updating:!1,remoteRevision:0,behindDocs:0,etag:""};try{const i=JSON.parse(q(L(K(e)),"utf8"));i?.provider===e.id&&(t={...t,...i.state,rev:i.state?.rev?M(i.state.rev):null,updating:!1})}catch{}return J.set(e.id,t),t}const se=(e,t)=>{try{W(r.dirOf(t.kbId),{recursive:!0,mode:448}),Q(L(t.kbId),JSON.stringify({provider:e.id,state:{...t,updating:!1}}))}catch(i){x(`[team] ${e.id}: state not saved — ${i.message}`)}};async function ie(e){const t=R(e),i=B(e),c=await i.get($(e,"revision.json"),{etag:t.rev?t.etag:""});if(t.checkedAt=u(),c.status===304)return t.error="",t.remoteRevision=t.revision,t.behindDocs=0,{upToDate:!0};if(c.status===404)throw new Error("no index has been published to this bucket yet — a builder has not run");const a=M(JSON.parse(new TextDecoder().decode(c.bytes)));t.remoteRevision=a.revision;const h=te(t.kbId);W(h,{recursive:!0,mode:448});const j=m=>le(A(h,m)),l=Ae({current:t.rev,next:a,have:j});if(l.upToDate)return t.etag=c.etag,t.error="",t.behindDocs=0,{upToDate:!0};t.behindDocs=l.added+l.changed+l.removed,t.updating=!0;try{for(const n of l.fetch){const v=await i.get($(e,n.file));if(v.status!==200)throw new Error(`part ${n.file} is missing from the bucket (${v.status})`);if(await G(v.bytes,E)!==n.hash)throw new Error(`part ${n.file} does not match its hash — not used`);Q(A(h,n.hash),v.bytes)}const m=$e(a,n=>new Uint8Array(q(A(h,n))));m.manifest={...m.manifest,id:t.kbId};const d=Te(m);r.save(d);const z=new Set([a.manifest,a.notes,...a.report?[a.report]:[],...a.docs.flatMap(n=>[n.chunksFile,n.vectorsFile].filter(Boolean))].map(n=>n.hash));for(const n of pe(h))z.has(n)||fe(A(h,n),{force:!0});return Object.assign(t,{rev:a,revision:a.revision,builtAt:a.builtAt,builtBy:a.builder.name,etag:c.etag,syncedAt:u(),error:"",behindDocs:0}),x(`[team] ${e.id}: revision ${a.revision} (${l.added} added, ${l.changed} changed, ${l.removed} removed; ${l.fetch.length} parts, ${l.bytes} bytes)`),{revision:a.revision,...l,fetch:l.fetch.length}}finally{t.updating=!1}}async function ne(e){const t=R(e),i=B(e),c=Y||Ee(e),a=`${c}#${process.pid}`,h=$(e,"lease.json"),j=await i.get(h).then(m=>m.status===200?JSON.parse(new TextDecoder().decode(m.bytes)):null).catch(()=>null);if(Oe(j,{holder:a,now:u()})==="held")throw new Error(`another builder (${j.holder}) is building until ${new Date(j.until).toISOString()}`);await i.put(h,JSON.stringify(Se({holder:a,now:u()})),{contentType:"application/json"});const l=await i.get(h);if(l.status!==200||JSON.parse(new TextDecoder().decode(l.bytes)).holder!==a)throw new Error("another builder took the lease at the same moment — this one stands aside");try{const m=await i.get($(e,"revision.json")),d=m.status===200?M(JSON.parse(new TextDecoder().decode(m.bytes))):null,z=S();let n=r.load(t.kbId);n||(n=Ne({id:t.kbId,name:e.name||e.bucket,now:u}));const v=`s3://${e.bucket}/${e.prefix||""}`;Array.isArray(n.sources)||(n.sources=[]);let b=n.sources.find(s=>s.kind==="bucket"&&s.path===v);b||(b={kind:"bucket",path:v,files:{},syncedAt:0},n.sources.push(b));const{objects:re}=await i.list(e.prefix||""),H=re.filter(s=>ge(e,s.key)).map(s=>({path:s.key,size:s.size,mtime:s.mtime,etag:s.etag})),oe=Object.entries(b.files).map(([s,o])=>({path:s,id:o.id,size:o.size,etag:o.etag})),f=xe({known:oe,listing:H}),k=[];for(const s of f.remove){Be(n,s,{now:u});for(const[o,p]of Object.entries(b.files))p.id===s&&delete b.files[o]}const ae=new Map(H.map(s=>[s.path,s]));for(const s of[...f.add,...f.change.map(o=>o.path)]){const o=ae.get(s);try{const p=await i.get(s);if(p.status!==200)throw new Error(`not readable (${p.status})`);const y=ke(s);await z.addBytes(n,Buffer.from(p.bytes),{name:me(s),source:{kind:"bucket",name:s},id:y,reach:"internal"}),b.files[s]={id:y,size:o.size,etag:o.etag,mtime:o.mtime}}catch(p){k.push({path:s,why:p.message})}}b.syncedAt=u(),b.lastSync={at:b.syncedAt,added:f.add.length,changed:f.change.length,removed:f.remove.length,same:f.same,skipped:k.length,skippedSample:k.slice(0,20)},await z.embedAll(n),r.save(n);const w=Re(n),U=we(w),ce=new Set(d?[d.manifest,d.notes,...d.report?[d.report]:[],...d.docs.flatMap(s=>[s.chunksFile,s.vectorsFile].filter(Boolean))].map(s=>s.hash):[]),D=async(s,o,p)=>{const y=Me(s),_=await G(y,E),V=`objects/${_}.${o}`;return ce.has(_)||await i.put($(e,V),y,{contentType:p}),{file:V,hash:_,bytes:y.length}},P=await D(U.manifest,"json","application/json");if(d&&d.manifest.hash===P.hash)return Object.assign(t,{revision:d.revision,rev:d,builtAt:d.builtAt,builtBy:d.builder.name,syncedAt:u(),error:""}),{published:!1,revision:d.revision,...f,skipped:k};const de=new Map(Object.entries(b.files).map(([s,o])=>[o.id,{key:s,...o}])),C=[];for(const s of U.docs){const o=w.manifest.docs.find(y=>y.id===s.id)||{},p=de.get(s.id)||{key:o.source?.name||s.id,etag:"",size:0};C.push({id:s.id,key:p.key,etag:p.etag||"",size:p.size||0,title:o.title||p.key,type:o.type||"",pages:o.pages||0,chunks:s.count,chunksFile:await D(s.chunks,"jsonl","application/x-ndjson"),...s.vectors?{vectorsFile:await D(new Uint8Array(s.vectors.buffer,s.vectors.byteOffset,s.vectors.byteLength),"f32","application/octet-stream")}:{}})}const g=M({format:Ie,kind:"chap-kb-index",kb:{id:t.kbId,name:n.name},revision:(d?.revision||0)+1,builtAt:u(),builder:{name:c,version:Z},embed:w.vectors.dims?{model:w.vectors.model,recipe:w.vectors.recipe,dims:w.vectors.dims}:null,manifest:P,notes:await D(U.notes,"json","application/json"),report:await D(Fe(n),"md","text/markdown"),docs:C});return await i.put($(e,"revision.json"),JSON.stringify(g),{contentType:"application/json"}),Object.assign(t,{rev:g,revision:g.revision,builtAt:g.builtAt,builtBy:c,syncedAt:u(),checkedAt:u(),remoteRevision:g.revision,error:""}),x(`[team] ${e.id}: published revision ${g.revision} (${f.add.length} added, ${f.change.length} changed, ${f.remove.length} removed, ${k.length} skipped)`),{published:!0,revision:g.revision,...f,skipped:k}}finally{await i.del(h).catch(()=>{})}}function T(e){if(O.has(e.id))return O.get(e.id);const t=R(e);t.role=e.role;const i=(e.role==="builder"?ne(e):ie(e)).then(c=>(t.error="",c)).catch(c=>(t.error=String(c?.message||c).slice(0,300),t.checkedAt=u(),x(`[team] ${e.id}: ${t.error}`),{error:t.error})).finally(()=>{O.delete(e.id),se(e,t)});return O.set(e.id,i),i}const F=()=>(I()||[]).filter(e=>e?.kind==="bucket"&&e.enabled!==!1);return{run:T,runById:e=>{const t=F().find(i=>i.id===e);return t?T(t):Promise.resolve({error:`no bucket source ${e}`})},test:e=>B(e).test(),upload:(e,t,i)=>B(e).put(`${e.prefix||""}${String(t).replace(/^\/+/,"")}`,i),teamOf(e){const t=F().find(c=>K(c)===e);if(!t)return null;const i=R(t);return{role:t.role,provider:t.id,revision:i.revision,builtAt:i.builtAt||0,...i.builtBy?{builtBy:i.builtBy}:{},syncedAt:i.syncedAt,where:De(t),freshness:je({revision:i.revision,remoteRevision:i.remoteRevision,syncedAt:i.syncedAt,checkedAt:i.checkedAt,error:i.error,updating:O.has(t.id),behindDocs:i.behindDocs,now:u()})}},start(){for(const e of F()){if(N.has(e.id))continue;const t=setInterval(()=>{const c=F().find(a=>a.id===e.id);c&&T(c)},Math.max(1,e.pollMinutes||5)*6e4);t.unref?.(),N.set(e.id,t),setTimeout(()=>T(e),2e3).unref?.()}},stop(){for(const e of N.values())clearInterval(e);N.clear()},restart(){this.stop(),this.start()}}}export{Ee as builderName,Ve as createBucketSync};
|
package/src/kb.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as le,statSync as
|
|
2
|
-
`).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(
|
|
3
|
-
`));if(k&&$){const i=e.docs.find(d=>d.textHash===$&&d.id!==r);if(i)return{duplicateOf:i}}const T=a.path&&s.links?.length?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};
|
|
1
|
+
import{readFileSync as le,statSync as ne,readdirSync as je,realpathSync as ue}from"node:fs";import{join as ze,basename as C,extname as fe,resolve as Be,dirname as De}from"node:path";import Fe from"node:os";import{createKb as pe,addDocument as se,removeDocument as V,addNote as Ne,setNoteStatus as Ce,searchKb as Ie,embedMissing as We,kbNeedsVectors as Re,kbStatus as Ue,readPage as Xe,chunkById as he,refreshKb as Y,setKbAccess as He,kbMayUse as re,graphWalk as Ve}from"@chatpanel/events/kb-index.js";import{kbResearch as Ye}from"@chatpanel/events/kb-research.js";import{neighbours as Je,pathBetween as Qe,resolveNode as ge,graphReport as Ze}from"@chatpanel/events/kb-graph.js";import{outlineOf as me}from"@chatpanel/events/kb-chunk.js";import{routeKb as qe,validateKbCreate as et,validateKbAdd as tt,validateKbSearch as nt,validateKbResearch as st,validateKbGraph as rt,validateKbNote as at,validateKbNoteStatus as ot,validateKbAccess as it,validateKbSync as ct,validateKbReveal as dt,kbGraphLimit as lt,KB_LOCAL_ACTIONS as ut}from"@chatpanel/events/kb-capability.js";import{communities as ft,topEntities as be}from"@chatpanel/events/kb-graph.js";import{kbCard as pt,pageStrip as ht}from"@chatpanel/events/kb-view.js";import{planFolderSync as gt,folderDocId as mt,folderSource as bt,knownFiles as kt}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as yt,markdownLinks as wt,resolveLinks as vt,visibleTextHash as St,decodeText as $t}from"@chatpanel/events/kb-html.js";import{secretReason as ke,SKIP_DIR_NAMES as Ot,sniffType as Tt,checkAttachablePath as xt}from"@chatpanel/events/attached-paths.js";import{paginateText as J,MAX_DOCUMENT_BYTES as ae}from"./extract-capability.js";import{defaultEmbeddedModel as _t}from"./embedded-models.js";import{primaryProvider as Et}from"./capability-config.js";function P(b,A){const S=Ue(b);return A?S:{...S,documents:S.documents.map(K=>{const{path:B,...L}=K.source||{};return{...K,source:L}})}}const I=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),ye=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Pt=new Set([".html",".htm",".xhtml"]),At=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(b,A,S,K={})=>({status:b,body:{error:{type:A,message:S},...K}}),w=b=>({status:200,body:b});function Kt(b,{limit:A=60}={}){Y(b);const S=b.graph||{nodes:[],edges:[]},K=new Set(be(S,{limit:A}).map(h=>h.id)),B=new Map(be(S,{limit:A}).map(h=>[h.id,h.weight])),L=S.nodes.filter(h=>h.kind==="entity"?K.has(h.id)||h.type==="person"||h.type==="role":h.kind!=="chunk").slice(0,A*6),D=new Set(L.map(h=>h.id)),j=S.edges.filter(h=>D.has(h.from)&&D.has(h.to)),y=h=>h.kind==="holds"||h.kind==="member"||h.kind==="has",W=[...j.filter(y),...j.filter(h=>!y(h))].slice(0,A*20),z=ft(S).map(h=>({...h,members:h.members.filter(R=>D.has(R))})).filter(h=>h.members.length>=2).slice(0,24);return{nodes:L.map(h=>({id:h.id,kind:h.kind,label:h.label,count:h.count,...h.type?{type:h.type}:{},...h.doc?{doc:h.doc}:{},...B.has(h.id)?{weight:B.get(h.id)}:{}})),edges:W,communities:z,total:{nodes:S.nodes.length,edges:S.edges.length}}}function Vt({store:b,extract:A=null,embedded:S=null,cfg:K={},rerank:B=null,read:L=null,completer:D=null,log:j=()=>{},now:y=()=>Date.now(),home:W=Fe.homedir(),team:z=()=>null,remoteCards:h=null,reveal:R=null,confined:we=()=>!1}={}){const N=()=>{const e=Et(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||_t("embed")||""},Q=(e="passage")=>{const t=N();if(!S||!t)return null;const c=S.health("embed",t);return c.state!=="ready"&&c.state!=="loading"&&!c.installed?(S.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await S.embed(t,l,{kind:e})).vectors},ve=typeof B=="function"?B:null,Z=new Set;function oe(e){!e||Z.has(e.id)||e.embed==="off"||!Q("passage")||Re(e)&&(Z.add(e.id),F(e).then(t=>{t&&(b.save(e),j(`[kb] ${e.id}: ${t} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>Z.delete(e.id)))}async function F(e,{late:t=()=>!1}={}){const c=Q("passage");if(!c)return 0;try{return await We(e,c,{model:N(),late:t})}catch(l){return j(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function Se(e,t,c=""){const l=Tt(e,t);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=$t(e);if(/\.x?html?$/i.test(t)||/html/i.test(l.label||"")){const s=yt(r);return{type:"html",pages:J(s.markdown).map(($,T)=>({page:T+1,text:$})),title:s.title,links:s.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
|
|
2
|
+
`).find(s=>s.trim())||""),k=/\.(md|markdown)$/i.test(t);return{type:l.label||"text",pages:J(r).map((s,$)=>({page:$+1,text:s})),title:f?f[1].trim():"",links:k?wt(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),a=await o.open(e,{name:t,hint:c}),u=[];for(let r=1;r<=a.pages;r+=1){let f="";try{f=String((await o.page(a.hash,r)).text||"")}catch(k){j(`[kb] ${t} p.${r}: ${k.message}`)}u.push({page:r,text:f,...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 U(e,t,{name:c,hint:l="",title:o="",source:a={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const s=await Se(t,c,l),$=St(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?vt(a.path,s.links,{root:f||De(a.path)}):[],n=se(e,{id:r,title:o||s.title||C(c),pages:s.pages,source:{kind:a.kind||"bytes",name:c,...a},hash:s.hash||"",type:s.type,reach:u,now:y,links:T,textHash:$,markdownHeadings:!!s.markdown});return{id:n.doc.id,title:n.doc.title,pages:n.doc.pages,chunks:n.doc.chunks,replaced:n.replaced,...s.scanned?{scanned:!0}:{}}}function $e(e,t){const c=fe(e).toLowerCase();return!ye.has(c)&&!At.has(c)?!1:t?.length?t.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return c===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function ie(e,{recursive:t=!0,include:c=null}={}){const l=xt(e,{home:W,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=ue(Be(e.replace(/^~(?=$|\/)/,W))),a=[],u=[];let r=0;const f=($,T)=>{if(a.length>=I.files)return u.push({path:T,why:`stopped at ${I.files} files`}),!1;if(ke($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let n;try{n=ne($)}catch{return!0}const i=fe($).toLowerCase(),d=ye.has(i)||Pt.has(i)?ae:I.textBytes;return n.size>d?(u.push({path:T,why:`too large (${Math.round(n.size/1048576)} MB)`}),!0):r+n.size>I.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=n.size,a.push({full:$,rel:T,size:n.size,mtime:Math.floor(n.mtimeMs)}),!0)};if(!ne(o).isDirectory())return f(o,C(o)),{root:o,files:a,skipped:u,single:!0};const s=($,T,n)=>{if(n>I.depth)return!0;let i=[];try{i=je($,{withFileTypes:!0}).sort((d,m)=>d.name.localeCompare(m.name))}catch{return!0}for(const d of i){const m=d.name;if(m.startsWith(".")&&d.isDirectory())continue;const v=ze($,m),p=T?`${T}/${m}`:m;if(d.isDirectory()){if(Ot.has(m)||!t)continue;try{if(!ue(v).startsWith(o)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(v,p,n+1))return!1;continue}if(!(!d.isFile()&&!d.isSymbolicLink())){if(ke(v)){u.push({path:p,why:"withheld (a credential store)"});continue}if($e(m,c)&&!f(v,p))return!1}}return!0};return s(o,"",0),{root:o,files:a,skipped:u}}async function Oe(e,{path:t,recursive:c=!0,include:l=null,title:o=""}){const{files:a,skipped:u,single:r}=ie(t,{recursive:c,include:l}),f=[];for(const k of a)try{const s=await U(e,le(k.full),{name:C(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Te(e,{path:t,include:c=null,rebuild:l=!1},{progress:o=null}={}){const{root:a,files:u,skipped:r}=ie(t,{recursive:!0,include:c}),f=bt(e,a,{include:c});if(l){for(const p of Object.values(f.files))p?.id&&V(e,p.id,{now:y});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,x]of Object.entries(f.files))x?.dupOf&&!k.has(x.dupOf)&&delete f.files[p];const s=gt({known:kt(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});o&&(o.total=s.add.length+s.change.length,o.done=0);const $=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){V(e,p,{now:y});for(const[x,E]of Object.entries(f.files))E.id===p&&(delete f.files[x],T.push(x.startsWith(`${a}/`)?x.slice(a.length+1):x))}const n=[],i=[],d=[],m=p=>String(p||"").startsWith(`${a}/`)?p.slice(a.length+1):p,v=async(p,x)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(p),G=mt(p);try{const _=await U(e,le(p),{name:C(p),source:{kind:"file",path:p},reach:"internal",id:G,root:a,dedupe:!0});_.duplicateOf?(e.docs.some(ee=>ee.id===G)&&V(e,G,{now:y}),f.files[p]={id:G,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},d.push({path:E.rel,of:m(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:G,size:E.size,mtime:E.mtime},x.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const p of s.add)await v(p,n);for(const p of s.change)await v(p.path,i);return f.syncedAt=y(),f.lastSync={at:f.syncedAt,added:n.length,changed:i.length,removed:T.length,same:s.same,duplicates:d.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:d.slice(0,20)},{root:a,added:n,changed:i,removed:T,same:s.same,duplicates:d,skipped:r}}async function xe(e,{url:t,title:c=""}){if(!L)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await L().read({url:t,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const a=J(o).map((r,f)=>({page:f+1,text:r})),u=se(e,{title:c||l.body.title||t,pages:a,source:{kind:"url",url:l.body.url||t,name:l.body.title||""},type:"html",reach:"web",now:y});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function _e(e,t,{admin:c=!1}={}){const l=y();let o=[],a=[];if(t.kind==="bytes"){const r=Buffer.from(t.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>ae)return g(413,"too_large",`kb: ${r.length} bytes is over the ${ae}-byte limit`);try{o.push(await U(e,r,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(f){return X(f)}}else if(t.kind==="path"){if(!c)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:o,skipped:a}=await Oe(e,t))}catch(r){return X(r)}}else if(t.kind==="url")try{o.push(await xe(e,t))}catch(r){return X(r)}else if(t.kind==="text"){const r=J(t.text).map((k,s)=>({page:s+1,text:k})),f=se(e,{title:t.title||t.name,pages:r,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:y});o.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=o.length?await F(e):0;return b.save(e),w({added:o,skipped:a,embedded:u,kb:P(e,c),ms:y()-l})}function X(e){const t=e?.code||"";return t==="refused"?g(403,"refused",`kb: ${e.message}`):t==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):t==="too_large"?g(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?g(502,"read_failed",`kb: ${e.message}`):t==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ee=e=>e.vectors?.model&&e.vectors.model!==N()?null:Q("query"),q=(e,t)=>Ie(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],...t.filters?{filters:t.filters}:{},embed:Ee(e),rerank:t.rerank===!1?null:ve,now:y}),Pe=(e,t)=>e.docs.find(c=>c.id===t)?.title||t,ce=(e,t)=>{const c=he(e,t);if(!c)return null;const l=c.kind==="note"?"Note":Pe(e,c.doc);return{...c,title:l,cite:c.kind==="note"?`[note ${c.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${c.page}]`}};function Ae(e,t){Y(e);const c=t.node.replace(/^chunk:/,""),l=(/#\d+$/.test(c)&&he(e,c)?{id:`chunk:${c}`,kind:"chunk",label:c}:null)||ge(e.graph,t.node);if(!l)return w({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},a=Ve(e,l.id,{limit:Math.min(8,t.limit||6),...t.query?{query:t.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:Je(e.graph,l.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit}),passages:a.passages,next:a.next};if(t.to){const r=ge(e.graph,t.to);u.to=t.to,u.path=r?(Qe(e.graph,l.id,r.id)||[]).map(o):null,r&&!u.path.length&&(u.path=null)}return w(u)}async function Ke(e,t,{admin:c=!1}={}){if(t.model&&!c)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=t.model&&typeof D=="function"?D(t.model):null,o=P(e,c),a=await Ye(t.question,{search:(u,r)=>q(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||t.docs||null}),outline:async u=>u?me(e.chunks,{doc:u}):e.outline,read:async u=>ce(e,u),complete:l,kbName:e.name,docs:o.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:y});return w({attachment:a.attachment,read:a.read,hits:a.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:a.queries,verdict:a.verdict,rounds:a.rounds,ask:a.ask,how:a.how,frame:{whole:a.frame.whole,docs:a.frame.docs},ms:a.ms})}const M=new Map;function de(e,t){const c=P(e,t),l=e.chunks.length?e.chunks.filter(a=>a.form||a.label).length/e.chunks.length:1,o=t?(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:{at:a.lastSync.at,added:a.lastSync.added,changed:a.lastSync.changed,removed:a.lastSync.removed,skipped:a.lastSync.skipped}}:{}})):(e.sources||[]).map(a=>({kind:a.kind,syncedAt:a.syncedAt||0}));return pt({...c,coverage:c.chunks?Math.round(c.vectors/c.chunks*100):0,placed:l,sources:o,...M.has(e.id)?{syncing:(({done:a,total:u})=>({done:a,total:u}))(M.get(e.id).progress)}:{}},{outline:e.outline,team:z(e.id),now:y()})}async function Me({method:e="GET",pathname:t="",query:c=new URLSearchParams,body:l=null,admin:o=!1,agent:a="",local:u=!0}={}){const r=qe(t);if(!r)return g(404,"not_found",`no route ${t}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ut.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:o,agent:String(a||c.get("agent")||"").trim().toLowerCase()},k=n=>{try{return{value:n()}}catch(i){return{res:g(400,"invalid_request",i.message)}}};if(!r.id){if(e==="GET"&&c.get("view")==="card"){const n=[];for(const{manifest:d}of b.list()){if(!re({access:d.access},f))continue;const m=b.load(d.id);m&&n.push(de(m,o))}const i=o&&typeof h=="function"?await h({admin:o}).catch(d=>[{gateway:"remote",error:d.message}]):[];return w({cards:n,...i.length?{remote:i}:{}})}if(e==="GET")return w({kbs:b.list().filter(({manifest:n})=>re({access:n.access},f)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=k(()=>et(l||{}));if(n.res)return n.res;const i=n.value;if(i.id&&b.load(i.id))return w({kb:P(b.load(i.id),o),existed:!0});const d=pe({id:i.id,name:i.name,embed:i.embed,now:y});return b.save(d),{status:201,body:{kb:P(d,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(z(r.id))return H(r.id);const n=k(()=>ct(l||{}));if(n.res)return n.res;const i=n.value,d=M.get(r.id);if(d)return{status:202,body:{running:!0,progress:{...d.progress},kb:d.base?P(d.base,o):null}};let m=b.load(r.id);const v=!m;m||(m=pe({id:r.id,name:i.name||C(String(i.path).replace(/[\\/]+$/,""))||r.id,now:y}),b.save(m));const p=y(),x={done:0,total:0},E=(async()=>{const O=await Te(m,i,{progress:x});if(x.cancel)return{cancelled:!0};const Ge=O.added.length+O.changed.length+O.removed.length,Le=O.added.length||O.changed.length?await F(m):0;return(Ge||v)&&b.save(m),{folder:O.root,added:O.added,changed:O.changed,removed:O.removed,same:O.same,duplicates:O.duplicates,skipped:O.skipped,embedded:Le,made:v,kb:P(m,o),ms:y()-p}})();M.set(r.id,{progress:x,base:m}),E.catch(O=>j(`[kb] ${r.id}: sync failed — ${O?.message||O}`)).finally(()=>M.delete(r.id));const G=i.waitMs??5e3;if(G===0)return{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}};let _=null;const ee=new Promise(O=>{_=setTimeout(()=>O(null),G)});let te;try{te=await Promise.race([E,ee])}catch(O){return clearTimeout(_),X(O)}return clearTimeout(_),te?w(te):{status:202,body:{running:!0,progress:{...x},made:v,kb:P(m,o)}}}const s=b.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=z(s.id)?.role==="replica",T=!!z(s.id);if(!re(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){M.has(s.id)||oe(s);const n=P(s,o),i=o?(s.sources||[]).map(d=>({kind:d.kind,path:d.path,files:Object.keys(d.files||{}).length,syncedAt:d.syncedAt||0,...d.lastSync?{lastSync:d.lastSync}:{}})):void 0;return w({kb:{...n,coverage:n.chunks?Math.round(n.vectors/n.chunks*100):0,bytes:b.sizeOf(s.id),dir:o?b.dirOf(s.id):void 0,...i?.length?{sources:i}:{},...M.has(s.id)?{syncing:(({done:d,total:m})=>({done:d,total:m}))(M.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const n=M.get(s.id);return n&&(n.progress.cancel=!0),b.remove(s.id),w({ok:!0,...n?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>tt(l||{}));return n.res?n.res:_e(s,n.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?V(s,r.rest,{now:y})?(b.save(s),w({ok:!0,kb:P(s,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const n=Number(c.get("page"))||1,i=Xe(s,r.rest,n);return i?w(i):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return w({documents:P(s,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const n=ce(s,r.rest);return n?w(n):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){Y(s);const n=c.get("doc");return w({outline:n?me(s.chunks,{doc:n}):s.outline})}break}case"search":{if(e==="POST"){const n=k(()=>nt(l||{}));if(n.res)return n.res;const i=y(),d=await q(s,n.value);return oe(s),w({...d,ms:y()-i})}break}case"research":{if(e==="POST"){const n=k(()=>st(l||{}));return n.res?n.res:Ke(s,n.value,{admin:o})}break}case"graph":{if(e==="GET")return w(Kt(s,{limit:lt(c.get("limit"))}));if(e==="POST"){const n=k(()=>rt(l||{}));return n.res?n.res:Ae(s,n.value)}break}case"report":{if(e==="GET")return Y(s),{status:200,text:Ze(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return w({notes:s.notes});if($&&e==="POST")return H(s.id);if(e==="POST"&&!r.rest){const n=k(()=>at(l||{}));if(n.res)return n.res;const i=n.value,d=i.status==="accepted"&&o?"accepted":"proposed",m=Ne(s,{text:i.text,cites:i.cites||[],by:i.by||(o?"user":"agent"),status:d,now:y});return await F(s),b.save(s),{status:201,body:{note:m}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=k(()=>ot(l||{}));if(n.res)return n.res;const i=n.value,d=Ce(s,r.rest,i.status,{now:y});return d?(b.save(s),w({note:d,removed:i.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return w({access:s.access});if($&&e==="POST")return H(s.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=k(()=>it(l||{}));if(n.res)return n.res;const i=He(s,n.value,{now:y});return b.save(s),w({access:i})}break}case"pages":{if(e!=="GET")break;const n=c.get("doc")||s.docs[0]?.id,i=s.docs.find(d=>d.id===n);return i?w(ht(s.chunks,i)):g(404,"not_found",`kb: no document ${n||""}`)}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(we())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(z(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof R!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const n=k(()=>dt(l||{}));if(n.res)return n.res;const i=n.value;let d="",m="file";if(i.doc){const v=s.docs.find(p=>p.id===i.doc);if(!v)return g(404,"not_found",`kb: no document ${i.doc}`);d=v.source?.path||"",d||(d=b.dirOf(s.id),m="index")}else if(i.source!=null){const v=(s.sources||[])[i.source];if(!v?.path)return g(404,"not_found",`kb: no kept folder ${i.source}`);d=v.path,m="folder"}else{const v=(s.sources||[]).find(p=>p.path);d=v?.path||b.dirOf(s.id),m=v?"folder":"index"}try{ne(d)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await R(d,{folder:m!=="file"})}catch(v){return g(502,"reveal_failed",`kb: the file manager did not open — ${v.message}`)}return w({ok:!0,revealed:m})}case"embed":{if(e==="POST"){const n=N(),i=S&&n?S.health("embed",n):{state:"off"},d=await F(s);return d&&b.save(s),w({embedded:d,vectors:s.vectors.by.size,model:s.vectors.model||n,dims:s.vectors.dims,state:i.state,...i.progress?{progress:i.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}function H(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:Me,store:b,embedModel:N,cardOf:de,addBytes:(e,t,c)=>U(e,t,c),embedAll:e=>F(e),searchBase:(e,t)=>q(e,t)}}export{I as KB_WALK_LIMITS,Vt as createKbService,P as kbStatusFor,Kt as wholeGraph};
|