@chatpanel/gateway 0.159.0 → 0.160.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/oidc.js +1 -0
- package/src/server.js +31 -31
- 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.160.1",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.510.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as l}from"node:fs";import{join as
|
|
1
|
+
import{readFileSync as d,existsSync as l}from"node:fs";import{join as c}from"node:path";import p 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"},identity:{oidc:null},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||c(p.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"}),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};
|
|
1
|
+
import{carriedKey as H}from"@chatpanel/events/destinations.js";import{patchApis as B,viewApis as M}from"./retrieval/search-apis.js";import{writeFileSync as X,mkdirSync as G,chmodSync as U}from"node:fs";import{join as q,dirname as z}from"node:path";import F from"node:os";import{usage as J}from"./freegate.js";import{applyFusionsPatch as W}from"./fusions.js";import{EMBEDDED_MODELS as Y,EMBEDDED_IDS as O,isEmbeddedModel as K}from"./embedded-models.js";import{capabilityList as x,isProviderList as _,listProblems as Z,primaryProvider as Q,storedShape as k}from"./capability-config.js";import{normalizeRegistries as V,REGISTRY_KINDS as ee}from"@chatpanel/events/registries.js";import{viewContextProviders as oe}from"@chatpanel/events/context-providers.js";import{assertEndpointUrl as E}from"@chatpanel/pii";import{normalizeGrant as N}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as S,parseWrapperTemplate as re}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as T}from"@chatpanel/events/policy.js";import{normalizeOidc as g}from"./oidc.js";const p=["open","allowlist","off"],R=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}$/,ie=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function te(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=N(t);ie(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&&!S.includes(o.runtime))throw m(`sandbox.runtime must be one of ${S.join(", ")} — got ${JSON.stringify(o.runtime)}`);const d=S.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{re(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}=N({hosts:o.hosts??[]}),y=te(o.agents,{strict:r});return{mode:i,reads:t,required:n,runtime:d,command:s,image:a,engine:u,hosts:f,write:R(o.write),denyRead:R(o.denyRead),...Object.keys(y).length?{agents:y}:{}}}const ne=["off","0","false"],v=e=>String(e||"").split(",").map(r=>r.trim()).filter(Boolean),D=(...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?ne.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");N(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 ve(e,r=process.env,o=null){const i=b(e?.sandbox),{sandbox:t}=T(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:D(t.hosts,v(r.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:D(t.write,v(r.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:D(t.denyRead,v(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||q(F.homedir(),".chatpanel","gateway.config.json")}function De(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 j(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 O.includes(e)&&o.model!=null?(K(e,o.model)||i(`capabilities.${e}.model must be one of ${Y[e].map(n=>n.id).join(", ")}`),{provider:"embedded",model:o.model}):{provider:"embedded"};if(o.provider==="none"&&O.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 C=e=>{const{token:r,...o}=e||{};return{...o,hasToken:!!r}};function Oe(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`);G(z(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,identity:{oidc:g(e.identity?.oidc)},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}:{}};X(r,JSON.stringify(o,null,2),{mode:384});try{U(r,384)}catch{}}function _e(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}=T(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:M(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,t])=>[i,_(t)?{...t,providers:t.providers.map(C)}:C(t)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],security:{personalReads:e.security?.personalReads==="open"?"open":"credential"},identity:{oidc:g(e.identity?.oidc)},pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:J(e)},context:{providers:oe(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 ke(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function se(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const I=["default","acceptEdits","bypassPermissions"];function Te(e,r={}){const o=e?.bridge||{};return{...I.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function Re(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=se(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=H(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),I.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),r.security&&["credential","open"].includes(r.security.personalReads)&&(e.security={...e.security||{},personalReads:r.security.personalReads}),r.identity&&typeof r.identity=="object"&&"oidc"in r.identity&&(e.identity={...e.identity||{},oidc:g(r.identity.oidc,{strict:!0})}),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=V(r.registries),i={...e.registries||{}};for(const t of ee)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=B(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=W(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(_(t)){const n=Z(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($=>$.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)}j(e,i,k({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);j(e,i,k({mode:n.mode,providers:d?[d,...n.providers.slice(1)]:n.providers.slice(1)},i))}if(i==="detect"){const n=Q(e.capabilities[i],i);n?.url&&n.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{I as PERMISSION_MODES,p as SANDBOX_MODES,Re as applyConfigPatch,ke as applyNerModelSelection,Te as bridgeAgentOptions,P as configPath,se as isSelfDestination,b as normalizeSandboxConfig,Oe as persistConfig,_e as publicConfig,De as registryChildEnv,ve 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 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
|
-
`)}export{
|
|
1
|
+
import{confinedLine as S}from"./confine.js";import{capabilityList as E}from"./capability-config.js";import{searchEngines as x}from"./retrieval/search-apis.js";import{linkPaths as A}from"@chatpanel/events/link-routes.js";import{isBlockedHost as y,isLoopbackHost as L}from"@chatpanel/pii";import{normalizeOidc as P}from"./oidc.js";const R=()=>new Date().toISOString();function b(t){try{const n=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.url),a=n.protocol.replace(":","");return{host:n.hostname,port:n.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const g=t=>{const n=String(t||"").toLowerCase();return n==="localhost"||n.endsWith(".localhost")||n==="::1"||n==="[::1]"?!0:y(n,{allowLoopback:!1,allowPrivate:!1})&&!y(n,{allowLoopback:!0,allowPrivate:!0})};function C({clock:t=R}={}){const n=new Map;return{record(a){const o=b(a);if(!o||!o.host)return;const p=`${o.scheme}://${o.host}:${o.port}`,s=t(),u=n.get(p);if(u){u.count+=1,u.lastAt=s;return}n.set(p,{host:o.host,port:o.port,scheme:o.scheme,local:g(o.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...n.values()].sort((a,o)=>a.local===o.local?o.count-a.count:a.local?1:-1)},reset(){n.clear()}}}let k=null;function j(t=globalThis,{allow:n=null}={}){if(t.__chatpanelEgress)return n&&t.__chatpanelEgress.setGate(n),t.__chatpanelEgress;const a=C();let o=n;a.setGate=d=>{o=d},a.blocked=[];const p=d=>{let r=null;try{r=b(d),a.record(d)}catch{}if(!o||!r?.host)return null;let h=!0;try{h=o(`${r.scheme}://${r.host}:${r.port}`,{local:g(r.host)})}catch{h=!0}if(h)return null;const l=`${r.host}:${r.port}`;a.blocked.includes(l)||a.blocked.push(l);const f=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return f.code="EGRESS_POLICY",f},s=t.fetch;typeof s=="function"&&(t.fetch=function(r,h){const l=p(r);return l?Promise.reject(l):s.call(this,r,h)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(d,r,h){const l=p(r[0]);if(l)throw l;return Reflect.construct(d,r,h)}})),t.__chatpanelEgress=a,t===globalThis&&(k=a),a}function T(){return k||(globalThis.__chatpanelEgress??null)}function m(t){try{return new URL(t).host}catch{return String(t||"")}}function O(t={},n=process.env,a=process.platform,o=process.arch){const p=[],s=(e,c,{when:i="always",off:w=null,local:v=!1,data:$=""}={})=>{e&&p.push({host:e,purpose:c,when:i,off:w,local:v,data:$})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),t.runtime?.services?.llama?.build!=="system"&&(s("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),s("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),s("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),n.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&o==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const u=t.link?.enabled===!1?null:A(t.link||{}).relay;if(u){const e=new URL(u).host;s(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"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const d=t.search?.searxng?.url||"";if(d){let e=d;try{e=new URL(d).host}catch{}s(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"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const e of x(t).filter(c=>c.kind==="api"&&c.enabled!==!1))s(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 c=`context.providers: [{ id: "${e.id}", enabled: false }] (Settings › Knowledge › Sources)`;if(e.kind==="bedrock"&&e.region)s(`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:c,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{}s(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:c,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 w=new URL(e.endpoint);i=e.addressing==="virtual"?`${e.bucket}.${w.host}`:w.host}catch{}s(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:c,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{}s(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,c]of Object.entries(r))for(const i of E(t.capabilities?.[e],e,{destinations:t.destinations||[]}).providers){if(!i?.url||i.provider==="embedded")continue;let w=i.url;try{w=new URL(i.url).host}catch{}s(w,`${c.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:`${c.data}${i.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}n.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[e,c]of Object.entries(t.upstreams||{}))c?.baseUrl&&s(m(c.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:g(m(c.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&s(m(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:g(m(e.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),t.ner?.url&&s(m(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:g(m(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?m(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(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"})}a==="darwin"&&t.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const l=P(t.identity?.oidc);if(l){const e=m(l.issuer);s(e,"company sign-in: the identity provider’s published signing keys",{when:"the first sign-in, then every ten minutes at most, or when the provider rotates its keys",off:"identity.oidc = null (Settings › People)",local:L(new URL(l.issuer).hostname),data:"nothing but the request for its public keys"})}const f=t.bridge?.url||"http://127.0.0.1:4319";return s(m(f),"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 D(t,{ledger:n=T(),version:a="",startedAt:o=null,env:p=process.env,managed:s=null,certificates:u=null,linkPartners:d=null,confined:r=null,readers:h=null,identity:l=null}={}){const f=O(t,p);l?.jwksHost&&!f.some(e=>e.host===l.jwksHost)&&f.push({host:l.jwksHost,purpose:`company sign-in: where ${m(l.issuer)} publishes its signing keys (its jwks_uri)`,when:"the same as the issuer",off:"identity.oidc = null (Settings › People)",local:!1,data:"nothing but the request for its public keys"});for(const e of d||[])!e.host||e.route!=="link"&&e.route!=="relay"||f.some(c=>c.host===e.host)||f.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:a,since:o?new Date(o).toISOString():null,...u?{certificates:u}:{},...r?{confined:r}:{},...h?{readers:h}:{},...s?{managed:s,blocked:n?.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:n?n.snapshot():[],declared:f,...d?{link:{partners:d.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 G(t){const n=[];n.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&n.push(`observed since ${t.since}`),n.push(""),n.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||n.push(" (none yet)");for(const a of t.observed||[])n.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);n.push(""),n.push("DECLARED — hosts this configuration allows, and why");for(const a of t.declared||[])n.push(` ${a.local?"[local] ":""}${a.host}`),n.push(` ${a.purpose}`),n.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&n.push(` sends: ${a.data}`);if(t.certificates){const a=t.certificates;n.push(""),n.push("CERTIFICATES — whose word is taken that a server is who it says"),n.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),n.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(t.confined&&(n.push(""),n.push("CONFINEMENT — what this process itself can reach on this computer"),n.push(` ${S(t.confined)}`),t.confined.on&&n.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 a=t.readers;n.push(""),n.push("READERS — who may read your history, memory and knowledge bases here"),n.push(a.personalReads==="credential"?" a credential is required: the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` (or issued below). A PERSON with a credential reaches only the binders shared with them — never your history, memory or knowledge bases. 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.'),n.push(" not covered: a program running as your user can read ~/.chatpanel directly — the operating-system account is that boundary."),a.oidc&&n.push(` company sign-in: a person signed in at ${a.oidc.issuer} (audience ${a.oidc.audience}) holds a credential here, like a person token issued below: the reads above, and contexts shared with them or their groups. Off: identity.oidc = null.`);for(const o of a.principals||[])n.push(` ${o.kind}:${o.name} …${o.hint||""}${o.revokedAt?" REVOKED":""}${o.expiresAt?` expires ${new Date(o.expiresAt).toISOString().slice(0,10)}`:""}`)}if(t.link){n.push(""),n.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),t.link.partners?.length||n.push(" (none — no partner can reach this gateway until you pair one)");for(const a of t.link.partners||[]){const o=a.lastSeen?new Date(a.lastSeen).toISOString():"never";n.push(` partner:${a.partner} scopes: ${a.scopes.join(", ")||"none"} agents: ${a.scopes.includes("agents")?"yes":"no"}`),n.push(` route: ${a.route||"?"}${a.host?` via ${a.host}`:""} · last seen ${o}${a.online?" (online)":""}`),a.scopes.includes("agents")&&n.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${a.folder||"its folder"}; it never answers their approval prompts`),n.push(` revoke: chatpanel-gateway link revoke ${a.id}`)}}return t.managed&&(n.push(""),n.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),n.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,a])=>a).map(([a,o])=>o===!0?a:`${a}=${o}`).join(", ")||"nothing yet"}`),n.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),n.push(""),n.push(`Scope: ${t.scope}`),n.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)."),n.join(`
|
|
2
|
+
`)}export{C as createEgressLedger,O as declaredEgress,D as egressAudit,T as egressLedger,G as formatAudit,j as installEgressLedger};
|
package/src/oidc.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as I,createPublicKey as X,verify as B,constants as G}from"node:crypto";import{isLoopbackHost as H,isMetadataHost as $}from"@chatpanel/pii";import{secureFetch as F}from"./secure-fetch.js";const S=60,Z=16*1024,T=256*1024,W=50,q=100,P=190,V=/^[A-Za-z0-9_-]{2,}\.[A-Za-z0-9_-]{2,}\.[A-Za-z0-9_-]{2,}$/,Y=/^[\x21-\x7e]{1,200}$/,_=Object.freeze({RS256:{kty:"RSA",hash:"sha256"},PS256:{kty:"RSA",hash:"sha256",padding:G.RSA_PKCS1_PSS_PADDING,saltLength:32},ES256:{kty:"EC",crv:"P-256",hash:"sha256",dsaEncoding:"ieee-p1363"}}),Q=Object.keys(_),g=e=>Object.assign(new Error(e),{code:"SHAPE"}),w=(e,i)=>{const t=String(e??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim();return t.length<=i?t:""},K=e=>JSON.parse(Buffer.from(e,"base64url").toString("utf8"));function M(e){let i;try{i=new URL(String(e||"").trim())}catch{throw g("identity.oidc.issuer: not a URL")}if(i.username||i.password||i.search||i.hash)throw g("identity.oidc.issuer: no credentials, query or fragment");if($(i.hostname))throw g("identity.oidc.issuer: cloud metadata is never an identity provider");if(i.protocol==="https:"||i.protocol==="http:"&&H(i.hostname))return i;throw g("identity.oidc.issuer: must be https:// (plain http only on this computer)")}function D(e,{strict:i=!1}={}){if(e==null||e===!1)return null;try{if(typeof e!="object"||Array.isArray(e))throw g("identity.oidc: an object, or null to switch it off");const t=String(e.issuer||"").trim();M(t);const u=w(e.audience,200);if(!u)throw g("identity.oidc.audience: the client id or API identifier tokens are issued for");const p=(d,k)=>{if(e[d]===void 0||e[d]==="")return k;if(!Y.test(String(e[d])))throw g(`identity.oidc.${d}: a claim name`);return String(e[d])};return{issuer:t,audience:u,emailClaim:p("emailClaim","email"),groupsClaim:p("groupsClaim","groups"),nameClaim:p("nameClaim","name")}}catch(t){if(i)throw t;return null}}const tt=e=>typeof e=="string"&&e.length<=Z&&V.test(e);function et(e){const i=[];for(const t of(Array.isArray(e?.keys)?e.keys:[]).slice(0,W))if(!(!t||typeof t!="object"||t.d!==void 0)&&!(t.use!==void 0&&t.use!=="sig")&&!(t.kty!=="RSA"&&t.kty!=="EC"))try{const u=X({key:{kty:t.kty,n:t.n,e:t.e,crv:t.crv,x:t.x,y:t.y},format:"jwk"});if(t.kty==="RSA"&&!(u.asymmetricKeyDetails?.modulusLength>=2048))continue;i.push({kid:typeof t.kid=="string"?t.kid:"",kty:t.kty,crv:t.crv,alg:typeof t.alg=="string"?t.alg:"",key:u})}catch{}return i}const rt=(e,i,t)=>e.kty===t.kty&&(!t.crv||e.crv===t.crv)&&(!e.alg||e.alg===i);function nt(e,i){const t=typeof e?.sub=="string"?w(e.sub,P):"";if(!t)return null;const u=e[i.groupsClaim],p=Array.isArray(u)?u:typeof u=="string"?[u]:[],d=[...new Set(p.filter(m=>typeof m=="string"||typeof m=="number").map(m=>w(m,P)).filter(Boolean))].slice(0,q),k=w(e[i.emailClaim],200)||w(e[i.nameClaim],200)||t;return{kind:"person",id:`oidc:${t}`,name:k.slice(0,80),groups:d}}function ct({getConfig:e=()=>null,fetchImpl:i=(s,h)=>F(s,h),now:t=()=>Date.now(),keysTtlMs:u=10*6e4,minRefreshMs:p=3e4,maxStaleMs:d=24*36e5,cacheMax:k=500,timeoutMs:m=5e3}={}){let s={fp:"",keys:[],fetchedAt:0,triedAt:0,jwksHost:"",inflight:null};const h=new Map,A=()=>{const r=D(e()),n=r?JSON.stringify(r):"";return n!==s.fp&&(s={fp:n,keys:[],fetchedAt:0,triedAt:0,jwksHost:"",inflight:null},h.clear()),r};async function E(r){const n=await i(r,{headers:{accept:"application/json"},maxRedirects:0,signal:AbortSignal.timeout(m)});if(!n.ok){try{await n.body?.cancel()}catch{}throw new Error(`${new URL(r).host} answered ${n.status}`)}const o=await n.text();if(o.length>T)throw new Error("the answer is too large");return JSON.parse(o)}async function v(r){const n=M(r.issuer).href.replace(/\/$/,""),o=await E(`${n}/.well-known/openid-configuration`);if(o?.issuer!==r.issuer)throw new Error("the discovery document names a different issuer");let c;try{c=new URL(String(o.jwks_uri||""))}catch{throw new Error("the discovery document has no jwks_uri")}if(!(c.protocol==="https:"||c.protocol==="http:"&&H(c.hostname)))throw new Error("jwks_uri must be https://");if($(c.hostname))throw new Error("jwks_uri points at cloud metadata");return{keys:et(await E(c.href)),jwksHost:c.host}}function O(r,{force:n=!1}={}){if(s.inflight)return s.inflight;const o=t();if(s.fetchedAt&&o-s.fetchedAt<u&&!n||s.triedAt&&o-s.triedAt<p)return Promise.resolve(!1);s.triedAt=o;const f=s.fp;return s.inflight=v(r).then(({keys:l,jwksHost:a})=>s.fp!==f?!1:(s.keys=l,s.jwksHost=a,s.fetchedAt=t(),!0)).catch(()=>!1).finally(()=>{s.fp===f&&(s.inflight=null)}),s.inflight}const R=(r,n)=>{const o=s.keys.filter(c=>rt(c,r.alg,n));return typeof r.kid=="string"?o.find(c=>c.kid===r.kid)||null:o.length===1?o[0]:null};async function J(r,n){const[o,c,f]=r.split(".");let l,a;try{l=K(o),a=K(c)}catch{return null}if(!l||typeof l!="object"||!a||typeof a!="object"||Array.isArray(a))return null;const y=Object.hasOwn(_,l.alg)?_[l.alg]:null;if(!y||l.crit!==void 0)return null;const j=t()/1e3;if(a.iss!==n.issuer||!(Array.isArray(a.aud)?a.aud:[a.aud]).includes(n.audience)||typeof a.exp!="number"||!Number.isFinite(a.exp)||j>a.exp+S||a.nbf!==void 0&&(typeof a.nbf!="number"||j+S<a.nbf)||a.iat!==void 0&&(typeof a.iat!="number"||a.iat>j+S))return null;const C=nt(a,n);if(!C)return null;(!s.fetchedAt||t()-s.fetchedAt>=u)&&await O(n);let b=R(l,y);if(!b&&typeof l.kid=="string"&&(await O(n,{force:!0}),b=R(l,y)),!b||!s.fetchedAt||t()-s.fetchedAt>d)return null;let L;try{L=Buffer.from(f,"base64url")}catch{return null}const z={key:b.key,...y.padding?{padding:y.padding,saltLength:y.saltLength}:{},...y.dsaEncoding?{dsaEncoding:y.dsaEncoding}:{}};let x=!1;try{x=B(y.hash,Buffer.from(`${o}.${c}`),z,L)}catch{x=!1}return x?{person:C,exp:a.exp}:null}async function N(r){try{const n=A();if(!n||!tt(r))return null;const o=I("sha256").update(r).digest("hex"),c=h.get(o);if(c){if(t()/1e3<=c.exp+S)return{...c.principal,groups:[...c.principal.groups]};h.delete(o)}const f=await J(r,n);if(!f||s.fp!==JSON.stringify(n))return null;for(h.set(o,{principal:f.person,exp:f.exp});h.size>k;)h.delete(h.keys().next().value);return{...f.person,groups:[...f.person.groups]}}catch{return null}}async function U(){let r;try{r=D(e(),{strict:!0})}catch(n){return{ok:!1,keys:0,issuer:"",error:n.message}}if(!r)return{ok:!1,keys:0,issuer:"",error:"company sign-in is off — set identity.oidc first"};A();try{const{keys:n,jwksHost:o}=await v(r);return Object.assign(s,{keys:n,jwksHost:o,fetchedAt:t(),triedAt:t()}),n.length?{ok:!0,keys:n.length,issuer:r.issuer}:{ok:!1,keys:0,issuer:r.issuer,error:`the provider publishes no signing key this gateway can use (${Q.join(", ")})`}}catch(n){return{ok:!1,keys:0,issuer:r.issuer,error:String(n?.message||n).slice(0,200)}}}return{verify:N,test:U,configured:()=>!!A(),status:()=>{const r=A();return r?{issuer:r.issuer,audience:r.audience,jwksHost:s.jwksHost||null}:null}}}export{Q as OIDC_ALGORITHMS,ct as createOidc,M as issuerUrl,tt as looksLikeJwt,D as normalizeOidc,nt as personOf};
|
package/src/server.js
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
|
-
import{createServer as gr}from"node:http";import{loadConfig as so}from"./config.js";import{startEntitlementRefresh as wr,maybeRevalidate as br}from"./entitlement-refresh.js";import{redactSegments as Xe,segment as dt,rememberAnswer as io}from"./redact.js";import{pipeRestoredStream as vr,pipeRestoredOpenAIStream as kr,makeTokenRestorer as lo,restoreDeep as Sr}from"./stream.js";import{restoreText as Tr,gatedDictionary as xr,narrowSpecs as _r,makeToolHarness as Or,placeholderToolNote as Er,placeholderNote as Pr,assertEndpointUrl as $r,capRunOptions as Ar,isPaired as co}from"@chatpanel/pii";import{ensureGatewayToken as Ne,currentGatewayToken as Ge,isAdminAuthorized as J,callerTrustOf as Ze,setPinnedExtensionIds as Nr,issuePairingCode as Br,claimPairingCode as Mr}from"./gateway-token.js";import{createPairAsk as Dr,nativeConfirm as Cr}from"./pair-prompt.js";import{createEngineProbe as Rr}from"./local-engine-probe.js";import{randomUUID as Ir}from"node:crypto";import{installEgressLedger as Jr,egressAudit as Lr}from"./egress.js";import{trustSystemCertificates as jr,systemCaWanted as uo,systemCaState as zr}from"./system-ca.js";import{initPolicy as Gr,activePolicy as ct,applyPolicyToConfig as mo,managedSummary as qe,PolicyLoadError as Hr}from"./policy.js";import{routeAllowed as po,agentAllowed as Ur,egressAllowed as Vr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as et}from"./bridge.js";import{secureFetch as He}from"./secure-fetch.js";import{fetchCard as ut,forgetCard as Fr,sendMessage as Wr,streamMessage as Kr,getTask as Qr,cancelTask as Yr,knownAgents as Xr,A2AError as ho}from"./a2a.js";import{streamBridgeChat as yo,readBridgeToken as tt,openBridgeChat as Zr,acceptedBridgeToken as fo}from"./bridge.js";import{createRelaySession as qr,getRelaySession as go,endRelaySession as ot,pumpBridgeStream as en,deliverToolResult as wo,toolsToSpecs as tn,wantsApprovals as on,parseToolCallId as bo,touchRelaySession as mt}from"./toolrelay.js";import{shaperFor as Ot}from"./shape.js";import{startNer as rn,ensureNer as pt,unionForThisMachine as nn,skippedCompanions as an}from"./ner.js";import{recommendDetector as vo}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as sn}from"./log.js";import{saveBackupSecret as ln,clearBackupSecret as dn,loadBackupSecret as Et,hasBackupSecret as ko}from"./history-store.js";import{createContextsApi as cn,handleContexts as un}from"./contexts-api.js";let So=null;import{createMemoryStore as mn}from"./memory-store.js";import{createPrefsStore as pn}from"./prefs-store.js";import{agentCardFor as To,runHintFor as xo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as hn}from"@chatpanel/events/agent-thread.js";import{portClashPlan as yn,serviceManagerOf as fn,STANDBY_POLL_MS as gn}from"@chatpanel/events/service-standby.js";import{threadTarget as wn,frameQuestion as bn,wireMessages as vn,appendExchange as kn,MAX_MESSAGE as _o}from"@chatpanel/events/thread-send.js";import{researchStore as Sn,researchResponse as Tn}from"./research.js";import{createTeamStore as xn,loadOrCreateKey as Pt}from"./team-store.js";import{createScorecardStore as _n}from"./scorecard-store.js";import{createEngineLedgerStore as On}from"./engine-ledger-store.js";import{createProjectStore as En}from"./project-store.js";import{applicationsFor as Pn,recruitPass as $n}from"./recruiting.js";import{ensureBridge as An,holderOf as Nn}from"./bridge-supervisor.js";import{checkForUpdate as Bn,updateStatus as Mn,startUpdate as Dn,updateJob as Cn,installKind as Rn}from"./update.js";import{confinedStatus as ht,confinedLine as In}from"./confine.js";import{appleHelperWanted as Jn,findAppleHelper as $t}from"./apple-helper-fetch.js";import{createHistoryStore as Ln}from"./sqlite-store.js";import{createEventStore as jn}from"./event-store.js";import{createGatewayEvents as zn}from"./gateway-events.js";import{createPrincipals as Gn,presentedToken as Hn,LOCAL_AGENT_ID as Oo}from"./principals.js";import{createLinkActivity as Un,linkSurface as Vn,sseUsageTap as Fn,usageOfBody as Wn,GATEWAY_HOST as Eo}from"./link-activity.js";import{ingestCloudEvents as Kn,cursorOf as Po}from"./event-sync.js";import{eventStats as Qn,projectYear as Yn}from"./event-stats.js";import{toCloudEvent as At,ceHostOf as Xn}from"./cloudevents.js";import{fusionsDocument as Zn,resolveFusionModel as qn}from"./fusions.js";import{ingestBackups as Nt}from"./backup-ingest.js";import{toSearchRecord as $o}from"@chatpanel/events/library.js";import{deriveBackupKey as ea,openRecord as ta,keyCache as oa,nodeCodec as ra}from"@chatpanel/events/backup-envelope.js";import na from"node:zlib";import*as j from"./ner-engine.js";import Bt from"node:os";import{capabilitiesDocument as aa,handleDetect as sa}from"./capabilities.js";import{createExtractService as ia}from"./extract/service.js";import{workerSandbox as la,disposeWorkerSandbox as da}from"./worker-sandbox.js";import{createRuntime as ca,SERVICES as ua}from"./runtime.js";import{createCapabilityProxy as ma}from"./capability-proxy.js";import{createEmbeddedCapabilities as pa}from"./capability-embedded.js";import{EMBEDDED_MODELS as ha,EMBEDDED_IDS as ya}from"./embedded-models.js";import{handleExtract as fa,handleExtractContext as ga}from"./extract/handler.js";import{createKbStore as wa}from"./kb-store.js";import{createKbService as ba}from"./kb.js";import{MAX_DOCUMENT_BYTES as yt}from"./extract-capability.js";import{createReader as va}from"./retrieval/read.js";import{createBrowserRelayHost as ka}from"./browser-relay.js";import{createLinkHost as Sa}from"./link-host.js";import{checkLinkRoute as Ta,tunnelHeader as xa,LINK_TUNNEL_ROOM_PATH as _a}from"@chatpanel/events/link-routes.js";import{linkCallerOf as Re,linkDestinationAllowed as Oa,linkVia as Ea,partnerRunHint as Pa,PARTNER_APPROVAL_DECISIONS as Ao,partnerFilePath as $a}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Aa,readPartnerFile as Na,writePartnerFile as Ba,removePartnerFile as Ma}from"./link-files.js";import{handleFileWrite as Da}from"./file-write.js";import{handleFileRead as Ca}from"./file-read.js";import{handleAppleNotes as Ra}from"./apple-notes.js";import{handlePickFolder as Ia}from"./folder-picker.js";import{createContextService as Ja}from"./context.js";import{createBucketSync as La}from"./kb-bucket-sync.js";import{createCloudProfiles as ja}from"./cloud-profiles.js";import{revealPath as za}from"./reveal.js";import{apiEnginesFrom as Ga}from"@chatpanel/events/search-api.js";import{CONTEXT_FEDERATED_HEADER as Ha}from"@chatpanel/events/context-api.js";import{WRITE_MAX_BYTES as Ua}from"@chatpanel/events/file-write.js";import{isPermissionTool as No}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as Va}from"./link-approvals.js";import{createSearcher as Fa,toJinaSearch as Wa,SEARCH_DEFAULTS as Ka}from"./retrieval/search.js";import{createSearxng as Qa}from"./retrieval/search-searxng.js";import{searchEngines as Ya}from"./retrieval/search-apis.js";import{toJinaText as Xa}from"./read-document.js";import*as $ from"./stt-engine.js";import*as P from"./diarize-engine.js";import*as Ie from"./translate-engine.js";import*as Za from"./indictrans-engine.js";import*as Mt from"./aec-engine.js";import{speechCoverage as qa}from"@chatpanel/events/speech-language.js";import*as es from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ts,DEFAULT_DIARIZE_MODEL as os,isKnownDiarizeModel as Bo,diarizeModelEntry as rs}from"./diarize-models.js";import{providerOf as Dt}from"./providers.js";import{createRemoteTranscriber as Mo}from"./stt-remote.js";import{parseMultipart as ns,decodeAudioFile as as}from"./audio-file.js";import{MODEL_CATALOG as Do,isKnownModel as Co,isValidCustomModelId as Ro,recommendFor as ss}from"./models.js";import{STT_MODEL_CATALOG as is,isKnownSttModel as ls,isValidCustomSttId as ds,DEFAULT_STT_MODEL as Ue,STT_DTYPES as cs,isValidDtype as us,sttModel as ft,sttModelUnavailable as Io,licenseAcceptance as Jo}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as Lo,TTS_VOICES as ms,isKnownTtsModel as ps,isValidCustomTtsId as hs,isKnownVoice as jo,isValidVoiceId as zo,DEFAULT_TTS_MODEL as Go,DEFAULT_TTS_VOICE as Be,TTS_DTYPES as ys,isValidTtsDtype as fs,MAX_TTS_CHARS as Ho,ttsModelHasCustomVoices as gs,resolveDefaultModel as Uo,POCKET_VOICES as ws,DEFAULT_POCKET_VOICE as gt,isPocketVoice as wt,ttsModelEngine as bt}from"./tts-models.js";import{ttsDestination as bs,synthesizeRemote as vs,isValidRemoteVoice as ks}from"./tts-remote.js";import{rawOrtAvailable as Ct}from"./ort.js";import*as ue from"./tts-voices.js";import{resolveTtsVoice as Ss}from"./tts-voice-resolve.js";import{resolvePro as xe,checkQuota as Ts,consume as xs,usage as _s}from"./freegate.js";import{publicConfig as Vo,applyConfigPatch as Rt,isSelfDestination as Os,registryChildEnv as Es,applyNerModelSelection as Fo,persistConfig as we,configPath as oe,bridgeAgentOptions as Wo,PERMISSION_MODES as Ps,sandboxEnvFor as $s,sandboxProblems as As}from"./configstore.js";import{createDestinationsService as Ns}from"./destinations-service.js";import{freeLimitProblem as Bs}from"./capability-config.js";import Ve from"node:path";import{resolveDestination as vt,aggregateModelsAsync as Ms,listDestinations as Ds,ensureModelCatalog as Cs,agentOwnsModel as Rs}from"./router.js";import{makeAccessEvent as Ko}from"./observability.js";import{createPersistentAccessLog as Is}from"./access-log-store.js";import{planQueries as Js,multiSearch as Ls}from"./rrf.js";import*as It from"./openai.js";import*as Qo from"./responses.js";import*as Jt from"./anthropic.js";import{closeAndExit as js}from"./shutdown.js";import{VERSION as le}from"./version.js";import{VERSION as gd}from"./version.js";const L=await Ln(),Ee=new Set;function Fe({ids:t=[]}={}){const c=L.lossless;if(!c||!Ee.size)return;const u={newest:c.newest,rev:c.rev,size:c.size,at:Date.now()},h=JSON.stringify({...u,ids:t.slice(0,50)}),v=JSON.stringify(u);for(const b of Ee)try{b.write(`event: records
|
|
2
|
-
data: ${
|
|
1
|
+
import{createServer as kr}from"node:http";import{loadConfig as lo}from"./config.js";import{startEntitlementRefresh as Sr,maybeRevalidate as Tr}from"./entitlement-refresh.js";import{redactSegments as Ze,segment as ut,rememberAnswer as co}from"./redact.js";import{pipeRestoredStream as xr,pipeRestoredOpenAIStream as _r,makeTokenRestorer as uo,restoreDeep as Or}from"./stream.js";import{restoreText as Er,gatedDictionary as Pr,narrowSpecs as $r,makeToolHarness as Ar,placeholderToolNote as Nr,placeholderNote as Br,assertEndpointUrl as Mr,capRunOptions as Dr,isPaired as mo}from"@chatpanel/pii";import{ensureGatewayToken as Ae,currentGatewayToken as Ge,isAdminAuthorized as J,callerTrustOf as qe,setPinnedExtensionIds as Cr,issuePairingCode as Rr,claimPairingCode as Ir}from"./gateway-token.js";import{createPairAsk as Jr,nativeConfirm as Lr}from"./pair-prompt.js";import{createEngineProbe as jr}from"./local-engine-probe.js";import{randomUUID as zr}from"node:crypto";import{installEgressLedger as Gr,egressAudit as Hr}from"./egress.js";import{trustSystemCertificates as Ur,systemCaWanted as po,systemCaState as Vr}from"./system-ca.js";import{initPolicy as Fr,activePolicy as mt,applyPolicyToConfig as ho,managedSummary as et,PolicyLoadError as Wr}from"./policy.js";import{routeAllowed as yo,agentAllowed as Kr,egressAllowed as Qr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as tt}from"./bridge.js";import{secureFetch as He}from"./secure-fetch.js";import{fetchCard as pt,forgetCard as Yr,sendMessage as Xr,streamMessage as Zr,getTask as qr,cancelTask as en,knownAgents as tn,A2AError as fo}from"./a2a.js";import{streamBridgeChat as go,readBridgeToken as ot,openBridgeChat as on,acceptedBridgeToken as wo}from"./bridge.js";import{createRelaySession as rn,getRelaySession as bo,endRelaySession as rt,pumpBridgeStream as nn,deliverToolResult as vo,toolsToSpecs as an,wantsApprovals as sn,parseToolCallId as ko,touchRelaySession as ht}from"./toolrelay.js";import{shaperFor as $t}from"./shape.js";import{startNer as ln,ensureNer as yt,unionForThisMachine as dn,skippedCompanions as cn}from"./ner.js";import{recommendDetector as So}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as un}from"./log.js";import{saveBackupSecret as mn,clearBackupSecret as pn,loadBackupSecret as At,hasBackupSecret as To}from"./history-store.js";import{createContextsApi as hn,handleContexts as yn}from"./contexts-api.js";let xo=null;import{createMemoryStore as fn}from"./memory-store.js";import{createPrefsStore as gn}from"./prefs-store.js";import{agentCardFor as _o,runHintFor as Oo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as wn}from"@chatpanel/events/agent-thread.js";import{portClashPlan as bn,serviceManagerOf as vn,STANDBY_POLL_MS as kn}from"@chatpanel/events/service-standby.js";import{threadTarget as Sn,frameQuestion as Tn,wireMessages as xn,appendExchange as _n,MAX_MESSAGE as Eo}from"@chatpanel/events/thread-send.js";import{researchStore as On,researchResponse as En}from"./research.js";import{createTeamStore as Pn,loadOrCreateKey as Nt}from"./team-store.js";import{createScorecardStore as $n}from"./scorecard-store.js";import{createEngineLedgerStore as An}from"./engine-ledger-store.js";import{createProjectStore as Nn}from"./project-store.js";import{applicationsFor as Bn,recruitPass as Mn}from"./recruiting.js";import{ensureBridge as Dn,holderOf as Cn}from"./bridge-supervisor.js";import{checkForUpdate as Rn,updateStatus as In,startUpdate as Jn,updateJob as Ln,installKind as jn}from"./update.js";import{confinedStatus as ft,confinedLine as zn}from"./confine.js";import{appleHelperWanted as Gn,findAppleHelper as Bt}from"./apple-helper-fetch.js";import{createHistoryStore as Hn}from"./sqlite-store.js";import{createEventStore as Un}from"./event-store.js";import{createGatewayEvents as Vn}from"./gateway-events.js";import{createPrincipals as Fn,presentedToken as Po,LOCAL_AGENT_ID as $o}from"./principals.js";import{createOidc as Wn,looksLikeJwt as Kn,normalizeOidc as Ao}from"./oidc.js";import{createLinkActivity as Qn,linkSurface as Yn,sseUsageTap as Xn,usageOfBody as Zn,GATEWAY_HOST as No}from"./link-activity.js";import{ingestCloudEvents as qn,cursorOf as Bo}from"./event-sync.js";import{eventStats as ea,projectYear as ta}from"./event-stats.js";import{toCloudEvent as Mt,ceHostOf as oa}from"./cloudevents.js";import{fusionsDocument as ra,resolveFusionModel as na}from"./fusions.js";import{ingestBackups as Dt}from"./backup-ingest.js";import{toSearchRecord as Mo}from"@chatpanel/events/library.js";import{deriveBackupKey as aa,openRecord as sa,keyCache as ia,nodeCodec as la}from"@chatpanel/events/backup-envelope.js";import da from"node:zlib";import*as j from"./ner-engine.js";import Ct from"node:os";import{capabilitiesDocument as ca,handleDetect as ua}from"./capabilities.js";import{createExtractService as ma}from"./extract/service.js";import{workerSandbox as pa,disposeWorkerSandbox as ha}from"./worker-sandbox.js";import{createRuntime as ya,SERVICES as fa}from"./runtime.js";import{createCapabilityProxy as ga}from"./capability-proxy.js";import{createEmbeddedCapabilities as wa}from"./capability-embedded.js";import{EMBEDDED_MODELS as ba,EMBEDDED_IDS as va}from"./embedded-models.js";import{handleExtract as ka,handleExtractContext as Sa}from"./extract/handler.js";import{createKbStore as Ta}from"./kb-store.js";import{createKbService as xa}from"./kb.js";import{MAX_DOCUMENT_BYTES as gt}from"./extract-capability.js";import{createReader as _a}from"./retrieval/read.js";import{createBrowserRelayHost as Oa}from"./browser-relay.js";import{createLinkHost as Ea}from"./link-host.js";import{checkLinkRoute as Pa,tunnelHeader as $a,LINK_TUNNEL_ROOM_PATH as Aa}from"@chatpanel/events/link-routes.js";import{linkCallerOf as Re,linkDestinationAllowed as Na,linkVia as Ba,partnerRunHint as Ma,PARTNER_APPROVAL_DECISIONS as Do,partnerFilePath as Da}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Ca,readPartnerFile as Ra,writePartnerFile as Ia,removePartnerFile as Ja}from"./link-files.js";import{handleFileWrite as La}from"./file-write.js";import{handleFileRead as ja}from"./file-read.js";import{handleAppleNotes as za}from"./apple-notes.js";import{handlePickFolder as Ga}from"./folder-picker.js";import{createContextService as Ha}from"./context.js";import{createBucketSync as Ua}from"./kb-bucket-sync.js";import{createCloudProfiles as Va}from"./cloud-profiles.js";import{revealPath as Fa}from"./reveal.js";import{apiEnginesFrom as Wa}from"@chatpanel/events/search-api.js";import{CONTEXT_FEDERATED_HEADER as Ka}from"@chatpanel/events/context-api.js";import{WRITE_MAX_BYTES as Qa}from"@chatpanel/events/file-write.js";import{isPermissionTool as Co}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as Ya}from"./link-approvals.js";import{createSearcher as Xa,toJinaSearch as Za,SEARCH_DEFAULTS as qa}from"./retrieval/search.js";import{createSearxng as es}from"./retrieval/search-searxng.js";import{searchEngines as ts}from"./retrieval/search-apis.js";import{toJinaText as os}from"./read-document.js";import*as A from"./stt-engine.js";import*as P from"./diarize-engine.js";import*as Ie from"./translate-engine.js";import*as rs from"./indictrans-engine.js";import*as Rt from"./aec-engine.js";import{speechCoverage as ns}from"@chatpanel/events/speech-language.js";import*as as from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ss,DEFAULT_DIARIZE_MODEL as is,isKnownDiarizeModel as Ro,diarizeModelEntry as ls}from"./diarize-models.js";import{providerOf as It}from"./providers.js";import{createRemoteTranscriber as Io}from"./stt-remote.js";import{parseMultipart as ds,decodeAudioFile as cs}from"./audio-file.js";import{MODEL_CATALOG as Jo,isKnownModel as Lo,isValidCustomModelId as jo,recommendFor as us}from"./models.js";import{STT_MODEL_CATALOG as ms,isKnownSttModel as ps,isValidCustomSttId as hs,DEFAULT_STT_MODEL as Ue,STT_DTYPES as ys,isValidDtype as fs,sttModel as wt,sttModelUnavailable as zo,licenseAcceptance as Go}from"./stt-models.js";import*as I from"./tts-engine.js";import{TTS_MODEL_CATALOG as Ho,TTS_VOICES as gs,isKnownTtsModel as ws,isValidCustomTtsId as bs,isKnownVoice as Uo,isValidVoiceId as Vo,DEFAULT_TTS_MODEL as Fo,DEFAULT_TTS_VOICE as Ne,TTS_DTYPES as vs,isValidTtsDtype as ks,MAX_TTS_CHARS as Wo,ttsModelHasCustomVoices as Ss,resolveDefaultModel as Ko,POCKET_VOICES as Ts,DEFAULT_POCKET_VOICE as bt,isPocketVoice as vt,ttsModelEngine as kt}from"./tts-models.js";import{ttsDestination as xs,synthesizeRemote as _s,isValidRemoteVoice as Os}from"./tts-remote.js";import{rawOrtAvailable as Jt}from"./ort.js";import*as ue from"./tts-voices.js";import{resolveTtsVoice as Es}from"./tts-voice-resolve.js";import{resolvePro as _e,checkQuota as Ps,consume as $s,usage as As}from"./freegate.js";import{publicConfig as Qo,applyConfigPatch as St,isSelfDestination as Ns,registryChildEnv as Bs,applyNerModelSelection as Yo,persistConfig as we,configPath as te,bridgeAgentOptions as Xo,PERMISSION_MODES as Ms,sandboxEnvFor as Ds,sandboxProblems as Cs}from"./configstore.js";import{createDestinationsService as Rs}from"./destinations-service.js";import{freeLimitProblem as Is}from"./capability-config.js";import Ve from"node:path";import{resolveDestination as Tt,aggregateModelsAsync as Js,listDestinations as Ls,ensureModelCatalog as js,agentOwnsModel as zs}from"./router.js";import{makeAccessEvent as Zo}from"./observability.js";import{createPersistentAccessLog as Gs}from"./access-log-store.js";import{planQueries as Hs,multiSearch as Us}from"./rrf.js";import*as Lt from"./openai.js";import*as qo from"./responses.js";import*as jt from"./anthropic.js";import{closeAndExit as Vs}from"./shutdown.js";import{VERSION as de}from"./version.js";import{VERSION as Td}from"./version.js";const L=await Hn(),Pe=new Set;function Fe({ids:t=[]}={}){const c=L.lossless;if(!c||!Pe.size)return;const u={newest:c.newest,rev:c.rev,size:c.size,at:Date.now()},h=JSON.stringify({...u,ids:t.slice(0,50)}),w=JSON.stringify(u);for(const S of Pe)try{S.write(`event: records
|
|
2
|
+
data: ${S.chatpanelCredentialed?h:w}
|
|
3
3
|
|
|
4
|
-
`)}catch{
|
|
4
|
+
`)}catch{Pe.delete(S)}}setInterval(()=>{for(const t of Pe)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}catch{Pe.delete(t)}},25e3).unref?.();const K=await Un(),nt=Vn({store:K,log:t=>console.log(t)}),zt=Qn({store:K,events:nt,log:t=>console.log(t)}),Be=new Set;K?.watch(t=>{if(!Be.size)return;const c=`event: cloudevent
|
|
7
|
+
data: ${JSON.stringify(Mt(t))}
|
|
8
8
|
|
|
9
|
-
`;for(const u of
|
|
9
|
+
`;for(const u of Be)try{u.write(c)}catch{Be.delete(u)}}),setInterval(()=>{for(const t of Be)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{
|
|
11
|
+
`)}catch{Be.delete(t)}},25e3).unref?.();const be=await fn(),me=gn(),We=$n({key:Nt()}),Ke=An({key:Nt()}),ye=Nn({key:Nt()}),re=Pn({scorecards:We,engines:Ke}),Gt=new Set,er=(t,c)=>{for(const h of Gt)try{h({applied:t,by:c,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const h of Pe)try{h.write(`event: prefs
|
|
12
12
|
data: ${u}
|
|
13
13
|
|
|
14
|
-
`)}catch{
|
|
14
|
+
`)}catch{Pe.delete(h)}},Ht=Gs(),tr=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Fs=16,Ws=/^mcp[_-]/i,or=t=>t&&t.function&&t.function.name||t&&t.name||"",Ks=t=>t&&t.function&&t.function.description||t&&t.description||"";function rr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function Qs(t,c){if(!t)return"";if(c==="responses"){const h=t.input;return typeof h=="string"?h:Array.isArray(h)?h.map(w=>rr(w&&(w.content??w))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let h=u.length-1;h>=0;h--)if(u[h]&&u[h].role==="user")return rr(u[h].content);return""}const nr=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function xt(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function Ys(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function Xs(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const ar=Date.now();function Zs(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function qs(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function ei(t){const c=performance.now(),u={};let h=!1;const w=(S,B)=>{u[S]=Math.round(B*10)/10};return{meta:{},timings:u,mark:w,lap(S,B){w(S,performance.now()-B)},clock(){return performance.now()},commit(){if(h)return;h=!0,w("total",performance.now()-c);const S={...this.meta,timings:u};setImmediate(()=>{t(S),console.log(`[gateway] model=${S.model||"-"} → ${S.dest?`${S.dest}(${S.type})`:"none"} · ${S.redaction==="off"?"redaction OFF (client request)":`redacted ${S.redacted||0}`}${S.sanitized?` · scrubbed ${S.sanitized} hidden`:""}${S.narrowed?` · narrowed -${S.narrowed}`:""} · ${Zs(u)}`)})}}}function sr(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[h,w]of t.byToken){const S=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(h),B=S?S[1]:"PII",M=h.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:M,type:B,value:w}:{token:M,type:B})}return u}function ti(t,c,u){return jt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:jt,redactable:jt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:qo.matches(t)?{kind:"responses",adapter:qo,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Lt,redactable:Lt.matches(t),base:u.upstreams?.openai?.baseUrl}}function Ut(t,c){const u=String(t||"");if(tr.has(u))return{agent:u,agentModel:""};const h=u.indexOf("/");if(h>0){const w=u.slice(0,h);if(tr.has(w))return{agent:w,agentModel:u.slice(h+1)}}return{agent:c.bridge.agent,agentModel:""}}function ir(t,c){return Ut(t,c).agent}function oi(t,c){if(c!=="openai"||!t)return!1;const u=Lt.extractLatestToolResult(t);if(!u)return!1;const h=ko(u.tool_call_id);return!!(h&&bo(h.gwId))}function ri(t,c){try{const u=new URL(t),h=u.hostname.replace(/^\[|\]$/g,""),w=h==="127.0.0.1"||h==="localhost"||h==="::1",S=u.port||(u.protocol==="https:"?"443":"80");return w&&String(S)===String(c.port)}catch{return!1}}const ni=25*1024*1024;async function v(t,c){const u=[];let h=0;for await(const w of t){if(h+=w.length,c&&h>c){const S=new Error("payload too large");throw S.code=413,S}u.push(w)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function lr(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Vt(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const h=j.health(),w=h.ok&&u==="full";return{source:"bundled",state:h.state,model:h.model||t?.ner?.model||null,installed:j.modelOnDisk(t?.ner?.model||void 0),error:h.error||null,ready:w,tier:u,coverage:w?"names":"patterns"}}async function dr(t){if(j.state()!=="off"){const u=j.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=lr(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await He(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const h=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:h.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function ai(t,c){const u={};for(const[h,w]of Object.entries(t)){const S=h.toLowerCase();S.startsWith("x-chatpanel-")||nr.has(S)||(u[h]=w)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function cr(t,c,u,h){const w=uo(c.vault),S=Wt();t.on("close",()=>{t.writableFinished||rt(c.id)});const B=c.linkTurn||null,M=h?h.clock():0;let $=M,b=!0;const x=()=>{h&&b&&(h.lap("upstream",M),$=h.clock(),b=!1)};let O="";const G=()=>{c.redaction&&O&&co(O,c.redaction),O=""};let F=null;const D={onText:H=>{x(),ht(c.id);const z=w.push(H);z&&(O+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:H,restoredArgs:z,toolId:oe})=>{if(x(),ht(c.id),c.ownerApprovals&&Co(H)){F=z;return}const ee=w.flush();ee&&(O+=ee,t.write(u.sseDelta(ee))),t.write(u.sseToolCalls([{id:oe,name:H,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(S.value)),h&&h.lap("stream",$),t.end(),h?.commit(),G()},onDone:()=>{const H=w.flush();H&&(O+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(S.value)),h&&h.lap("stream",$),t.end(),B?.end("ok"),rt(c.id),h?.commit(),G(),Ft(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),
|
|
16
|
+
`),t.end(),B?.end("error",{code:"bridge_error"}),rt(c.id),h?.commit(),Ft(c)},onUsage:H=>{S.add(H),B?.add(H)}};for(;;){if(F=null,await nn(c,D)!=="parked"||!F)return;const z=c.ownerApprovals,oe=new AbortController,ee=()=>oe.abort();t.once("close",ee);const X=setInterval(()=>{ht(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
|
|
17
17
|
|
|
18
|
-
`)},15e3);X.unref?.();let
|
|
18
|
+
`)},15e3);X.unref?.();let V;try{V=await z.inbox.ask(F,{partner:z.partner,device:z.device,conversation:z.conversation,signal:oe.signal})}finally{clearInterval(X),t.off("close",ee)}if(oe.signal.aborted||t.writableEnded){Ft(c);return}try{await vo(c,JSON.stringify(V))}catch(Z){D.onError(Z);return}}}function Ft(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function si(t,c,{kind:u,adapter:h,agent:w,run:S=null,owner:B=null,linkTurn:M=null},$,b,x,O,G,F=null,D=null){const{messages:H,system:z}=h.toTurn($),{agentModel:oe}=Ut($?.model,x),ee=Xo(x,{...oe?{model:oe}:{},...S||{}}),X=ot(x.bridge.token),V=$t(u,$?.model||w),Z={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Pr(x.redaction,O),entities:[]},fe=await tt(x),C=rn({vault:b,redactOpts:Z,bridgeUrl:fe,token:X,harness:F});B&&(C.ownerApprovals={...B,conversation:B.conversation||`partner.${B.device}.turn-${C.id}`,turnScoped:!B.conversation}),M&&(C.linkTurn=M,C.onEnd=()=>M.end("aborted")),b&&(C.redaction=x.redaction);let Y;try{Y=await on({bridgeUrl:fe,agent:w,token:X,messages:H,system:z,specs:an(G),options:ee,signal:void 0,approvals:!!B||sn(G)})}catch(ve){return M?.end("error",{code:"bridge_error"}),rt(C.id),D?.commit(),a(c,502,{error:{message:`bridge: ${ve.message}`,type:"bridge_error"}})}return C.reader=Y.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(V.sseHead()),cr(c,C,V,D)}async function ii(t,c,u,h,w=null){ht(c.id),c.rounds=(c.rounds||0)+1;try{const B=w?w.clock():0;await vo(c,u),w&&w.lap("redact",B)}catch(B){return c.linkTurn?.end("error",{code:"tool_result"}),rt(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${B.message}`,type:"bridge_error"}})}const S=$t("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(S.sseHead()),cr(t,c,S,w)}function Wt(){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 li(t,c,{kind:u,adapter:h,redactable:w,pathname:S,agentOverride:B,harness:M,trace:$,run:b=null,owner:x=null,link:O=null},G,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${S} not supported by the bridge backend`});if(u==="openai"){const ae=h.extractLatestToolResult(G);if(ae){const se=ko(ae.tool_call_id),he=se&&bo(se.gwId);if(he)return ii(c,he,ae.content,G?.model,$)}const pe=h.extractTools(G);if((pe.length||x)&&G?.stream===!0){const se=B||ir(G?.model,D),he=O?zt.begin({...O,agentId:se}):null;return si(t,c,{kind:u,adapter:h,agent:se,run:b,owner:x,linkTurn:he},G,F,D,H,pe,M,$)}}const{messages:z,system:oe}=h.toTurn(G),ee=B||ir(G?.model,D),X=O?zt.begin({...O,agentId:ee}):null,V=G?.stream===!0,Z=$t(u,G?.model||ee),fe=ot(D.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Y}=Ut(G?.model,D),ve={bridgeUrl:await tt(D),agent:ee,token:fe,messages:z,system:oe,signal:C.signal,options:Xo(D,{...Y?{model:Y}:{},...b||{}})};if(!V)try{let ae="";const pe=Wt(),se=$?$.clock():0;await go(ve,ke=>{ae+=ke},null,ke=>pe.add(ke)),$&&$.lap("upstream",se);const he=$?$.clock():0,Ot=Z.full(Er(ae,F),pe.value);return $&&$.lap("restore",he),c.writeHead(200,{"content-type":Z.contentType}),c.end(Ot),X?.add(pe.value),X?.end("ok"),$?.commit()}catch(ae){return X?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.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(Z.sseHead());const Je=uo(F),Me=$?$.clock():0;let Le=Me;const De=Wt();let $e="",Ye=!1;try{let ae=!0;await go(ve,se=>{$&&ae&&($.lap("upstream",Me),Le=$.clock(),ae=!1);const he=Je.push(se);he&&($e+=he,c.write(Z.sseDelta(he)))},Z.sseActivity?se=>{try{c.write(Z.sseActivity(Or(se,F)))}catch{}}:null,se=>De.add(se));const pe=Je.flush();pe&&($e+=pe,c.write(Z.sseDelta(pe))),c.write(Z.sseTail(De.value))}catch(ae){Ye=!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==="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.
|
|
20
|
+
`)}$&&$.lap("stream",Le),c.end(),X&&(X.add(De.value),X.end(C.signal.aborted?"aborted":Ye?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&$e&&co($e,D.redaction)}function di(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const ur=9e4,Kt=60,mr=Kt*16e3*4,ci=4e3;function ui(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let S=0;S<w.length;S++){const B=S*h,M=Math.floor(B),$=Math.min(t.length-1,M+1),b=B-M;w[S]=t[M]*(1-b)+t[$]*b}return w}const pr=new WeakMap,mi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function hr(t,c){const u=wt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Go(u):null}function Qt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function Te(t,c,u,h,{method:w="GET",timeoutMs:S=8e3,pick:B=M=>M}={}){const M=await tt(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=ot(u.bridge?.token),b=w!=="GET"&&w!=="DELETE";try{const x=b?(await v(t,u.maxBodyBytes)).toString("utf8"):"",O=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...b?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...b?{body:x||"{}"}:{},signal:AbortSignal.timeout(S)}),G=await O.json().catch(()=>({}));return O.ok?a(c,200,B(G)):a(c,O.status,{error:{message:G?.error||`bridge ${O.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Qe(t,c){const u=new URLSearchParams;for(const S of t.searchParams.getAll("dir"))S&&u.append("dir",S);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function pi(t,c,{adapter:u,kind:h,pathname:w,search:S,base:B,destKey:M,destProtocol:$,harness:b,trace:x,link:O=null},G,F){let D;const H=x?x.clock():0,z=O?zt.begin(O):null;let oe=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(oe=!0,ee.abort())});const X=(C,Y)=>{z&&(z.add(Y),z.end(oe?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=ai(t.headers,B);M&&($==="anthropic"?(C["x-api-key"]=M,delete C.authorization):C.authorization=`Bearer ${M}`);const Y=Mr(di(B,w,S)).toString();D=await fetch(Y,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:G,signal:ee.signal})}catch(C){return oe?(X(499),x?.commit()):(z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const V=D.headers.get("content-type")||"",Z={};if(D.headers.forEach((C,Y)=>{nr.has(Y.toLowerCase())||(Z[Y]=C)}),V.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(D.status,Z);const Y=z?Xn():null,ve=Y?D.body.pipeThrough(Y.stream):D.body,Je=h==="openai"?_r(ve,c,F,b):xr(ve,c,F);return Promise.resolve(Je).catch(Me=>{if(!oe)throw Me}).finally(()=>{x&&x.lap("stream",C),X(D.status,Y?.usage()),x?.commit()})}let fe;try{fe=Buffer.from(await D.arrayBuffer())}catch(C){if(oe)return X(499),x?.commit();throw C}if(x&&x.lap("upstream",H),z&&X(D.status,V.includes("json")?Zn(fe.toString("utf8")):null),F&&V.includes("application/json"))try{const C=x?x.clock():0,Y=u.restoreResponse(JSON.parse(fe.toString("utf8")),F,b);return x&&x.lap("restore",C),c.writeHead(D.status,{...Z,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Y),"utf8")),x?.commit()}catch{}c.writeHead(D.status,Z),c.end(fe),x?.commit()}function hi(t=lo()){const c=Fn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Wn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Po(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===$o,name:String(o.id===$o?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",S=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),B=r=>/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)&&r!=="/v1/history/stream",M=jr({first:async r=>{const o=Number(new URL(r).port),y=fa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await ee())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=Jr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Lr(r),newId:()=>zr()}),b=Oa({version:de}),x=Ya({log:r=>console.log(` ${r}`)}),O=t.link?.enabled===!1?null:Ea({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:q,signal:W})=>fetch(`http://127.0.0.1:${ke.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Ge()||Ae(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>_e(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Ro(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 ${is}`));let G=null;const F=()=>{if(!G){const r=t.read||{};G=_a({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return G};let D=null;const H=()=>(D||(D=ma({wrap:(r,o,y,i)=>pa().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),D);let z={at:0,fn:()=>"unknown"},oe=null;async function ee(){if(Date.now()-z.at<1e4)return z.fn;let r=new Map;try{const i=await V().health();for(const[q,W]of Object.entries(i)){const xe=(t.destinations||[]).filter(ge=>ge?.service===q).flatMap(ge=>[ge.id,...ge.models||[]]);for(const ge of[q,...xe])r.set(ge,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 V().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return V().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),z={at:Date.now(),fn:o},z.fn}let X=null;const V=()=>(X||(X=ya({cfg:t,bridgeHealth:async()=>{const r=await tt(t);if(!r)return null;const o=ot(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,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Ve.join(Ve.dirname(te()),"runtime"),workers:()=>{const r=D?.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)})),X),Z=Number(t.runtime?.idleMinutes),fe=wa({warmMs:(Number.isFinite(Z)&&Z>=0?Z:10)*6e4,log:r=>console.log(r)}),C=ga({cfg:t,wake:(r,o)=>V().wake(r,o),embedded:fe,asleep:r=>V().isAsleep(r)});let Y=null;const ve=()=>(Y||(Y=xa({store:Ta({log:r=>console.warn(`[kb] ${r}`)}),extract:H,embedded:fe,cfg:t,rerank:async(r,o)=>{const y=await C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},read:()=>F(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,q=setTimeout(()=>i.abort(),3e4);try{const W=Ge()||Ae(),xe=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})}),ge=await xe.json().catch(()=>({}));return xe.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:r=>console.warn(r),team:r=>De().teamOf(r),remoteCards:()=>Ye().remoteCards(),reveal:(r,o)=>Fa(r,o),confined:()=>!!ft({stateDir:Ve.dirname(te())}).on})),Y);let Je=null;const Me=()=>Je||=Va();let Le=null;const De=()=>(Le||(Le=Ua({store:ve().store,kb:()=>ve(),profiles:Me(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>He(r,{...o,maxRedirects:0}),version:de,log:r=>console.log(r)})),Le);let $e=null;const Ye=()=>($e||($e=Ha({cfg:t,kb:()=>ve(),buckets:De(),profiles:Me(),search:async(r,{limit:o=8}={})=>{ae();const y=await se().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"?[]:Wa(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await Ze([ut(()=>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 C.call("rerank",{query:r,documents:o.map(q=>String(q).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const q of y.body.results||[])i[q.index]=q.relevance_score;return i},fetchFn:(r,o)=>He(r,o),persist:()=>we(t,te()),log:r=>console.log(r)})),$e),ae=()=>{t.search?.searxng?.url&&V().wake("searxng").catch(()=>{})};let pe=null;const se=()=>{if(!pe){const r=t.search||{},o=r.searxng?.url?es({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;pe=Xa({reader:F(),searxng:o,engines:()=>ts(t),wakeSearxng:()=>V().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await Ze([ut(()=>i,q=>{i=q})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return pe};Cr(t.allowedExtensionIds||[]);const he=[],Ot=r=>{he.push(r),he.length>50&&he.shift()},ke=kr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!xt(r.headers.host))return a(o,403,{error:"loopback only"});if(!Ys(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(xt(t.host)&&$a(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&&Xs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Po(r.headers);Kn(e)&&(r.chatpanelOidc=await u.verify(e))}if(w()==="credential"&&B(i)&&!S(h(r),i))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 v(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 nt("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)?(nt("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/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{St(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{we(t,te())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return nt("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Ao(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Ae()}):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=Rr();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 v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Ir(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${qe(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${qe(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await wo(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()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=qe(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(mo(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 v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.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 v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status: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 wo(t);return a(o,200,{ok:!0,status:n,token:Ge()||Ae(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=qe(r);return a(o,200,{ok:!0,trust:e,paired:mo(e),version:de})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Hr(t,{version:de,startedAt:ar,managed:et(),certificates:{...Vr(),wanted:po(t)},linkPartners:O?O.status().devices.filter(e=>e.kind==="partner"):[],confined:ft({stateDir:Ve.dirname(te())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):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 Rn(de,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:de,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Ln()})}if(i==="/update"&&r.method==="POST"){const e=Jn(de);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")&&!h(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${de} 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).
|
|
24
24
|
In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
25
|
-
`);if(r.method==="GET"&&i==="/health"){const e
|
|
25
|
+
`);if(r.method==="GET"&&i==="/health"){const e=A.health(),n=I.health();return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,personalReads:w(),pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...et()?{managed:et()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:jn(),confined:ft({stateDir:Ve.dirname(te())}),...Gn({release:Ct.release()})?{appleHelper:!!Bt()}:{},...at?{bridge:at.status()}:_t?{bridge:_t}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ue,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Fo,voice:t.tts?.voice||Ne,runtime:n.runtime,dtype:n.dtype},events:K?{count:K.count(),hosts:K.hosts().length}:null,browser:b.health()})}if(i==="/status"&&r.method==="GET"){Tr(t);const e=await _e(t.pro?.entitlementToken),n=await dr(t);return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...et()?{managed:et()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Vt(t),pro:{unlocked:e},usage:As(t),uptimeSeconds:Math.floor((Date.now()-ar)/1e3),update:In(de)})}if(i==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:n})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&r.method==="GET"){const e=String(y.searchParams.get("section")||"");return y.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(i==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=me.put(e.sections||{},{by:e.by||""});return n.applied.length&&er(n.applied,e.by||""),a(o,200,{ok:!0,...n})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&r.method==="DELETE"){const e=String(y.searchParams.get("section")||""),n=e?me.remove(e):!1;return n&&er([e],""),a(o,200,{ok:!0,removed:n})}if(i==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
|
|
26
26
|
|
|
27
|
-
`);e({type:"hello",revision:me.revision,stamps:me.stamps()});const n=l=>e({type:"changed",...l});
|
|
27
|
+
`);e({type:"hello",revision:me.revision,stamps:me.stamps()});const n=l=>e({type:"changed",...l});Gt.add(n);const s=setInterval(()=>{try{o.write(`: keep-alive
|
|
28
28
|
|
|
29
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
29
|
+
`)}catch{}},25e3);o.on("close",()=>{Gt.delete(n),clearInterval(s)});return}if(i==="/v1/projects"&&r.method==="GET")return a(o,200,{ok:!0,projects:ye.list({limit:y.searchParams.get("limit")||50,status:y.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&r.method==="GET")return a(o,200,{ok:!0,jobs:ye.openJobs()});if(i==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ye.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const n=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(d){const p=ye.get(n);if(!p)return m();const f=p.jobs.find(k=>k.id===l);if(!f)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const g={cfg:t,prefsStore:me,scorecards:We,engines:Ke,engineAt:M.engineAt};if(d==="/applications"&&r.method==="GET"){const k=await Bn(f,{...g,reach:y.searchParams.get("reach")||"any",chatModel:y.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:f,...k})}if(d==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(f.status))return a(o,400,{error:{message:`job ${l} is ${f.status}; only an open job is recruited`,type:"project_error"}});try{const k=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(k.by||"evaluator").slice(0,80),T=await Mn(f,{...g,record:p,reach:k.reach||"any",chatModel:k.chatModel||null,evaluation:k.evaluation||null,text:k.text??null,by:_});let R=null;for(const Q of T.events)Q.type==="job.updated"?R=ye.updateJob(n,l,Q.job,{by:Q.by||_}):R=ye.append(n,[Q]);return a(o,200,{ok:!0,project:R,decision:T.decision,applications:T.applications,evaluation:T.evaluation})}catch(k){return a(o,400,{error:{message:`recruit: ${k.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&r.method==="GET"){const p=ye.get(n,{events:y.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):m()}if(!s&&r.method==="DELETE")return a(o,200,{ok:!0,removed:ye.remove(n)});if(r.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},f=String(p.by||"person").slice(0,80),g=s==="/events"?ye.append(n,p.events||[]):l?ye.updateJob(n,l,p.patch||p,{by:f}):ye.postJob(n,p.job||p,{by:f});return a(o,200,{ok:!0,project:g})}catch(p){return a(o,p.message.startsWith("no ")?404:400,{error:{message:`project: ${p.message}`,type:"project_error"}})}if(s==="/events"&&r.method==="GET"){if(!ye.get(n))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=_=>o.write(`data: ${JSON.stringify(_)}
|
|
30
30
|
|
|
31
|
-
`);let f=y.searchParams.has("after")?Number(y.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:ye.get(n),after:f}});const
|
|
31
|
+
`);let f=y.searchParams.has("after")?Number(y.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:ye.get(n),after:f}});const g=ye.watch(n,_=>{_.seq>f&&(f=_.seq,p(_))});for(const _ of ye.eventsSince(n,f))f=_.seq,p(_);const k=setInterval(()=>{try{o.write(`: keep
|
|
32
32
|
|
|
33
|
-
`)}catch{}},25e3);r.on("close",()=>{clearInterval(k),
|
|
33
|
+
`)}catch{}},25e3);r.on("close",()=>{clearInterval(k),g()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:We.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await We.get(n)});if(r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await We.append({agentId:n,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Ke.fromRating(We.chains.get(n)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&r.method==="GET")return a(o,200,ca(t,{version:de,reader:G,searcher:pe,extract:H(),proxy:C}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:j.health().model||t.ner?.model||null,companions:j.companions()};let n=null;try{n=await V().status()}catch{n=null}return a(o,200,ra({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(va.map(n=>{const s=It(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ba[n],threads:fe.threads,...s.kind==="embedded"?fe.health(n,s.model):{}}]}));return a(o,200,{...await V().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await V().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await V().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=V(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await C.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await C.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await ua(e,{ensure:()=>yt(t),model:j.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(gt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await Sa(e,{service:H()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!J(r)||Re(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Qa*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await La(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!J(r)||Re(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await ja(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!J(r)||Re(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ga(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!J(r)||Re(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await za(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,Math.max(t.maxBodyBytes,Math.ceil(gt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await ka(e,{service:H()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await F().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ae();const n=await se().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):qa.aliasRead;ae();const s=await se().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?Za(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await F().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(os(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ke.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ke.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||qs(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Ke.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
|
|
34
34
|
|
|
35
35
|
`)}catch{}};e({type:"hello",at:Date.now()});const n=re.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
|
|
36
36
|
|
|
37
|
-
`)}catch{}},25e3);o.on("close",()=>{n(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&r.method==="GET")return a(o,200,{ok:!0,runs:re.list({limit:y.searchParams.get("limit")||50,team:y.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await
|
|
37
|
+
`)}catch{}},25e3);o.on("close",()=>{n(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&r.method==="GET")return a(o,200,{ok:!0,runs:re.list({limit:y.searchParams.get("limit")||50,team:y.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:re.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(i);if(e){const n=e[1],s=e[2]||"";if(!s&&r.method==="GET"){const l=re.get(n,{events:y.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!s&&r.method==="DELETE")return re.stop(n),a(o,200,{ok:!0,removed:re.remove(n)});if(s==="/stop"&&r.method==="POST"){const l=re.stop(n);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(s==="/checkpoint"&&r.method==="GET")try{return a(o,200,{ok:!0,checkpoint:re.checkpoint(n)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?re.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):re.claim(n,{client:l.client});return a(o,200,{ok:!0,run:d})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&r.method==="DELETE")try{return a(o,200,{ok:!0,run:re.removeThread(n,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},d=String(l.by||"person").slice(0,40),m=s==="/answer"?re.answer(n,{threadId:l.threadId,text:l.text,by:d}):s==="/decide"?re.decide(n,{postId:l.postId,status:l.status,by:d}):re.post(n,{threadId:l.threadId,text:l.text,by:d,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:m})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:re.append(n,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&r.method==="GET"){if(!re.get(n))return a(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=g=>o.write(`data: ${JSON.stringify(g)}
|
|
38
38
|
|
|
39
|
-
`),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(n),after:m}});const p=re.watch(n,
|
|
39
|
+
`),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(n),after:m}});const p=re.watch(n,g=>{g.seq==null?l(g):g.seq>m&&(m=g.seq,l(g))});for(const g of re.eventsSince(n,m))m=g.seq,l(g);const f=setInterval(()=>{try{o.write(`: keep-alive
|
|
40
40
|
|
|
41
|
-
`)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});So||=cn({store:e,notify:Fe,audit:kt});const n=async l=>{const d=(await S(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=u(r);if(await un(r,o,{pathname:i,api:So,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Js(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Ls(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(w,{maxTokens:k=220}={})=>{const x=new AbortController,T=setTimeout(()=>x.abort(),3e4);try{const D=Ge()||Ne(),Y=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:x.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:k,temperature:.2})}),ve=await Y.json().catch(()=>({}));return Y.ok?String(ve?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await Sn(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Tn(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(yt*4/3)+1024:t.maxBodyBytes;try{const l=(await S(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await Le().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Ha]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await S(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ns({cfg:t,apply:Rt,persist:()=>we(t,oe()),isSelf:l=>Os(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await S(r,Math.max(t.maxBodyBytes,Math.ceil(yt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await I().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Re(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:zt.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{},n=zt.push(Ko({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await S(r,Math.max(t.maxBodyBytes||0,qs))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],w=[];const k={upserts:[],removes:[]},x=T=>{if(!T||T.deletedAt){T?.id&&k.removes.push(T.id);return}try{const D=$o(T);D&&k.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)x(e.get(D))}if(Array.isArray(n.entries)){const T=Et(),D=T?oa((ne,Oe)=>ea(T,{salt:ne,iterations:Oe})):null,Y=async ne=>{if(!D||!ne.blob)return null;const Oe=await D(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?ra(na,ne.blob.compression):null;return ta(ne.blob,Oe,{codec:U})},ve=await e.upsertEntries(n.entries,{open:Y});d.push(...ve.written),m+=ve.sealed;for(const ne of ve.written)x(e.get(ne))}return(k.upserts.length||k.removes.length)&&L.bulk(k),d.length&&Fe({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Me)try{m.write(`event: deleted
|
|
41
|
+
`)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=L.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});xo||=hn({store:e,notify:Fe,audit:nt});const n=async l=>{const d=(await v(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await yn(r,o,{pathname:i,api:xo,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=L.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:L.size,newest:L.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Hs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Us(s,f=>L.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:L.size,newest:L.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!J(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(g,{maxTokens:k=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Ge()||Ae(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:k,temperature:.2})}),Se=await Q.json().catch(()=>({}));return Q.ok?String(Se?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await On(n,{store:L,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,En(n,f,{size:L.size,newest:L.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(gt*4/3)+1024:t.maxBodyBytes;try{const l=(await v(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await Ye().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Ka]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await v(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Rs({cfg:t,apply:St,persist:()=>we(t,te()),isSelf:l=>Ns(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await v(r,Math.max(t.maxBodyBytes,Math.ceil(gt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await ve().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Re(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:L.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:L.size,bytes:L.bytes,newest:L.newest}},access:Ht.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ht.push(Zo({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,Math.max(t.maxBodyBytes||0,ni))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const k={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&k.removes.push(T.id);return}try{const R=Mo(T);R&&k.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=At(),R=T?ia((ne,Ee)=>aa(T,{salt:ne,iterations:Ee})):null,Q=async ne=>{if(!R||!ne.blob)return null;const Ee=await R(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?la(da,ne.blob.compression):null;return sa(ne.blob,Ee,{codec:U})},Se=await e.upsertEntries(n.entries,{open:Q});d.push(...Se.written),m+=Se.sealed;for(const ne of Se.written)_(e.get(ne))}return(k.upserts.length||k.removes.length)&&L.bulk(k),d.length&&Fe({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=K.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=K.deleteOf(l);for(const m of Be)try{m.write(`event: deleted
|
|
42
42
|
data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
|
|
43
43
|
|
|
44
|
-
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:K.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await
|
|
45
|
-
data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:
|
|
44
|
+
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:K.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:oa(m?.source))===No,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${No}" is this gateway's own log`})),d=qn(K,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:K.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return K?a(o,200,{ok:!0,cursor:K.cursor(),count:K.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=ea(K.all());return a(o,200,{ok:!0,stats:e,year:ta(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Bo(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=K.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>Mt(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=Bo(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
45
|
+
data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:de})}
|
|
46
46
|
|
|
47
|
-
`),
|
|
48
|
-
data: ${JSON.stringify(
|
|
47
|
+
`),Be.add(o),r.on("close",()=>Be.delete(o)),e){let n={cursor:e,more:!0};for(;n.more;){n=K.since(n.cursor);for(const s of n.events)o.write(`event: cloudevent
|
|
48
|
+
data: ${JSON.stringify(Mt(s))}
|
|
49
49
|
|
|
50
|
-
`)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...
|
|
50
|
+
`)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...O?{enabled:!0,...O.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&r.method==="POST"){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{we(t,te())}catch(n){console.warn(`[link] could not persist the settings: ${n.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&r.method==="POST"){if(!O)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const n={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=O.previewPartner(n)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await O.pairPartner(n)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await O.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(n){return a(o,502,{error:{message:n?.message||String(n),type:"relay"}})}}if(i==="/v1/link/route"&&r.method==="POST"){if(!O)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let n;try{n=Pa({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:n.id,fallback:e.fallback!==!1};n.id==="relay"?s.relayUrl=n.url:n.id==="link"&&delete s.relayUrl,(n.id==="tailscale"||n.id==="cloudflare")&&(s.tunnelUrl=n.url),t.link=s;try{we(t,te())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await O.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&r.method==="DELETE"){if(!O)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await O.remove(e)?(x.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=Re(r.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const n=O?.partnerFolderOf(e.device);if(!n)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=r.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=Da(s,{listing:d})}catch(p){return a(o,400,{error:{message:p.message,type:"invalid_request",code:"bad_path"}})}try{if(r.method==="GET"&&d)return a(o,200,{folder:"its own",files:Ca(n,m.replace(/\/$/,""))});if(r.method==="GET"){const p=Ra(n,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(p.size)}),p.stream.pipe(o);return}return r.method==="PUT"?a(o,200,Ia(n,m,await v(r,t.maxBodyBytes))):r.method==="DELETE"?Ja(n,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(p){const f=p?.status||(p?.code===413?413:p?.code==="bad_partner"?400:500);return a(o,f,{error:{message:p?.message||String(p),type:f===404?"not_found":f===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&r.method==="GET")return a(o,200,{pending:x.list()});if(i==="/v1/link/approvals/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const n=d=>o.write(`event: approvals
|
|
51
51
|
data: ${JSON.stringify({pending:d})}
|
|
52
52
|
|
|
53
|
-
`);n(
|
|
53
|
+
`);n(x.list());const s=x.subscribe(n),l=setInterval(()=>o.write(`:
|
|
54
54
|
|
|
55
|
-
`),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await
|
|
56
|
-
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:
|
|
55
|
+
`),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}return Do.some(s=>s.id===n.decision)?x.answer(e[1],n.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${Do.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&r.method==="GET")return a(o,200,b.status());if(i==="/v1/browser/stream"&&r.method==="GET"){b.stream(r,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&r.method==="POST"){let e;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const n=i==="/v1/browser/call"?await b.call(e,r):i==="/v1/browser/announce"?b.announce(e):b.result(e);return a(o,n.status,n.body)}if(i==="/v1/history/stream"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
56
|
+
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:de,prefsRevision:me.revision})}
|
|
57
57
|
|
|
58
|
-
`),o.chatpanelCredentialed=!!u(r),Ee.add(o),r.on("close",()=>Ee.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...L.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=L.get(String(y.searchParams.get("id")||""),{maxChars:e,offset:n});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:ko()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?ln(String(e.passphrase)):dn();const n=e.passphrase?await Nt(L,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&Fe(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Nt(L,Et());return e.ok&&e.whole&&Fe(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await ar(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await pt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await S(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=nr(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await S(r,t.maxBodyBytes),s=await He(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ht(t)});try{let n=e;const s=await xe(t.pro?.entitlementToken);await pt(t);const l=await Xe([dt(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:or(l.vault,"types")||[],detector:Ht(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Bt.totalmem()/1048576),s=ss(Do,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:an(),recommendation:vo(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Bt.totalmem()/1048576),l=vo(Do.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Co(d)||Ro(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&Fo(t,n);try{we(t,oe())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=nn(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!(Co(n)||Ro(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Fo(t,n);try{we(t,oe())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=$.health().model||t.stt?.model||Ue,n={platform:process.platform,arch:process.arch,helper:!!$t()},s=is.map(l=>{const d=Io(l,n);return{...l,installed:$.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:cs,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ls(n)||ds(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=Io(ft(n),{platform:process.platform,arch:process.arch,helper:!!$t()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=ft(n)?.license||null;if(l){const m=Jo(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&us(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{we(t,oe())}catch{}return $.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Wt(t,{installing:!0}),licenseAccepted:cr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:$.state(),progress:$.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=ts.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),segment:es.health(),translate:Ie.health(),indictrans:Za.health(),aec:Mt.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Bo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{we(t,oe())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=C.health().model||t.tts?.model||Uo(Ct()),n=Ct(),s=Lo.find(d=>d.id===e)||null,l=Lo.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(bt(e)==="pocket-tts"?gt:Be),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&bt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():ws).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:ms.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:ys})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ps(n)||hs(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ue.parseCustomVoice(s);if(!(d?!!ue.getVoice(d):wt(s)||jo(s)&&zo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&fs(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Go,voice:Be,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=gs(n),m=ue.parseCustomVoice(t.tts.voice||""),p=!!(m&&ue.getVoice(m));if(d&&!p)if(bt(n)==="pocket-tts")t.tts.voice=gt;else{const w=ue.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&p&&(t.tts.voice=Be);const f=bt(n)==="pocket-tts";f&&!ue.parseCustomVoice(t.tts.voice||"")&&!wt(t.tts.voice)&&(t.tts.voice=gt),!f&&wt(t.tts.voice)&&(t.tts.voice=Be)}l&&(t.tts.dtype=l==="auto"?null:l);try{we(t,oe())}catch{}return n&&C.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ue.listVoices(),usable:C.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ue.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ue.renameVoice(l,n),usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=rs(P.activeModel())?.dim===ue.EMBED_DIM;if(d&&!P.isReady()){const x=P.download({onLog:Y=>console.log(Y)}),T=Symbol("timeout"),D=await Promise.race([x.then(()=>null).catch(Y=>Y),new Promise(Y=>setTimeout(()=>Y(T),ir))]);if(D===T||!P.isReady())return a(o,503,{error:{message:D===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const x=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});x&&(f=await x.encodeVoice(si(m,16e3,24e3)))}catch(x){console.log(`[tts] pocket conditioning unavailable for this voice (${x.message})`)}const w=l?ue.replaceVoice(l,{vec:p,pocket:f}):ue.saveVoice({name:n,vec:p,pocket:f}),k=l&&n&&n!==w.name?ue.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${k.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...k,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ue.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ue.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Be;try{we(t,oe())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ho)return a(o,413,{error:{message:`text too long (max ${Ho} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=bs(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Be);if(l&&!ks(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ne,contentType:Oe,redacted:U}=await vs({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await xe(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Oe,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await C.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Uo(Ct()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Ss({requested:d,configured:m,engine:C,voices:ue,isPocketVoice:wt,isKnownVoice:jo,isValidVoiceId:zo,defaultVoice:Be,defaultPocketVoice:gt});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:k,customId:x,speakerEmbedding:T}=w,D=await C.synth(n,{voice:k,speed:s,speakerEmbedding:T}),Y=C.sampleRate(),ve=p==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,Y);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ve.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...x||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":k}:{}}),o.end(ve)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ns(await S(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(k){return a(o,k.code===413?413:415,{error:{message:k.message,type:"bad_request"}})}const n=k=>e.find(x=>x.name===k&&!x.filename)?.data.toString("utf8").trim()||"",s=e.find(k=>k.name==="file"&&k.filename)||e.find(k=>k.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await as(s.data)}catch(k){return a(o,k.code===415?415:500,{error:{message:k.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=Dt(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=Mo(m,{fetchImpl:He})}catch(k){return a(o,500,{error:{message:`stt provider: ${k.message}`,type:"bad_provider"}})}if(!p&&!$.isReady()&&await $.init({model:t.stt?.model||Ue,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Wt(t),onLog:k=>console.log(k)}),!p&&!$.isReady())return a(o,503,{error:{message:`speech model not ready: ${$.health().error||$.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:k=>console.log(k)});const w=Date.now();try{const{id:k}=$.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),x=[],T=[];let D=null;$.subscribe(k,U=>{U.type==="final"&&U.text?x.push(U):U.type==="language"?D=U.lang:U.type==="error"&&T.push(U.message||U.code)});const Y=16e3*5;for(let U=0;U<l.pcm.length;U+=Y)$.pushAudio(k,l.pcm.subarray(U,Math.min(l.pcm.length,U+Y))),await $.decodeNow(k);if(await $.endSession(k),!x.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let ve=0;const ne=x.map((U,yr)=>{const ao=typeof U.startMs=="number"?U.startMs/1e3:ve,fr=(U.durationMs||0)/1e3;return ve=ao+fr,{id:yr,start:Math.round(ao*100)/100,end:Math.round(ve*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(lt=>({start:Math.round(lt.startMs/10)/100,end:Math.round((lt.startMs+lt.durationMs)/10)/100,speaker:lt.speaker}))}:{}}}),Oe=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Oe)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Oe,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Oe})}catch(k){return a(o,k.code==="too_many_sessions"?429:500,{error:{message:k.message,type:k.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>lr)return a(o,413,{error:{message:`at most ${Ft} s of audio`,type:"too_large"}});let n;try{n=await S(r,lr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Ft} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=$.toFloat32(n);if(s.length<ai)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),ir).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=Dt(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Mo(n,{fetchImpl:He})}catch(x){return a(o,500,{error:{message:`stt provider: ${x.message}`,type:"bad_provider"}})}!s&&!$.isReady()&&$.init({model:t.stt?.model||Ue,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Wt(t),licenseAccepted:cr(t,t.stt?.model||Ue),onLog:x=>console.log(x)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:x=>console.log(x)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:x=>console.log(x)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&Mt.state()==="off"&&Mt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:x=>console.log(x)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||Ue,k=f&&!s?qa(f,{engine:ft(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const x=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",D=l&&e?.vectors===!0,{id:Y}=$.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:x,format:T});return a(o,201,{id:Y,state:$.state(),format:T,...x?{poll:!0}:{},...D?{vectors:!0}:{},...k.length?{languagesMissing:k}:{},...d?{translate:Ie.state()}:{}})}catch(x){return a(o,x.code==="too_many_sessions"?429:500,{error:{message:x.message,type:x.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await Xe([dt(()=>f,w=>{f=w})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=$.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const w=d.remote?"ready":$.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...$.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Ie.state())?p.push({type:"translate-progress",state:Ie.state(),...Ie.progress()||{}}):dr.get(d)!==w&&(dr.set(d,w),p.push({type:"state",state:w}))}const f=d?.redact?await xe(t.pro?.entitlementToken):!0;for(const w of m)d?p.push(await s(d,w,f)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&p.push(w);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=$.getSession(n)||$.endedSession(n);try{const m=await S(r,t.maxBodyBytes);$.pushAudio(n,$.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:$.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=$.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
|
|
58
|
+
`),o.chatpanelCredentialed=!!h(r),Pe.add(o),r.on("close",()=>Pe.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=L.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...L.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=L.get(String(y.searchParams.get("id")||""),{maxChars:e,offset:n});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:To()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?mn(String(e.passphrase)):pn();const n=e.passphrase?await Dt(L,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&Fe(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Dt(L,At());return e.ok&&e.whole&&Fe(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await dr(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await yt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=lr(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),s=await He(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Vt(t)});try{let n=e;const s=await _e(t.pro?.entitlementToken);await yt(t);const l=await Ze([ut(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:sr(l.vault,"types")||[],detector:Vt(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Ct.totalmem()/1048576),s=us(Jo,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:cn(),recommendation:So(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Ct.totalmem()/1048576),l=So(Jo.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Lo(d)||jo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&Yo(t,n);try{we(t,te())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=dn(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!(Lo(n)||jo(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Yo(t,n);try{we(t,te())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Ue,n={platform:process.platform,arch:process.arch,helper:!!Bt()},s=ms.map(l=>{const d=zo(l,n);return{...l,installed:A.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:ys,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ps(n)||hs(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=zo(wt(n),{platform:process.platform,arch:process.arch,helper:!!Bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=wt(n)?.license||null;if(l){const m=Go(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&fs(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{we(t,te())}catch{}return A.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Qt(t,{installing:!0}),licenseAccepted:hr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=ss.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),segment:as.health(),translate:Ie.health(),indictrans:rs.health(),aec:Rt.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Ro(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{we(t,te())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=I.health().model||t.tts?.model||Ko(Jt()),n=Jt(),s=Ho.find(d=>d.id===e)||null,l=Ho.map(d=>({...d,installed:I.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:I.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:I.state(),progress:I.progress(),available:l,voice:t.tts?.voice||(kt(e)==="pocket-tts"?bt:Ne),arch:I.arch(),supportsVoices:I.arch()?I.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:I.arch()?I.supportsCustomVoices():!!s?.customVoices,sampleRate:I.sampleRate(),voices:I.isPocket()||!I.arch()&&kt(e)==="pocket-tts"?(I.builtinVoices().length?I.builtinVoices():Ts).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:I.builtinVoices().includes(d)})):I.arch()&&I.arch()!=="style-tts2"?[]:gs.map(d=>({...d,installed:I.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:I.health().dtype,runtime:I.health().runtime,dtypes:vs})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ws(n)||bs(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ue.parseCustomVoice(s);if(!(d?!!ue.getVoice(d):vt(s)||Uo(s)&&Vo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&ks(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Fo,voice:Ne,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=Ss(n),m=ue.parseCustomVoice(t.tts.voice||""),p=!!(m&&ue.getVoice(m));if(d&&!p)if(kt(n)==="pocket-tts")t.tts.voice=bt;else{const g=ue.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!d&&p&&(t.tts.voice=Ne);const f=kt(n)==="pocket-tts";f&&!ue.parseCustomVoice(t.tts.voice||"")&&!vt(t.tts.voice)&&(t.tts.voice=bt),!f&&vt(t.tts.voice)&&(t.tts.voice=Ne)}l&&(t.tts.dtype=l==="auto"?null:l);try{we(t,te())}catch{}return n&&I.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:I.state(),progress:I.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ue.listVoices(),usable:I.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ue.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ue.renameVoice(l,n),usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=ls(P.activeModel())?.dim===ue.EMBED_DIM;if(d&&!P.isReady()){const _=P.download({onLog:Q=>console.log(Q)}),T=Symbol("timeout"),R=await Promise.race([_.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(T),ur))]);if(R===T||!P.isReady())return a(o,503,{error:{message:R===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const _=await I.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(ui(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const g=l?ue.replaceVoice(l,{vec:p,pocket:f}):ue.saveVoice({name:n,vec:p,pocket:f}),k=l&&n&&n!==g.name?ue.renameVoice(l,n):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${k.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...k,usable:I.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ue.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ue.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Ne;try{we(t,te())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Wo)return a(o,413,{error:{message:`text too long (max ${Wo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=xs(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Ne);if(l&&!Os(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ne,contentType:Ee,redacted:U}=await _s({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await _e(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Ee,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await I.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ko(Jt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:I.health().error||"tts model not ready",type:"tts_unavailable"}});const g=Es({requested:d,configured:m,engine:I,voices:ue,isPocketVoice:vt,isKnownVoice:Uo,isValidVoiceId:Vo,defaultVoice:Ne,defaultPocketVoice:bt});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:k,customId:_,speakerEmbedding:T}=g,R=await I.synth(n,{voice:k,speed:s,speakerEmbedding:T}),Q=I.sampleRate(),Se=p==="pcm"?Buffer.from(new Float32Array(R).buffer):I.toWav(R,Q);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(Se.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||I.isPocket()||I.supportsVoices()?{"X-Tts-Voice":k}:{}}),o.end(Se)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ds(await v(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(k){return a(o,k.code===413?413:415,{error:{message:k.message,type:"bad_request"}})}const n=k=>e.find(_=>_.name===k&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(k=>k.name==="file"&&k.filename)||e.find(k=>k.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await cs(s.data)}catch(k){return a(o,k.code===415?415:500,{error:{message:k.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=It(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=Io(m,{fetchImpl:He})}catch(k){return a(o,500,{error:{message:`stt provider: ${k.message}`,type:"bad_provider"}})}if(!p&&!A.isReady()&&await A.init({model:t.stt?.model||Ue,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Qt(t),onLog:k=>console.log(k)}),!p&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:k=>console.log(k)});const g=Date.now();try{const{id:k}=A.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),_=[],T=[];let R=null;A.subscribe(k,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"?R=U.lang:U.type==="error"&&T.push(U.message||U.code)});const Q=16e3*5;for(let U=0;U<l.pcm.length;U+=Q)A.pushAudio(k,l.pcm.subarray(U,Math.min(l.pcm.length,U+Q))),await A.decodeNow(k);if(await A.endSession(k),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let Se=0;const ne=_.map((U,br)=>{const io=typeof U.startMs=="number"?U.startMs/1e3:Se,vr=(U.durationMs||0)/1e3;return Se=io+vr,{id:br,start:Math.round(io*100)/100,end:Math.round(Se*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(ct=>({start:Math.round(ct.startMs/10)/100,end:Math.round((ct.startMs+ct.durationMs)/10)/100,speaker:ct.speaker}))}:{}}}),Ee=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Ee)):d==="verbose_json"?a(o,200,{task:"transcribe",language:R||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Ee,segments:ne,provider:m.kind,took_ms:Date.now()-g}):a(o,200,{text:Ee})}catch(k){return a(o,k.code==="too_many_sessions"?429:500,{error:{message:k.message,type:k.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>mr)return a(o,413,{error:{message:`at most ${Kt} s of audio`,type:"too_large"}});let n;try{n=await v(r,mr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Kt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=A.toFloat32(n);if(s.length<ci)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),ur).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=It(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Io(n,{fetchImpl:He})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Ue,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Qt(t),licenseAccepted:hr(t,t.stt?.model||Ue),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&Rt.state()==="off"&&Rt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,g=t.stt?.model||Ue,k=f&&!s?ns(f,{engine:wt(g)?.engine||"",englishOnly:/\.en$/.test(g)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",R=l&&e?.vectors===!0,{id:Q}=A.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:R,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:Q,state:A.state(),format:T,..._?{poll:!0}:{},...R?{vectors:!0}:{},...k.length?{languagesMissing:k}:{},...d?{translate:Ie.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await Ze([ut(()=>f,g=>{f=g})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=A.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const g=d.remote?"ready":A.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...A.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Ie.state())?p.push({type:"translate-progress",state:Ie.state(),...Ie.progress()||{}}):pr.get(d)!==g&&(pr.set(d,g),p.push({type:"state",state:g}))}const f=d?.redact?await _e(t.pro?.entitlementToken):!0;for(const g of m)d?p.push(await s(d,g,f)):g.type!=="final"&&g.type!=="interim"&&g.type!=="translation"&&p.push(g);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=A.getSession(n)||A.endedSession(n);try{const m=await v(r,t.maxBodyBytes);A.pushAudio(n,A.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=A.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
|
|
59
59
|
|
|
60
|
-
`),p=d.redact?await
|
|
60
|
+
`),p=d.redact?await _e(t.pro?.entitlementToken):!0,f=T=>s(d,T,p);m({type:"state",state:d.remote?"ready":A.state()});const g=setInterval(()=>{const T=d.remote?"ready":A.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...A.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(g);return}if(d.diarize){const R=P.state();if(R==="downloading"||R==="loading"){m({type:"diarize-progress",state:R,...P.progress()||{}});return}}if(d.translateTo){const R=Ie.state();if(R==="downloading"||R==="loading"){m({type:"translate-progress",state:R,...Ie.progress()||{}});return}}m({type:"state",state:T}),clearInterval(g)},500);g.unref?.();let k=Promise.resolve();const _=A.subscribe(n,T=>{k=k.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(g),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(g),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=A.getSession(n);await A.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...he].reverse()});if(i==="/config"&&r.method==="GET"){const e=await _e(t.pro?.entitlementToken);return a(o,200,Qo(t,{proUnlocked:e,policy:mt()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const p=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{St(p,{capabilities:e.capabilities})}catch(g){if(g?.code==="SHAPE")return a(o,400,{error:g.message});throw g}const f=Object.keys(e.capabilities).map(g=>Is(g,t.capabilities?.[g],p.capabilities?.[g])).find(Boolean);if(f&&!await _e(t.pro?.entitlementToken))return a(o,403,{error:f,needs:"pro"})}try{St(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}ho(t),JSON.stringify(t.sandbox||null)!==n&&at?.restart("sandbox settings changed");try{we(t,te())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=j.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&j.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await _e(t.pro?.entitlementToken);return a(o,200,Qo(t,{proUnlocked:m,policy:mt()}))}if(r.method==="GET"&&i==="/skills")return Te(r,o,t,`/skills${Qe(y,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(r.method==="POST"&&i==="/v1/threads/send"){if(!J(r))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=L.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let n={};try{n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(n.to||""),l=String(n.message||"").trim();if(!l||l.length>Eo)return a(o,400,{error:{message:`threads/send: a message of 1–${Eo} characters`,type:"invalid_request"}});const d=n.from&&typeof n.from=="object"?{id:String(n.from.id||"").slice(0,200),title:String(n.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=Sn(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(n.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:p.model});const f=Tn({fromTitle:d?.title,message:l}),g={thread:{id:p.thread,...m.title?{title:m.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let k="";try{const T=await fetch(`http://127.0.0.1:${r.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Ge()||Ae(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(g))},body:JSON.stringify({model:p.model,messages:[...xn(m),{role:"user",content:f}],stream:!1}),signal:AbortSignal.timeout(6e5)}),R=await T.json().catch(()=>null);if(!T.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${R?.error?.message||`HTTP ${T.status}`}`,type:"upstream"}});k=String(R?.choices?.[0]?.message?.content||"")}catch(T){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${T?.message||T}`,type:"upstream"}})}const _=_n(e.get(s)||m,{question:f,reply:k,model:p.model,from:d});e.write([_],{host:"gateway",at:Date.now()});try{const T=Mo(e.get(s));T&&L.bulk({upserts:[T],removes:[]})}catch{}return Fe({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:p.model,reply:k})}const q=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(r.method==="POST"&&q)return J(r)?r.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):Te(r,o,t,q,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/skills-quarantined")return Te(r,o,t,`/skills-quarantined${Qe(y,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&r.method==="POST")return J(r)?Te(r,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&r.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Yt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):J(r)?Te(r,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&r.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]);return Yt(n)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):J(r)?Te(r,o,t,`/skills/${encodeURIComponent(n)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(r.method==="GET"&&i==="/agent-defs")return Te(r,o,t,`/agent-defs${Qe(y,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(r.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Yt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):Te(r,o,t,`/agent-defs/${encodeURIComponent(e)}${Qe(y,t)}`)}if(i.startsWith("/a2a/")){if(!J(r))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(r.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:tn()});if(r.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Yr(e.url||"");const n=await pt(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:n.card,fingerprint:n.fingerprint,fresh:n.fresh,changed:!!n.changed,url:n.url})}if(r.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await pt(e.url,{auth:String(e.auth||"")})).card,s=await Xr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(r.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await pt(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
|
|
61
61
|
data: ${JSON.stringify(d)}
|
|
62
62
|
|
|
63
|
-
`);try{const l=await Kr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ut(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Yr({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await Qr({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof ho||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof ho&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?ke(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(e)}${Qe(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await et(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=tt(t.bridge?.token);try{const s=r.method==="POST"?(await S(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ke(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Qe(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await H(),n=e.sig!==void 0&&e.sig!==F;return F=e.sig,a(o,200,await Ms(t,{serviceHealth:async()=>e,fresh:n,engineAt:b.engineAt}))}if(ii.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=Ys(i,r.headers,t);let Te;try{Te=await S(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let fe=null,E=null,Ye=Te,Yt=0,Xt=0,Zt=0,_e=!1,Ce=!1,qt="",je=!0;const se=t.logRequests&&W.redactable&&r.method==="POST"?Qs(he):null,ur=Date.now();if(W.redactable&&r.method==="POST"&&Te.length){try{E=JSON.parse(Te.toString("utf8"))}catch{E=null}if(E&&Xs(E,W.kind))Ye=Te;else if(E){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(E.tools)&&E.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):zs,w=e.narrowAll?null:x=>!Gs.test(Zo(x)),k=E.tools.length;E.tools=_r(E.tools,Us(E,W.kind),{cap:f,keep:w,name:Zo,description:Hs}),Zt=k-E.tools.length}if(je=await xe(t.pro?.entitlementToken),_e=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!_e){const f=vt(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:()=>!1}),w=f?.type==="api"?await b.decide(f,E?.model).catch(()=>null):null;Ce=w?.redact===!1,qt=Ce?w.engine||"declared":""}if(!_e&&!Ce){const f=Ts(t,je);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!_e&&!Ce&&await pt(t);const n=_e?[]:W.adapter.collectSegments(E,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=se?se.clock():0,{vault:d,count:m,sanitized:p}=_e?{vault:null,count:0,sanitized:0}:await Xe(n,t.redaction,{signal:s.signal,isPro:je,sanitizeOnly:Ce,onEgress:f=>zt.push(Ko({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(se&&se.lap("redact",l),W.adapter.joinTextParts?.(E),fe=d,Yt=m,Xt=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!je&&m>0){xs(t,je);try{we(t,oe())}catch{}}if(!_e&&!Ce&&Array.isArray(E.tools)&&E.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=vt(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:k=>!!k.service&&M.fn(k.id)==="down"}),w=!(f&&f.type==="api");W.adapter.injectSystemNote(E,Er({toolData:t.tools?.toolData,ownTools:w}))}else!_e&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(E,Pr());Ye=Buffer.from(JSON.stringify(E),"utf8")}}const eo=Or({vault:fe,toolData:t.tools?.toolData}),nt=E&&typeof E.chatpanel=="object"&&E.chatpanel||null;if(nt&&(delete E.chatpanel,Ye=Buffer.from(JSON.stringify(E),"utf8")),typeof E?.model=="string"&&E.model.startsWith("fusion:")){const e=qn(E.model,t,await H());if(e?.error)return se?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(E.model=e.model,Ye=Buffer.from(JSON.stringify(E),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ie={destination:String(r.headers["x-chatpanel-destination"]||nt?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||nt?.reach||"").trim(),run:Qt(r.headers["x-chatpanel-run"],nt?.run)},at=await H(),to=e=>!!e.service&&at(e.id)==="down";let B=vt(E?.model,t,W.kind,{destination:ie.destination,down:to});B?.type==="agent"&&E?.model&&!ie.destination&&!Rs(B,E.model)&&(await Cs(t,{serviceHealth:async()=>at,engineAt:b.engineAt}),B=vt(E?.model,t,W.kind,{destination:ie.destination,down:to}));const oo=B?.service&&at(B.id)==="down"?await G().revive(B.service).catch(()=>null):null;if(oo?.ok&&(M.at=0),B?.service&&at(B.id)==="down"&&!oo?.ok)return se?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(E?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ie.destination&&(!B||B.id!==ie.destination))return se?.commit(),a(o,404,{error:{message:`no destination "${ie.destination}" is configured on this gateway`,type:"unknown_destination",known:Ds(t).map(e=>e.id)}});const ce=Re(r.headers);if(ce&&!Oa(ce,B?.type==="api"?"api":"agent"))return se?.commit(),a(o,403,{error:{message:`link: partner "${ce.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ce.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const st=ce&&W.redactable&&r.method==="POST"&&E?{caller:ce,surface:Vn(ce,ce.kind==="partner"?"":g?.deviceNameOf(ce.device)),model:E.model||null,startedAt:ur}:null;se&&(se.meta={t:Date.now(),model:E?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:Yt,sanitized:Xt,narrowed:Zt,detail:or(fe,t.logDetail),redaction:_e?"off":Ce?`on-device (${qt})`:t.redaction.tier||"basic",...ce?.kind==="partner"?{via:Ea(ce)}:{}});const it=ct();if(it&&B){const e=B.type==="api"?po(it,{model:E?.model||"",endpoint:B.baseUrl||""}):Ur(it,B.agent||B.id)?po(it,{model:E?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return se?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?Zs(B.baseUrl,t)?(se?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):li(r,o,{...W,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:eo,trace:se,link:st&&{...st,agentId:B.id,dest:{type:"api",id:B.id}}},Ye,fe):(se?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const xt=Ze(r),ro=xt==="local"&&t.bridge?.openAgentLane?"token":xt;if(ro==="local")return se?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const no=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),mr=new Set(["thread","ephemeral","workingDir","worker"]),_t=ce?.kind==="partner";if(xt==="token"&&r.headers["x-chatpanel-link-device"]&&!_t&&!(ie.run&&Object.keys(ie.run).some(e=>!mr.has(e)))){const e=Qt(null,xo(To(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));e&&(ie.run={...e,...ie.run||{}})}if(_t){const e=Qt(null,xo(To(me.get("agentTools").agentTools?.value,B?.agent||E?.model)));ie.run={...e||{},...Pa(ie.run,ce.device)};const n=g?.partnerFolderOf(ce.device);if(!n)return se?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ie.run.workingDir=n,ie.reach="",Array.isArray(E?.tools)&&(E.tools=E.tools.filter(s=>!No(s?.function?.name??s?.name)))}const ze=Ar({...ie.run||{},...ie.reach?{reach:ie.reach}:{},...no?{askDepth:no}:{}},ro);ze.reach&&o.setHeader("x-chatpanel-reach-used",ze.reach);const pr=_t?{inbox:O,partner:ce.partner,device:ce.device,conversation:ze.thread?.id||null}:null,hr=st&&{...st,dest:{type:"agent",id:B?.id||"bridge"},threadId:ze.thread?.id||null};return ri(r,o,{...W,pathname:i,agentOverride:B?.agent,harness:eo,trace:se,run:Object.keys(ze).length?ze:null,owner:pr,link:hr},E,fe,t,je)});return te.on("close",()=>{z?.stop("closed"),da(),A.close(),g?.stop(),O.stop()}),te.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(g&&i.startsWith(_a)){g.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
63
|
+
`);try{const l=await Zr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await pt(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await en({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await qr({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof fo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof fo&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?Te(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):Te(r,o,t,`/skills/${encodeURIComponent(e)}${Qe(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await tt(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ot(t.bridge?.token);try{const s=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):Te(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Qe(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await ee(),n=e.sig!==void 0&&e.sig!==oe;return oe=e.sig,a(o,200,await Js(t,{serviceHealth:async()=>e,fresh:n,engineAt:M.engineAt}))}if(mi.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${de}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=ti(i,r.headers,t);let xe;try{xe=await v(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let ge=null,E=null,Xe=xe,Zt=0,qt=0,eo=0,Oe=!1,Ce=!1,to="",je=!0;const ie=t.logRequests&&W.redactable&&r.method==="POST"?ei(Ot):null,yr=Date.now();if(W.redactable&&r.method==="POST"&&xe.length){try{E=JSON.parse(xe.toString("utf8"))}catch{E=null}if(E&&oi(E,W.kind))Xe=xe;else if(E){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(E.tools)&&E.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Fs,g=e.narrowAll?null:_=>!Ws.test(or(_)),k=E.tools.length;E.tools=$r(E.tools,Qs(E,W.kind),{cap:f,keep:g,name:or,description:Ks}),eo=k-E.tools.length}if(je=await _e(t.pro?.entitlementToken),Oe=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!Oe){const f=Tt(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:()=>!1}),g=f?.type==="api"?await M.decide(f,E?.model).catch(()=>null):null;Ce=g?.redact===!1,to=Ce?g.engine||"declared":""}if(!Oe&&!Ce){const f=Ps(t,je);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Oe&&!Ce&&await yt(t);const n=Oe?[]:W.adapter.collectSegments(E,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ie?ie.clock():0,{vault:d,count:m,sanitized:p}=Oe?{vault:null,count:0,sanitized:0}:await Ze(n,t.redaction,{signal:s.signal,isPro:je,sanitizeOnly:Ce,onEgress:f=>Ht.push(Zo({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(ie&&ie.lap("redact",l),W.adapter.joinTextParts?.(E),ge=d,Zt=m,qt=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!je&&m>0){$s(t,je);try{we(t,te())}catch{}}if(!Oe&&!Ce&&Array.isArray(E.tools)&&E.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=Tt(E?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||E?.chatpanel?.destination||"").trim(),down:k=>!!k.service&&z.fn(k.id)==="down"}),g=!(f&&f.type==="api");W.adapter.injectSystemNote(E,Nr({toolData:t.tools?.toolData,ownTools:g}))}else!Oe&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(E,Br());Xe=Buffer.from(JSON.stringify(E),"utf8")}}const oo=Ar({vault:ge,toolData:t.tools?.toolData}),st=E&&typeof E.chatpanel=="object"&&E.chatpanel||null;if(st&&(delete E.chatpanel,Xe=Buffer.from(JSON.stringify(E),"utf8")),typeof E?.model=="string"&&E.model.startsWith("fusion:")){const e=na(E.model,t,await ee());if(e?.error)return ie?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(E.model=e.model,Xe=Buffer.from(JSON.stringify(E),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const le={destination:String(r.headers["x-chatpanel-destination"]||st?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||st?.reach||"").trim(),run:Xt(r.headers["x-chatpanel-run"],st?.run)},it=await ee(),ro=e=>!!e.service&&it(e.id)==="down";let N=Tt(E?.model,t,W.kind,{destination:le.destination,down:ro});N?.type==="agent"&&E?.model&&!le.destination&&!zs(N,E.model)&&(await js(t,{serviceHealth:async()=>it,engineAt:M.engineAt}),N=Tt(E?.model,t,W.kind,{destination:le.destination,down:ro}));const no=N?.service&&it(N.id)==="down"?await V().revive(N.service).catch(()=>null):null;if(no?.ok&&(z.at=0),N?.service&&it(N.id)==="down"&&!no?.ok)return ie?.commit(),a(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(E?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(le.destination&&(!N||N.id!==le.destination))return ie?.commit(),a(o,404,{error:{message:`no destination "${le.destination}" is configured on this gateway`,type:"unknown_destination",known:Ls(t).map(e=>e.id)}});const ce=Re(r.headers);if(ce&&!Na(ce,N?.type==="api"?"api":"agent"))return ie?.commit(),a(o,403,{error:{message:`link: partner "${ce.partner}" may not use ${N?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ce.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const lt=ce&&W.redactable&&r.method==="POST"&&E?{caller:ce,surface:Yn(ce,ce.kind==="partner"?"":O?.deviceNameOf(ce.device)),model:E.model||null,startedAt:yr}:null;ie&&(ie.meta={t:Date.now(),model:E?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:Zt,sanitized:qt,narrowed:eo,detail:sr(ge,t.logDetail),redaction:Oe?"off":Ce?`on-device (${to})`:t.redaction.tier||"basic",...ce?.kind==="partner"?{via:Ba(ce)}:{}});const dt=mt();if(dt&&N){const e=N.type==="api"?yo(dt,{model:E?.model||"",endpoint:N.baseUrl||""}):Kr(dt,N.agent||N.id)?yo(dt,{model:E?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ie?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?ri(N.baseUrl,t)?(ie?.commit(),a(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):pi(r,o,{...W,pathname:i,search:y.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:oo,trace:ie,link:lt&&{...lt,agentId:N.id,dest:{type:"api",id:N.id}}},Xe,ge):(ie?.commit(),a(o,502,{error:`destination "${N.id}" has no baseUrl`}));const Et=qe(r),ao=Et==="local"&&t.bridge?.openAgentLane?"token":Et;if(ao==="local")return ie?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const so=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),fr=new Set(["thread","ephemeral","workingDir","worker"]),Pt=ce?.kind==="partner";if(Et==="token"&&r.headers["x-chatpanel-link-device"]&&!Pt&&!(le.run&&Object.keys(le.run).some(e=>!fr.has(e)))){const e=Xt(null,Oo(_o(me.get("agentTools").agentTools?.value,N?.agent||E?.model)));e&&(le.run={...e,...le.run||{}})}if(Pt){const e=Xt(null,Oo(_o(me.get("agentTools").agentTools?.value,N?.agent||E?.model)));le.run={...e||{},...Ma(le.run,ce.device)};const n=O?.partnerFolderOf(ce.device);if(!n)return ie?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});le.run.workingDir=n,le.reach="",Array.isArray(E?.tools)&&(E.tools=E.tools.filter(s=>!Co(s?.function?.name??s?.name)))}const ze=Dr({...le.run||{},...le.reach?{reach:le.reach}:{},...so?{askDepth:so}:{}},ao);ze.reach&&o.setHeader("x-chatpanel-reach-used",ze.reach);const gr=Pt?{inbox:x,partner:ce.partner,device:ce.device,conversation:ze.thread?.id||null}:null,wr=lt&&{...lt,dest:{type:"agent",id:N?.id||"bridge"},threadId:ze.thread?.id||null};return li(r,o,{...W,pathname:i,agentOverride:N?.agent,harness:oo,trace:ie,run:Object.keys(ze).length?ze:null,owner:gr,link:wr},E,ge,t,je)});return ke.on("close",()=>{D?.stop("closed"),ha(),b.close(),O?.stop(),x.stop()}),ke.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(O&&i.startsWith(Aa)){O.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
64
64
|
connection: close\r
|
|
65
65
|
content-length: 0\r
|
|
66
66
|
\r
|
|
67
|
-
`)}catch{}}),
|
|
67
|
+
`)}catch{}}),ke.once("listening",()=>{V()}),ke.linkHost=O,ke.teamBuckets=De,ke.runtimeDefaults=()=>V().ensureDefaults(),ke}function Xt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const h={};if(Array.isArray(u.grants)&&(h.grants=u.grants.map(S=>String(S).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const S=u.workspace;h.workspace={repo:String(S.repo).slice(0,400),projectId:String(S.projectId||"").slice(0,120),jobId:String(S.jobId||"").slice(0,120),...S.base?{base:String(S.base).slice(0,120)}:{}}}if(u.connectionId&&(h.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(h.workingDir=u.workingDir.trim().slice(0,1024)),Ms.includes(u.permissionMode)&&u.permissionMode!=="default"&&(h.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const S=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(b=>String(b).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),B=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(b=>String(b).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,$=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(b=>String(b).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(S.length||B.length||M||$.length)&&(h.sandbox={...S.length?{hosts:S}:{},...B.length?{write:B}:{},...M?{outside:!0}:{},...$.length?{signIn:$}:{}})}const w=wn(u.thread);return w&&(h.thread=w),u.ephemeral===!0&&(h.ephemeral=!0),u.worker===!0&&(h.worker=!0,h.ephemeral=!0),u.lean===!0&&(h.lean=!0,h.ephemeral=!0),Object.keys(h).length?h:null}let at=null,_t=null;async function vd(t=lo()){un();let c=null;try{c=await Fr()}catch(b){throw b instanceof Wr&&(console.error(`[chatpanel-gateway] org policy: ${b.message}`),process.exit(78)),b}const u=c?.policy||null;u&&(ho(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const h=Ur({enabled:po(t)});console.log(`[chatpanel-gateway] certificates: ${h.on?`this computer's list is trusted too (${h.added} added to the runtime's own)`:`the runtime's own list only — ${h.why}`}`),Gr(globalThis,{allow:u?.egress?(b,{local:x})=>Qr(u,b,{local:x}):null}),Ae();const w=hi(t),S=ln(t),B=Sr(t);let M=!1;w.on("error",b=>{if(b&&b.code==="EADDRINUSE"){const x=xt(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(O=>O.ok?O.json():null).catch(()=>null).then(O=>{const G=!!(O?.version&&typeof O.tier=="string"),F=bn({name:"gateway",self:de,holder:G?{ours:G,version:O.version}:null,managedBy:vn(process.env),port:t.port});if(F.action==="standby"||M&&!O){if(!M)for(const D of F.lines)console.error(D);M=!0,setTimeout(()=>w.listen(t.port,t.host),kn);return}if(G){const D=O.managedBy?` (run by ${O.managedBy})`:"";for(const[H,z]of F.lines.entries())console.error(H===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${D}`):z)}else{const D=Cn(t.port);console.error(`Port ${t.port} is held by ${D||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${b?.message||b}`),process.exit(1)}),w.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(b=>console.log(` link : not started (${b?.message||b})`)),(t.context?.providers||[]).some(b=>b?.kind==="bucket"&&b.enabled!==!1))try{w.teamBuckets?.().start()}catch(b){console.log(` team : not started (${b?.message||b})`)}w.runtimeDefaults?.().then(b=>{for(const x of b||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(b=>console.log(` runtime : defaults not started (${b?.message||b})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const b of Cs(t))console.log(` ⚠ sandbox : ${b}`);console.log(` confined : ${zn(ft({stateDir:Ve.dirname(te())}))}`),_t={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Dn(t,{childEnv:()=>({...Ds(t,process.env,mt()),...Bs(t)})}).then(b=>{at=b}).catch(b=>{_t={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${b?.message||b})`},console.log(` bridge : not supervised (${b?.message||b})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),xt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),To()&&Dt(L,At()).then(b=>{b?.ok&&(console.log(` warm : seeded ${b.ingested} records from ${b.file}`),b.whole&&Fe())}).catch(()=>{});const $=()=>{S?.stop(),B.stop(),at?.stop(),Vs(w)};return process.on("SIGINT",$),process.on("SIGTERM",$),w}export{ni as RECORDS_MAX_BYTES,Td as VERSION,hi as createGateway,di as joinUpstream,Ut as parseAgentModel,vd as start};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.160.1";export{o as VERSION};
|