@chatpanel/gateway 0.86.0 → 0.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/bin/chatpanel-gateway-bin.mjs +2 -2
- package/bin/chatpanel-gateway.js +3 -3
- package/package.json +1 -1
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/server.js +21 -21
- package/src/system-ca.js +1 -0
- package/src/update.js +3 -3
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -86,6 +86,16 @@ npm the company's certificate (`npm config set cafile /path/to/company-ca.pem`),
|
|
|
86
86
|
standalone binary above. Do not set `strict-ssl=false`. The in-app Update does the first of these
|
|
87
87
|
by itself, and when an update fails it says which of these it was and the command to run.
|
|
88
88
|
|
|
89
|
+
**Whose certificates the gateway accepts.** Once installed, the gateway trusts the certificates
|
|
90
|
+
this computer trusts (the keychain, the Windows store, the distribution's bundle) as well as its
|
|
91
|
+
runtime's own list — so behind a proxy that re-signs HTTPS it reaches its models, its downloads
|
|
92
|
+
and its updates the way the browser on that machine does. Checks are never switched off: a
|
|
93
|
+
certificate nobody trusts is refused as before. The trade is the usual one on such a network: the
|
|
94
|
+
company's proxy can read what the gateway sends to a cloud model, after redaction has run. To
|
|
95
|
+
keep to the runtime's list alone, set `"tls": { "systemCa": false }` in
|
|
96
|
+
`~/.chatpanel/gateway.config.json` (or `CHATPANEL_SYSTEM_CA=off`) and restart;
|
|
97
|
+
`chatpanel-gateway --audit` says which is in effect. Needs Node 22.19+ for the npm install.
|
|
98
|
+
|
|
89
99
|
**Why `--ignore-scripts`.** The gateway itself has no install script, and the two in its tree — both
|
|
90
100
|
under `@huggingface/transformers`, the native model runtime — are ones it needs nothing from:
|
|
91
101
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{pathToFileURL as o}from"node:url";import{createRequire as l}from"node:module";import{existsSync as f,readFileSync as u}from"node:fs";import{join as g}from"node:path";import{homedir as
|
|
2
|
-
`)}catch{}};let s=null,c=!1;function
|
|
1
|
+
import{pathToFileURL as o}from"node:url";import{createRequire as l}from"node:module";import{existsSync as f,readFileSync as u}from"node:fs";import{join as g}from"node:path";import{homedir as d}from"node:os";import{normalizeRegistries as h}from"@chatpanel/events/registries.js";import p from"../assets/ort-wasm-simd-threaded.wasm";import _ from"../assets/ort-wasm-simd-threaded.mjs";import{findNativeBinding as v,ensureNativeOrt as a}from"../src/ort-native.js";import{trustSystemCertificates as w,systemCaWantedOnDisk as y}from"../src/system-ca.js";w({enabled:y()});function m(){try{const e=process.env.CHATPANEL_GATEWAY_CONFIG||g(d(),".chatpanel","gateway.config.json"),r=f(e)?JSON.parse(u(e,"utf8")):{},n={npm:process.env.CHATPANEL_REGISTRY_NPM,models:process.env.CHATPANEL_REGISTRY_MODELS};return h({...r.registries||{},...n.npm?{npm:n.npm}:{},...n.models?{models:n.models}:{}})}catch{return{}}}const t=e=>{try{process.stderr.write(`[ort] ${e}
|
|
2
|
+
`)}catch{}};let s=null,c=!1;function A(e){if(c)return s;c=!0;try{s=l(import.meta.url)(e),t(`native runtime loaded — ${e}`)}catch(r){t(`native runtime would not load (${String(r?.message||r).slice(0,120)}) — falling back to WASM`),s=null}return s}let i=v();const S=process.argv.includes("--install")||process.argv.includes("--fetch-runtime");if(!i&&S)try{i=await a({registries:m(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host}…`)}}),t(`native runtime ready — ${i}`)}catch(e){t(`no native runtime yet (${String(e?.message||e).slice(0,120)}) — the gateway will fetch it when it starts`)}process.argv.includes("--fetch-runtime")&&process.exit(i?0:1),i||a({registries:m(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host} — WASM answers until it lands`)}}).then(e=>t(`native runtime ready — ${e} (restart to use it)`)).catch(e=>t(`no native runtime (${String(e?.message||e).slice(0,120)}) — staying on WASM`)),i?globalThis.__CHATPANEL_ORT_BINDING__=()=>A(i):globalThis.__CHATPANEL_WASM_PATHS__={wasm:o(p).href,mjs:o(_).href},await import("./chatpanel-gateway.js");
|
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js")
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:
|
|
2
|
+
const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:t,systemCaWantedOnDisk:o}=await import("../src/system-ca.js");t({enabled:o()})}await import("@chatpanel/bridge/src/server.js")}else if(n==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(n==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(n==="tools"||n==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(n==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:c}=await import("../src/policy.js");try{const i=await t();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(o(i))}catch(i){throw i instanceof c&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(n==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:c}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:w}=await import("node:path"),g=await import("node:os"),p=c(),e=`http://127.0.0.1:${p.port||4320}`;let a=null,r=`no gateway running at ${e}`;try{const h=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(g.homedir(),".chatpanel","gateway-token"),"utf8").trim(),s=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(s.ok)a=await s.json();else if(s.status===404){const l=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);r=`the gateway running at ${e}${l?.version?` (${l.version})`:""} predates --audit (0.7.0) — restart it after updating`}else r=`the gateway at ${e} refused the audit (HTTP ${s.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js"),{systemCaWanted:s}=await import("../src/system-ca.js"),l=s(p);a={...t(p,{ledger:null,version:h,certificates:{on:!1,added:0,wanted:l,why:l?"no gateway is running; when one starts it adds this computer's list":"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"}}),observed:[]},console.log(`(${r}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:c}=await import("node:path"),i=await import("node:os"),g=`http://127.0.0.1:${t().port||4320}`,p=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||c(i.homedir(),".chatpanel","gateway-token");try{const e=o(p,"utf8").trim(),a=await fetch(`${g}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),r=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${g} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(r.error||`HTTP ${a.status}`);console.log(`Pairing code: ${r.display||r.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${g}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${p} — has the gateway started once?)`:""}`),process.exit(1)}}else if(n==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(n==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),c=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:c}),{dryRun:c}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:c,uninstallService:i,serviceReport:w,stopService:g,pathWithDir:p}=await import("../src/service.js");switch(n){case"--stop":g(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":{const e=await c({version:o,force:process.argv.includes("--force")}),a=e.health;if(e.newer){const r=a.managedBy&&a.managedBy!=="gateway"?` (run by the ${a.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${a.version} is already running at ${a.url}${r} — newer than this copy (v${o}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${o} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const r=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${a.version}) is the one answering right now; this install takes over at the next login`:"",h=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${a.version}: already running at ${a.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}${h}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${r}.`);let s=null;for(let l=0;l<30;l++){try{s=(await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),s?.version){const{staleBridgeCommands:l,staleBridgeLines:d}=await import("../src/service.js");for(const y of d(l({embedded:s.version}),{embedded:s.version}))console.log(y)}}else a.ok?(console.error(`ChatPanel Privacy Gateway: v${o} is registered to start at login, but v${a.version} still answers at ${a.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
|
|
4
4
|
${e.errLog.split(`
|
|
5
5
|
`).map(r=>` ${r}`).join(`
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:l=>console.error(l)}));s&&console.log(s)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&p(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await w());break;case void 0:await t();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${o}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
|
|
7
7
|
`));break;default:console.error(`unknown option: ${n}
|
|
8
8
|
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.87.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as
|
|
1
|
+
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}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:[],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:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,diarizeModel:m,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 g(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(A.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,g as loadConfig};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),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,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),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:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),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),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),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 i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}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 i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}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 i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(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 i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}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 i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
|
|
1
|
+
import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),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,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),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:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),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),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),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 i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}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 i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}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 i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(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 i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}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 i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),s=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[s]||"",scheme:s}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(s){const r=g(s);if(!r||!r.host)return;const o=`${r.scheme}://${r.host}:${r.port}`,h=e(),c=t.get(o);if(c){c.count+=1,c.lastAt=h;return}t.set(o,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:h,lastAt:h})},snapshot(){return[...t.values()].sort((s,r)=>s.local===r.local?r.count-s.count:s.local?1:-1)},reset(){t.clear()}}}let y=null;function U(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const s=L();let r=t;s.setGate=d=>{r=d},s.blocked=[];const o=d=>{let n=null;try{n=g(d),s.record(d)}catch{}if(!r||!n?.host)return null;let u=!0;try{u=r(`${n.scheme}://${n.host}:${n.port}`,{local:w(n.host)})}catch{u=!0}if(u)return null;const a=`${n.host}:${n.port}`;s.blocked.includes(a)||s.blocked.push(a);const i=new Error(`egress to ${n.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},h=e.fetch;typeof h=="function"&&(e.fetch=function(n,u){const a=o(n);return a?Promise.reject(a):h.call(this,n,u)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(d,n,u){const a=o(n[0]);if(a)throw a;return Reflect.construct(d,n,u)}})),e.__chatpanelEgress=s,e===globalThis&&(y=s),s}function P(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function S(e={},t=process.env,s=process.platform){const r=[],o=(a,i,{when:l="always",off:f=null,local:b=!1,data:v=""}={})=>{a&&r.push({host:a,purpose:i,when:l,off:f,local:b,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("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.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"});const h=e.link?.enabled===!1?null:$(e.link||{}).relay;if(h){const a=new URL(h).host;o(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=e.search?.searxng?.url||"";if(c){let a=c;try{a=new URL(c).host}catch{}o(a,"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(a)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(a.api.host,`web search: ${a.api.name} (search API${a.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: "${a.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}o(a,"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(a)})}const d={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",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[a,i]of Object.entries(d)){const l=e.capabilities?.[a];if(!l?.url||l.provider==="embedded")continue;let f=l.url;try{f=new URL(l.url).host}catch{}o(f,`${i.what}${l.service?` (the ${l.service} container, started under Settings › Runtime)`:` (${l.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:l.service?`stop the ${l.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${l.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.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[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(p(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:w(p(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const n=e.tts||{};if(n.provider==="openai"||n.provider==="elevenlabs"){const a=n.remote?.baseUrl?p(n.remote.baseUrl):n.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${n.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:n.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}s==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"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"}),r}function q(e,{ledger:t=P(),version:s="",startedAt:r=null,env:o=process.env,managed:h=null}={}){return{ok:!0,version:s,since:r?new Date(r).toISOString():null,...h?{managed:h,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:S(e,o)}}function T(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const s of e.observed||[])t.push(` ${s.local?"[local] ":""}${s.scheme}://${s.host}:${s.port} ×${s.count} last ${s.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const s of e.declared||[])t.push(` ${s.local?"[local] ":""}${s.host}`),t.push(` ${s.purpose}`),t.push(` when: ${s.when}${s.off?` · off: ${s.off}`:""}`),s.data&&t.push(` sends: ${s.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,s])=>s).map(([s,r])=>r===!0?s:`${s}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
-
`)}export{L as createEgressLedger,
|
|
1
|
+
import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(a){const n=g(a);if(!n||!n.host)return;const o=`${n.scheme}://${n.host}:${n.port}`,l=e(),h=t.get(o);if(h){h.count+=1,h.lastAt=l;return}t.set(o,{host:n.host,port:n.port,scheme:n.scheme,local:w(n.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((a,n)=>a.local===n.local?n.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let y=null;function R(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=L();let n=t;a.setGate=d=>{n=d},a.blocked=[];const o=d=>{let r=null;try{r=g(d),a.record(d)}catch{}if(!n||!r?.host)return null;let u=!0;try{u=n(`${r.scheme}://${r.host}:${r.port}`,{local:w(r.host)})}catch{u=!0}if(u)return null;const s=`${r.host}:${r.port}`;a.blocked.includes(s)||a.blocked.push(s);const i=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},l=e.fetch;typeof l=="function"&&(e.fetch=function(r,u){const s=o(r);return s?Promise.reject(s):l.call(this,r,u)});const h=e.WebSocket;return typeof h=="function"&&(e.WebSocket=new Proxy(h,{construct(d,r,u){const s=o(r[0]);if(s)throw s;return Reflect.construct(d,r,u)}})),e.__chatpanelEgress=a,e===globalThis&&(y=a),a}function S(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function P(e={},t=process.env,a=process.platform){const n=[],o=(s,i,{when:c="always",off:f=null,local:b=!1,data:v=""}={})=>{s&&n.push({host:s,purpose:i,when:c,off:f,local:b,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("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.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"});const l=e.link?.enabled===!1?null:$(e.link||{}).relay;if(l){const s=new URL(l).host;o(s,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",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 h=e.search?.searxng?.url||"";if(h){let s=h;try{s=new URL(h).host}catch{}o(s,"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(s)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const s of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(s.api.host,`web search: ${s.api.name} (search API${s.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: "${s.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}o(s,"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(s)})}const d={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",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[s,i]of Object.entries(d)){const c=e.capabilities?.[s];if(!c?.url||c.provider==="embedded")continue;let f=c.url;try{f=new URL(c.url).host}catch{}o(f,`${i.what}${c.service?` (the ${c.service} container, started under Settings › Runtime)`:` (${c.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:c.service?`stop the ${c.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${i.data}${c.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.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[s,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&o(p(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:w(p(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const r=e.tts||{};if(r.provider==="openai"||r.provider==="elevenlabs"){const s=r.remote?.baseUrl?p(r.remote.baseUrl):r.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(s,`remote read-aloud voice (${r.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:r.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&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 u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"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"}),n}function _(e,{ledger:t=S(),version:a="",startedAt:n=null,env:o=process.env,managed:l=null,certificates:h=null}={}){return{ok:!0,version:a,since:n?new Date(n).toISOString():null,...h?{certificates:h}:{},...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:P(e,o)}}function C(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,n])=>n===!0?a:`${a}=${n}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
+
`)}export{L as createEgressLedger,P as declaredEgress,_ as egressAudit,S as egressLedger,C as formatAudit,R as installEgressLedger};
|
package/src/server.js
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as xo}from"node:http";import{loadConfig as _t}from"./config.js";import{startEntitlementRefresh as Oo,maybeRevalidate as _o}from"./entitlement-refresh.js";import{redactSegments as Ge,segment as et,rememberAnswer as Et}from"./redact.js";import{pipeRestoredStream as Eo,pipeRestoredOpenAIStream as $o,makeTokenRestorer as $t,restoreDeep as Po}from"./stream.js";import{restoreText as Ao,gatedDictionary as No,narrowSpecs as Bo,makeToolHarness as Mo,placeholderToolNote as Co,placeholderNote as Do,assertEndpointUrl as Ro,capRunOptions as Io,isPaired as Pt}from"@chatpanel/pii";import{ensureGatewayToken as ve,currentGatewayToken as Ae,isAdminAuthorized as G,callerTrustOf as Ne,setPinnedExtensionIds as jo,issuePairingCode as Lo,claimPairingCode as Jo}from"./gateway-token.js";import{createPairAsk as zo,nativeConfirm as Go}from"./pair-prompt.js";import{createEngineProbe as Uo}from"./local-engine-probe.js";import{randomUUID as Ho}from"node:crypto";import{installEgressLedger as Vo,egressAudit as Fo}from"./egress.js";import{trustSystemCertificates as Wo,systemCaWanted as At,systemCaState as Ko}from"./system-ca.js";import{initPolicy as Qo,activePolicy as Yo,applyPolicyToConfig as Nt,managedSummary as Be,PolicyLoadError as Xo}from"./policy.js";import{routeAllowed as Bt,agentAllowed as Zo,egressAllowed as qo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Me}from"./bridge.js";import{secureFetch as Ue}from"./secure-fetch.js";import{fetchCard as He,forgetCard as er,sendMessage as tr,streamMessage as or,getTask as rr,cancelTask as nr,knownAgents as ar,A2AError as Mt}from"./a2a.js";import{streamBridgeChat as Ct,readBridgeToken as Ce,openBridgeChat as sr,acceptedBridgeToken as Dt}from"./bridge.js";import{createRelaySession as ir,getRelaySession as Rt,endRelaySession as De,pumpBridgeStream as lr,deliverToolResult as dr,toolsToSpecs as cr,wantsApprovals as ur,parseToolCallId as It,touchRelaySession as tt}from"./toolrelay.js";import{shaperFor as ot}from"./shape.js";import{startNer as mr,ensureNer as Ve,unionForThisMachine as pr,skippedCompanions as hr}from"./ner.js";import{recommendDetector as jt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as yr}from"./log.js";import{saveBackupSecret as fr,clearBackupSecret as gr,loadBackupSecret as rt,hasBackupSecret as Lt}from"./history-store.js";import{createMemoryStore as wr}from"./memory-store.js";import{createPrefsStore as br}from"./prefs-store.js";import{agentCardFor as kr,runHintFor as vr}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Sr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Tr,serviceManagerOf as xr,STANDBY_POLL_MS as Or}from"@chatpanel/events/service-standby.js";import{threadTarget as _r,frameQuestion as Er,wireMessages as $r,appendExchange as Pr,MAX_MESSAGE as Jt}from"@chatpanel/events/thread-send.js";import{researchStore as Ar,researchResponse as Nr}from"./research.js";import{createTeamStore as Br,loadOrCreateKey as nt}from"./team-store.js";import{createScorecardStore as Mr}from"./scorecard-store.js";import{createEngineLedgerStore as Cr}from"./engine-ledger-store.js";import{createProjectStore as Dr}from"./project-store.js";import{applicationsFor as Rr,recruitPass as Ir}from"./recruiting.js";import{ensureBridge as jr,holderOf as Lr}from"./bridge-supervisor.js";import{checkForUpdate as Jr,updateStatus as zr,startUpdate as Gr,updateJob as Ur}from"./update.js";import{createHistoryStore as Hr}from"./sqlite-store.js";import{createEventStore as Vr}from"./event-store.js";import{ingestCloudEvents as Fr,cursorOf as zt}from"./event-sync.js";import{eventStats as Wr,projectYear as Kr}from"./event-stats.js";import{toCloudEvent as at}from"./cloudevents.js";import{fusionsDocument as Qr,resolveFusionModel as Yr}from"./fusions.js";import{ingestBackups as st}from"./backup-ingest.js";import{toSearchRecord as Gt}from"@chatpanel/events/library.js";import{deriveBackupKey as Xr,openRecord as Zr,keyCache as qr,nodeCodec as en}from"@chatpanel/events/backup-envelope.js";import tn from"node:zlib";import*as R from"./ner-engine.js";import Ut from"node:os";import{capabilitiesDocument as on,handleDetect as rn}from"./capabilities.js";import{createExtractService as nn}from"./extract/service.js";import{workerSandbox as an,disposeWorkerSandbox as sn}from"./worker-sandbox.js";import{createRuntime as ln,SERVICES as dn}from"./runtime.js";import{createCapabilityProxy as cn}from"./capability-proxy.js";import{createEmbeddedCapabilities as un}from"./capability-embedded.js";import{EMBEDDED_MODELS as mn,EMBEDDED_IDS as pn}from"./embedded-models.js";import{handleExtract as hn}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as yn}from"./extract-capability.js";import{createReader as fn}from"./retrieval/read.js";import{createBrowserRelayHost as gn}from"./browser-relay.js";import{createLinkHost as wn}from"./link-host.js";import{checkLinkRoute as bn,tunnelHeader as kn,LINK_TUNNEL_ROOM_PATH as vn}from"@chatpanel/events/link-routes.js";import{createSearcher as Sn,toJinaSearch as Tn,SEARCH_DEFAULTS as xn}from"./retrieval/search.js";import{createSearxng as On}from"./retrieval/search-searxng.js";import{searchEngines as _n}from"./retrieval/search-apis.js";import{toJinaText as En}from"./read-document.js";import*as B from"./stt-engine.js";import*as M from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as $n,DEFAULT_DIARIZE_MODEL as Pn,isKnownDiarizeModel as Ht}from"./diarize-models.js";import{providerOf as it}from"./providers.js";import{createRemoteTranscriber as Vt}from"./stt-remote.js";import{parseMultipart as An,decodeAudioFile as Nn}from"./audio-file.js";import{MODEL_CATALOG as Ft,isKnownModel as Wt,isValidCustomModelId as Kt,recommendFor as Bn}from"./models.js";import{STT_MODEL_CATALOG as Mn,isKnownSttModel as Cn,isValidCustomSttId as Dn,DEFAULT_STT_MODEL as Fe,STT_DTYPES as Rn,isValidDtype as In}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as Qt,TTS_VOICES as jn,isKnownTtsModel as Ln,isValidCustomTtsId as Jn,isKnownVoice as Yt,isValidVoiceId as Xt,DEFAULT_TTS_MODEL as Zt,DEFAULT_TTS_VOICE as we,TTS_DTYPES as zn,isValidTtsDtype as Gn,MAX_TTS_CHARS as qt,ttsModelHasCustomVoices as Un,resolveDefaultModel as eo,POCKET_VOICES as Hn,DEFAULT_POCKET_VOICE as We,isPocketVoice as Ke,ttsModelEngine as Qe}from"./tts-models.js";import{ttsDestination as Vn,synthesizeRemote as Fn,isValidRemoteVoice as Wn}from"./tts-remote.js";import{rawOrtAvailable as lt}from"./ort.js";import*as oe from"./tts-voices.js";import{resolveTtsVoice as Kn}from"./tts-voice-resolve.js";import{resolvePro as be,checkQuota as Qn,consume as Yn,usage as Xn}from"./freegate.js";import{publicConfig as to,applyConfigPatch as Zn,registryChildEnv as qn,applyNerModelSelection as oo,persistConfig as ue,configPath as ie,bridgeAgentOptions as ro,PERMISSION_MODES as ea,sandboxEnvFor as ta}from"./configstore.js";import no from"node:path";import{resolveDestination as Ye,aggregateModelsAsync as oa,listDestinations as ra,ensureModelCatalog as na,agentOwnsModel as aa}from"./router.js";import{makeAccessEvent as ao}from"./observability.js";import{createPersistentAccessLog as sa}from"./access-log-store.js";import{planQueries as ia,multiSearch as la}from"./rrf.js";import*as dt from"./openai.js";import*as so from"./responses.js";import*as ct from"./anthropic.js";import{closeAndExit as da}from"./shutdown.js";import{VERSION as Z}from"./version.js";import{VERSION as hi}from"./version.js";const I=await Hr(),fe=new Set;function Re({ids:t=[]}={}){const d=I.lossless;if(!d||!fe.size)return;const u=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of fe)try{m.write(`event: records
|
|
2
2
|
data: ${u}
|
|
3
3
|
|
|
4
4
|
`)}catch{fe.delete(m)}}setInterval(()=>{for(const t of fe)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{fe.delete(t)}},25e3).unref?.();const K=await
|
|
6
|
+
`)}catch{fe.delete(t)}},25e3).unref?.();const K=await Vr(),Se=new Set;K?.watch(t=>{if(!Se.size)return;const d=`event: cloudevent
|
|
7
7
|
data: ${JSON.stringify(at(t))}
|
|
8
8
|
|
|
9
9
|
`;for(const u of Se)try{u.write(d)}catch{Se.delete(u)}}),setInterval(()=>{for(const t of Se)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{Se.delete(t)}},25e3).unref?.();const
|
|
11
|
+
`)}catch{Se.delete(t)}},25e3).unref?.();const le=await wr(),re=br(),_e=Mr({key:nt()}),Ee=Cr({key:nt()}),ne=Dr({key:nt()}),F=Br({scorecards:_e,engines:Ee}),ut=new Set,io=(t,d)=>{for(const m of ut)try{m({applied:t,by:d,revision:re.revision})}catch{}const u=JSON.stringify({revision:re.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of fe)try{m.write(`event: prefs
|
|
12
12
|
data: ${u}
|
|
13
13
|
|
|
14
|
-
`)}catch{fe.delete(m)}},mt=
|
|
14
|
+
`)}catch{fe.delete(m)}},mt=sa(),lo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ca=16,ua=/^mcp[_-]/i,co=t=>t&&t.function&&t.function.name||t&&t.name||"",ma=t=>t&&t.function&&t.function.description||t&&t.description||"";function uo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function pa(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(y=>uo(y&&(y.content??y))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return uo(u[m].content);return""}const mo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Xe(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function ha(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function ya(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),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 po=Date.now();function fa(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${d[u]||u} ${t[u]}ms`).join(" · ")}function ga(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function wa(t){const d=performance.now(),u={};let m=!1;const y=(b,A)=>{u[b]=Math.round(A*10)/10};return{meta:{},timings:u,mark:y,lap(b,A){y(b,performance.now()-A)},clock(){return performance.now()},commit(){if(m)return;m=!0,y("total",performance.now()-d);const b={...this.meta,timings:u};setImmediate(()=>{t(b),console.log(`[gateway] model=${b.model||"-"} → ${b.dest?`${b.dest}(${b.type})`:"none"} · ${b.redaction==="off"?"redaction OFF (client request)":`redacted ${b.redacted||0}`}${b.sanitized?` · scrubbed ${b.sanitized} hidden`:""}${b.narrowed?` · narrowed -${b.narrowed}`:""} · ${fa(u)}`)})}}}function ho(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[m,y]of t.byToken){const b=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),A=b?b[1]:"PII",$=m.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:$,type:A,value:y}:{token:$,type:A})}return u}function ba(t,d,u){return ct.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:ct,redactable:ct.matches(t),base:u.upstreams?.anthropic?.baseUrl}:so.matches(t)?{kind:"responses",adapter:so,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:dt,redactable:dt.matches(t),base:u.upstreams?.openai?.baseUrl}}function pt(t,d){const u=String(t||"");if(lo.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const y=u.slice(0,m);if(lo.has(y))return{agent:y,agentModel:u.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function yo(t,d){return pt(t,d).agent}function ka(t,d){if(d!=="openai"||!t)return!1;const u=dt.extractLatestToolResult(t);if(!u)return!1;const m=It(u.tool_call_id);return!!(m&&Rt(m.gwId))}function va(t,d){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),y=m==="127.0.0.1"||m==="localhost"||m==="::1",b=u.port||(u.protocol==="https:"?"443":"80");return y&&String(b)===String(d.port)}catch{return!1}}const Sa=25*1024*1024;async function v(t,d){const u=[];let m=0;for await(const y of t){if(m+=y.length,d&&m>d){const b=new Error("payload too large");throw b.code=413,b}u.push(y)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function fo(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function ht(t){const d=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=R.health(),y=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:R.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:y,tier:u,coverage:y?"names":"patterns"}}async function go(t){if(R.state()!=="off"){const u=R.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 d=fo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ue(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Ta(t,d){const u={};for(const[m,y]of Object.entries(t)){const b=m.toLowerCase();b.startsWith("x-chatpanel-")||mo.has(b)||(u[m]=y)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function wo(t,d,u,m){const y=$t(d.vault),b=yt();t.on("close",()=>{t.writableFinished||De(d.id)});const A=m?m.clock():0;let $=A,_=!0;const S=()=>{m&&_&&(m.lap("upstream",A),$=m.clock(),_=!1)};let k="";const L=()=>{d.redaction&&k&&Et(k,d.redaction),k=""};await lr(d,{onText:P=>{S(),tt(d.id);const N=y.push(P);N&&(k+=N,t.write(u.sseDelta(N)))},onToolRequest:({name:P,restoredArgs:N,toolId:W})=>{S(),tt(d.id);const Q=y.flush();Q&&(k+=Q,t.write(u.sseDelta(Q))),t.write(u.sseToolCalls([{id:W,name:P,arguments:JSON.stringify(N)}])),t.write(u.sseToolFinish(b.value)),m&&m.lap("stream",$),t.end(),m?.commit(),L()},onDone:()=>{const P=y.flush();P&&(k+=P,t.write(u.sseDelta(P))),t.write(u.sseTail(b.value)),m&&m.lap("stream",$),t.end(),De(d.id),m?.commit(),L()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),
|
|
16
|
+
`),t.end(),De(d.id),m?.commit()},onUsage:P=>b.add(P)})}async function xa(t,d,{kind:u,adapter:m,agent:y,run:b=null},A,$,_,S,k,L=null,P=null){const{messages:N,system:W}=m.toTurn(A),{agentModel:Q}=pt(A?.model,_),q=ro(_,{...Q?{model:Q}:{},...b||{}}),pe=Ce(_.bridge.token),z=ot(u,A?.model||y),ee={tier:_.redaction.tier==="full"?"full":"basic",dictionary:No(_.redaction,S),entities:[]},he=await Me(_),ye=ir({vault:$,redactOpts:ee,bridgeUrl:he,token:pe,harness:L});$&&(ye.redaction=_.redaction);let de;try{de=await sr({bridgeUrl:he,agent:y,token:pe,messages:N,system:W,specs:cr(k),options:q,signal:void 0,approvals:ur(k)})}catch(n){return De(ye.id),P?.commit(),a(d,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return ye.reader=de.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(z.sseHead()),wo(d,ye,z,P)}async function Oa(t,d,u,m,y=null){tt(d.id),d.rounds=(d.rounds||0)+1;try{const A=y?y.clock():0;await dr(d,u),y&&y.lap("redact",A)}catch(A){return De(d.id),y?.commit(),a(t,502,{error:{message:`tool-result: ${A.message}`,type:"bridge_error"}})}const b=ot("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(b.sseHead()),wo(t,d,b,y)}function yt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?d:null}}}async function _a(t,d,{kind:u,adapter:m,redactable:y,pathname:b,agentOverride:A,harness:$,trace:_,run:S=null},k,L,P,N){if(!y)return _?.commit(),a(d,404,{error:`endpoint ${b} not supported by the bridge backend`});if(u==="openai"){const J=m.extractLatestToolResult(k);if(J){const U=It(J.tool_call_id),O=U&&Rt(U.gwId);if(O)return Oa(d,O,J.content,k?.model,_)}const Y=m.extractTools(k);if(Y.length&&k?.stream===!0)return xa(t,d,{kind:u,adapter:m,agent:A||yo(k?.model,P),run:S},k,L,P,N,Y,$,_)}const{messages:W,system:Q}=m.toTurn(k),q=A||yo(k?.model,P),pe=k?.stream===!0,z=ot(u,k?.model||q),ee=Ce(P.bridge.token),he=new AbortController;d.on("close",()=>{d.writableFinished||he.abort()});const{agentModel:ye}=pt(k?.model,P),de={bridgeUrl:await Me(P),agent:q,token:ee,messages:W,system:Q,signal:he.signal,options:ro(P,{...ye?{model:ye}:{},...S||{}})};if(!pe)try{let J="";const Y=yt(),U=_?_.clock():0;await Ct(de,Te=>{J+=Te},null,Te=>Y.add(Te)),_&&_.lap("upstream",U);const O=_?_.clock():0,ke=z.full(Ao(J,L),Y.value);return _&&_.lap("restore",O),d.writeHead(200,{"content-type":z.contentType}),d.end(ke),_?.commit()}catch(J){return _?.commit(),a(d,502,{error:{message:`bridge backend failed: ${J.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(z.sseHead());const n=$t(L),o=_?_.clock():0;let f=o;const i=yt();let ae="";try{let J=!0;await Ct(de,U=>{_&&J&&(_.lap("upstream",o),f=_.clock(),J=!1);const O=n.push(U);O&&(ae+=O,d.write(z.sseDelta(O)))},z.sseActivity?U=>{try{d.write(z.sseActivity(Po(U,L)))}catch{}}:null,U=>i.add(U));const Y=n.flush();Y&&(ae+=Y,d.write(z.sseDelta(Y))),d.write(z.sseTail(i.value))}catch(J){d.write(`data: ${JSON.stringify({error:{message:J.message,type:"bridge_error"}})}
|
|
17
17
|
|
|
18
|
-
`)}y&&y.lap("stream",f),d.end(),y?.commit(),z&&ne&&Et(ne,P.redaction)}function xa(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),g=String(d||"").split("/")[1];return g&&m.endsWith(`/${g}`)?m.slice(0,-(g.length+1))+d+u:m+d+u}const Oa=9e4;function _a(t,d,u){if(d===u)return t;const m=d/u,g=new Float32Array(Math.floor(t.length/m));for(let k=0;k<g.length;k++){const _=k*m,M=Math.floor(_),y=Math.min(t.length-1,M+1),D=_-M;g[k]=t[M]*(1-D)+t[y]*D}return g}const wo=new WeakMap,Ea=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ft(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,d,u,m,{method:g="GET",timeoutMs:k=8e3,pick:_=M=>M}={}){const M=await Me(u);if(!M)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const y=De(u.bridge?.token),D=g!=="GET"&&g!=="DELETE";try{const v=D?(await S(t,u.maxBodyBytes)).toString("utf8"):"",z=await fetch(`${M}${m}`,{method:g,headers:{Accept:"application/json",...D?{"content-type":"application/json"}:{},...y?{Authorization:`Bearer ${y}`}:{}},...D?{body:v||"{}"}:{},signal:AbortSignal.timeout(k)}),P=await z.json().catch(()=>({}));return z.ok?a(d,200,_(P)):a(d,z.status,{error:{message:P?.error||`bridge ${z.status}`,type:"bridge_error"}})}catch(v){return a(d,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function gt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function $e(t,d){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const g=u.toString();return g?`?${g}`:""}async function $a(t,d,{adapter:u,kind:m,pathname:g,search:k,base:_,destKey:M,destProtocol:y,harness:D,trace:v},z,P){let E;const re=v?v.clock():0;try{const J=ka(t.headers,_);M&&(y==="anthropic"?(J["x-api-key"]=M,delete J.authorization):J.authorization=`Bearer ${M}`);const Z=Co(xa(_,g,k)).toString();E=await fetch(Z,{method:t.method,headers:J,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch(J){return v?.commit(),a(d,502,{error:`upstream fetch failed: ${J.message}`})}const W=E.headers.get("content-type")||"",le={};if(E.headers.forEach((J,Z)=>{uo.has(Z.toLowerCase())||(le[Z]=J)}),W.includes("text/event-stream")&&E.body){v&&v.lap("upstream",re);const J=v?v.clock():0;d.writeHead(E.status,le);const Z=m==="openai"?Eo(E.body,d,P,D):_o(E.body,d,P);return Promise.resolve(Z).finally(()=>{v&&v.lap("stream",J),v?.commit()})}const pe=Buffer.from(await E.arrayBuffer());if(v&&v.lap("upstream",re),P&&W.includes("application/json"))try{const J=v?v.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),P,D);return v&&v.lap("restore",J),d.writeHead(E.status,{...le,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(Z),"utf8")),v?.commit()}catch{}d.writeHead(E.status,le),d.end(pe),v?.commit()}function Pa(t=_t()){const d=Go({first:async n=>{const o=Number(new URL(n).port),f=an.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await z())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=Jo({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):zo(n),newId:()=>Uo()}),m=hn({version:X}),g=t.link?.enabled===!1?null:yn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:ne})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ae()||ve(),"x-chatpanel-link-device":String(ne||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==N.activeModel()&&(Ut(t.stt.diarizeModel)?N.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${_n}`));let k=null;const _=()=>{if(!k){const n=t.read||{};k=pn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return k};let M=null;const y=()=>(M||(M=tn({wrap:(n,o,f,i)=>on().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),M);let D={at:0,fn:()=>"unknown"},v=null;async function z(){if(Date.now()-D.at<1e4)return D.fn;let n=new Map;try{const i=await E().health();for(const[ne,L]of Object.entries(i)){const Q=(t.destinations||[]).filter(U=>U?.service===ne).flatMap(U=>[U.id,...U.models||[]]);for(const U of[ne,...Q])n.set(U,L)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return E().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return E().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),D={at:Date.now(),fn:o},D.fn}let P=null;const E=()=>(P||(P=nn({cfg:t,bridgeHealth:async()=>{const n=await Me(t);if(!n)return null;const o=De(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{ue(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:ro.join(ro.dirname(se()),"runtime"),workers:()=>{const n=M?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),P),re=Number(t.runtime?.idleMinutes),W=ln({warmMs:(Number.isFinite(re)&&re>=0?re:10)*6e4,log:n=>console.log(n)}),le=sn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:W}),pe=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let J=null;const Z=()=>{if(!J){const n=t.search||{},o=n.searxng?.url?Sn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;J=bn({reader:_(),searxng:o,engines:()=>Tn(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ge([et(()=>i,ne=>{i=ne})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return J};Io(t.allowedExtensionIds||[]);const he=[],ye=n=>{he.push(n),he.length>50&&he.shift()},de=To(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!Xe(n.headers.host))return a(o,403,{error:"loopback only"});if(!ua(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Xe(t.host)&&gn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&ma(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:ve()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=jo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Lo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ne(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ne(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Dt(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:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ne(n);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(Pt(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 r=null;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.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 (${n.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"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await Dt(t);return a(o,200,{ok:!0,status:r,token:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ne(n);return a(o,200,{ok:!0,trust:e,paired:Pt(e),version:X})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Vo(t,{version:X,startedAt:mo,managed:Be()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Ir(X,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:X,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Jr()})}if(i==="/update"&&n.method==="POST"){const e=Lr(X);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))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")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))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"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${X} is running.
|
|
18
|
+
`)}_&&_.lap("stream",f),d.end(),_?.commit(),L&&ae&&Et(ae,P.redaction)}function Ea(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),y=String(d||"").split("/")[1];return y&&m.endsWith(`/${y}`)?m.slice(0,-(y.length+1))+d+u:m+d+u}const $a=9e4;function Pa(t,d,u){if(d===u)return t;const m=d/u,y=new Float32Array(Math.floor(t.length/m));for(let b=0;b<y.length;b++){const A=b*m,$=Math.floor(A),_=Math.min(t.length-1,$+1),S=A-$;y[b]=t[$]*(1-S)+t[_]*S}return y}const bo=new WeakMap,Aa=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ft(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,d,u,m,{method:y="GET",timeoutMs:b=8e3,pick:A=$=>$}={}){const $=await Me(u);if(!$)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const _=Ce(u.bridge?.token),S=y!=="GET"&&y!=="DELETE";try{const k=S?(await v(t,u.maxBodyBytes)).toString("utf8"):"",L=await fetch(`${$}${m}`,{method:y,headers:{Accept:"application/json",...S?{"content-type":"application/json"}:{},..._?{Authorization:`Bearer ${_}`}:{}},...S?{body:k||"{}"}:{},signal:AbortSignal.timeout(b)}),P=await L.json().catch(()=>({}));return L.ok?a(d,200,A(P)):a(d,L.status,{error:{message:P?.error||`bridge ${L.status}`,type:"bridge_error"}})}catch(k){return a(d,502,{error:{message:`bridge unreachable: ${k.message}`,type:"bridge_unreachable"}})}}function gt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function $e(t,d){const u=new URLSearchParams;for(const b of t.searchParams.getAll("dir"))b&&u.append("dir",b);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const y=u.toString();return y?`?${y}`:""}async function Na(t,d,{adapter:u,kind:m,pathname:y,search:b,base:A,destKey:$,destProtocol:_,harness:S,trace:k},L,P){let N;const W=k?k.clock():0;try{const z=Ta(t.headers,A);$&&(_==="anthropic"?(z["x-api-key"]=$,delete z.authorization):z.authorization=`Bearer ${$}`);const ee=Ro(Ea(A,y,b)).toString();N=await fetch(ee,{method:t.method,headers:z,body:["GET","HEAD"].includes(t.method)?void 0:L})}catch(z){return k?.commit(),a(d,502,{error:`upstream fetch failed: ${z.message}`})}const Q=N.headers.get("content-type")||"",q={};if(N.headers.forEach((z,ee)=>{mo.has(ee.toLowerCase())||(q[ee]=z)}),Q.includes("text/event-stream")&&N.body){k&&k.lap("upstream",W);const z=k?k.clock():0;d.writeHead(N.status,q);const ee=m==="openai"?$o(N.body,d,P,S):Eo(N.body,d,P);return Promise.resolve(ee).finally(()=>{k&&k.lap("stream",z),k?.commit()})}const pe=Buffer.from(await N.arrayBuffer());if(k&&k.lap("upstream",W),P&&Q.includes("application/json"))try{const z=k?k.clock():0,ee=u.restoreResponse(JSON.parse(pe.toString("utf8")),P,S);return k&&k.lap("restore",z),d.writeHead(N.status,{...q,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(ee),"utf8")),k?.commit()}catch{}d.writeHead(N.status,q),d.end(pe),k?.commit()}function Ba(t=_t()){const d=Uo({first:async n=>{const o=Number(new URL(n).port),f=dn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await L())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=zo({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Go(n),newId:()=>Ho()}),m=gn({version:Z}),y=t.link?.enabled===!1?null:wn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:ae})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ae()||ve(),"x-chatpanel-link-device":String(ae||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(Ht(t.stt.diarizeModel)?M.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Pn}`));let b=null;const A=()=>{if(!b){const n=t.read||{};b=fn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return b};let $=null;const _=()=>($||($=nn({wrap:(n,o,f,i)=>an().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),$);let S={at:0,fn:()=>"unknown"},k=null;async function L(){if(Date.now()-S.at<1e4)return S.fn;let n=new Map;try{const i=await N().health();for(const[ae,J]of Object.entries(i)){const Y=(t.destinations||[]).filter(U=>U?.service===ae).flatMap(U=>[U.id,...U.models||[]]);for(const U of[ae,...Y])n.set(U,J)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return N().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return N().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),S={at:Date.now(),fn:o},S.fn}let P=null;const N=()=>(P||(P=ln({cfg:t,bridgeHealth:async()=>{const n=await Me(t);if(!n)return null;const o=Ce(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{ue(t,ie())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:no.join(no.dirname(ie()),"runtime"),workers:()=>{const n=$?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),P),W=Number(t.runtime?.idleMinutes),Q=un({warmMs:(Number.isFinite(W)&&W>=0?W:10)*6e4,log:n=>console.log(n)}),q=cn({cfg:t,wake:(n,o)=>N().wake(n,o),embedded:Q}),pe=()=>{t.search?.searxng?.url&&N().wake("searxng").catch(()=>{})};let z=null;const ee=()=>{if(!z){const n=t.search||{},o=n.searxng?.url?On({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;z=Sn({reader:A(),searxng:o,engines:()=>_n(t),wakeSearxng:()=>N().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ge([et(()=>i,ae=>{i=ae})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return z};jo(t.allowedExtensionIds||[]);const he=[],ye=n=>{he.push(n),he.length>50&&he.shift()},de=xo(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!Xe(n.headers.host))return a(o,403,{error:"loopback only"});if(!ha(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Xe(t.host)&&kn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&ya(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:ve()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Lo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Jo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ne(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ne(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Dt(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:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ne(n);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(Pt(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 r=null;try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.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 (${n.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"&&n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await Dt(t);return a(o,200,{ok:!0,status:r,token:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ne(n);return a(o,200,{ok:!0,trust:e,paired:Pt(e),version:Z})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Fo(t,{version:Z,startedAt:po,managed:Be(),certificates:{...Ko(),wanted:At(t)}})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Jr(Z,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:Z,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Ur()})}if(i==="/update"&&n.method==="POST"){const e=Gr(Z);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))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")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))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"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${Z} is running.
|
|
19
19
|
|
|
20
20
|
This address is for ChatPanel's apps, not a web page — there is nothing to open here.
|
|
21
21
|
Use ChatPanel itself (the browser extension's Settings, or the desktop app).
|
|
22
22
|
In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
23
|
-
`);if(n.method==="GET"&&i==="/health"){const e=
|
|
23
|
+
`);if(n.method==="GET"&&i==="/health"){const e=B.health(),r=C.health();return a(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Be()?{managed:Be()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Ie?{bridge:Ie.status()}:Ze?{bridge:Ze}:{},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||Fe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Zt,voice:t.tts?.voice||we,runtime:r.runtime,dtype:r.dtype},events:K?{count:K.count(),hosts:K.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){_o(t);const e=await be(t.pro?.entitlementToken),r=await go(t);return a(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Be()?{managed:Be()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:ht(t),pro:{unlocked:e},usage:Xn(t),uptimeSeconds:Math.floor((Date.now()-po)/1e3),update:zr(Z)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=I.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:re.revision,stamps:re.stamps()}):a(o,200,{ok:!0,revision:re.revision,sections:re.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=re.put(e.sections||{},{by:e.by||""});return r.applied.length&&io(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?re.remove(e):!1;return r&&io([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
|
|
24
24
|
|
|
25
|
-
`);e({type:"hello",revision:
|
|
25
|
+
`);e({type:"hello",revision:re.revision,stamps:re.stamps()});const r=l=>e({type:"changed",...l});ut.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
|
|
26
26
|
|
|
27
|
-
`)}catch{}},25e3);o.on("close",()=>{ut.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:
|
|
27
|
+
`)}catch{}},25e3);o.on("close",()=>{ut.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:ne.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:ne.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ne.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 r=e[1],s=e[2]||"",l=e[3]||"",c=e[4]||"",h=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const p=ne.get(r);if(!p)return h();const T=p.jobs.find(w=>w.id===l);if(!T)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const g={cfg:t,prefsStore:re,scorecards:_e,engines:Ee,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const w=await Rr(T,{...g,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:T,...w})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(T.status))return a(o,400,{error:{message:`job ${l} is ${T.status}; only an open job is recruited`,type:"project_error"}});try{const w=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(w.by||"evaluator").slice(0,80),x=await Ir(T,{...g,record:p,reach:w.reach||"any",chatModel:w.chatModel||null,evaluation:w.evaluation||null,text:w.text??null,by:E});let j=null;for(const X of x.events)X.type==="job.updated"?j=ne.updateJob(r,l,X.job,{by:X.by||E}):j=ne.append(r,[X]);return a(o,200,{ok:!0,project:j,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(w){return a(o,400,{error:{message:`recruit: ${w.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const p=ne.get(r,{events:f.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):h()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:ne.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},T=String(p.by||"person").slice(0,80),g=s==="/events"?ne.append(r,p.events||[]):l?ne.updateJob(r,l,p.patch||p,{by:T}):ne.postJob(r,p.job||p,{by:T});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"&&n.method==="GET"){if(!ne.get(r))return h();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=E=>o.write(`data: ${JSON.stringify(E)}
|
|
28
28
|
|
|
29
|
-
`);let T=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:
|
|
29
|
+
`);let T=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:ne.get(r),after:T}});const g=ne.watch(r,E=>{E.seq>T&&(T=E.seq,p(E))});for(const E of ne.eventsSince(r,T))T=E.seq,p(E);const w=setInterval(()=>{try{o.write(`: keep
|
|
30
30
|
|
|
31
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(
|
|
31
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(w),g()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:_e.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await _e.get(r)});if(n.method==="POST")try{const s=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},l=await _e.append({agentId:r,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 Ee.fromRating(_e.chains.get(r)||[],{...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"&&n.method==="GET")return a(o,200,on(t,{version:Z,reader:b,searcher:z,extract:_(),proxy:q}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:R.health().model||t.ner?.model||null,companions:R.companions()};let r=null;try{r=await N().status()}catch{r=null}return a(o,200,Qr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(pn.map(r=>{const s=it(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:mn[r],threads:Q.threads,...s.kind==="embedded"?Q.health(r,s.model):{}}]}));return a(o,200,{...await N().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await N().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=N(),c=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,c.ok?200:400,c)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await q.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await rn(e,{ensure:()=>Ve(t),model:R.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,Math.max(t.maxBodyBytes,Math.ceil(yn*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await hn(e,{service:_()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await A().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}pe();const r=await ee().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):xn.aliasRead;pe();const s=await ee().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?Tn(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",c=await A().read({url:r,format:l});return c.status!==200||s?a(o,c.status,c.status===200?{code:200,status:2e4,data:c.body}:c.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":c.body.provider}),o.end(En(c.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ee.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ee.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ga(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Ee.append({...s,engine:l,kind:s.kind||"call"});return c.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${c.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:c})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.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)}
|
|
32
32
|
|
|
33
33
|
`)}catch{}};e({type:"hello",at:Date.now()});const r=F.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
|
|
34
34
|
|
|
35
|
-
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:F.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await
|
|
35
|
+
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:F.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.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 r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=F.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return F.stop(r),a(o,200,{ok:!0,removed:F.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=F.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:F.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},c=s==="/handoff"?F.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):F.claim(r,{client:l.client});return a(o,200,{ok:!0,run:c})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:F.removeThread(r,{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")&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},c=String(l.by||"person").slice(0,40),h=s==="/answer"?F.answer(r,{threadId:l.threadId,text:l.text,by:c}):s==="/decide"?F.decide(r,{postId:l.postId,status:l.status,by:c}):F.post(r,{threadId:l.threadId,text:l.text,by:c,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:h})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.append(r,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"&&n.method==="GET"){if(!F.get(r))return a(o,404,{error:{message:`no run ${r}`,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)}
|
|
36
36
|
|
|
37
|
-
`),c=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let h=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:F.get(r),after:h}});const p=F.watch(r,
|
|
37
|
+
`),c=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let h=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:F.get(r),after:h}});const p=F.watch(r,g=>{g.seq==null?l(g):g.seq>h&&(h=g.seq,l(g))});for(const g of F.eventsSince(r,h))h=g.seq,l(g);const T=setInterval(()=>{try{o.write(`: keep-alive
|
|
38
38
|
|
|
39
|
-
`)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:
|
|
40
|
-
data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:
|
|
39
|
+
`)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:le.size,memories:le.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=le.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:le.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=le.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:r.action,record:r.record,replaced:r.replaces||null,size:le.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=le.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:le.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=le.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:le.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:le.clear(),size:le.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=I.clear();return a(o,200,{ok:!0,dropped:e,size:I.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=I.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:I.size,newest:I.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=ia(r,{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},c=Math.min(30,Math.max(5,Number(e.limit)||10)*2),h=await la(s,T=>I.search(T,{limit:c,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?h:[...h.filter(T=>T.type==="brief"),...h.filter(T=>T.type!=="brief")];return a(o,200,{ok:!0,size:I.size,newest:I.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"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)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&&!G(n))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:${n.socket.localPort}`,c=s?async(g,{maxTokens:w=220}={})=>{const E=new AbortController,x=setTimeout(()=>E.abort(),3e4);try{const j=Ae()||ve(),X=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:E.signal,headers:{"content-type":"application/json",...j?{Authorization:`Bearer ${j}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:w,temperature:.2})}),ce=await X.json().catch(()=>({}));return X.ok?String(ce?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,h=re.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,T=await Ar(r,{store:I,memories:le.list(),complete:c,previous:p,self:String(h.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Nr(r,T,{size:I.size,newest:I.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:I.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:I.size,newest:I.newest,bytes:I.bytes,lossless:I.lossless?{records:I.lossless.size,newest:I.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:I.size,bytes:I.bytes,newest:I.newest}},access:mt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=mt.push(ao({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=I.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await v(n,Math.max(t.maxBodyBytes||0,Sa))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let h=0,p={},T=[],g=[];const w={upserts:[],removes:[]},E=x=>{if(!x||x.deletedAt){x?.id&&w.removes.push(x.id);return}try{const j=Gt(x);j&&w.upserts.push(j)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});c.push(...x.written),p=x.revs,T=x.conflicts,g=x.merged;for(const j of x.written)E(e.get(j))}if(Array.isArray(r.entries)){const x=rt(),j=x?qr((V,H)=>Xr(x,{salt:V,iterations:H})):null,X=async V=>{if(!j||!V.blob)return null;const H=await j(V.blob),Pe=V.blob.compression&&V.blob.compression!=="none"?en(tn,V.blob.compression):null;return Zr(V.blob,H,{codec:Pe})},ce=await e.upsertEntries(r.entries,{open:X});c.push(...ce.written),h+=ce.sealed;for(const V of ce.written)E(e.get(V))}return(w.upserts.length||w.removes.length)&&I.bulk(w),c.length&&Re({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:p,conflicts:T,merged:g,sealed:h,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=Fr(K,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.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"&&n.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"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Wr(K.all());return a(o,200,{ok:!0,stats:e,year:Kr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=zt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=K.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>at(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=zt(JSON.parse(f.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
|
|
40
|
+
data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:Z})}
|
|
41
41
|
|
|
42
42
|
`),Se.add(o),n.on("close",()=>Se.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=K.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
|
|
43
43
|
data: ${JSON.stringify(at(s))}
|
|
44
44
|
|
|
45
|
-
`)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...
|
|
46
|
-
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:
|
|
45
|
+
`)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.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(n,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{ue(t,ie())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.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(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.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(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=bn({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:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{ue(t,ie())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=I.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
|
|
46
|
+
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:Z,prefsRevision:re.revision})}
|
|
47
47
|
|
|
48
|
-
`),fe.add(o),n.on("close",()=>fe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=I.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...I.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=I.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});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"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:jt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?pr(String(e.passphrase)):hr();const r=e.passphrase?await st(I,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Re(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await st(I,rt());return e.ok&&e.whole&&Re(),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(n.method==="GET"){const e=await fo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ve(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await S(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const c=await R.detect(s,{strict:l});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=yo(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:R.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await Ue(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:ht(t)});try{let r=e;const s=await be(t.pro?.entitlementToken);await Ve(t);const l=await Ge([et(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:po(l.vault,"types")||[],detector:ht(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(Gt.totalmem()/1048576),s=Pn(Vt,{totalRamMB:r}).map(l=>({...l,installed:R.modelOnDisk(l.id)}));for(const l of[e,...R.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:R.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:ur(),recommendation:It(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Gt.totalmem()/1048576),l=It(Vt.map(c=>({...c,installed:R.modelOnDisk(c.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(Ft(c)||Wt(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&to(t,r);try{ue(t,se())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:h=>console.log(h)});const c=cr(t.ner,{log:h=>console.log(h)});for(const h of R.companions())c.includes(h.model)||await R.removeCompanion(h.model);for(const h of c)await R.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(Ft(r)||Wt(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});to(t,r);try{ue(t,se())}catch{}return R.setModel(r,{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:r,state:R.state(),progress:R.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Fe,r=An.map(s=>({...s,installed:A.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.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:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Mn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Nn(r)||Bn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&Dn(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{ue(t,se())}catch{}return A.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ft(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:N.activeModel(),state:N.state(),installed:N.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=N.activeModel(),r=On.map(s=>({...s,installed:N.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:N.state(),threshold:N.activeThreshold(),progress:N.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Ut(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await N.setModel(r,{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=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{ue(t,se())}catch{}return N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:N.activeModel(),state:N.state(),threshold:N.activeThreshold(),progress:N.progress()})}return N.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:N.activeModel(),state:N.state(),threshold:N.activeThreshold(),progress:N.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=B.health().model||t.tts?.model||qt(lt()),r=lt(),s=Kt.find(c=>c.id===e)||null,l=Kt.map(c=>({...c,installed:B.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(c=>c.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:B.state(),progress:B.progress(),available:l,voice:t.tts?.voice||(Qe(e)==="pocket-tts"?We:we),arch:B.arch(),supportsVoices:B.arch()?B.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:B.arch()?B.supportsCustomVoices():!!s?.customVoices,sampleRate:B.sampleRate(),voices:B.isPocket()||!B.arch()&&Qe(e)==="pocket-tts"?(B.builtinVoices().length?B.builtinVoices():zn).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:B.builtinVoices().includes(c)})):B.arch()&&B.arch()!=="style-tts2"?[]:Cn.map(c=>({...c,installed:B.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:jn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Rn(r)||In(r)))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 c=ee.parseCustomVoice(s);if(!(c?!!ee.getVoice(c):Ke(s)||Qt(s)&&Yt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ln(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Xt,voice:we,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=Jn(r),h=ee.parseCustomVoice(t.tts.voice||""),p=!!(h&&ee.getVoice(h));if(c&&!p)if(Qe(r)==="pocket-tts")t.tts.voice=We;else{const w=ee.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&p&&(t.tts.voice=we);const T=Qe(r)==="pocket-tts";T&&!ee.parseCustomVoice(t.tts.voice||"")&&!Ke(t.tts.voice)&&(t.tts.voice=We),!T&&Ke(t.tts.voice)&&(t.tts.voice=we)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,se())}catch{}return r&&B.setModel(r,{onLog:c=>console.log(c),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:B.state(),progress:B.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:ee.listVoices(),usable:B.supportsCustomVoices(),embedder:N.activeModel(),embedderReady:N.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=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(!ee.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ee.renameVoice(l,r),usable:B.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.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(!r)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{if(!N.isReady()){const b=N.download({onLog:j=>console.log(j)}),$=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(j=>j),new Promise(j=>setTimeout(()=>j($),Oa))]);if(x===$||!N.isReady())return a(o,503,{error:{message:x===$?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${N.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:N.progress()})}const c=Float32Array.from(s),h=await N.embed(c);let p=null;try{const b=await B.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:$=>console.log($)});b&&(p=await b.encodeVoice(_a(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const T=l?ee.replaceVoice(l,{vec:h,pocket:p}):ee.saveVoice({name:r,vec:h,pocket:p}),w=l&&r&&r!==T.name?ee.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...T,...w,usable:B.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=ee.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=ee.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:we;try{ue(t,se())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.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(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Zt)return a(o,413,{error:{message:`text too long (max ${Zt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Gn(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=c||(l?l.voice:t.tts?.voice||we);if(l&&!Hn(h))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:V,contentType:H,redacted:Pe}=await Un({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await be(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":H,"Content-Length":String(V.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Pe)}),o.end(V)}if(!await B.ready({onLog:V=>console.log(V),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||qt(lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:B.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Vn({requested:c,configured:h,engine:B,voices:ee,isPocketVoice:Ke,isKnownVoice:Qt,isValidVoiceId:Yt,defaultVoice:we,defaultPocketVoice:We});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:$,speakerEmbedding:x}=w,j=await B.synth(r,{voice:b,speed:s,speakerEmbedding:x}),Y=B.sampleRate(),ce=p==="pcm"?Buffer.from(new Float32Array(j).buffer):B.toWav(j,Y);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...$||B.isPocket()||B.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ce)}catch(T){return a(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.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=En(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find($=>$.name===b&&!$.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await $n(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",h=it(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=Ht(h,{fetchImpl:Ue})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!p&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:b=>console.log(b)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!N.isReady()&&N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=A.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:p}),$=[];let x=null;A.subscribe(b,H=>{H.type==="final"&&H.text?$.push(H):H.type==="language"&&(x=H.lang)});const j=16e3*5;for(let H=0;H<l.pcm.length;H+=j)A.pushAudio(b,l.pcm.subarray(H,Math.min(l.pcm.length,H+j)));await A.endSession(b);let Y=0;const ce=$.map((H,Pe)=>{const vo=Y,So=(H.durationMs||0)/1e3;return Y+=So,{id:Pe,start:Math.round(vo*100)/100,end:Math.round(Y*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{}}}),V=ce.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(V)):c==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:V,segments:ce,provider:h.kind,took_ms:Date.now()-w}):a(o,200,{text:V})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.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(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=it(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Ht(r,{fetchImpl:Ue})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:c=>console.log(c)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!N.isReady()&&N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:h}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:h,state:A.state(),...c?{poll:!0}:{}})}catch(c){return a(o,c.code==="too_many_sessions"?429:500,{error:{message:c.message,type:c.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,h,p)=>{if(h.type!=="final"||!c.redact)return h;try{let T=h.text;return await Ge([et(()=>T,w=>{T=w})],t.redaction,{isPro:p}),{...h,text:T}}catch{return h}},l=async c=>{const h=A.drainEvents(r);if(!h)return null;const p=[];if(c&&!c.closed){const w=c.remote?"ready":A.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...A.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(N.state())?p.push({type:"diarize-progress",state:N.state(),...N.progress()||{}}):wo.get(c)!==w&&(wo.set(c,w),p.push({type:"state",state:w}))}const T=c?.redact?await be(t.pro?.entitlementToken):!0;for(const w of h)c?p.push(await s(c,w,T)):w.type!=="final"&&w.type!=="interim"&&p.push(w);return p};if(e[2]==="/audio"&&n.method==="POST"){const c=A.getSession(r)||A.endedSession(r);try{const h=await S(n,t.maxBodyBytes);A.pushAudio(r,A.toFloat32(h));const p=await l(c);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(c).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=A.getSession(r);if(!c)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 h=x=>o.write(`data: ${JSON.stringify(x)}
|
|
48
|
+
`),fe.add(o),n.on("close",()=>fe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=I.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...I.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=I.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});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"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:Lt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?fr(String(e.passphrase)):gr();const r=e.passphrase?await st(I,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Re(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await st(I,rt());return e.ok&&e.whole&&Re(),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(n.method==="GET"){const e=await go(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ve(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await v(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const c=await R.detect(s,{strict:l});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=fo(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:R.state(),model:t.ner?.model||null})}try{const r=await v(n,t.maxBodyBytes),s=await Ue(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:ht(t)});try{let r=e;const s=await be(t.pro?.entitlementToken);await Ve(t);const l=await Ge([et(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:ho(l.vault,"types")||[],detector:ht(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(Ut.totalmem()/1048576),s=Bn(Ft,{totalRamMB:r}).map(l=>({...l,installed:R.modelOnDisk(l.id)}));for(const l of[e,...R.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:R.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:hr(),recommendation:jt(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Ut.totalmem()/1048576),l=jt(Ft.map(c=>({...c,installed:R.modelOnDisk(c.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(Wt(c)||Kt(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&oo(t,r);try{ue(t,ie())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:h=>console.log(h)});const c=pr(t.ner,{log:h=>console.log(h)});for(const h of R.companions())c.includes(h.model)||await R.removeCompanion(h.model);for(const h of c)await R.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(Wt(r)||Kt(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});oo(t,r);try{ue(t,ie())}catch{}return R.setModel(r,{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:r,state:R.state(),progress:R.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||Fe,r=Mn.map(s=>({...s,installed:B.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:B.state(),progress:B.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:Rn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Cn(r)||Dn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&In(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{ue(t,ie())}catch{}return B.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ft(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:B.state(),progress:B.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=$n.map(s=>({...s,installed:M.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:M.state(),threshold:M.activeThreshold(),progress:M.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Ht(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await M.setModel(r,{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=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{ue(t,ie())}catch{}return M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}return M.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=C.health().model||t.tts?.model||eo(lt()),r=lt(),s=Qt.find(c=>c.id===e)||null,l=Qt.map(c=>({...c,installed:C.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(c=>c.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||(Qe(e)==="pocket-tts"?We:we),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()&&Qe(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():Hn).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:C.builtinVoices().includes(c)})):C.arch()&&C.arch()!=="style-tts2"?[]:jn.map(c=>({...c,installed:C.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:zn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Ln(r)||Jn(r)))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 c=oe.parseCustomVoice(s);if(!(c?!!oe.getVoice(c):Ke(s)||Yt(s)&&Xt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Gn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Zt,voice:we,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=Un(r),h=oe.parseCustomVoice(t.tts.voice||""),p=!!(h&&oe.getVoice(h));if(c&&!p)if(Qe(r)==="pocket-tts")t.tts.voice=We;else{const g=oe.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!c&&p&&(t.tts.voice=we);const T=Qe(r)==="pocket-tts";T&&!oe.parseCustomVoice(t.tts.voice||"")&&!Ke(t.tts.voice)&&(t.tts.voice=We),!T&&Ke(t.tts.voice)&&(t.tts.voice=we)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,ie())}catch{}return r&&C.setModel(r,{onLog:c=>console.log(c),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(n.method==="GET")return a(o,200,{voices:oe.listVoices(),usable:C.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=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(!oe.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...oe.renameVoice(l,r),usable:C.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.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(!r)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{if(!M.isReady()){const w=M.download({onLog:j=>console.log(j)}),E=Symbol("timeout"),x=await Promise.race([w.then(()=>null).catch(j=>j),new Promise(j=>setTimeout(()=>j(E),$a))]);if(x===E||!M.isReady())return a(o,503,{error:{message:x===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${M.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:M.progress()})}const c=Float32Array.from(s),h=await M.embed(c);let p=null;try{const w=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});w&&(p=await w.encodeVoice(Pa(c,16e3,24e3)))}catch(w){console.log(`[tts] pocket conditioning unavailable for this voice (${w.message})`)}const T=l?oe.replaceVoice(l,{vec:h,pocket:p}):oe.saveVoice({name:r,vec:h,pocket:p}),g=l&&r&&r!==T.name?oe.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${g.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...T,...g,usable:C.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=oe.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=oe.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:we;try{ue(t,ie())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.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(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>qt)return a(o,413,{error:{message:`text too long (max ${qt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Vn(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=c||(l?l.voice:t.tts?.voice||we);if(l&&!Wn(h))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:V,contentType:H,redacted:Pe}=await Fn({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await be(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":H,"Content-Length":String(V.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Pe)}),o.end(V)}if(!await C.ready({onLog:V=>console.log(V),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||eo(lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const g=Kn({requested:c,configured:h,engine:C,voices:oe,isPocketVoice:Ke,isKnownVoice:Yt,isValidVoiceId:Xt,defaultVoice:we,defaultPocketVoice:We});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:w,customId:E,speakerEmbedding:x}=g,j=await C.synth(r,{voice:w,speed:s,speakerEmbedding:x}),X=C.sampleRate(),ce=p==="pcm"?Buffer.from(new Float32Array(j).buffer):C.toWav(j,X);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(X),...E||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":w}:{}}),o.end(ce)}catch(T){return a(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.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=An(await v(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(w){return a(o,w.code===413?413:415,{error:{message:w.message,type:"bad_request"}})}const r=w=>e.find(E=>E.name===w&&!E.filename)?.data.toString("utf8").trim()||"",s=e.find(w=>w.name==="file"&&w.filename)||e.find(w=>w.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Nn(s.data)}catch(w){return a(o,w.code===415?415:500,{error:{message:w.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",h=it(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=Vt(h,{fetchImpl:Ue})}catch(w){return a(o,500,{error:{message:`stt provider: ${w.message}`,type:"bad_provider"}})}!p&&!B.isReady()&&B.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:w=>console.log(w)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:w=>console.log(w)});const g=Date.now();try{const{id:w}=B.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:p}),E=[];let x=null;B.subscribe(w,H=>{H.type==="final"&&H.text?E.push(H):H.type==="language"&&(x=H.lang)});const j=16e3*5;for(let H=0;H<l.pcm.length;H+=j)B.pushAudio(w,l.pcm.subarray(H,Math.min(l.pcm.length,H+j)));await B.endSession(w);let X=0;const ce=E.map((H,Pe)=>{const So=X,To=(H.durationMs||0)/1e3;return X+=To,{id:Pe,start:Math.round(So*100)/100,end:Math.round(X*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{}}}),V=ce.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(V)):c==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:V,segments:ce,provider:h.kind,took_ms:Date.now()-g}):a(o,200,{text:V})}catch(w){return a(o,w.code==="too_many_sessions"?429:500,{error:{message:w.message,type:w.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.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(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=it(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Vt(r,{fetchImpl:Ue})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!B.isReady()&&B.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:c=>console.log(c)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:h}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:h,state:B.state(),...c?{poll:!0}:{}})}catch(c){return a(o,c.code==="too_many_sessions"?429:500,{error:{message:c.message,type:c.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,h,p)=>{if(h.type!=="final"||!c.redact)return h;try{let T=h.text;return await Ge([et(()=>T,g=>{T=g})],t.redaction,{isPro:p}),{...h,text:T}}catch{return h}},l=async c=>{const h=B.drainEvents(r);if(!h)return null;const p=[];if(c&&!c.closed){const g=c.remote?"ready":B.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...B.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(M.state())?p.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):bo.get(c)!==g&&(bo.set(c,g),p.push({type:"state",state:g}))}const T=c?.redact?await be(t.pro?.entitlementToken):!0;for(const g of h)c?p.push(await s(c,g,T)):g.type!=="final"&&g.type!=="interim"&&p.push(g);return p};if(e[2]==="/audio"&&n.method==="POST"){const c=B.getSession(r)||B.endedSession(r);try{const h=await v(n,t.maxBodyBytes);B.pushAudio(r,B.toFloat32(h));const p=await l(c);return a(o,200,{ok:!0,state:B.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(c).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=B.getSession(r);if(!c)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 h=x=>o.write(`data: ${JSON.stringify(x)}
|
|
49
49
|
|
|
50
|
-
`),p=c.redact?await be(t.pro?.entitlementToken):!0,T=x=>s(c,x,p);h({type:"state",state:c.remote?"ready":
|
|
50
|
+
`),p=c.redact?await be(t.pro?.entitlementToken):!0,T=x=>s(c,x,p);h({type:"state",state:c.remote?"ready":B.state()});const g=setInterval(()=>{const x=c.remote?"ready":B.state();if(x==="downloading"||x==="loading"){h({type:"progress",state:x,...B.progress()||{}});return}if(x==="error"){h({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}),clearInterval(g);return}if(c.diarize){const j=M.state();if(j==="downloading"||j==="loading"){h({type:"diarize-progress",state:j,...M.progress()||{}});return}}h({type:"state",state:x}),clearInterval(g)},500);g.unref?.();let w=Promise.resolve();const E=B.subscribe(r,x=>{w=w.then(async()=>{h(await T(x)),x.type==="end"&&(clearInterval(g),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(g),E?.()});return}if(!e[2]&&n.method==="DELETE"){const c=B.getSession(r);await B.endSession(r);const h=c?.poll?await l(c).catch(()=>null):null;return a(o,200,{ok:!0,...h?{events:h}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...he].reverse()});if(i==="/config"&&n.method==="GET"){const e=await be(t.pro?.entitlementToken);return a(o,200,to(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Zn(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}Nt(t),JSON.stringify(t.sandbox||null)!==r&&Ie?.restart("sandbox settings changed");try{ue(t,ie())}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",c=R.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&R.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const h=await be(t.pro?.entitlementToken);return a(o,200,to(t,{proUnlocked:h}))}if(n.method==="GET"&&i==="/skills")return me(n,o,t,`/skills${$e(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!G(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.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=I.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>Jt)return a(o,400,{error:{message:`threads/send: a message of 1–${Jt} characters`,type:"invalid_request"}});const c=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,h=e.get(s);if(!h||h.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=_r(h,{cards:re.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:h.title,model:p.model});const T=Er({fromTitle:c?.title,message:l}),g={thread:{id:p.thread,...h.title?{title:h.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let w="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Ae()||ve(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(g))},body:JSON.stringify({model:p.model,messages:[...$r(h),{role:"user",content:T}],stream:!1}),signal:AbortSignal.timeout(6e5)}),j=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${j?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});w=String(j?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const E=Pr(e.get(s)||h,{question:T,reply:w,model:p.model,from:c});e.write([E],{host:"gateway",at:Date.now()});try{const x=Gt(e.get(s));x&&I.bulk({upserts:[x],removes:[]})}catch{}return Re({ids:[s]}),a(o,200,{ok:!0,title:h.title,model:p.model,reply:w})}const ae=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&ae)return G(n)?n.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 › Your phone",type:"forbidden"}}):me(n,o,t,ae,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/skills-quarantined")return me(n,o,t,`/skills-quarantined${$e(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return G(n)?me(n,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)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return gt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?me(n,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)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return gt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?me(n,o,t,`/skills/${encodeURIComponent(r)}/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(n.method==="GET"&&i==="/agent-defs")return me(n,o,t,`/agent-defs${$e(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return gt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):me(n,o,t,`/agent-defs/${encodeURIComponent(e)}${$e(f,t)}`)}if(i.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:ar()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&er(e.url||"");const r=await He(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(e.url,{auth:String(e.auth||"")})).card,s=await tr({card:r,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(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(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,c)=>o.write(`event: ${l}
|
|
51
51
|
data: ${JSON.stringify(c)}
|
|
52
52
|
|
|
53
|
-
`);try{const l=await
|
|
53
|
+
`);try{const l=await or({card:r,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:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await nr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await rr({card:r,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 r=e instanceof Mt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Mt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?me(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.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"}}):me(n,o,t,`/skills/${encodeURIComponent(e)}${$e(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Me(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Ce(t.bridge?.token);try{const s=n.method==="POST"?(await v(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),c=await l.json().catch(()=>({}));return a(o,l.status,c)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${$e(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await L(),r=e.sig!==void 0&&e.sig!==k;return k=e.sig,a(o,200,await oa(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Aa.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${Z}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const J=ba(i,n.headers,t);let Y;try{Y=await v(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let U=null,O=null,ke=Y,Te=0,wt=0,bt=0,ge=!1,xe=!1,kt="",Oe=!0;const te=t.logRequests&&J.redactable&&n.method==="POST"?wa(ye):null;if(J.redactable&&n.method==="POST"&&Y.length){try{O=JSON.parse(Y.toString("utf8"))}catch{O=null}if(O&&ka(O,J.kind))ke=Y;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ca,w=e.narrowAll?null:x=>!ua.test(co(x)),E=O.tools.length;O.tools=Bo(O.tools,pa(O,J.kind),{cap:g,keep:w,name:co,description:ma}),bt=E-O.tools.length}Oe=await be(t.pro?.entitlementToken);const r=Qn(t,Oe);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});if(ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!ge){const g=Ye(O?.model,t,J.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),w=g?.type==="api"?await d.decide(g,O?.model).catch(()=>null):null;xe=w?.redact===!1,kt=xe?w.engine||"declared":""}!ge&&!xe&&await Ve(t);const s=ge?[]:J.adapter.collectSegments(O,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const c=te?te.clock():0,{vault:h,count:p,sanitized:T}=ge?{vault:null,count:0,sanitized:0}:await Ge(s,t.redaction,{signal:l.signal,isPro:Oe,sanitizeOnly:xe,onEgress:g=>mt.push(ao({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(te&&te.lap("redact",c),U=h,Te=p,wt=T||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!Oe&&p>0){Yn(t,Oe);try{ue(t,ie())}catch{}}if(!ge&&!xe&&Array.isArray(O.tools)&&O.tools.length&&typeof J.adapter.injectSystemNote=="function"){const g=Ye(O?.model,t,J.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:E=>!!E.service&&S.fn(E.id)==="down"}),w=!(g&&g.type==="api");J.adapter.injectSystemNote(O,Co({toolData:t.tools?.toolData,ownTools:w}))}else!ge&&p>0&&typeof J.adapter.injectSystemNote=="function"&&J.adapter.injectSystemNote(O,Do());ke=Buffer.from(JSON.stringify(O),"utf8")}}const vt=Mo({vault:U,toolData:t.tools?.toolData}),je=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(je&&(delete O.chatpanel,ke=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Yr(O.model,t,await L());if(e?.error)return te?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,ke=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||je?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||je?.reach||"").trim(),run:ko(n.headers["x-chatpanel-run"],je?.run)},Le=await L(),St=e=>!!e.service&&Le(e.id)==="down";let D=Ye(O?.model,t,J.kind,{destination:se.destination,down:St});D?.type==="agent"&&O?.model&&!se.destination&&!aa(D,O.model)&&(await na(t,{serviceHealth:async()=>Le,engineAt:d.engineAt}),D=Ye(O?.model,t,J.kind,{destination:se.destination,down:St}));const Tt=D?.service&&Le(D.id)==="down"?await N().revive(D.service).catch(()=>null):null;if(Tt?.ok&&(S.at=0),D?.service&&Le(D.id)==="down"&&!Tt?.ok)return te?.commit(),a(o,503,{error:{message:`${D.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:D.service}});if(se.destination&&(!D||D.id!==se.destination))return te?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:ra(t).map(e=>e.id)}});te&&(te.meta={t:Date.now(),model:O?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:Te,sanitized:wt,narrowed:bt,detail:ho(U,t.logDetail),redaction:ge?"off":xe?`on-device (${kt})`:t.redaction.tier||"basic"});const Je=Yo();if(Je&&D){const e=D.type==="api"?Bt(Je,{model:O?.model||"",endpoint:D.baseUrl||""}):Zo(Je,D.agent||D.id)?Bt(Je,{model:O?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return te?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?va(D.baseUrl,t)?(te?.commit(),a(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Na(n,o,{...J,pathname:i,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:vt,trace:te},ke,U):(te?.commit(),a(o,502,{error:`destination "${D.id}" has no baseUrl`}));const qe=Ne(n),xt=qe==="local"&&t.bridge?.openAgentLane?"token":qe;if(xt==="local")return te?.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 Ot=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),vo=new Set(["thread","ephemeral","workingDir"]);if(qe==="token"&&n.headers["x-chatpanel-link-device"]&&!(se.run&&Object.keys(se.run).some(e=>!vo.has(e)))){const e=ko(null,vr(kr(re.get("agentTools").agentTools?.value,D?.agent||O?.model)));e&&(se.run={...e,...se.run||{}})}const ze=Io({...se.run||{},...se.reach?{reach:se.reach}:{},...Ot?{askDepth:Ot}:{}},xt);return ze.reach&&o.setHeader("x-chatpanel-reach-used",ze.reach),_a(n,o,{...J,pathname:i,agentOverride:D?.agent,harness:vt,trace:te,run:Object.keys(ze).length?ze:null},O,U,t,Oe)});return de.on("close",()=>{$?.stop("closed"),sn(),m.close(),y?.stop()}),de.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(vn)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
54
54
|
connection: close\r
|
|
55
55
|
content-length: 0\r
|
|
56
56
|
\r
|
|
57
|
-
`)}catch{}}),de.once("listening",()=>{
|
|
57
|
+
`)}catch{}}),de.once("listening",()=>{N()}),de.linkHost=y,de.runtimeDefaults=()=>N().ensureDefaults(),de}function ko(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(b=>String(b).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const b=u.workspace;m.workspace={repo:String(b.repo).slice(0,400),projectId:String(b.projectId||"").slice(0,120),jobId:String(b.jobId||"").slice(0,120),...b.base?{base:String(b.base).slice(0,120)}:{}}}if(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),ea.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const b=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(_=>String(_).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),A=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(_=>String(_).slice(0,1024)).filter(Boolean).slice(0,32),$=u.sandbox.outside===!0;(b.length||A.length||$)&&(m.sandbox={...b.length?{hosts:b}:{},...A.length?{write:A}:{},...$?{outside:!0}:{}})}const y=Sr(u.thread);return y&&(m.thread=y),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Ie=null,Ze=null;async function ui(t=_t()){yr();let d=null;try{d=await Qo()}catch(S){throw S instanceof Xo&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const u=d?.policy||null;u&&(Nt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const m=Wo({enabled:At(t)});console.log(`[chatpanel-gateway] certificates: ${m.on?`this computer's list is trusted too (${m.added} added to the runtime's own)`:`the runtime's own list only — ${m.why}`}`),Vo(globalThis,{allow:u?.egress?(S,{local:k})=>qo(u,S,{local:k}):null}),ve();const y=Ba(t),b=mr(t),A=Oo(t);let $=!1;y.on("error",S=>{if(S&&S.code==="EADDRINUSE"){const k=Xe(t.host)?"127.0.0.1":t.host;fetch(`http://${k}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(L=>L.ok?L.json():null).catch(()=>null).then(L=>{const P=!!(L?.version&&typeof L.tier=="string"),N=Tr({name:"gateway",self:Z,holder:P?{ours:P,version:L.version}:null,managedBy:xr(process.env),port:t.port});if(N.action==="standby"||$&&!L){if(!$)for(const W of N.lines)console.error(W);$=!0,setTimeout(()=>y.listen(t.port,t.host),Or);return}if(P){const W=L.managedBy?` (run by ${L.managedBy})`:"";for(const[Q,q]of N.lines.entries())console.error(Q===0?q.replace(` on ${t.port}`,` at http://${k}:${t.port}${W}`):q)}else{const W=Lr(t.port);console.error(`Port ${t.port} is held by ${W||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ie()} (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: ${S?.message||S}`),process.exit(1)}),y.listen(t.port,t.host,()=>{$&&console.log(" standby : the other gateway is gone — this copy has the port now"),$=!1,console.log(`ChatPanel Privacy Gateway v${Z} on http://${t.host}:${t.port}`),y.linkHost?.start().catch(S=>console.log(` link : not started (${S?.message||S})`)),y.runtimeDefaults?.().then(S=>{for(const k of S||[])console.log(` ${k.label.toLowerCase().padEnd(9).slice(0,9)}: ${k.ok?k.already?"running":k.adopted?"already running — adopted":"started":`not started (${k.skipped})`}`)}).catch(S=>console.log(` runtime : defaults not started (${S?.message||S})`)),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"),Ze={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},jr(t,{childEnv:()=>({...ta(t),...qn(t)})}).then(S=>{Ie=S}).catch(S=>{Ze={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${S?.message||S})`},console.log(` bridge : not supervised (${S?.message||S})`)}),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…)":"")),Xe(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.`)}),Lt()&&st(I,rt()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Re())}).catch(()=>{});const _=()=>{b?.stop(),A.stop(),Ie?.stop(),da(y)};return process.on("SIGINT",_),process.on("SIGTERM",_),y}export{Sa as RECORDS_MAX_BYTES,hi as VERSION,Ba as createGateway,Ea as joinUpstream,pt as parseAgentModel,ui as start};
|
package/src/system-ca.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import i from"node:tls";import d from"node:os";import{existsSync as l,readFileSync as u}from"node:fs";import{join as h}from"node:path";const y=/^(off|0|false|no)$/i;function C(s=null,e=process.env){return y.test(String(e.CHATPANEL_SYSTEM_CA||""))?!1:s?.tls?.systemCa!==!1}function w(s=process.env,e=d.homedir()){let t=null;try{const a=s.CHATPANEL_GATEWAY_CONFIG||h(e,".chatpanel","gateway.config.json");l(a)&&(t=JSON.parse(u(a,"utf8")))}catch{t=null}return C(t,s)}let r={on:!1,added:0,why:"not applied yet"};function x(){return{...r}}function p(s,e){const t=(a,n)=>s(a,n?.tls?.ca?n:{...n,tls:{...n?.tls,ca:e}});for(const a of Object.keys(s))t[a]=s[a];return t.chatpanelSystemCa=!0,t}function T({enabled:s=!0,tlsImpl:e=i,scope:t=globalThis,bun:a=!!process.versions.bun}={}){if(!s)return r={on:!1,added:0,why:"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"};if(typeof e.getCACertificates!="function"||typeof e.setDefaultCACertificates!="function")return r={on:!1,added:0,why:"this runtime cannot change its certificate list — Node 22.19 or newer can"};try{const n=e.getCACertificates("default"),c=new Set(n),f=e.getCACertificates("system").filter(o=>!c.has(o));if(f.length){const o=[...n,...f];e.setDefaultCACertificates(o),a&&typeof t.fetch=="function"&&!t.fetch.chatpanelSystemCa&&(t.fetch=p(t.fetch,o))}return r={on:!0,added:f.length+(r.on?r.added:0)}}catch(n){return r={on:!1,added:0,why:`the system's certificates could not be read (${String(n?.message||n).slice(0,120)})`}}}function _(){r={on:!1,added:0,why:"not applied yet"}}export{_ as _resetSystemCaState,x as systemCaState,C as systemCaWanted,w as systemCaWantedOnDisk,T as trustSystemCertificates};
|
package/src/update.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import R from"node:os";import l from"node:path";import{execFile as S}from"node:child_process";import{chmod as q,rename as L,mkdir as z,readFile as Q,writeFile as I,rm as X}from"node:fs/promises";import{existsSync as Z,readFileSync as ee,realpathSync as te}from"node:fs";import{explainInstallFailure as y,adviceText as x,npmInstallCommand as ne}from"@chatpanel/events/install-advice.js";import{restartService as ae,serviceRegistered as b}from"./service.js";const A="@chatpanel/gateway",Oe="chatpanel/chatpanel-gateway",H="https://dl.chatpanel.net/version/gateway",_=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),se=`${_}/${A}/latest`,re=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,F=360*60*1e3,M=600*1e3,oe=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),ie=15*6e4,B=20*6e4,T=process.env.CHATPANEL_UPDATE_CACHE||l.join(R.homedir(),".chatpanel","gateway-update-check.json"),C=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",J={"User-Agent":"chatpanel-gateway-updater"},le=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ce(e){try{const t=new URL(e);return t.protocol==="https:"&&le.has(t.hostname)}catch{return!1}}let f={at:0,error:""};function Ue(){f={at:0,error:""}}function P(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function de(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function h(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function G(e,t){const n=String(e).split(".").map(Number),s=String(t).split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a+=1){const r=(n[a]||0)-(s[a]||0);if(r)return r>0?1:-1}return 0}async function pe(){try{return JSON.parse(await Q(T,"utf8"))}catch{return null}}async function ue(e){try{await z(l.dirname(T),{recursive:!0}),await I(T,JSON.stringify(e))}catch{}}async function N(e,t=oe){const n=new AbortController,s=setTimeout(()=>n.abort(),t);try{const a=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...J},signal:n.signal});if(!a.ok)throw new Error(a.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${a.status}`);return await a.json()}catch(a){const r=a?.cause?.code||a?.cause?.message||a?.message||String(a);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${r}`)}finally{clearTimeout(s)}}function k(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=te(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function me(){const e=k();if(!e)return"";try{return String(JSON.parse(ee(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function E(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"..","libexec","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>Z(n))||""}function fe(e=process.env,t=process.execPath){const n={...e,npm_config_registry:_,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const s=Object.keys(n).find(a=>a.toLowerCase()==="path")||"PATH";return n[s]=[l.dirname(t),...(n[s]||"").split(l.delimiter).filter(Boolean)].filter((a,r,c)=>c.indexOf(a)===r).join(l.delimiter),n}function he(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:s=>console.log(s)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function we(){return["install","-g",`${A}@latest`,"--ignore-scripts"]}function ge(e,{home:t=R.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(e||""))return"";const s=(e.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",a=s.indexOf(`${l.sep}lib${l.sep}node_modules`),r=a>0?s.slice(0,a):"";return r?r===t||r.startsWith(t+l.sep)?`npm cannot write ${r} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${r}" — then update again.`:`npm cannot write ${r}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function ye(e=process.allowedNodeEnvironmentFlags){try{return!process.versions.bun&&e.has("--use-system-ca")}catch{return!1}}function be({cli:e=E(),systemCa:t=!1,env:n=fe(),execPath:s=process.execPath}={}){const a=we();return e?{cmd:s,args:[...t?["--use-system-ca"]:[],e,...a],env:n}:{cmd:"npm",args:a,env:t?{...n,NODE_OPTIONS:`${n.NODE_OPTIONS?`${n.NODE_OPTIONS} `:""}--use-system-ca`}:n}}function Ae({systemCa:e=!1}={}){const t=E(),{cmd:n,args:s,env:a}=be({cli:t,systemCa:e});return new Promise(r=>{S(n,s,{env:a,timeout:B,maxBuffer:8<<20,windowsHide:!0},(c,u,o)=>{const i=`${u||""}${o||""}`.trim();return c?c.killed&&!i?r({ok:!1,out:`npm was still running after ${Math.round(B/6e4)} minutes and was stopped`}):r({ok:!1,out:i||(t?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(he(),r({ok:!0,out:i}))})})}async function Ee({run:e=Ae,canSystemCa:t=ye()}={}){const n=await e({systemCa:!1});if(n.ok||!t||y(n.out)?.kind!=="certificate")return n;console.log("[update] npm refused the registry's certificate (a re-signing proxy) — trying once more with the system's certificates");const s=await e({systemCa:!0});return s.ok?{...s,via:"system-ca"}:s}function ve(e,t=process.versions.node,n=process.platform){return!e||process.versions.bun?null:y("",{node:t,needsNode:e,platform:n})}async function W(e,{force:t=!1}={}){const n=P()?"binary":"npm";if(C)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const s=de();let a=null,r=null,c=!1,u="",o=0,i="";const d=await pe(),g=d&&d.mode===n,U=()=>{a=g&&d.latest||null,r=g&&d.assetUrl||null,o=g&&d.checkedAt||0,i=g&&d.needsNode||"",c=!0};if(!t&&g&&Date.now()-d.checkedAt<F)a=d.latest,r=d.assetUrl,o=d.checkedAt,i=d.needsNode||"";else if(!t&&f.at&&Date.now()-f.at<M)u=f.error,U();else try{if(n==="npm"){let m;try{m=await N(se),a=h(m.version),i=String(m.engines?.node||"")}catch(Y){const D=await N(H);if(a=h(D?.npm?.version)||h(D?.version),!a)throw Y}}else{const m=await N(H);a=h(m.version)||h(m.release?.tag),r=s&&(m.release?.assets||[]).includes(s)?re(s):null}o=Date.now(),await ue({checkedAt:o,mode:n,latest:a,assetUrl:r,needsNode:i}),f={at:0,error:""}}catch(m){u=m.message,f={at:Date.now(),error:u},U()}const j=!!a&&G(a,e)>0,$=n==="npm"&&j?ve(i):null,K=$?!1:n==="binary"?!!r&&(process.platform!=="win32"||b()):!!k()&&(process.platform!=="win32"||b()&&!!E()),V=n==="npm"?ne({pkg:A,platform:process.platform}):null;return{current:e,latest:a,updateAvailable:j,mode:n,canSelfUpdate:K,assetUrl:r,stale:c,error:u,npmCommand:V,channel:n==="npm"?"npm":"release",service:b(),checkedAt:o,...n==="npm"?{node:process.versions.node,...i?{needsNode:i}:{}}:{},...$?{blocked:$}:{}}}let w=null,v=null;function je(e){const t=P()?"binary":"npm";return C?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(f.at&&Date.now()-f.at<M):Date.now()-w.seenAt>F))&&!v&&(v=W(e).then(s=>{w={...s,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{v=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:b()})}function De(){w=null,v=null}async function $e(e){const t=process.execPath,n=l.dirname(t),s=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),a=new AbortController,r=setTimeout(()=>a.abort(),ie);let c;try{let o;try{o=await fetch(e.assetUrl,{headers:J,redirect:"follow",signal:a.signal})}catch(i){throw new Error(`download failed: ${a.signal.aborted?"timed out":i?.cause?.code||i?.cause?.message||i?.message||i}`)}if(!o.ok)throw new Error(`download failed (HTTP ${o.status})`);if(!ce(o.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${o.url}, which is not a ChatPanel release host`);c=Buffer.from(await o.arrayBuffer())}finally{clearTimeout(r)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await I(s,c),process.platform!=="win32"&&await q(s,493),process.platform==="darwin"&&await new Promise(o=>S("xattr",["-c",s],()=>o()));const u=await new Promise(o=>S(s,["--version"],{timeout:6e4,windowsHide:!0},(i,d)=>o(i?"":String(d||"").trim())));if(!h(u))throw await X(s,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await L(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await L(s,t),h(u)}const O=(e,t=null,n="")=>Object.assign(new Error(e),{advice:t,raw:n});async function Se(e){if(C)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await W(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(t.blocked)throw O(`v${t.latest} was not installed. ${x(t.blocked)}`,t.blocked);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")try{return{from:e,to:await $e(t),mode:"binary"}}catch(a){const r=y(a.message,{platform:process.platform,channel:"binary"});throw r?O(`${x(r)}
|
|
1
|
+
import R from"node:os";import l from"node:path";import{execFile as S}from"node:child_process";import{chmod as q,rename as L,mkdir as z,readFile as Q,writeFile as I,rm as X}from"node:fs/promises";import{existsSync as Z,readFileSync as ee,realpathSync as te}from"node:fs";import{explainInstallFailure as y,adviceText as x,npmInstallCommand as ne}from"@chatpanel/events/install-advice.js";import{restartService as ae,serviceRegistered as b}from"./service.js";import{systemCaWantedOnDisk as se}from"./system-ca.js";const A="@chatpanel/gateway",De="chatpanel/chatpanel-gateway",H="https://dl.chatpanel.net/version/gateway",_=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),re=`${_}/${A}/latest`,oe=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,F=360*60*1e3,M=600*1e3,ie=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),le=15*6e4,B=20*6e4,T=process.env.CHATPANEL_UPDATE_CACHE||l.join(R.homedir(),".chatpanel","gateway-update-check.json"),C=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",J={"User-Agent":"chatpanel-gateway-updater"},ce=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function de(e){try{const t=new URL(e);return t.protocol==="https:"&&ce.has(t.hostname)}catch{return!1}}let f={at:0,error:""};function je(){f={at:0,error:""}}function P(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function pe(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function h(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function W(e,t){const n=String(e).split(".").map(Number),s=String(t).split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a+=1){const r=(n[a]||0)-(s[a]||0);if(r)return r>0?1:-1}return 0}async function ue(){try{return JSON.parse(await Q(T,"utf8"))}catch{return null}}async function me(e){try{await z(l.dirname(T),{recursive:!0}),await I(T,JSON.stringify(e))}catch{}}async function N(e,t=ie){const n=new AbortController,s=setTimeout(()=>n.abort(),t);try{const a=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...J},signal:n.signal});if(!a.ok)throw new Error(a.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${a.status}`);return await a.json()}catch(a){const r=a?.cause?.code||a?.cause?.message||a?.message||String(a);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${r}`)}finally{clearTimeout(s)}}function k(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=te(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function fe(){const e=k();if(!e)return"";try{return String(JSON.parse(ee(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function E(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"..","libexec","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>Z(n))||""}function he(e=process.env,t=process.execPath){const n={...e,npm_config_registry:_,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const s=Object.keys(n).find(a=>a.toLowerCase()==="path")||"PATH";return n[s]=[l.dirname(t),...(n[s]||"").split(l.delimiter).filter(Boolean)].filter((a,r,c)=>c.indexOf(a)===r).join(l.delimiter),n}function we(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:s=>console.log(s)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function ge(){return["install","-g",`${A}@latest`,"--ignore-scripts"]}function ye(e,{home:t=R.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(e||""))return"";const s=(e.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",a=s.indexOf(`${l.sep}lib${l.sep}node_modules`),r=a>0?s.slice(0,a):"";return r?r===t||r.startsWith(t+l.sep)?`npm cannot write ${r} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${r}" — then update again.`:`npm cannot write ${r}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function be(e=process.allowedNodeEnvironmentFlags){try{return!process.versions.bun&&e.has("--use-system-ca")}catch{return!1}}function Ae({cli:e=E(),systemCa:t=!1,env:n=he(),execPath:s=process.execPath}={}){const a=ge();return e?{cmd:s,args:[...t?["--use-system-ca"]:[],e,...a],env:n}:{cmd:"npm",args:a,env:t?{...n,NODE_OPTIONS:`${n.NODE_OPTIONS?`${n.NODE_OPTIONS} `:""}--use-system-ca`}:n}}function Ee({systemCa:e=!1}={}){const t=E(),{cmd:n,args:s,env:a}=Ae({cli:t,systemCa:e});return new Promise(r=>{S(n,s,{env:a,timeout:B,maxBuffer:8<<20,windowsHide:!0},(c,u,o)=>{const i=`${u||""}${o||""}`.trim();return c?c.killed&&!i?r({ok:!1,out:`npm was still running after ${Math.round(B/6e4)} minutes and was stopped`}):r({ok:!1,out:i||(t?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(we(),r({ok:!0,out:i}))})})}async function ve({run:e=Ee,canSystemCa:t=be()&&se()}={}){const n=await e({systemCa:!1});if(n.ok||!t||y(n.out)?.kind!=="certificate")return n;console.log("[update] npm refused the registry's certificate (a re-signing proxy) — trying once more with the system's certificates");const s=await e({systemCa:!0});return s.ok?{...s,via:"system-ca"}:s}function $e(e,t=process.versions.node,n=process.platform){return!e||process.versions.bun?null:y("",{node:t,needsNode:e,platform:n})}async function G(e,{force:t=!1}={}){const n=P()?"binary":"npm";if(C)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const s=pe();let a=null,r=null,c=!1,u="",o=0,i="";const d=await ue(),g=d&&d.mode===n,U=()=>{a=g&&d.latest||null,r=g&&d.assetUrl||null,o=g&&d.checkedAt||0,i=g&&d.needsNode||"",c=!0};if(!t&&g&&Date.now()-d.checkedAt<F)a=d.latest,r=d.assetUrl,o=d.checkedAt,i=d.needsNode||"";else if(!t&&f.at&&Date.now()-f.at<M)u=f.error,U();else try{if(n==="npm"){let m;try{m=await N(re),a=h(m.version),i=String(m.engines?.node||"")}catch(Y){const j=await N(H);if(a=h(j?.npm?.version)||h(j?.version),!a)throw Y}}else{const m=await N(H);a=h(m.version)||h(m.release?.tag),r=s&&(m.release?.assets||[]).includes(s)?oe(s):null}o=Date.now(),await me({checkedAt:o,mode:n,latest:a,assetUrl:r,needsNode:i}),f={at:0,error:""}}catch(m){u=m.message,f={at:Date.now(),error:u},U()}const D=!!a&&W(a,e)>0,$=n==="npm"&&D?$e(i):null,K=$?!1:n==="binary"?!!r&&(process.platform!=="win32"||b()):!!k()&&(process.platform!=="win32"||b()&&!!E()),V=n==="npm"?ne({pkg:A,platform:process.platform}):null;return{current:e,latest:a,updateAvailable:D,mode:n,canSelfUpdate:K,assetUrl:r,stale:c,error:u,npmCommand:V,channel:n==="npm"?"npm":"release",service:b(),checkedAt:o,...n==="npm"?{node:process.versions.node,...i?{needsNode:i}:{}}:{},...$?{blocked:$}:{}}}let w=null,v=null;function Re(e){const t=P()?"binary":"npm";return C?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(f.at&&Date.now()-f.at<M):Date.now()-w.seenAt>F))&&!v&&(v=G(e).then(s=>{w={...s,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{v=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:b()})}function Le(){w=null,v=null}async function Se(e){const t=process.execPath,n=l.dirname(t),s=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),a=new AbortController,r=setTimeout(()=>a.abort(),le);let c;try{let o;try{o=await fetch(e.assetUrl,{headers:J,redirect:"follow",signal:a.signal})}catch(i){throw new Error(`download failed: ${a.signal.aborted?"timed out":i?.cause?.code||i?.cause?.message||i?.message||i}`)}if(!o.ok)throw new Error(`download failed (HTTP ${o.status})`);if(!de(o.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${o.url}, which is not a ChatPanel release host`);c=Buffer.from(await o.arrayBuffer())}finally{clearTimeout(r)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await I(s,c),process.platform!=="win32"&&await q(s,493),process.platform==="darwin"&&await new Promise(o=>S("xattr",["-c",s],()=>o()));const u=await new Promise(o=>S(s,["--version"],{timeout:6e4,windowsHide:!0},(i,d)=>o(i?"":String(d||"").trim())));if(!h(u))throw await X(s,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await L(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await L(s,t),h(u)}const O=(e,t=null,n="")=>Object.assign(new Error(e),{advice:t,raw:n});async function xe(e){if(C)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await G(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(t.blocked)throw O(`v${t.latest} was not installed. ${x(t.blocked)}`,t.blocked);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")try{return{from:e,to:await Se(t),mode:"binary"}}catch(a){const r=y(a.message,{platform:process.platform,channel:"binary"});throw r?O(`${x(r)}
|
|
2
2
|
|
|
3
|
-
The download said: ${a.message}`,r,a.message):a}if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${E()}" install -g ${A}@latest --registry=${_} --no-fund --no-audit`};const n=await
|
|
3
|
+
The download said: ${a.message}`,r,a.message):a}if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${E()}" install -g ${A}@latest --registry=${_} --no-fund --no-audit`};const n=await ve();if(!n.ok){const a=ye(n.out),r=a?null:y(n.out,{platform:process.platform,node:process.versions.node,needsNode:t.needsNode}),c=n.out.slice(0,600);throw O(a?`${a}
|
|
4
4
|
|
|
5
5
|
npm said: ${c}`:r?`${x(r)}
|
|
6
6
|
|
|
7
|
-
npm said: ${c}`:`npm install failed: ${n.out.slice(0,800)}`,r,c)}n.via==="system-ca"&&console.log("[update] installed through the system's certificates — a proxy on this network re-signs npm's traffic");const s=
|
|
7
|
+
npm said: ${c}`:`npm install failed: ${n.out.slice(0,800)}`,r,c)}n.via==="system-ca"&&console.log("[update] installed through the system's certificates — a proxy on this network re-signs npm's traffic");const s=fe();if(!s||W(s,e)<=0)throw new Error(`npm ran, but the install at ${k()} is still ${s||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:s,mode:"npm"}}const p={state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0};function Ie(){return{...p}}function He(e,{restart:t=ae,apply:n=xe}={}){return p.state==="installing"||p.state==="restarting"?{...p,already:!0}:(Object.assign(p,{state:"installing",mode:P()?"binary":"npm",from:e,to:"",detail:"",advice:null,raw:"",startedAt:Date.now(),endedAt:0}),n(e).then(s=>{Object.assign(p,{state:"restarting",to:s.to,mode:s.mode,detail:s.deferred?`stopping to install v${s.to}, then relaunching`:`v${s.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:s.deferred||""})||Object.assign(p,{state:"done",endedAt:Date.now(),detail:`v${s.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(s=>{const a=String(s?.message||s);Object.assign(p,{state:"failed",endedAt:Date.now(),detail:a.slice(0,2400),advice:s?.advice||y(a,{platform:process.platform,channel:p.mode==="binary"?"binary":"npm"}),raw:String(s?.raw||"").slice(0,800)})}),{...p})}function Fe(){Object.assign(p,{state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0})}export{Fe as _resetUpdateJob,Le as _resetUpdateStatus,G as checkForUpdate,W as cmpVersions,de as downloadHostAllowed,ve as installWithRetry,P as isCompiledBinary,$e as nodeGate,ge as npmInstallArgs,he as npmInstallEnv,k as npmPackageRoot,ye as npmPermissionHint,Ae as npmSpawn,je as resetUpdateBackoff,xe as selfUpdate,He as startUpdate,be as systemCaAvailable,Ie as updateJob,Re as updateStatus};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.87.0";export{o as VERSION};
|