@chatpanel/gateway 0.158.0 → 0.159.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 +1 -1
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +1 -1
- package/src/server.js +1 -1
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.159.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": {
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import
|
|
1
|
+
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import c from"node:os";import{DEFAULT_MODEL as A}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],security:{personalReads:"credential"},maxBodyBytes:26214400,tls:{systemCa:!0},pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},mcp:{ask:{maxReach:"device",defaultModel:"",delegate:{roots:[],permissionMode:"acceptEdits"}}},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:A,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,diarizeModel:m,segment:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function L(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(c.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,L as loadConfig};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 d=N.includes(o.runtime)?o.runtime:"srt";let s="";if(o.command!==void 0&&String(Array.isArray(o.command)?o.command.join(""):o.command).trim())try{oe(o.command),s=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: /,"")}`);s=""}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&&d==="command"&&!s)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(r&&d==="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:d,command:s,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 d=c(r),s=f(i).reads;return d&&d!==s&&o.push(`what agents may read is "${d}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${s}"; 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 d={};try{const a=JSON.parse(r.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(d=a)}catch{}const s={...d,...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(s).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(s)}:{}}}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 d=s=>{try{return new URL(s).origin}catch{return s}};r.url&&n&&d(r.url)!==d(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(s=>typeof s=="string"&&s):[]};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 s=$(o.get(i.id),{type:"api",baseUrl:t.baseUrl,apiKey:i.apiKey});s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;n&&(t.service=n);for(const s of["local","redact"]){const a=typeof i[s]=="boolean"?i[s]:o.get(i.id)?.[s];typeof a=="boolean"&&(t[s]=a)}(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(t.fromEndpoint=!0);const d=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return d&&(t.endpointId=d),t}).filter((i,t,n)=>!i.endpointId||n.findIndex(d=>d.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 d=x(e.capabilities[i],i).providers,s=[];for(const a of t.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=d.find(I=>I.service===a.service);l&&s.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},y=(typeof a.id=="string"?d.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?d.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,y,a,o);b&&s.push(typeof a.id=="string"?{...b,id:a.id}:b)}h(e,i,_({mode:t.mode??x(e.capabilities[i],i).mode,providers:s},i))}else{const n=x(e.capabilities[i],i),d=R(i,n.providers[0]||{},t,o);h(e,i,_({mode:n.mode,providers:d?[d,...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};
|
|
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"}),R=/^[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(!R.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 b(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 d=N.includes(o.runtime)?o.runtime:"srt";let s="";if(o.command!==void 0&&String(Array.isArray(o.command)?o.command.join(""):o.command).trim())try{oe(o.command),s=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: /,"")}`);s=""}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&&d==="command"&&!s)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(r&&d==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:f}=g({hosts:o.hosts??[]}),y=ie(o.agents,{strict:r});return{mode:i,reads:t,required:n,runtime:d,command:s,image:a,engine:u,hosts:f,write:T(o.write),denyRead:T(o.denyRead),...Object.keys(y).length?{agents:y}:{}}}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(!R.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=b(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 d=c(r),s=b(i).reads;return d&&d!==s&&o.push(`what agents may read is "${d}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${s}"; Settings › Runtime cannot change it while that variable is set`),o}function Ne(e,r=process.env,o=null){const i=b(e?.sandbox),{sandbox:t}=k(i,o);Array.isArray(t.command)&&(t.command=JSON.stringify(t.command));const n=w(r);let d={};try{const a=JSON.parse(r.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(d=a)}catch{}const s={...d,...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(s).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(s)}:{}}}function L(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 P(e,r,o){o?e.capabilities[r]=o:delete e.capabilities[r]}function h(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 d=s=>{try{return new URL(s).origin}catch{return s}};r.url&&n&&d(r.url)!==d(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=L()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===L({}))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,security:e.security,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(b(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:[],security:{personalReads:e.security?.personalReads==="open"?"open":"credential"},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(s=>typeof s=="string"&&s):[]};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 s=$(o.get(i.id),{type:"api",baseUrl:t.baseUrl,apiKey:i.apiKey});s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;n&&(t.service=n);for(const s of["local","redact"]){const a=typeof i[s]=="boolean"?i[s]:o.get(i.id)?.[s];typeof a=="boolean"&&(t[s]=a)}(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(t.fromEndpoint=!0);const d=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return d&&(t.endpointId=d),t}).filter((i,t,n)=>!i.endpointId||n.findIndex(d=>d.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)),r.security&&["credential","open"].includes(r.security.personalReads)&&(e.security={...e.security||{},personalReads:r.security.personalReads}),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=b(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=b(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 d=x(e.capabilities[i],i).providers,s=[];for(const a of t.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=d.find(I=>I.service===a.service);l&&s.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},f=(typeof a.id=="string"?d.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?d.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},y=h(i,f,a,o);y&&s.push(typeof a.id=="string"?{...y,id:a.id}:y)}P(e,i,_({mode:t.mode??x(e.capabilities[i],i).mode,providers:s},i))}else{const n=x(e.capabilities[i],i),d=h(i,n.providers[0]||{},t,o);P(e,i,_({mode:n.mode,providers:d?[d,...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,L as configPath,ne as isSelfDestination,b 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/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 x}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const A=()=>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 m=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 L({clock:t=A}={}){const a=new Map;return{record(n){const s=y(n);if(!s||!s.host)return;const p=`${s.scheme}://${s.host}:${s.port}`,o=t(),u=a.get(p);if(u){u.count+=1,u.lastAt=o;return}a.set(p,{host:s.host,port:s.port,scheme:s.scheme,local:m(s.host),count:1,firstAt:o,lastAt:o})},snapshot(){return[...a.values()].sort((n,s)=>n.local===s.local?s.count-n.count:n.local?1:-1)},reset(){a.clear()}}}let b=null;function q(t=globalThis,{allow:a=null}={}){if(t.__chatpanelEgress)return a&&t.__chatpanelEgress.setGate(a),t.__chatpanelEgress;const n=L();let s=a;n.setGate=c=>{s=c},n.blocked=[];const p=c=>{let r=null;try{r=y(c),n.record(c)}catch{}if(!s||!r?.host)return null;let h=!0;try{h=s(`${r.scheme}://${r.host}:${r.port}`,{local:m(r.host)})}catch{h=!0}if(h)return null;const d=`${r.host}:${r.port}`;n.blocked.includes(d)||n.blocked.push(d);const e=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return e.code="EGRESS_POLICY",e},o=t.fetch;typeof o=="function"&&(t.fetch=function(r,h){const d=p(r);return d?Promise.reject(d):o.call(this,r,h)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(c,r,h){const d=p(r[0]);if(d)throw d;return Reflect.construct(c,r,h)}})),t.__chatpanelEgress=n,t===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function w(t){try{return new URL(t).host}catch{return String(t||"")}}function R(t={},a=process.env,n=process.platform,s=process.arch){const p=[],o=(e,l,{when:i="always",off:f=null,local:k=!1,data:v=""}={})=>{e&&p.push({host:e,purpose:l,when:i,off:f,local:k,data:v})};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"&&s==="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:x(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(l=>l.kind==="api"&&l.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 l=`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:l,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 i=e.url;try{i=new URL(e.url).host}catch{}o(i,`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:l,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(i)})}else if(e.kind==="bucket"&&e.endpoint){let i=e.endpoint;try{const f=new URL(e.endpoint);i=e.addressing==="virtual"?`${e.bucket}.${f.host}`:f.host}catch{}o(i,`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:l,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(i)})}}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 r={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,l]of Object.entries(r))for(const i of S(t.capabilities?.[e],e,{destinations:t.destinations||[]}).providers){if(!i?.url||i.provider==="embedded")continue;let f=i.url;try{f=new URL(i.url).host}catch{}o(f,`${l.what}${i.service?` (the ${i.service} container, started under Settings › Runtime)`:` (${i.adapter} at the address you configured)`}`,{when:`a client calls /v1/${e}`,off:i.service?`stop the ${i.service} service under Settings › Runtime`:`capabilities.${e} = null`,data:`${l.data}${i.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,l]of Object.entries(t.upstreams||{}))l?.baseUrl&&o(w(l.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:m(w(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&o(w(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:m(w(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(w(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(w(t.ner.url).split(":")[0]),data:"the text being redacted"});const h=t.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const e=h.remote?.baseUrl?w(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(e,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}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 d=t.bridge?.url||"http://127.0.0.1:4319";return o(w(d),"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 N(t,{ledger:a=P(),version:n="",startedAt:s=null,env:p=process.env,managed:o=null,certificates:u=null,linkPartners:c=null,confined:r=null,readers:h=null}={}){const d=R(t,p);for(const e of c||[])!e.host||e.route!=="link"&&e.route!=="relay"||d.some(l=>l.host===e.host)||d.push({host:e.host,purpose:`ChatPanel Link: the relay partner "${e.partner?.name||e.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${e.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:s?new Date(s).toISOString():null,...u?{certificates:u}:{},...r?{confined:r}:{},...h?{readers:h}:{},...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:d,...c?{link:{partners:c.map(e=>({id:e.id,partner:e.partner?.name||e.name,scopes:e.scopes||[],route:e.route||null,host:e.host||null,...e.folder?{folder:e.folder}:{},pairedAt:e.pairedAt||null,lastSeen:e.lastSeen||null,online:!!e.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.readers){const n=t.readers;a.push(""),a.push("READERS — who may read your history, memory and knowledge bases here"),a.push(n.personalReads==="credential"?" a credential is required: the gateway token, the ChatPanel extension, an agent connected with `chatpanel-gateway connect`, or one issued below. Websites and other browser extensions are refused.":' OPEN to any program on this computer (and a browser extension holding no token can also read). Require a credential: security.personalReads: "credential" in the config, then restart.'),a.push(" not covered: a program running as your user can read ~/.chatpanel directly — the operating-system account is that boundary.");for(const s of n.principals||[])a.push(` ${s.kind}:${s.name} …${s.hint||""}${s.revokedAt?" REVOKED":""}${s.expiresAt?` expires ${new Date(s.expiresAt).toISOString().slice(0,10)}`:""}`)}if(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 s=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 ${s}${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,s])=>s===!0?n:`${n}=${s}`).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(`
|
|
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 x}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const A=()=>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 m=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 L({clock:t=A}={}){const a=new Map;return{record(n){const s=y(n);if(!s||!s.host)return;const p=`${s.scheme}://${s.host}:${s.port}`,o=t(),u=a.get(p);if(u){u.count+=1,u.lastAt=o;return}a.set(p,{host:s.host,port:s.port,scheme:s.scheme,local:m(s.host),count:1,firstAt:o,lastAt:o})},snapshot(){return[...a.values()].sort((n,s)=>n.local===s.local?s.count-n.count:n.local?1:-1)},reset(){a.clear()}}}let b=null;function q(t=globalThis,{allow:a=null}={}){if(t.__chatpanelEgress)return a&&t.__chatpanelEgress.setGate(a),t.__chatpanelEgress;const n=L();let s=a;n.setGate=c=>{s=c},n.blocked=[];const p=c=>{let r=null;try{r=y(c),n.record(c)}catch{}if(!s||!r?.host)return null;let h=!0;try{h=s(`${r.scheme}://${r.host}:${r.port}`,{local:m(r.host)})}catch{h=!0}if(h)return null;const d=`${r.host}:${r.port}`;n.blocked.includes(d)||n.blocked.push(d);const e=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return e.code="EGRESS_POLICY",e},o=t.fetch;typeof o=="function"&&(t.fetch=function(r,h){const d=p(r);return d?Promise.reject(d):o.call(this,r,h)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(c,r,h){const d=p(r[0]);if(d)throw d;return Reflect.construct(c,r,h)}})),t.__chatpanelEgress=n,t===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function w(t){try{return new URL(t).host}catch{return String(t||"")}}function R(t={},a=process.env,n=process.platform,s=process.arch){const p=[],o=(e,l,{when:i="always",off:f=null,local:k=!1,data:v=""}={})=>{e&&p.push({host:e,purpose:l,when:i,off:f,local:k,data:v})};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"&&s==="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:x(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(l=>l.kind==="api"&&l.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 l=`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:l,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 i=e.url;try{i=new URL(e.url).host}catch{}o(i,`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:l,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(i)})}else if(e.kind==="bucket"&&e.endpoint){let i=e.endpoint;try{const f=new URL(e.endpoint);i=e.addressing==="virtual"?`${e.bucket}.${f.host}`:f.host}catch{}o(i,`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:l,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(i)})}}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 r={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,l]of Object.entries(r))for(const i of S(t.capabilities?.[e],e,{destinations:t.destinations||[]}).providers){if(!i?.url||i.provider==="embedded")continue;let f=i.url;try{f=new URL(i.url).host}catch{}o(f,`${l.what}${i.service?` (the ${i.service} container, started under Settings › Runtime)`:` (${i.adapter} at the address you configured)`}`,{when:`a client calls /v1/${e}`,off:i.service?`stop the ${i.service} service under Settings › Runtime`:`capabilities.${e} = null`,data:`${l.data}${i.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,l]of Object.entries(t.upstreams||{}))l?.baseUrl&&o(w(l.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:m(w(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&o(w(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:m(w(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(w(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(w(t.ner.url).split(":")[0]),data:"the text being redacted"});const h=t.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const e=h.remote?.baseUrl?w(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(e,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}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 d=t.bridge?.url||"http://127.0.0.1:4319";return o(w(d),"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 N(t,{ledger:a=P(),version:n="",startedAt:s=null,env:p=process.env,managed:o=null,certificates:u=null,linkPartners:c=null,confined:r=null,readers:h=null}={}){const d=R(t,p);for(const e of c||[])!e.host||e.route!=="link"&&e.route!=="relay"||d.some(l=>l.host===e.host)||d.push({host:e.host,purpose:`ChatPanel Link: the relay partner "${e.partner?.name||e.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${e.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:s?new Date(s).toISOString():null,...u?{certificates:u}:{},...r?{confined:r}:{},...h?{readers:h}:{},...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:d,...c?{link:{partners:c.map(e=>({id:e.id,partner:e.partner?.name||e.name,scopes:e.scopes||[],route:e.route||null,host:e.host||null,...e.folder?{folder:e.folder}:{},pairedAt:e.pairedAt||null,lastSeen:e.lastSeen||null,online:!!e.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.readers){const n=t.readers;a.push(""),a.push("READERS — who may read your history, memory and knowledge bases here"),a.push(n.personalReads==="credential"?" a credential is required: the gateway token, the ChatPanel extension, an agent connected with `chatpanel-gateway connect`, or one issued below. Websites and other browser extensions are refused.":' OPEN to any program on this computer (and a browser extension holding no token can also read). Require a credential again: security.personalReads: "credential" in the config (the default), or the People page.'),a.push(" not covered: a program running as your user can read ~/.chatpanel directly — the operating-system account is that boundary.");for(const s of n.principals||[])a.push(` ${s.kind}:${s.name} …${s.hint||""}${s.revokedAt?" REVOKED":""}${s.expiresAt?` expires ${new Date(s.expiresAt).toISOString().slice(0,10)}`:""}`)}if(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 s=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 ${s}${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,s])=>s===!0?n:`${n}=${s}`).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{L as createEgressLedger,R as declaredEgress,N as egressAudit,P as egressLedger,_ as formatAudit,q as installEgressLedger};
|
package/src/server.js
CHANGED
|
@@ -17,7 +17,7 @@ data: ${u}
|
|
|
17
17
|
|
|
18
18
|
`)},15e3);X.unref?.();let de;try{de=await H.inbox.ask(V,{partner:H.partner,device:H.device,conversation:H.conversation,signal:q.signal})}finally{clearInterval(X),t.off("close",G)}if(q.signal.aborted||t.writableEnded){Ut(c);return}try{await wo(c,JSON.stringify(de))}catch(Q){M.onError(Q);return}}}function Ut(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function ti(t,c,{kind:u,adapter:h,agent:v,run:b=null,owner:N=null,linkTurn:A=null},O,g,_,R,z,V=null,M=null){const{messages:F,system:H}=h.toTurn(O),{agentModel:q}=Gt(O?.model,_),G=Wo(_,{...q?{model:q}:{},...b||{}}),X=tt(_.bridge.token),de=Ot(u,O?.model||v),Q={tier:_.redaction.tier==="full"?"full":"basic",dictionary:xr(_.redaction,R),entities:[]},ge=await et(_),I=qr({vault:g,redactOpts:Q,bridgeUrl:ge,token:X,harness:V});N&&(I.ownerApprovals={...N,conversation:N.conversation||`partner.${N.device}.turn-${I.id}`,turnScoped:!N.conversation}),A&&(I.linkTurn=A,I.onEnd=()=>A.end("aborted")),g&&(I.redaction=_.redaction);let ee;try{ee=await Zr({bridgeUrl:ge,agent:v,token:X,messages:F,system:H,specs:tn(z),options:G,signal:void 0,approvals:!!N||on(z)})}catch(Se){return A?.end("error",{code:"bridge_error"}),ot(I.id),M?.commit(),a(c,502,{error:{message:`bridge: ${Se.message}`,type:"bridge_error"}})}return I.reader=ee.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(de.sseHead()),sr(c,I,de,M)}async function oi(t,c,u,h,v=null){mt(c.id),c.rounds=(c.rounds||0)+1;try{const N=v?v.clock():0;await wo(c,u),v&&v.lap("redact",N)}catch(N){return c.linkTurn?.end("error",{code:"tool_result"}),ot(c.id),v?.commit(),a(t,502,{error:{message:`tool-result: ${N.message}`,type:"bridge_error"}})}const b=Ot("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(b.sseHead()),sr(t,c,b,v)}function Vt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function ri(t,c,{kind:u,adapter:h,redactable:v,pathname:b,agentOverride:N,harness:A,trace:O,run:g=null,owner:_=null,link:R=null},z,V,M,F){if(!v)return O?.commit(),a(c,404,{error:`endpoint ${b} not supported by the bridge backend`});if(u==="openai"){const ae=h.extractLatestToolResult(z);if(ae){const he=bo(ae.tool_call_id),te=he&&go(he.gwId);if(te)return oi(c,te,ae.content,z?.model,O)}const pe=h.extractTools(z);if((pe.length||_)&&z?.stream===!0){const he=N||rr(z?.model,M),te=R?Lt.begin({...R,agentId:he}):null;return ti(t,c,{kind:u,adapter:h,agent:he,run:g,owner:_,linkTurn:te},z,V,M,F,pe,A,O)}}const{messages:H,system:q}=h.toTurn(z),G=N||rr(z?.model,M),X=R?Lt.begin({...R,agentId:G}):null,de=z?.stream===!0,Q=Ot(u,z?.model||G),ge=tt(M.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:ee}=Gt(z?.model,M),Se={bridgeUrl:await et(M),agent:G,token:ge,messages:H,system:q,signal:I.signal,options:Wo(M,{...ee?{model:ee}:{},...g||{}})};if(!de)try{let ae="";const pe=Vt(),he=O?O.clock():0;await yo(Se,o=>{ae+=o},null,o=>pe.add(o)),O&&O.lap("upstream",he);const te=O?O.clock():0,r=Q.full(Tr(ae,V),pe.value);return O&&O.lap("restore",te),c.writeHead(200,{"content-type":Q.contentType}),c.end(r),X?.add(pe.value),X?.end("ok"),O?.commit()}catch(ae){return X?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),O?.commit(),a(c,502,{error:{message:`bridge backend failed: ${ae.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Q.sseHead());const Pe=lo(V),$e=O?O.clock():0;let Je=$e;const Le=Vt();let Ae="",De=!1;try{let ae=!0;await yo(Se,he=>{O&&ae&&(O.lap("upstream",$e),Je=O.clock(),ae=!1);const te=Pe.push(he);te&&(Ae+=te,c.write(Q.sseDelta(te)))},Q.sseActivity?he=>{try{c.write(Q.sseActivity(Sr(he,V)))}catch{}}:null,he=>Le.add(he));const pe=Pe.flush();pe&&(Ae+=pe,c.write(Q.sseDelta(pe))),c.write(Q.sseTail(Le.value))}catch(ae){De=!0,c.write(`data: ${JSON.stringify({error:{message:ae.message,type:"bridge_error"}})}
|
|
19
19
|
|
|
20
|
-
`)}O&&O.lap("stream",Je),c.end(),X&&(X.add(Le.value),X.end(I.signal.aborted?"aborted":De?"error":"ok",{code:"bridge_error"})),O?.commit(),V&&Ae&&io(Ae,M.redaction)}function ni(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),v=String(c||"").split("/")[1];return v&&h.endsWith(`/${v}`)?h.slice(0,-(v.length+1))+c+u:h+c+u}const ir=9e4,Ft=60,lr=Ft*16e3*4,ai=4e3;function si(t,c,u){if(c===u)return t;const h=c/u,v=new Float32Array(Math.floor(t.length/h));for(let b=0;b<v.length;b++){const N=b*h,A=Math.floor(N),O=Math.min(t.length-1,A+1),g=N-A;v[b]=t[A]*(1-g)+t[O]*g}return v}const dr=new WeakMap,ii=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function cr(t,c){const u=ft(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Jo(u):null}function Wt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ke(t,c,u,h,{method:v="GET",timeoutMs:b=8e3,pick:N=A=>A}={}){const A=await et(u);if(!A)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=tt(u.bridge?.token),g=v!=="GET"&&v!=="DELETE";try{const _=g?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${A}${h}`,{method:v,headers:{Accept:"application/json",...g?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...g?{body:_||"{}"}:{},signal:AbortSignal.timeout(b)}),z=await R.json().catch(()=>({}));return R.ok?a(c,200,N(z)):a(c,R.status,{error:{message:z?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Kt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Qe(t,c){const u=new URLSearchParams;for(const b of t.searchParams.getAll("dir"))b&&u.append("dir",b);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const v=u.toString();return v?`?${v}`:""}async function li(t,c,{adapter:u,kind:h,pathname:v,search:b,base:N,destKey:A,destProtocol:O,harness:g,trace:_,link:R=null},z,V){let M;const F=_?_.clock():0,H=R?Lt.begin(R):null;let q=!1;const G=new AbortController;c.on("close",()=>{c.writableFinished||(q=!0,G.abort())});const X=(I,ee)=>{H&&(H.add(ee),H.end(q?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=ei(t.headers,N);A&&(O==="anthropic"?(I["x-api-key"]=A,delete I.authorization):I.authorization=`Bearer ${A}`);const ee=$r(ni(N,v,b)).toString();M=await fetch(ee,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:G.signal})}catch(I){return q?(X(499),_?.commit()):(H?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const de=M.headers.get("content-type")||"",Q={};if(M.headers.forEach((I,ee)=>{er.has(ee.toLowerCase())||(Q[ee]=I)}),de.includes("text/event-stream")&&M.body){_&&_.lap("upstream",F);const I=_?_.clock():0;c.writeHead(M.status,Q);const ee=H?Fn():null,Se=ee?M.body.pipeThrough(ee.stream):M.body,Pe=h==="openai"?kr(Se,c,V,g):vr(Se,c,V);return Promise.resolve(Pe).catch($e=>{if(!q)throw $e}).finally(()=>{_&&_.lap("stream",I),X(M.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await M.arrayBuffer())}catch(I){if(q)return X(499),_?.commit();throw I}if(_&&_.lap("upstream",F),H&&X(M.status,de.includes("json")?Wn(ge.toString("utf8")):null),V&&de.includes("application/json"))try{const I=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),V,g);return _&&_.lap("restore",I),c.writeHead(M.status,{...Q,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}c.writeHead(M.status,Q),c.end(ge),_?.commit()}function di(t=so()){const c=Gn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Hn(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===Oo,name:String(o.id===Oo?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:null},h=()=>t.security?.personalReads==="credential"?"credential":"open",v=r=>/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)&&r!=="/v1/history/stream",b=Rr({first:async r=>{const o=Number(new URL(r).port),y=ua.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await H())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),N=Dr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Cr(r),newId:()=>Ir()}),A=ka({version:le}),O=Va({log:r=>console.log(` ${r}`)}),g=t.link?.enabled===!1?null:Sa({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:Z,signal:W})=>fetch(`http://127.0.0.1:${te.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Ge()||Ne(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>xe(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Bo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${os}`));let _=null;const R=()=>{if(!_){const r=t.read||{};_=va({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return _};let z=null;const V=()=>(z||(z=ia({wrap:(r,o,y,i)=>la().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),z);let M={at:0,fn:()=>"unknown"},F=null;async function H(){if(Date.now()-M.at<1e4)return M.fn;let r=new Map;try{const i=await G().health();for(const[Z,W]of Object.entries(i)){const Te=(t.destinations||[]).filter(fe=>fe?.service===Z).flatMap(fe=>[fe.id,...fe.models||[]]);for(const fe of[Z,...Te])r.set(fe,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return G().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return G().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),M={at:Date.now(),fn:o},M.fn}let q=null;const G=()=>(q||(q=ca({cfg:t,bridgeHealth:async()=>{const r=await et(t);if(!r)return null;const o=tt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,oe())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Ve.join(Ve.dirname(oe()),"runtime"),workers:()=>{const r=z?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),q),X=Number(t.runtime?.idleMinutes),de=pa({warmMs:(Number.isFinite(X)&&X>=0?X:10)*6e4,log:r=>console.log(r)}),Q=ma({cfg:t,wake:(r,o)=>G().wake(r,o),embedded:de,asleep:r=>G().isAsleep(r)});let ge=null;const I=()=>(ge||(ge=ba({store:wa({log:r=>console.warn(`[kb] ${r}`)}),extract:V,embedded:de,cfg:t,rerank:async(r,o)=>{const y=await Q.call("rerank",{query:r,documents:o.map(Z=>String(Z).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of y.body.results||[])i[Z.index]=Z.relevance_score;return i},read:()=>R(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const W=Ge()||Ne(),Te=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),fe=await Te.json().catch(()=>({}));return Te.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(Z)}},log:r=>console.warn(r),team:r=>$e().teamOf(r),remoteCards:()=>Le().remoteCards(),reveal:(r,o)=>za(r,o),confined:()=>!!ht({stateDir:Ve.dirname(oe())}).on})),ge);let ee=null;const Se=()=>ee||=ja();let Pe=null;const $e=()=>(Pe||(Pe=La({store:I().store,kb:()=>I(),profiles:Se(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>He(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),Pe);let Je=null;const Le=()=>(Je||(Je=Ja({cfg:t,kb:()=>I(),buckets:$e(),profiles:Se(),search:async(r,{limit:o=8}={})=>{Ae();const y=await ae().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ga(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await Xe([dt(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await Q.call("rerank",{query:r,documents:o.map(Z=>String(Z).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of y.body.results||[])i[Z.index]=Z.relevance_score;return i},fetchFn:(r,o)=>He(r,o),persist:()=>we(t,oe()),log:r=>console.log(r)})),Je),Ae=()=>{t.search?.searxng?.url&&G().wake("searxng").catch(()=>{})};let De=null;const ae=()=>{if(!De){const r=t.search||{},o=r.searxng?.url?Qa({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;De=Fa({reader:R(),searxng:o,engines:()=>Ya(t),wakeSearxng:()=>G().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await Xe([dt(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return De};Nr(t.allowedExtensionIds||[]);const pe=[],he=r=>{pe.push(r),pe.length>50&&pe.shift()},te=gr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!St(r.headers.host))return a(o,403,{error:"loopback only"});if(!Vs(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(St(t.host)&&xa(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Fs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(h()==="credential"&&v(i)&&!u(r))return a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await S(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return kt("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(kt("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Ne()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Br();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Mr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${Ze(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${Ze(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await fo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Ge()||Ne(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=Ze(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(co(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=N.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=N.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await fo(t);return a(o,200,{ok:!0,status:n,token:Ge()||Ne(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=Ze(r);return a(o,200,{ok:!0,trust:e,paired:co(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Lr(t,{version:le,startedAt:tr,managed:qe(),certificates:{...zr(),wanted:uo(t)},linkPartners:g?g.status().devices.filter(e=>e.kind==="partner"):[],confined:ht({stateDir:Ve.dirname(oe())}),readers:{personalReads:h(),principals:c.list()}})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Bn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Cn()})}if(i==="/update"&&r.method==="POST"){const e=Dn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!u(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
|
|
20
|
+
`)}O&&O.lap("stream",Je),c.end(),X&&(X.add(Le.value),X.end(I.signal.aborted?"aborted":De?"error":"ok",{code:"bridge_error"})),O?.commit(),V&&Ae&&io(Ae,M.redaction)}function ni(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),v=String(c||"").split("/")[1];return v&&h.endsWith(`/${v}`)?h.slice(0,-(v.length+1))+c+u:h+c+u}const ir=9e4,Ft=60,lr=Ft*16e3*4,ai=4e3;function si(t,c,u){if(c===u)return t;const h=c/u,v=new Float32Array(Math.floor(t.length/h));for(let b=0;b<v.length;b++){const N=b*h,A=Math.floor(N),O=Math.min(t.length-1,A+1),g=N-A;v[b]=t[A]*(1-g)+t[O]*g}return v}const dr=new WeakMap,ii=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function cr(t,c){const u=ft(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Jo(u):null}function Wt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ke(t,c,u,h,{method:v="GET",timeoutMs:b=8e3,pick:N=A=>A}={}){const A=await et(u);if(!A)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=tt(u.bridge?.token),g=v!=="GET"&&v!=="DELETE";try{const _=g?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${A}${h}`,{method:v,headers:{Accept:"application/json",...g?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...g?{body:_||"{}"}:{},signal:AbortSignal.timeout(b)}),z=await R.json().catch(()=>({}));return R.ok?a(c,200,N(z)):a(c,R.status,{error:{message:z?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Kt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Qe(t,c){const u=new URLSearchParams;for(const b of t.searchParams.getAll("dir"))b&&u.append("dir",b);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const v=u.toString();return v?`?${v}`:""}async function li(t,c,{adapter:u,kind:h,pathname:v,search:b,base:N,destKey:A,destProtocol:O,harness:g,trace:_,link:R=null},z,V){let M;const F=_?_.clock():0,H=R?Lt.begin(R):null;let q=!1;const G=new AbortController;c.on("close",()=>{c.writableFinished||(q=!0,G.abort())});const X=(I,ee)=>{H&&(H.add(ee),H.end(q?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=ei(t.headers,N);A&&(O==="anthropic"?(I["x-api-key"]=A,delete I.authorization):I.authorization=`Bearer ${A}`);const ee=$r(ni(N,v,b)).toString();M=await fetch(ee,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:G.signal})}catch(I){return q?(X(499),_?.commit()):(H?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const de=M.headers.get("content-type")||"",Q={};if(M.headers.forEach((I,ee)=>{er.has(ee.toLowerCase())||(Q[ee]=I)}),de.includes("text/event-stream")&&M.body){_&&_.lap("upstream",F);const I=_?_.clock():0;c.writeHead(M.status,Q);const ee=H?Fn():null,Se=ee?M.body.pipeThrough(ee.stream):M.body,Pe=h==="openai"?kr(Se,c,V,g):vr(Se,c,V);return Promise.resolve(Pe).catch($e=>{if(!q)throw $e}).finally(()=>{_&&_.lap("stream",I),X(M.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await M.arrayBuffer())}catch(I){if(q)return X(499),_?.commit();throw I}if(_&&_.lap("upstream",F),H&&X(M.status,de.includes("json")?Wn(ge.toString("utf8")):null),V&&de.includes("application/json"))try{const I=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),V,g);return _&&_.lap("restore",I),c.writeHead(M.status,{...Q,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}c.writeHead(M.status,Q),c.end(ge),_?.commit()}function di(t=so()){const c=Gn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Hn(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===Oo,name:String(o.id===Oo?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:null},h=()=>t.security?.personalReads==="open"?"open":"credential",v=r=>/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)&&r!=="/v1/history/stream",b=Rr({first:async r=>{const o=Number(new URL(r).port),y=ua.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await H())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),N=Dr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Cr(r),newId:()=>Ir()}),A=ka({version:le}),O=Va({log:r=>console.log(` ${r}`)}),g=t.link?.enabled===!1?null:Sa({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:Z,signal:W})=>fetch(`http://127.0.0.1:${te.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Ge()||Ne(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>xe(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Bo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${os}`));let _=null;const R=()=>{if(!_){const r=t.read||{};_=va({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return _};let z=null;const V=()=>(z||(z=ia({wrap:(r,o,y,i)=>la().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),z);let M={at:0,fn:()=>"unknown"},F=null;async function H(){if(Date.now()-M.at<1e4)return M.fn;let r=new Map;try{const i=await G().health();for(const[Z,W]of Object.entries(i)){const Te=(t.destinations||[]).filter(fe=>fe?.service===Z).flatMap(fe=>[fe.id,...fe.models||[]]);for(const fe of[Z,...Te])r.set(fe,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return G().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return G().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),M={at:Date.now(),fn:o},M.fn}let q=null;const G=()=>(q||(q=ca({cfg:t,bridgeHealth:async()=>{const r=await et(t);if(!r)return null;const o=tt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{we(t,oe())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Ve.join(Ve.dirname(oe()),"runtime"),workers:()=>{const r=z?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),q),X=Number(t.runtime?.idleMinutes),de=pa({warmMs:(Number.isFinite(X)&&X>=0?X:10)*6e4,log:r=>console.log(r)}),Q=ma({cfg:t,wake:(r,o)=>G().wake(r,o),embedded:de,asleep:r=>G().isAsleep(r)});let ge=null;const I=()=>(ge||(ge=ba({store:wa({log:r=>console.warn(`[kb] ${r}`)}),extract:V,embedded:de,cfg:t,rerank:async(r,o)=>{const y=await Q.call("rerank",{query:r,documents:o.map(Z=>String(Z).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of y.body.results||[])i[Z.index]=Z.relevance_score;return i},read:()=>R(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const W=Ge()||Ne(),Te=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),fe=await Te.json().catch(()=>({}));return Te.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(Z)}},log:r=>console.warn(r),team:r=>$e().teamOf(r),remoteCards:()=>Le().remoteCards(),reveal:(r,o)=>za(r,o),confined:()=>!!ht({stateDir:Ve.dirname(oe())}).on})),ge);let ee=null;const Se=()=>ee||=ja();let Pe=null;const $e=()=>(Pe||(Pe=La({store:I().store,kb:()=>I(),profiles:Se(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>He(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),Pe);let Je=null;const Le=()=>(Je||(Je=Ja({cfg:t,kb:()=>I(),buckets:$e(),profiles:Se(),search:async(r,{limit:o=8}={})=>{Ae();const y=await ae().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ga(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await Xe([dt(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await Q.call("rerank",{query:r,documents:o.map(Z=>String(Z).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of y.body.results||[])i[Z.index]=Z.relevance_score;return i},fetchFn:(r,o)=>He(r,o),persist:()=>we(t,oe()),log:r=>console.log(r)})),Je),Ae=()=>{t.search?.searxng?.url&&G().wake("searxng").catch(()=>{})};let De=null;const ae=()=>{if(!De){const r=t.search||{},o=r.searxng?.url?Qa({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;De=Fa({reader:R(),searxng:o,engines:()=>Ya(t),wakeSearxng:()=>G().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await Xe([dt(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return De};Nr(t.allowedExtensionIds||[]);const pe=[],he=r=>{pe.push(r),pe.length>50&&pe.shift()},te=gr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!St(r.headers.host))return a(o,403,{error:"loopback only"});if(!Vs(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(St(t.host)&&xa(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Fs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(h()==="credential"&&v(i)&&!u(r))return a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await S(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return kt("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(kt("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Ne()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Br();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Mr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${Ze(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${Ze(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await fo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Ge()||Ne(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=Ze(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(co(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=N.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=N.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await fo(t);return a(o,200,{ok:!0,status:n,token:Ge()||Ne(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=Ze(r);return a(o,200,{ok:!0,trust:e,paired:co(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Lr(t,{version:le,startedAt:tr,managed:qe(),certificates:{...zr(),wanted:uo(t)},linkPartners:g?g.status().devices.filter(e=>e.kind==="partner"):[],confined:ht({stateDir:Ve.dirname(oe())}),readers:{personalReads:h(),principals:c.list()}})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await Bn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Cn()})}if(i==="/update"&&r.method==="POST"){const e=Dn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!u(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
|
|
21
21
|
|
|
22
22
|
This address is for ChatPanel's apps, not a web page — there is nothing to open here.
|
|
23
23
|
Use ChatPanel itself (the browser extension's Settings, or the desktop app).
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.159.0";export{o as VERSION};
|