@chatpanel/gateway 0.88.0 → 0.97.2

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 CHANGED
@@ -510,6 +510,39 @@ prints what is running — the gateway (this) and the bridge (your agents + skil
510
510
  can see the whole local runtime at a glance. The bridge is an optional companion; a missing
511
511
  one is reported plainly, never as an error.
512
512
 
513
+ ### Letting a partner server in (ChatPanel Link)
514
+
515
+ ```bash
516
+ chatpanel-gateway link pair --partner acme [--scopes models,chat[,agents]] [--route link|relay|tailscale|cloudflare] [--relay <url>] [--yes]
517
+ chatpanel-gateway link # every paired device: kind, partner, scopes, route, last seen
518
+ chatpanel-gateway link revoke <id> # removed at once — its key, its room, its connection
519
+ chatpanel-gateway link route <mode> [--relay <url>] [--gw <tunnel url>] [--no-fallback]
520
+ ```
521
+
522
+ A service you use can reach this gateway's models from its own server through ChatPanel Link —
523
+ end-to-end encrypted, no port opened — but only after you pair it here. `link pair` shows what
524
+ the partner will be able to do (its scopes, whether it may reach your coding agents — off unless
525
+ you add `agents` — the route and the one host it connects to) and asks before it prints a
526
+ one-time `cplink1.` code (10 minutes, one use). The route is the gateway's own unless `--route`
527
+ names another: a Tailscale or Cloudflare Tunnel route reaches this computer's tunnel door with no
528
+ relay at all. A partner reaches only `GET /v1/models` and chat with API models — never pairing,
529
+ settings, history or memory. Granted `agents` (`--scopes models,chat,agents`), its coding-agent turns
530
+ run as yours do: your Coding Agents settings, the sandbox and your organisation's policy decide what
531
+ they may do, in a folder of its own (`--folder`, default `~/.chatpanel/partners/<name>`) where its
532
+ skills (`.claude/skills`), subagents (`.claude/agents`) and instructions live. The partner chooses
533
+ none of that, and never answers an agent's approval prompt: when one of its agents asks to do
534
+ something your permission mode does not already allow, the request waits for YOU — Settings › Link,
535
+ or `chatpanel-gateway link approvals` then `link approve <id> [--for action|all]` / `link deny <id>`
536
+ — and you allow it once, allow that action for the rest of the conversation, allow everything in it,
537
+ or say no (no answer in 10 minutes is a no). The partner's streamed response stays open meanwhile.
538
+ Granted `files` too (`--scopes models,chat,agents,files`), the partner may put its data (`data/`),
539
+ skills, subagents and instructions in that folder and read back what its agents wrote there
540
+ (`GET/PUT/DELETE /v1/link/files/<path>`) — never `.claude/settings*.json`, hooks, `.mcp.json` or
541
+ `.codex/`, never a skill or subagent whose front matter would widen what the agent may do, and never
542
+ through a link out of the folder.
543
+ Partners show
544
+ in `--audit` and in Settings › Link › Servers, with Revoke — where a server can also be connected without a terminal.
545
+
513
546
  ### What leaves your machine — and how to check
514
547
 
515
548
  ```bash
@@ -1,2 +1,3 @@
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");
1
+ import{pathToFileURL as o}from"node:url";import{createRequire as f}from"node:module";import{existsSync as p,readFileSync as u}from"node:fs";import{join as d}from"node:path";import{homedir as g}from"node:os";import{normalizeRegistries as h}from"@chatpanel/events/registries.js";import _ from"../assets/ort-wasm-simd-threaded.wasm";import w from"../assets/ort-wasm-simd-threaded.mjs";import A from"../assets/sandbox-runtime.zip";import{unpackSandboxRuntime as v}from"../src/sandbox-runtime-unpack.js";import{findNativeBinding as S,ensureNativeOrt as a}from"../src/ort-native.js";import{trustSystemCertificates as T,systemCaWantedOnDisk as y}from"../src/system-ca.js";const m=process.argv.indexOf("--sandbox-host");if(m>=0){const{runSandboxHost:e}=await import("@chatpanel/bridge/src/sandbox-host.js");await e(process.argv[m+1],{compiled:!0}),await new Promise(()=>{})}T({enabled:y()});function c(){try{const e=process.env.CHATPANEL_GATEWAY_CONFIG||d(g(),".chatpanel","gateway.config.json"),r=p(e)?JSON.parse(u(e,"utf8")):{},s={npm:process.env.CHATPANEL_REGISTRY_NPM,models:process.env.CHATPANEL_REGISTRY_MODELS};return h({...r.registries||{},...s.npm?{npm:s.npm}:{},...s.models?{models:s.models}:{}})}catch{return{}}}const t=e=>{try{process.stderr.write(`[ort] ${e}
2
+ `)}catch{}};let n=null,l=!1;function N(e){if(l)return n;l=!0;try{n=f(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`),n=null}return n}let i=S();const R=process.argv.includes("--install")||process.argv.includes("--fetch-runtime")||process.argv[2]==="--confined";if(!i&&R)try{i=await a({registries:c(),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`)}if(process.argv.includes("--fetch-runtime")&&process.exit(i?0:1),i||a({registries:c(),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__=()=>N(i):globalThis.__CHATPANEL_WASM_PATHS__={wasm:o(_).href,mjs:o(w).href},!process.env.CHATPANEL_SRT_MODULE){const e=v({zipPath:A,meta:globalThis.__CHATPANEL_SRT__||null,log:r=>{try{process.stderr.write(`[sandbox] ${r}
3
+ `)}catch{}}});e&&(process.env.CHATPANEL_SRT_MODULE=e)}await import("./chatpanel-gateway.js");
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- const i=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},m=(a=process.argv)=>a.includes("--mcp-stdio")?u["--mcp-stdio"]:u[a[2]]||"chatpanel-gateway";try{process.title=m()}catch{}if(!process.versions.bun&&i!=="--version"&&i!=="-v"){const[a,s]=String(process.versions.node||"0.0").split(".").map(Number);(a<22||a===22&&s<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(i==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:a}=await import("../src/extract/worker.js");a()}else if(i==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:a,systemCaWantedOnDisk:s}=await import("../src/system-ca.js");a({enabled:s()})}await import("@chatpanel/bridge/src/server.js")}else if(i==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(i==="mcp"){const{runMcpServer:a}=await import("../src/mcp.js");await a()}else if(i==="tools"||i==="call"){const{runMcpCli:a}=await import("../src/mcp-cli.js");process.exit(await a(process.argv.slice(2)))}else if(i==="policy"){const{loadPolicy:a,formatPolicy:s,PolicyLoadError:p}=await import("../src/policy.js");try{const l=await a();process.argv.includes("--json")?console.log(JSON.stringify(l?{...l,label:void 0}:null,null,2)):console.log(s(l))}catch(l){throw l instanceof p&&(console.error(`org policy: ${l.message}`),process.exit(78)),l}}else if(i==="--audit"){const{egressAudit:a,formatAudit:s}=await import("../src/egress.js"),{loadConfig:p}=await import("../src/config.js"),{readFileSync:l}=await import("node:fs"),{join:w}=await import("node:path"),h=await import("node:os"),g=p(),e=`http://127.0.0.1:${g.port||4320}`;let t=null,n=`no gateway running at ${e}`;try{const c=l(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(h.homedir(),".chatpanel","gateway-token"),"utf8").trim(),o=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${c}`},signal:AbortSignal.timeout(2500)});if(o.ok)t=await o.json();else if(o.status===404){const r=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);n=`the gateway running at ${e}${r?.version?` (${r.version})`:""} predates --audit (0.7.0) — restart it after updating`}else n=`the gateway at ${e} refused the audit (HTTP ${o.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!t){const{VERSION:c}=await import("../src/server.js"),{systemCaWanted:o}=await import("../src/system-ca.js"),r=o(g);t={...a(g,{ledger:null,version:c,certificates:{on:!1,added:0,wanted:r,why:r?"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(`(${n}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(t,null,2)):console.log(s(t))}else if(i==="sandbox"){const{srtModuleUrl:a}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&a()&&(process.env.CHATPANEL_SRT_MODULE=a());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js"),{sandboxCommand:p}=await import("../src/sandbox-cli.js"),{loadConfig:l}=await import("../src/config.js"),{readFileSync:w}=await import("node:fs"),{join:h}=await import("node:path"),g=await import("node:os");let e="";try{e=w(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(g.homedir(),".chatpanel","gateway-token"),"utf8").trim()}catch{}process.exit(await p(process.argv.slice(3),{cfg:l(),token:e,local:t=>s(t)}))}else if(i==="pair"){const{loadConfig:a}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:p}=await import("node:path"),l=await import("node:os"),h=`http://127.0.0.1:${a().port||4320}`,g=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(l.homedir(),".chatpanel","gateway-token");try{const e=s(g,"utf8").trim(),t=await fetch(`${h}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),n=await t.json().catch(()=>({}));if(t.status===404)throw new Error(`the gateway at ${h} predates pairing (0.9.0) — update and restart it`);if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);console.log(`Pairing code: ${n.display||n.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 ${h}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${g} — has the gateway started once?)`:""}`),process.exit(1)}}else if(i==="local"){const{localStatus:a,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await a()))}else if(i==="connect"){const{connectAgents:a,formatConnect:s}=await import("../src/connect-agents.js"),p=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(a({dryRun:p}),{dryRun:p}))}else{const{start:a,VERSION:s}=await import("../src/server.js"),{installService:p,uninstallService:l,serviceReport:w,stopService:h,pathWithDir:g}=await import("../src/service.js");switch(i){case"--stop":h(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--fetch-apple-helper":{const{ensureAppleHelper:e,appleHelperWanted:t}=await import("../src/apple-helper-fetch.js"),n=await import("node:os");if(!t({release:n.release()})){console.log("Apple’s on-device model needs an Apple Silicon Mac on macOS 26 or later — nothing to fetch here.");break}try{const{loadConfig:c}=await import("../src/config.js"),o=await e({version:s,registries:c().registries||{},onProgress:r=>{r.phase==="download"&&console.log(`fetching the Apple on-device helper (v${r.version}) from ${new URL(r.url).host}…`)}});console.log(`Apple on-device helper: ${o}`)}catch(c){console.error(`could not fetch the Apple on-device helper: ${c?.message||c}`),process.exit(1)}break}case"--install":{try{const{ensureAppleHelper:n,appleHelperWanted:c,findAppleHelper:o}=await import("../src/apple-helper-fetch.js"),r=await import("node:os");if(c({release:r.release()})&&!o()){const{loadConfig:d}=await import("../src/config.js");await n({version:s,registries:d().registries||{}}),console.log("Apple on-device helper: fetched (this install came without it).")}}catch(n){console.log(`Apple on-device helper: not fetched (${String(n?.message||n).slice(0,160)}) — \`chatpanel-gateway --fetch-apple-helper\` tries again; everything else works without it.`)}const e=await p({version:s,force:process.argv.includes("--force")}),t=e.health;if(e.newer){const n=t.managedBy&&t.managedBy!=="gateway"?` (run by the ${t.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${t.version} is already running at ${t.url}${n} — newer than this copy (v${s}). 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${s} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const n=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${t.version}) is the one answering right now; this install takes over at the next login`:"",c=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${t.version}: already running at ${t.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${t.version}: running at ${t.url}${c}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${n}.`);let o=null;for(let r=0;r<30;r++){try{o=(await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{o=null}if(o&&o.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(o?["embedded","standalone","adopted"].includes(o.mode)?console.log(` bridge: ${o.mode}${o.version?` v${o.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${o.why||o.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),o?.version){const{staleBridgeCommands:r,staleBridgeLines:d}=await import("../src/service.js");for(const y of d(r({embedded:o.version}),{embedded:o.version}))console.log(y)}}else t.ok?(console.error(`ChatPanel Privacy Gateway: v${s} is registered to start at login, but v${t.version} still answers at ${t.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 ${t.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
2
+ const i=process.argv[2],m={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},y=(a=process.argv)=>a.includes("--mcp-stdio")?m["--mcp-stdio"]:m[a[2]]||"chatpanel-gateway";try{process.title=y()}catch{}if(!process.versions.bun&&i!=="--version"&&i!=="-v"){const[a,s]=String(process.versions.node||"0.0").split(".").map(Number);(a<22||a===22&&s<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(i==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:a}=await import("../src/extract/worker.js");a()}else if(i==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:a,systemCaWantedOnDisk:s}=await import("../src/system-ca.js");a({enabled:s()})}await import("@chatpanel/bridge/src/server.js")}else if(i==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(i==="mcp"){const{runMcpServer:a}=await import("../src/mcp.js");await a()}else if(i==="tools"||i==="call"){const{runMcpCli:a}=await import("../src/mcp-cli.js");process.exit(await a(process.argv.slice(2)))}else if(i==="policy"){const{loadPolicy:a,formatPolicy:s,PolicyLoadError:h}=await import("../src/policy.js");try{const l=await a();process.argv.includes("--json")?console.log(JSON.stringify(l?{...l,label:void 0}:null,null,2)):console.log(s(l))}catch(l){throw l instanceof h&&(console.error(`org policy: ${l.message}`),process.exit(78)),l}}else if(i==="--audit"){const{egressAudit:a,formatAudit:s}=await import("../src/egress.js"),{loadConfig:h}=await import("../src/config.js"),{readFileSync:l}=await import("node:fs"),{join:u}=await import("node:path"),g=await import("node:os"),c=h(),e=`http://127.0.0.1:${c.port||4320}`;let t=null,n=`no gateway running at ${e}`;try{const p=l(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||u(g.homedir(),".chatpanel","gateway-token"),"utf8").trim(),o=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${p}`},signal:AbortSignal.timeout(2500)});if(o.ok)t=await o.json();else if(o.status===404){const r=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);n=`the gateway running at ${e}${r?.version?` (${r.version})`:""} predates --audit (0.7.0) — restart it after updating`}else n=`the gateway at ${e} refused the audit (HTTP ${o.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!t){const{VERSION:p}=await import("../src/server.js"),{systemCaWanted:o}=await import("../src/system-ca.js"),r=o(c),{partnerDevicesOnDisk:d}=await import("../src/link-host.js"),w=c.link?.enabled===!1?[]:d(...c.link?.path?[c.link.path]:[]);t={...a(c,{ledger:null,version:p,linkPartners:w,certificates:{on:!1,added:0,wanted:r,why:r?"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(`(${n}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(t,null,2)):console.log(s(t))}else if(i==="sandbox"){const{srtModuleUrl:a}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&a()&&(process.env.CHATPANEL_SRT_MODULE=a());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js"),{sandboxCommand:h}=await import("../src/sandbox-cli.js"),{loadConfig:l}=await import("../src/config.js"),{readFileSync:u}=await import("node:fs"),{join:g}=await import("node:path"),c=await import("node:os");let e="";try{e=u(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||g(c.homedir(),".chatpanel","gateway-token"),"utf8").trim()}catch{}process.exit(await h(process.argv.slice(3),{cfg:l(),token:e,local:t=>s(t)}))}else if(i==="pair"){const{loadConfig:a}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),g=`http://127.0.0.1:${a().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token");try{const e=s(c,"utf8").trim(),t=await fetch(`${g}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),n=await t.json().catch(()=>({}));if(t.status===404)throw new Error(`the gateway at ${g} predates pairing (0.9.0) — update and restart it`);if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);console.log(`Pairing code: ${n.display||n.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 ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(i==="link"){const{linkCommand:a}=await import("../src/link-cli.js"),{loadConfig:s}=await import("../src/config.js"),{readFileSync:h}=await import("node:fs"),{join:l}=await import("node:path"),u=await import("node:os"),c=`http://127.0.0.1:${s().port||4320}`,e=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(u.homedir(),".chatpanel","gateway-token");let t="";try{t=h(e,"utf8").trim()}catch{console.error(`no gateway token at ${e} — has the gateway started once?`),process.exit(1)}const n=async(o,r,d)=>{try{const w=await fetch(`${c}${r}`,{method:o,headers:{authorization:`Bearer ${t}`,...d?{"content-type":"application/json"}:{}},body:d?JSON.stringify(d):void 0,signal:AbortSignal.timeout(2e4)});return{status:w.status,json:await w.json().catch(()=>null)}}catch(w){return{status:0,json:{error:{message:`no gateway answering at ${c} (${w?.message||w})`}}}}},p=process.stdin.isTTY?async o=>{const{createInterface:r}=await import("node:readline/promises"),d=r({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await d.question(o)).trim())}finally{d.close()}}:null;process.exit(await a(process.argv.slice(3),{call:n,ask:p}))}else if(i==="local"){const{localStatus:a,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await a()))}else if(i==="connect"){const{connectAgents:a,formatConnect:s}=await import("../src/connect-agents.js"),h=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(a({dryRun:h}),{dryRun:h}))}else if(i==="--confined"||i===void 0&&process.env.CHATPANEL_CONFINED!=="1"&&await(await import("../src/confine-start.js")).confinedByPolicy()){const{startConfined:a}=await import("../src/confine-start.js");await a({by:i==="--confined"?"flag":"policy"})}else{const{start:a,VERSION:s}=await import("../src/server.js"),{installService:h,uninstallService:l,serviceReport:u,stopService:g,pathWithDir:c}=await import("../src/service.js");switch(i){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(s);break;case"--fetch-apple-helper":{const{ensureAppleHelper:e,appleHelperWanted:t}=await import("../src/apple-helper-fetch.js"),n=await import("node:os");if(!t({release:n.release()})){console.log("Apple’s on-device model needs an Apple Silicon Mac on macOS 26 or later — nothing to fetch here.");break}try{const{loadConfig:p}=await import("../src/config.js"),o=await e({version:s,registries:p().registries||{},onProgress:r=>{r.phase==="download"&&console.log(`fetching the Apple on-device helper (v${r.version}) from ${new URL(r.url).host}…`)}});console.log(`Apple on-device helper: ${o}`)}catch(p){console.error(`could not fetch the Apple on-device helper: ${p?.message||p}`),process.exit(1)}break}case"--install":{try{const{ensureAppleHelper:n,appleHelperWanted:p,findAppleHelper:o}=await import("../src/apple-helper-fetch.js"),r=await import("node:os");if(p({release:r.release()})&&!o()){const{loadConfig:d}=await import("../src/config.js");await n({version:s,registries:d().registries||{}}),console.log("Apple on-device helper: fetched (this install came without it).")}}catch(n){console.log(`Apple on-device helper: not fetched (${String(n?.message||n).slice(0,160)}) — \`chatpanel-gateway --fetch-apple-helper\` tries again; everything else works without it.`)}const e=await h({version:s,force:process.argv.includes("--force")}),t=e.health;if(e.newer){const n=t.managedBy&&t.managedBy!=="gateway"?` (run by the ${t.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${t.version} is already running at ${t.url}${n} — newer than this copy (v${s}). 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${s} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const n=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${t.version}) is the one answering right now; this install takes over at the next login`:"",p=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${t.version}: already running at ${t.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${t.version}: running at ${t.url}${p}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${n}.`);let o=null;for(let r=0;r<30;r++){try{o=(await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{o=null}if(o&&o.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(o?["embedded","standalone","adopted"].includes(o.mode)?console.log(` bridge: ${o.mode}${o.version?` v${o.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${o.why||o.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),o?.version){const{staleBridgeCommands:r,staleBridgeLines:d}=await import("../src/service.js");for(const w of d(r({embedded:o.version}),{embedded:o.version}))console.log(w)}}else t.ok?(console.error(`ChatPanel Privacy Gateway: v${s} is registered to start at login, but v${t.version} still answers at ${t.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 ${t.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
4
4
  ${e.errLog.split(`
5
5
  `).map(n=>` ${n}`).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${s}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${s} either way.)`));try{const{pruneForeignPrebuilds:n,pruneLine:c}=await import("../src/prune-install.js"),o=c(n({log:r=>console.error(r)}));o&&console.log(o)}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&&g(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),t.ok||process.exit(1);break}case"--uninstall":l(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":{console.log(await w());try{const{loadConfig:e}=await import("../src/config.js"),{sandboxProblems:t}=await import("../src/configstore.js");for(const n of t(e()))console.log(` ⚠ ${n}`)}catch{}break}case void 0:await a();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${s}`,""," 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, how agents are sandboxed"," chatpanel-gateway sandbox what the sandbox is doing; `sandbox allow <agent> aws` lets one agent use a sign-in"," 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(`
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${s}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${s} either way.)`));try{const{pruneForeignPrebuilds:n,pruneLine:p}=await import("../src/prune-install.js"),o=p(n({log:r=>console.error(r)}));o&&console.log(o)}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&&c(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),t.ok||process.exit(1);break}case"--uninstall":l(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":{console.log(await u());try{const{loadConfig:e}=await import("../src/config.js"),{sandboxProblems:t}=await import("../src/configstore.js");for(const n of t(e()))console.log(` ⚠ ${n}`)}catch{}break}case void 0:await a();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${s}`,""," 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, how agents are sandboxed"," chatpanel-gateway sandbox what the sandbox is doing; `sandbox allow <agent> aws` lets one agent use a sign-in"," 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 link ChatPanel Link: paired devices; `link pair --partner <name>` lets a partner server in (shown and confirmed first); `link revoke <id>`; `link route <mode>`"," 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: ${i}
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(a){console.error(`error: ${a.message}`),process.exit(1)}
8
+ Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|link|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(a){console.error(`error: ${a.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.88.0",
3
+ "version": "0.97.2",
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": {
@@ -15,16 +15,15 @@
15
15
  "bin",
16
16
  "gateway.config.example.json",
17
17
  "LICENSE",
18
- "README.md",
19
- "native/darwin-arm64"
18
+ "README.md"
20
19
  ],
21
20
  "engines": {
22
21
  "node": ">=22.13"
23
22
  },
24
23
  "dependencies": {
25
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
- "@chatpanel/bridge": "^0.45.2",
27
- "@chatpanel/events": "^0.356.1",
25
+ "@chatpanel/bridge": "^0.46.0",
26
+ "@chatpanel/events": "^0.358.1",
28
27
  "@chatpanel/pii": "^0.15.0",
29
28
  "@huggingface/transformers": "^4.2.0",
30
29
  "defuddle": "^0.19.4",
@@ -1,5 +1,5 @@
1
- import"node:path";import{existsSync as et}from"node:fs";import{spawn as nt,spawnSync as D}from"node:child_process";import{createServer as rt}from"node:net";import{resolveLaunch as it,standaloneCandidates as K,retireStandaloneBridge as ot,compareVersions as k}from"./service.js";import{DEFAULT_BRIDGE_URL as P}from"./bridge.js";import{srtModuleUrl as st}from"./worker-sandbox.js";const w=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,X=[1e3,2e3,5e3,1e4,3e4],at=6e4,dt=1200;function lt(){if(process.env.CHATPANEL_SRT_MODULE)return{};const a=st();return a?{CHATPANEL_SRT_MODULE:a}:{}}function Y({managed:a=!0,cfgUrl:r="",healthy:t=null,standalone:d=null,embeddedVersion:o=null}={}){if(a===!1||a==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const u=String(r||P);if(!w.test(u))return{action:"off",why:`bridge.url ${u} is not on this machine; nothing to start here`};if(t)return!t.managedBy&&o&&t.version&&k(t.version,o)<0?{action:"replace",why:`a standalone bridge (v${t.version}, run by nobody) answers at ${u} and is older than the embedded one (v${o}) — retiring it`}:t.managedBy==="gateway"&&t.orphaned&&o&&t.version&&k(t.version,o)<0?{action:"replace",why:`a bridge an earlier gateway started (v${t.version}) answers at ${u} and is older than the embedded one (v${o}) — replacing it`}:{action:"adopt",why:`a bridge already answers at ${u}${t.version?` (v${t.version}${t.managedBy?`, run by ${t.managedBy}`:""})`:""}`};const f=d?.version||null;return d?.path&&o&&k(f,o)>0?{action:"spawn-standalone",why:`the installed bridge (v${f}) is newer than the embedded one (v${o})`,path:d.path}:o?{action:"spawn-embedded",why:`starting the embedded bridge (v${o})${d?.path?` — the installed one is v${f||"?"}`:""}`}:d?.path?{action:"spawn-standalone",why:`starting the installed bridge${f?` (v${f})`:""}`,path:d.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function ct(a,{timeoutMs:r=dt,fetchImpl:t=fetch}={}){const d=new AbortController,o=setTimeout(()=>d.abort(),r);try{const u=await t(`${String(a).replace(/\/$/,"")}/health`,{signal:d.signal});if(!u.ok)return null;const f=await u.json().catch(()=>null);return f&&f.ok!==!1?{version:f.version||null,managedBy:f.managedBy||null}:null}catch{return null}finally{clearTimeout(o)}}function ut(a,r=[],{timeoutMs:t=8e3}={}){try{const d=D(a,[...r,"--version"],{encoding:"utf8",timeout:t,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),o=String(d.stdout||"").trim().split(`
2
- `).pop();return/^\d+\.\d+\.\d+/.test(o)?o:null}catch{return null}}function ft(){const{program:a,args:r}=it();return{program:a,args:[...r,"--bridge"]}}const U=a=>w.exec(String(a||P))?.[3]||"4319";function pt(a){const r=w.exec(String(a||""));if(!r||!r[3])return!1;const t=Number(r[3]);return t===0||t>=32768}function gt(a,r="127.0.0.1"){return new Promise(t=>{const d=rt();d.once("error",()=>t(!1)),d.listen(Number(a),r,()=>d.close(()=>t(!0)))})}function mt(a,{platform:r=process.platform,runImpl:t=D,kill:d=o=>process.kill(o,"SIGTERM")}={}){if(r==="win32")return!1;try{const o=Number(String(t("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
3
- `)[0]);if(!o||o===process.pid)return!1;const u=String(t("ps",["-o","command=","-p",String(o)],{encoding:"utf8",timeout:2e3}).stdout||"");return/chatpanel-bridge/.test(u)?(d(o),!0):!1}catch{return!1}}function ht(a,{platform:r=process.platform,runImpl:t=D}={}){if(r==="win32")return!1;try{const d=Number(String(t("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
4
- `)[0]);return d?Number(String(t("ps",["-o","ppid=","-p",String(d)],{encoding:"utf8",timeout:2e3}).stdout||"").trim())===1:!1}catch{return!1}}function vt(a,{platform:r=process.platform}={}){if(r==="win32")return"";try{const t=D("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-Fpc"],{encoding:"utf8",timeout:2e3}),d=/^p(\d+)/m.exec(t.stdout||"")?.[1],o=/^c(.+)$/m.exec(t.stdout||"")?.[1];return d?`${o||"a process"} (pid ${d})`:""}catch{return""}}async function At(a,{log:r=n=>console.log(n),probe:t=ct,spawnImpl:d=nt,version:o=ut,candidates:u=K(),exists:f=et,launch:q=ft,managed:y=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:a?.bridge?.managed,waitForSiblingMs:H=2500,retire:z=ot,retireOnPort:J=mt,orphaned:Q=ht,retireWaitMs:Z=6e3,childEnv:W=()=>({}),now:B=Date.now,setTimer:O=setTimeout,setWatch:_=(n,e)=>{const g=setTimeout(n,e);return g.unref?.(),g},watchEveryMs:E=1e4,isFree:R=gt,holder:V=vt}={}){let n=String(a?.bridge?.url||P).replace(/\/$/,"");const e={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},g=(i,c,s={})=>{Object.assign(e,{mode:i,why:c},s),r(` bridge : ${c}`)};pt(n)&&!await t(n)&&(r(` bridge : bridge.url ${n} is a leftover OS-assigned port and nothing answers there — using ${P}`),n=P,a?.bridge&&(a.bridge.url=P));let p=await t(n);if(!p&&y!==!1&&y!=="off"&&w.test(n)&&H>0){const i=B()+H;for(;!p&&B()<i;)await new Promise(c=>O(c,500)),p=await t(n)}const N=q(),tt=y!==!1&&y!=="off";p?.managedBy==="gateway"&&w.test(n)&&(p.orphaned=Q(U(n)));const S=!tt||p&&p.managedBy&&!p.orphaned?null:o(N.program,N.args),M=u.find(i=>f(i))||null,G=M&&!p?{path:M,version:o(M,[])}:null,m=Y({managed:y,cfgUrl:n,healthy:p,standalone:G,embeddedVersion:S});if(m.action==="off")return g("off",m.why),A();const I=i=>i.action==="spawn-embedded"?{...N,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:i.version||S}:{program:i.path,args:[],env:{},mode:"standalone",version:G?.version||null};let l=m.action==="adopt"||m.action==="replace"?null:I(m),j=0,$=null,L=0;const T=(i,c)=>{g("adopted",i,{version:c||null}),L=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const C=await t(n);if(C){L=0,e.version=C.version||e.version,$=_(s,E);return}if(L+=1,L<2){$=_(s,Math.min(E,3e3));return}if(!l){const h=S||o(N.program,N.args),v=Y({managed:y,cfgUrl:n,healthy:null,standalone:G,embeddedVersion:h});if(v.action==="off"){g("off",`the adopted bridge went away and ${v.why}`);return}l=I({...v,version:h})}r(` bridge : the adopted bridge at ${n} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),g(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),x()};$=_(s,E)},b=U(n),F=()=>{const i=V(b);g("blocked",`port ${b} is held by ${i||"another program"}, which is not a ChatPanel bridge — no bridge started; free the port or set bridge.url to a free one (checking again every ${Math.round(E/1e3)} s)`,{version:null,pid:null});const c=async()=>{if(e.stopping||e.mode!=="blocked")return;const s=await t(n);if(s){T(`a bridge now answers at ${n} (v${s.version||"?"}${s.managedBy?`, run by ${s.managedBy}`:""})`,s.version);return}if(await R(b)){g(l.mode,`port ${b} is free again — starting the ${l.mode} bridge (v${l.version||"?"})`,{version:l.version}),x();return}$=_(c,E)};$=_(c,E)},x=async()=>{if(e.stopping)return;if(w.test(n)&&!await R(b)){const s=await t(n);if(s){T(`a bridge already answers at ${n} (v${s.version||"?"}${s.managedBy?`, run by ${s.managedBy}`:""})`,s.version);return}F();return}if(e.stopping)return;const i=d(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...W(),...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:U(n),...lt()}});j=B(),e.child=i,e.pid=i.pid||null;const c=(s,C)=>s?.on("data",h=>{for(const v of String(h).split(`
5
- `))v.trim()&&r(`[bridge] ${v}`)});c(i.stdout,"out"),c(i.stderr,"err"),i.on("error",s=>r(`[bridge] could not start ${l.program}: ${s?.message||s}`)),i.on("exit",async(s,C)=>{if(e.child=null,e.pid=null,e.stopping)return;const h=await t(n);if(h){T(`a bridge already answers at ${n} (v${h.version||"?"}${h.managedBy?`, run by ${h.managedBy}`:""}) — ours stepped aside`,h.version);return}B()-j>at&&(e.backoff=0);const v=X[Math.min(e.backoff,X.length-1)];e.backoff+=1,e.restarts+=1,r(`[bridge] exited (${C||s}); restarting in ${v/1e3}s`),O(x,v)})};if(m.action==="adopt")return T(m.why,p.version),A();if(m.action==="replace"){r(` bridge : ${m.why}`);try{p.managedBy!=="gateway"&&z({paths:u})}catch(s){r(` bridge : could not retire the standalone bridge: ${s?.message||s}`)}await t(n)&&J(b);const i=B()+Z;let c=await t(n);for(;c&&B()<i;)await new Promise(s=>O(s,500)),c=await t(n);return c?(T(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=I({action:"spawn-embedded",version:S}),g("embedded",`the standalone bridge was retired; starting the embedded bridge (v${S})`,{version:S}),x(),A())}if(w.test(n)&&!await R(b)){const i=await t(n);return i?T(`a bridge already answers at ${n} (v${i.version||"?"}${i.managedBy?`, run by ${i.managedBy}`:""})`,i.version):F(),A()}return g(l.mode,m.why,{version:l.version}),x(),A();function A(){return{status:()=>({mode:e.mode,version:e.version,pid:e.pid,restarts:e.restarts,why:e.why}),stop:()=>{if(e.stopping=!0,$&&(clearTimeout($),$=null),e.child&&!e.child.killed)try{e.child.kill("SIGTERM")}catch{}},restart:(i="settings changed")=>{if(!e.child||e.stopping)return e.mode==="adopted"&&r(`[bridge] ${i} — the bridge on ${n} is not ours (${e.why}); set CHATPANEL_SANDBOX* in its own service`),!1;r(`[bridge] restarting: ${i}`),e.backoff=0;try{e.child.kill("SIGTERM")}catch{}return!0}}}}export{k as compareVersions,ft as embeddedLaunch,At as ensureBridge,vt as holderOf,pt as isEphemeralBridgeUrl,ht as listenerOrphaned,Y as planBridge,gt as portFree,ct as probeBridge,mt as retireBridgeOnPort,lt as srtModuleEnv,K as standaloneCandidates,ut as versionOf};
1
+ import"node:path";import{existsSync as ne}from"node:fs";import{spawn as re,spawnSync as D}from"node:child_process";import{createServer as ie}from"node:net";import{resolveLaunch as oe,standaloneCandidates as K,retireStandaloneBridge as se,compareVersions as k}from"./service.js";import{DEFAULT_BRIDGE_URL as N}from"./bridge.js";import{srtModuleUrl as ae}from"./worker-sandbox.js";const y=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,X=[1e3,2e3,5e3,1e4,3e4],de=6e4,le=1200;function ce(){if(process.env.CHATPANEL_SRT_MODULE)return{};const a=ae();return a?{CHATPANEL_SRT_MODULE:a}:{}}function Y({managed:a=!0,cfgUrl:o="",healthy:e=null,standalone:d=null,embeddedVersion:s=null}={}){if(a===!1||a==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const u=String(o||N);if(!y.test(u))return{action:"off",why:`bridge.url ${u} is not on this machine; nothing to start here`};if(e)return!e.managedBy&&s&&e.version&&k(e.version,s)<0?{action:"replace",why:`a standalone bridge (v${e.version}, run by nobody) answers at ${u} and is older than the embedded one (v${s}) — retiring it`}:e.managedBy==="gateway"&&e.orphaned&&s&&e.version&&k(e.version,s)<0?{action:"replace",why:`a bridge an earlier gateway started (v${e.version}) answers at ${u} and is older than the embedded one (v${s}) — replacing it`}:{action:"adopt",why:`a bridge already answers at ${u}${e.version?` (v${e.version}${e.managedBy?`, run by ${e.managedBy}`:""})`:""}`};const p=d?.version||null;return d?.path&&s&&k(p,s)>0?{action:"spawn-standalone",why:`the installed bridge (v${p}) is newer than the embedded one (v${s})`,path:d.path}:s?{action:"spawn-embedded",why:`starting the embedded bridge (v${s})${d?.path?` — the installed one is v${p||"?"}`:""}`}:d?.path?{action:"spawn-standalone",why:`starting the installed bridge${p?` (v${p})`:""}`,path:d.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function ue(a,{timeoutMs:o=le,fetchImpl:e=fetch}={}){const d=new AbortController,s=setTimeout(()=>d.abort(),o);try{const u=await e(`${String(a).replace(/\/$/,"")}/health`,{signal:d.signal});if(!u.ok)return null;const p=await u.json().catch(()=>null);return p&&p.ok!==!1?{version:p.version||null,managedBy:p.managedBy||null}:null}catch{return null}finally{clearTimeout(s)}}function fe(a,o=[],{timeoutMs:e=8e3}={}){try{const d=D(a,[...o,"--version"],{encoding:"utf8",timeout:e,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),s=String(d.stdout||"").trim().split(`
2
+ `).pop();return/^\d+\.\d+\.\d+/.test(s)?s:null}catch{return null}}function pe(){const{program:a,args:o}=oe();return{program:a,args:[...o,"--bridge"]}}const H=a=>y.exec(String(a||N))?.[3]||"4319";function ge(a){const o=y.exec(String(a||""));if(!o||!o[3])return!1;const e=Number(o[3]);return e===0||e>=32768}function me(a,o="127.0.0.1"){return new Promise(e=>{const d=ie();d.once("error",()=>e(!1)),d.listen(Number(a),o,()=>d.close(()=>e(!0)))})}function he(a,{platform:o=process.platform,runImpl:e=D,kill:d=s=>process.kill(s,"SIGTERM")}={}){if(o==="win32")return!1;try{const s=Number(String(e("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
3
+ `)[0]);if(!s||s===process.pid)return!1;const u=String(e("ps",["-o","command=","-p",String(s)],{encoding:"utf8",timeout:2e3}).stdout||"");return/chatpanel-bridge/.test(u)?(d(s),!0):!1}catch{return!1}}function ve(a,{platform:o=process.platform,runImpl:e=D}={}){if(o==="win32")return!1;try{const d=Number(String(e("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
4
+ `)[0]);return d?Number(String(e("ps",["-o","ppid=","-p",String(d)],{encoding:"utf8",timeout:2e3}).stdout||"").trim())===1:!1}catch{return!1}}function $e(a,{platform:o=process.platform}={}){if(o==="win32")return"";try{const e=D("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-Fpc"],{encoding:"utf8",timeout:2e3}),d=/^p(\d+)/m.exec(e.stdout||"")?.[1],s=/^c(.+)$/m.exec(e.stdout||"")?.[1];return d?`${s||"a process"} (pid ${d})`:""}catch{return""}}async function Pe(a,{log:o=r=>console.log(r),probe:e=ue,spawnImpl:d=re,version:s=fe,candidates:u=K(),exists:p=ne,launch:q=pe,managed:B=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:a?.bridge?.managed,waitForSiblingMs:U=2500,retire:z=se,retireOnPort:J=he,orphaned:Q=ve,retireWaitMs:Z=6e3,childEnv:W=()=>({}),now:T=Date.now,setTimer:O=setTimeout,setWatch:E=(r,t)=>{const f=setTimeout(r,t);return f.unref?.(),f},watchEveryMs:b=1e4,isFree:R=me,holder:V=$e,beside:ee=process.env.CHATPANEL_CONFINED==="1"}={}){let r=String(a?.bridge?.url||N).replace(/\/$/,"");const t={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},f=(i,l,n={})=>{Object.assign(t,{mode:i,why:l},n),o(` bridge : ${l}`)};if(ge(r)&&!await e(r)&&(o(` bridge : bridge.url ${r} is a leftover OS-assigned port and nothing answers there — using ${N}`),r=N,a?.bridge&&(a.bridge.url=N)),ee){let i=null;const l=async()=>{if(t.stopping)return;const n=await e(r);n&&t.mode!=="adopted"?f("adopted",`run beside this confined gateway by its launcher (v${n.version||"?"})`,{version:n.version||null}):n?t.version=n.version||t.version:!n&&(t.mode!=="off"||!t.why)&&f("off",`the launcher outside the sandbox runs the bridge — nothing answers at ${r} right now`,{version:null}),i=E(l,b)};return await l(),{status:()=>({mode:t.mode,version:t.version,pid:null,restarts:0,why:t.why}),stop:()=>{t.stopping=!0,i&&clearTimeout(i)},restart:()=>!1}}let g=await e(r);if(!g&&B!==!1&&B!=="off"&&y.test(r)&&U>0){const i=T()+U;for(;!g&&T()<i;)await new Promise(l=>O(l,500)),g=await e(r)}const _=q(),te=B!==!1&&B!=="off";g?.managedBy==="gateway"&&y.test(r)&&(g.orphaned=Q(H(r)));const S=!te||g&&g.managedBy&&!g.orphaned?null:s(_.program,_.args),I=u.find(i=>p(i))||null,M=I&&!g?{path:I,version:s(I,[])}:null,m=Y({managed:B,cfgUrl:r,healthy:g,standalone:M,embeddedVersion:S});if(m.action==="off")return f("off",m.why),P();const G=i=>i.action==="spawn-embedded"?{..._,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:i.version||S}:{program:i.path,args:[],env:{},mode:"standalone",version:M?.version||null};let c=m.action==="adopt"||m.action==="replace"?null:G(m),F=0,$=null,L=0;const A=(i,l)=>{f("adopted",i,{version:l||null}),L=0;const n=async()=>{if(t.stopping||t.mode!=="adopted")return;const C=await e(r);if(C){L=0,t.version=C.version||t.version,$=E(n,b);return}if(L+=1,L<2){$=E(n,Math.min(b,3e3));return}if(!c){const h=S||s(_.program,_.args),v=Y({managed:B,cfgUrl:r,healthy:null,standalone:M,embeddedVersion:h});if(v.action==="off"){f("off",`the adopted bridge went away and ${v.why}`);return}c=G({...v,version:h})}o(` bridge : the adopted bridge at ${r} went away — ${c.mode==="embedded"?`starting the embedded bridge (v${c.version||"?"})`:`starting the installed bridge (v${c.version||"?"})`}`),f(c.mode,`the adopted bridge went away; ${c.mode} bridge started in its place`,{version:c.version}),x()};$=E(n,b)},w=H(r),j=()=>{const i=V(w);f("blocked",`port ${w} is held by ${i||"another program"}, which is not a ChatPanel bridge — no bridge started; free the port or set bridge.url to a free one (checking again every ${Math.round(b/1e3)} s)`,{version:null,pid:null});const l=async()=>{if(t.stopping||t.mode!=="blocked")return;const n=await e(r);if(n){A(`a bridge now answers at ${r} (v${n.version||"?"}${n.managedBy?`, run by ${n.managedBy}`:""})`,n.version);return}if(await R(w)){f(c.mode,`port ${w} is free again — starting the ${c.mode} bridge (v${c.version||"?"})`,{version:c.version}),x();return}$=E(l,b)};$=E(l,b)},x=async()=>{if(t.stopping)return;if(y.test(r)&&!await R(w)){const n=await e(r);if(n){A(`a bridge already answers at ${r} (v${n.version||"?"}${n.managedBy?`, run by ${n.managedBy}`:""})`,n.version);return}j();return}if(t.stopping)return;const i=d(c.program,c.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...W(),...c.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:H(r),...ce()}});F=T(),t.child=i,t.pid=i.pid||null;const l=(n,C)=>n?.on("data",h=>{for(const v of String(h).split(`
5
+ `))v.trim()&&o(`[bridge] ${v}`)});l(i.stdout,"out"),l(i.stderr,"err"),i.on("error",n=>o(`[bridge] could not start ${c.program}: ${n?.message||n}`)),i.on("exit",async(n,C)=>{if(t.child=null,t.pid=null,t.stopping)return;const h=await e(r);if(h){A(`a bridge already answers at ${r} (v${h.version||"?"}${h.managedBy?`, run by ${h.managedBy}`:""}) — ours stepped aside`,h.version);return}T()-F>de&&(t.backoff=0);const v=X[Math.min(t.backoff,X.length-1)];t.backoff+=1,t.restarts+=1,o(`[bridge] exited (${C||n}); restarting in ${v/1e3}s`),O(x,v)})};if(m.action==="adopt")return A(m.why,g.version),P();if(m.action==="replace"){o(` bridge : ${m.why}`);try{g.managedBy!=="gateway"&&z({paths:u})}catch(n){o(` bridge : could not retire the standalone bridge: ${n?.message||n}`)}await e(r)&&J(w);const i=T()+Z;let l=await e(r);for(;l&&T()<i;)await new Promise(n=>O(n,500)),l=await e(r);return l?(A(`the standalone bridge (v${l.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,l.version),P()):(c=G({action:"spawn-embedded",version:S}),f("embedded",`the standalone bridge was retired; starting the embedded bridge (v${S})`,{version:S}),x(),P())}if(y.test(r)&&!await R(w)){const i=await e(r);return i?A(`a bridge already answers at ${r} (v${i.version||"?"}${i.managedBy?`, run by ${i.managedBy}`:""})`,i.version):j(),P()}return f(c.mode,m.why,{version:c.version}),x(),P();function P(){return{status:()=>({mode:t.mode,version:t.version,pid:t.pid,restarts:t.restarts,why:t.why}),stop:()=>{if(t.stopping=!0,$&&(clearTimeout($),$=null),t.child&&!t.child.killed)try{t.child.kill("SIGTERM")}catch{}},restart:(i="settings changed")=>{if(!t.child||t.stopping)return t.mode==="adopted"&&o(`[bridge] ${i} — the bridge on ${r} is not ours (${t.why}); set CHATPANEL_SANDBOX* in its own service`),!1;o(`[bridge] restarting: ${i}`),t.backoff=0;try{t.child.kill("SIGTERM")}catch{}return!0}}}}export{k as compareVersions,pe as embeddedLaunch,Pe as ensureBridge,$e as holderOf,ge as isEphemeralBridgeUrl,ve as listenerOrphaned,Y as planBridge,me as portFree,ue as probeBridge,he as retireBridgeOnPort,ce as srtModuleEnv,K as standaloneCandidates,fe as versionOf};
@@ -1 +1 @@
1
- import{patchApis as S,viewApis as N}from"./retrieval/search-apis.js";import{writeFileSync as D,mkdirSync as O,chmodSync as T}from"node:fs";import{join as _,dirname as v}from"node:path";import g from"node:os";import{usage as j}from"./freegate.js";import{applyFusionsPatch as L}from"./fusions.js";import{EMBEDDED_MODELS as P,EMBEDDED_IDS as c,isEmbeddedModel as R}from"./embedded-models.js";import{normalizeRegistries as C,REGISTRY_KINDS as I}from"@chatpanel/events/registries.js";import{assertEndpointUrl as b}from"@chatpanel/pii";import{normalizeGrant as p}from"@chatpanel/bridge/src/events/sandbox-policy.js";const a=["open","allowlist","off"],w=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(o=>String(o).trim()).filter(o=>o&&o.length<1024&&!o.includes("\0")),y=e=>Object.assign(new Error(e),{code:"SHAPE"}),x=/^[A-Za-z0-9][\w.-]{0,63}$/,H=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function M(e,{strict:o=!1}={}){const r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(const[i,t]of Object.entries(e))if(t!=null)try{if(!x.test(i))throw y(`not an agent id: ${JSON.stringify(i)}`);const n=p(t);H(n)||(r[i]=n)}catch(n){if(o)throw y(`sandbox.agents.${i}: ${n.message}`)}return r}function l(e={},{strict:o=!1}={}){const r=e&&typeof e=="object"?e:{};if(o&&r.mode!==void 0&&!a.includes(r.mode))throw y(`sandbox.mode must be one of ${a.join(", ")} — got ${JSON.stringify(r.mode)}`);const i=a.includes(r.mode)?r.mode:"open",{hosts:t}=p({hosts:r.hosts??[]}),n=M(r.agents,{strict:o});return{mode:i,hosts:t,write:w(r.write),denyRead:w(r.denyRead),...Object.keys(n).length?{agents:n}:{}}}const $=["off","0","false"],A=e=>String(e||"").split(",").map(o=>o.trim()).filter(Boolean),f=(...e)=>[...new Set(e.flat())];function m(e=process.env){const o=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return o?$.includes(o)?{mode:"off"}:a.includes(o)?{mode:o}:{unknown:o}:{}}function J(e,o=process.env){const r=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!a.includes(i.mode)&&r.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${a.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[s,d]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!x.test(s))throw new Error("not an agent id");p(d)}catch(u){r.push(`sandbox.agents.${s} in the config is not valid and is ignored — ${u.message}`)}const t=m(o),n=l(i).mode;return t.unknown&&r.push(`CHATPANEL_SANDBOX="${t.unknown}" in this process's environment is not one of ${a.join(", ")} — ignored; the config's "${n}" applies`),t.mode&&t.mode!==n&&r.push(`the sandbox mode is "${t.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${n}"; Settings › Runtime cannot change it while that variable is set`),r}function Z(e,o=process.env){const r=l(e?.sandbox),i=m(o);let t={};try{const s=JSON.parse(o.CHATPANEL_SANDBOX_AGENTS||"{}");s&&typeof s=="object"&&!Array.isArray(s)&&(t=s)}catch{}const n={...t,...r.agents||{}};return{CHATPANEL_SANDBOX:i.mode||r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:f(r.hosts,A(o.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:f(r.write,A(o.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:f(r.denyRead,A(o.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(n).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(n)}:{}}}function E(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||_(g.homedir(),".chatpanel","gateway.config.json")}function Q(e){const o=e?.registries||{},r={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])o[i]&&(r[t]=o[i]);return r}function V(e,o=E()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&o===E({}))throw new Error(`refusing to persist the real gateway config (${o}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);O(v(o),{recursive:!0,mode:448});const r={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};D(o,JSON.stringify(r,null,2),{mode:384});try{T(o,384)}catch{}}function ee(e,{proUnlocked:o=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(r=>{const{apiKey:i,...t}=r;return{...t,hasKey:!!i}}),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:r,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:{...l(e.sandbox),...m().mode?{envMode:m().mode}:{}},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:N(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([r,i])=>{const{token:t,...n}=i||{};return[r,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:j(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 oe(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function B(e,o={}){if(!e||e.type!=="api")return!1;let r;try{r=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(r.hostname),t=Number(r.port)||(r.protocol==="https:"?443:80);return i&&t===(Number(o.port)||4320)}const k=["default","acceptEdits","bypassPermissions"];function re(e,o={}){const r=e?.bridge||{};return{...k.includes(r.permissionMode)&&r.permissionMode!=="default"?{permissionMode:r.permissionMode}:{},...typeof r.workingDir=="string"&&r.workingDir.trim()?{workingDir:r.workingDir.trim()}:{},...o}}function ie(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const r=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=o.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=B(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:r.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:r.get(i.id)?.service;return n&&(t.service=n),t})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),k.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(r=>String(r).trim()).filter(r=>/^[a-p]{32}$/.test(r))),o.upstreams&&typeof o.upstreams=="object")for(const r of["openai","anthropic"]){const i=o.upstreams[r];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[r]={...e.upstreams[r],baseUrl:i.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const r=o.redaction;(r.tier==="basic"||r.tier==="full")&&(e.redaction.tier=r.tier),"redactSystem"in r&&(e.redaction.redactSystem=!!r.redactSystem),Array.isArray(r.dictionary)&&(e.redaction.dictionary=r.dictionary),r.detection&&typeof r.detection=="object"&&(e.redaction.detection=r.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.sandbox&&typeof o.sandbox=="object"){const r=l(e.sandbox),i={...r,...o.sandbox};o.sandbox.agents&&typeof o.sandbox.agents=="object"&&!Array.isArray(o.sandbox.agents)&&(i.agents={...r.agents||{},...o.sandbox.agents}),e.sandbox=l(i,{strict:!0})}if(o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),o.read&&typeof o.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},o.read.remote&&typeof o.read.remote=="object"){if("url"in o.read.remote){const r=String(o.read.remote.url||"").trim();r&&b(r),e.read.remote.url=r}typeof o.read.remote.key=="string"&&(e.read.remote.key=o.read.remote.key)}["defuddle","text","remote"].includes(o.read.provider)&&(e.read.provider=o.read.provider==="remote"&&!e.read.remote.url?e.read.provider:o.read.provider)}if(o.registries&&typeof o.registries=="object"){const r=C(o.registries),i={...e.registries||{}};for(const t of I)t in o.registries&&(r[t]?i[t]=r[t]:delete i[t]);e.registries=i}if(o.search&&typeof o.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 r=o.search.searxng;if(r&&typeof r=="object"){if("url"in r){const i=String(r.url||"").trim();i&&b(i),e.search.searxng.url=i}typeof r.token=="string"&&(e.search.searxng.token=r.token),typeof r.engines=="string"&&(e.search.searxng.engines=r.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(r.safesearch)&&(e.search.searxng.safesearch=r.safesearch)}"apis"in o.search&&(e.search.apis=S(e.search.apis,o.search.apis)),["auto","serp","searxng"].includes(o.search.provider)&&(e.search.provider=o.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:o.search.provider)}if("fusions"in o){const r=L(e,o.fusions);if(r){const i=new Error(r);throw i.code="SHAPE",i}}if(o.capabilities&&typeof o.capabilities=="object"){e.capabilities=e.capabilities||{};for(const r of["rerank","decide","stt","tts","detect","embed"]){if(!(r in o.capabilities))continue;const i=o.capabilities[r];if(i===null){delete e.capabilities[r],r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t=e.capabilities[r]||{},n={...t};if(i.provider==="embedded"){if(c.includes(r)&&i.model!=null){if(!R(r,i.model)){const s=new Error(`capabilities.${r}.model must be one of ${P[r].map(d=>d.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[r]={provider:"embedded",model:i.model};continue}e.capabilities[r]={provider:"embedded"},r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&c.includes(r)){e.capabilities[r]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&b(s);const d=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&d(t.url)!==d(s)&&typeof i.token!="string"&&delete n.token,n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[r];continue}n.provider="remote",delete n.service,e.capabilities[r]=n,r==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const r=Number(o.tools.maxPerTurn);Number.isFinite(r)&&r>=1&&(e.tools.maxPerTurn=Math.floor(r))}return e}export{k as PERMISSION_MODES,a as SANDBOX_MODES,ie as applyConfigPatch,oe as applyNerModelSelection,re as bridgeAgentOptions,E as configPath,B as isSelfDestination,l as normalizeSandboxConfig,V as persistConfig,ee as publicConfig,Q as registryChildEnv,Z as sandboxEnvFor,m as sandboxModeFromEnv,J as sandboxProblems};
1
+ import{patchApis as R,viewApis as L}from"./retrieval/search-apis.js";import{writeFileSync as P,mkdirSync as h,chmodSync as j}from"node:fs";import{join as C,dirname as H}from"node:path";import B from"node:os";import{usage as I}from"./freegate.js";import{applyFusionsPatch as $}from"./fusions.js";import{EMBEDDED_MODELS as M,EMBEDDED_IDS as g,isEmbeddedModel as X}from"./embedded-models.js";import{normalizeRegistries as G,REGISTRY_KINDS as q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as c}from"@chatpanel/pii";import{normalizeGrant as w}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as b,SANDBOX_RUNTIMES as E,parseWrapperTemplate as U}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as D}from"@chatpanel/events/policy.js";const m=["open","allowlist","off"],O=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(o=>String(o).trim()).filter(o=>o&&o.length<1024&&!o.includes("\0")),l=e=>Object.assign(new Error(e),{code:"SHAPE"}),_=/^[A-Za-z0-9][\w.-]{0,63}$/,F=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function J(e,{strict:o=!1}={}){const r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(const[i,n]of Object.entries(e))if(n!=null)try{if(!_.test(i))throw l(`not an agent id: ${JSON.stringify(i)}`);const t=w(n);F(t)||(r[i]=t)}catch(t){if(o)throw l(`sandbox.agents.${i}: ${t.message}`)}return r}function u(e={},{strict:o=!1}={}){const r=e&&typeof e=="object"?e:{};if(o&&r.mode!==void 0&&!m.includes(r.mode))throw l(`sandbox.mode must be one of ${m.join(", ")} — got ${JSON.stringify(r.mode)}`);const i=m.includes(r.mode)?r.mode:"open";if(o&&r.reads!==void 0&&!b.includes(r.reads))throw l(`sandbox.reads must be one of ${b.join(", ")} — got ${JSON.stringify(r.reads)}`);const n=b.includes(r.reads)?r.reads:b[0];if(o&&r.required!==void 0&&typeof r.required!="boolean")throw l(`sandbox.required must be true or false — got ${JSON.stringify(r.required)}`);if(o&&r.required===!0&&r.mode==="off")throw l("the sandbox cannot be required while it is off — choose open or allowlist first");const t=r.required===!0&&i!=="off";if(o&&r.runtime!==void 0&&!E.includes(r.runtime))throw l(`sandbox.runtime must be one of ${E.join(", ")} — got ${JSON.stringify(r.runtime)}`);const s=E.includes(r.runtime)?r.runtime:"srt";let a="";if(r.command!==void 0&&String(Array.isArray(r.command)?r.command.join(""):r.command).trim())try{U(r.command),a=Array.isArray(r.command)?JSON.stringify(r.command):String(r.command).trim()}catch(v){if(o)throw l(`sandbox.command: ${v.message.replace(/^sandbox command: /,"")}`);a=""}const d=typeof r.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(r.image.trim())?r.image.trim():"";if(o&&r.image!==void 0&&String(r.image).trim()&&!d)throw l("sandbox.image must be an image reference (registry/name:tag)");const A=["podman","docker"].includes(r.engine)?r.engine:"";if(o&&s==="command"&&!a)throw l("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(o&&s==="container"&&!d)throw l("a container needs an image — name the image the agents run in");const{hosts:f}=w({hosts:r.hosts??[]}),x=J(r.agents,{strict:o});return{mode:i,reads:n,required:t,runtime:s,command:a,image:d,engine:A,hosts:f,write:O(r.write),denyRead:O(r.denyRead),...Object.keys(x).length?{agents:x}:{}}}const K=["off","0","false"],N=e=>String(e||"").split(",").map(o=>o.trim()).filter(Boolean),S=(...e)=>[...new Set(e.flat())];function p(e=process.env){const o=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return b.includes(o)?o:""}function y(e=process.env){const o=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return o?K.includes(o)?{mode:"off"}:m.includes(o)?{mode:o}:{unknown:o}:{}}function ae(e,o=process.env){const r=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!m.includes(i.mode)&&r.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${m.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[d,A]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!_.test(d))throw new Error("not an agent id");w(A)}catch(f){r.push(`sandbox.agents.${d} in the config is not valid and is ignored — ${f.message}`)}const n=y(o),t=u(i).mode;n.unknown&&r.push(`CHATPANEL_SANDBOX="${n.unknown}" in this process's environment is not one of ${m.join(", ")} — ignored; the config's "${t}" applies`),n.mode&&n.mode!==t&&r.push(`the sandbox mode is "${n.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${t}"; Settings › Runtime cannot change it while that variable is set`);const s=p(o),a=u(i).reads;return s&&s!==a&&r.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${a}"; Settings › Runtime cannot change it while that variable is set`),r}function de(e,o=process.env,r=null){const i=u(e?.sandbox),{sandbox:n}=D(i,r);Array.isArray(n.command)&&(n.command=JSON.stringify(n.command));const t=y(o);let s={};try{const d=JSON.parse(o.CHATPANEL_SANDBOX_AGENTS||"{}");d&&typeof d=="object"&&!Array.isArray(d)&&(s=d)}catch{}const a={...s,...n.agents||{}};return{CHATPANEL_SANDBOX:r?.sandbox?.mode||t.mode||n.mode,CHATPANEL_SANDBOX_RUNTIME:n.runtime,CHATPANEL_SANDBOX_COMMAND:n.command||"",CHATPANEL_SANDBOX_IMAGE:n.image||"",CHATPANEL_SANDBOX_ENGINE:n.engine||"",CHATPANEL_SANDBOX_READS:r?.sandbox?.reads||p(o)||n.reads,CHATPANEL_SANDBOX_REQUIRED:n.required==="policy"?"policy":String(o.CHATPANEL_SANDBOX_REQUIRED||"")||(n.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:S(n.hosts,N(o.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:S(n.write,N(o.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:S(n.denyRead,N(o.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(a).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(a)}:{}}}function k(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||C(B.homedir(),".chatpanel","gateway.config.json")}function le(e){const o=e?.registries||{},r={};for(const[i,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])o[i]&&(r[n]=o[i]);return r}function me(e,o=k()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&o===k({}))throw new Error(`refusing to persist the real gateway config (${o}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);h(H(o),{recursive:!0,mode:448});const r={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};P(o,JSON.stringify(r,null,2),{mode:384});try{j(o,384)}catch{}}function ue(e,{proUnlocked:o=!1,policy:r=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:n,...t}=i;return{...t,hasKey:!!n}}),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,...n}=e.redaction?.detection||{backend:"off"};return n})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:n}=D(u(e.sandbox),r);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...y().mode?{envMode:y().mode}:{},...p()?{envReads:p()}:{},...n.length?{locked:n,lockedBy:r?.org?.name||"your organisation"}:{}}})(),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:L(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,n])=>{const{token:t,...s}=n||{};return[i,{...s,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:I(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 be(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function W(e,o={}){if(!e||e.type!=="api")return!1;let r;try{r=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(r.hostname),n=Number(r.port)||(r.protocol==="https:"?443:80);return i&&n===(Number(o.port)||4320)}const T=["default","acceptEdits","bypassPermissions"];function pe(e,o={}){const r=e?.bridge||{};return{...T.includes(r.permissionMode)&&r.permissionMode!=="default"?{permissionMode:r.permissionMode}:{},...typeof r.workingDir=="string"&&r.workingDir.trim()?{workingDir:r.workingDir.trim()}:{},...o}}function ye(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const r=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=o.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=W(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:r.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:r.get(i.id)?.service;return t&&(n.service=t),n})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),T.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(r=>String(r).trim()).filter(r=>/^[a-p]{32}$/.test(r))),o.upstreams&&typeof o.upstreams=="object")for(const r of["openai","anthropic"]){const i=o.upstreams[r];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[r]={...e.upstreams[r],baseUrl:i.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const r=o.redaction;(r.tier==="basic"||r.tier==="full")&&(e.redaction.tier=r.tier),"redactSystem"in r&&(e.redaction.redactSystem=!!r.redactSystem),Array.isArray(r.dictionary)&&(e.redaction.dictionary=r.dictionary),r.detection&&typeof r.detection=="object"&&(e.redaction.detection=r.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.sandbox&&typeof o.sandbox=="object"){const r=u(e.sandbox),i={...r,...o.sandbox};o.sandbox.agents&&typeof o.sandbox.agents=="object"&&!Array.isArray(o.sandbox.agents)&&(i.agents={...r.agents||{},...o.sandbox.agents}),e.sandbox=u(i,{strict:!0})}if(o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),o.read&&typeof o.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},o.read.remote&&typeof o.read.remote=="object"){if("url"in o.read.remote){const r=String(o.read.remote.url||"").trim();r&&c(r),e.read.remote.url=r}typeof o.read.remote.key=="string"&&(e.read.remote.key=o.read.remote.key)}["defuddle","text","remote"].includes(o.read.provider)&&(e.read.provider=o.read.provider==="remote"&&!e.read.remote.url?e.read.provider:o.read.provider)}if(o.registries&&typeof o.registries=="object"){const r=G(o.registries),i={...e.registries||{}};for(const n of q)n in o.registries&&(r[n]?i[n]=r[n]:delete i[n]);e.registries=i}if(o.search&&typeof o.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 r=o.search.searxng;if(r&&typeof r=="object"){if("url"in r){const i=String(r.url||"").trim();i&&c(i),e.search.searxng.url=i}typeof r.token=="string"&&(e.search.searxng.token=r.token),typeof r.engines=="string"&&(e.search.searxng.engines=r.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(r.safesearch)&&(e.search.searxng.safesearch=r.safesearch)}"apis"in o.search&&(e.search.apis=R(e.search.apis,o.search.apis)),["auto","serp","searxng"].includes(o.search.provider)&&(e.search.provider=o.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:o.search.provider)}if("fusions"in o){const r=$(e,o.fusions);if(r){const i=new Error(r);throw i.code="SHAPE",i}}if(o.capabilities&&typeof o.capabilities=="object"){e.capabilities=e.capabilities||{};for(const r of["rerank","decide","stt","tts","detect","embed"]){if(!(r in o.capabilities))continue;const i=o.capabilities[r];if(i===null){delete e.capabilities[r],r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n=e.capabilities[r]||{},t={...n};if(i.provider==="embedded"){if(g.includes(r)&&i.model!=null){if(!X(r,i.model)){const s=new Error(`capabilities.${r}.model must be one of ${M[r].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[r]={provider:"embedded",model:i.model};continue}e.capabilities[r]={provider:"embedded"},r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&g.includes(r)){e.capabilities[r]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&c(s);const a=d=>{try{return new URL(d).origin}catch{return d}};n.url&&s&&a(n.url)!==a(s)&&typeof i.token!="string"&&delete t.token,t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[r];continue}t.provider="remote",delete t.service,e.capabilities[r]=t,r==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}})}}if(typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const r=Number(o.tools.maxPerTurn);Number.isFinite(r)&&r>=1&&(e.tools.maxPerTurn=Math.floor(r))}return e}export{T as PERMISSION_MODES,m as SANDBOX_MODES,ye as applyConfigPatch,be as applyNerModelSelection,pe as bridgeAgentOptions,k as configPath,W as isSelfDestination,u as normalizeSandboxConfig,me as persistConfig,ue as publicConfig,le as registryChildEnv,de as sandboxEnvFor,y as sandboxModeFromEnv,ae as sandboxProblems,p as sandboxReadsFromEnv};
@@ -0,0 +1 @@
1
+ import a from"node:path";import{runConfined as s,systemCaFile as m}from"./confine.js";import{systemCaWantedOnDisk as c}from"./system-ca.js";import{loadConfig as d}from"./config.js";import{configPath as f,sandboxEnvFor as p,registryChildEnv as l}from"./configstore.js";import{initPolicy as e,activePolicy as n}from"./policy.js";import{ensureBridge as y}from"./bridge-supervisor.js";import{createSandbox as u}from"@chatpanel/bridge/src/sandbox.js";import{srtModuleUrl as g}from"./worker-sandbox.js";import{selfUpdate as h}from"./update.js";import{restartService as C}from"./service.js";import{VERSION as w}from"./version.js";async function j({by:i="flag"}={}){try{await e()}catch(r){console.error(`ChatPanel Gateway: the org policy could not be read — ${r?.message||r}`),process.exit(1)}const t=g(),o=a.dirname(f());return s({by:i,stateDir:o,systemCa:()=>m({stateDir:o,wanted:c()}),loadCfg:()=>d(),bridgeEnv:r=>({...p(r,process.env,n()),...l(r)}),ensureBridge:y,createSandbox:u,loadSrt:()=>t?import(t):Promise.reject(new Error("the sandbox runtime is not installed — the standalone binary carries it; for npm: npm i -g @anthropic-ai/sandbox-runtime")),update:async()=>{const r=await h(w);C({winInstall:r?.deferred||""})}})}async function k(){try{return await e(),!!n()?.gateway?.confined}catch{return!1}}export{k as confinedByPolicy,j as startConfined};
package/src/confine.js ADDED
@@ -0,0 +1 @@
1
+ import r from"node:path";import C from"node:os";import{existsSync as T,readdirSync as B,realpathSync as J,writeFileSync as A,readFileSync as Y,rmSync as x,lstatSync as q,watchFile as I,mkdirSync as K}from"node:fs";import Q from"node:tls";import{spawn as V}from"node:child_process";import{gatewayKit as z}from"@chatpanel/events/sandbox-policy.js";import{isCompiledBinary as O,hostFacts as P}from"@chatpanel/events/runtime-host.js";const R=[1e3,2e3,5e3,1e4,3e4],Z=6e4,$="update-request.json",U="update-result.json";function ut({argv:t=process.argv,env:e=process.env,policy:n=null}={}){return e.CHATPANEL_CONFINED==="1"?{confined:!1,inside:!0,by:e.CHATPANEL_CONFINED_BY||"flag"}:n?.gateway?.confined?{confined:!0,inside:!1,by:"policy"}:t.includes("--confined")?{confined:!0,inside:!1,by:"flag"}:{confined:!1,inside:!1,by:null}}function tt(t={}){const e=new Set([Number(t.port)||4320,4319,8895]);for(const n of JSON.stringify(t||{}).matchAll(/(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d{2,5})/gi))e.add(Number(n[1]));return[...e].filter(n=>n>0&&n<65536).sort((n,o)=>n-o)}const g=t=>{try{return J(t)}catch{return t}};function et({facts:t=P(),execPath:e=process.execPath,entry:n=process.argv[1]||"",exists:o=T}={}){const i=g(e);if(O(t))return[r.dirname(i)];const p=r.dirname(r.dirname(g(n))),h=[p,r.dirname(r.dirname(i))];for(const y of["@chatpanel","@anthropic-ai"]){const d=r.join(p,"node_modules",y);let u=[];try{u=B(d)}catch{continue}for(const m of u){const l=r.join(d,m);try{q(l).isSymbolicLink()&&o(l)&&h.push(g(l))}catch{}}}return[...new Set(h)]}function nt({stateDir:t,home:e=C.homedir(),codeDirs:n=et()}={}){const o=C.tmpdir();return z({stateDir:t,codeDirs:n,home:e,mode:"open",scratch:[...new Set([o,g(o)])]})}function ot(t){return{...t,CHATPANEL_SANDBOX:/^(off|0|false)$/i.test(String(t.CHATPANEL_SANDBOX||""))||!t.CHATPANEL_SANDBOX?"open":t.CHATPANEL_SANDBOX,CHATPANEL_SANDBOX_REQUIRED:t.CHATPANEL_SANDBOX_REQUIRED==="policy"?"policy":"on"}}function rt({home:t=C.homedir(),stateDir:e,fenced:n=r.join(e||"","runtime","sandbox-runtime")}={}){const o=N=>{try{return N(),!0}catch{return!1}},i=`.chatpanel-confined-probe-${process.pid}`,p=o(()=>B(t)),h=r.join(t,i),y=o(()=>A(h,""));y&&o(()=>x(h,{force:!0}));const d=r.join(n,i),u=T(n)?o(()=>A(d,"")):!1;u&&o(()=>x(d,{force:!0}));const m=r.join(e,i),l=o(()=>A(m,""));return o(()=>x(m,{force:!0})),{holding:!p&&!y&&!u&&l,homeListed:p,homeWritten:y,fenceWritten:u,stateWritten:l}}let b=null;function pt({env:t=process.env,stateDir:e}={}){return t.CHATPANEL_CONFINED!=="1"?{on:!1}:(b||(b={on:!0,by:t.CHATPANEL_CONFINED_BY||"flag",...rt({stateDir:e})}),b)}function ht(){b=null}function yt(t){return t?.on?t.holding?`confined (${t.by==="policy"?"your organisation's policy":"--confined"}) — the home folder is closed to it; it writes only its own folder`:`confined, but the sandbox is NOT holding: ${[t.homeListed&&"it can list the home folder",t.homeWritten&&"it can write the home folder",t.fenceWritten&&"it can write the sandbox runtime",!t.stateWritten&&"it cannot write its own folder"].filter(Boolean).join("; ")}`:"not confined — runs with your account's full access (chatpanel-gateway --install --confined confines it)"}function mt({stateDir:t,wanted:e=!0,tlsImpl:n=Q}={}){if(!e||typeof n.getCACertificates!="function")return"";try{const o=n.getCACertificates("system"),i=r.join(t,"runtime","system-certificates.txt");return K(r.dirname(i),{recursive:!0}),A(i,o.join("")),i}catch{return""}}function At(t){try{return JSON.parse(Y(r.join(t,U),"utf8"))}catch{return null}}function Nt({stateDir:t,version:e}){A(r.join(t,$),JSON.stringify({at:Date.now(),from:e}))}async function gt({by:t="flag",log:e=f=>console.log(f),stateDir:n,loadCfg:o,bridgeEnv:i=()=>({}),ensureBridge:p,createSandbox:h,loadSrt:y,update:d=null,systemCa:u=()=>"",spawnImpl:m=V,setTimer:l=setTimeout,now:N=Date.now,entryArgs:W=O(P())?[]:[g(process.argv[1]||"")],execPath:M=process.execPath,kit:X=nt({stateDir:n}),onSignal:L=(f,w)=>process.on(f,w),exit:F=f=>process.exit(f)}={}){e(`ChatPanel Gateway — confined (${t==="policy"?"your organisation's policy":"--confined"}): it writes only ${n}, the rest of your home folder is closed to it`);const f=await p(o(),{childEnv:()=>ot(i(o())),beside:!1}),w=h({config:{enabled:!0,mode:"open",extraHosts:[],extraWrite:[],extraDenyRead:[],reads:"inverted",required:"on"},runtimeId:"srt",compiled:O(P()),loopback:tt(o()),loadSrt:y,log:c=>e(` sandbox : ${c}`)}),s={child:null,stopping:!1,backoff:0,startedAt:0},j=async()=>{if(s.stopping)return;const c=u(),E={...process.env,CHATPANEL_CONFINED:"1",CHATPANEL_CONFINED_BY:t,CHATPANEL_BRIDGE_MANAGED:"off",NODE_USE_ENV_PROXY:"1",...c?{CHATPANEL_SYSTEM_CA_FILE:c}:{}};let a;try{a=await w.wrap(M,W,{cwd:n,env:E},{engine:"custom",cwd:n,kit:X})}catch(S){a={record:{layer:"none",reason:S?.message||String(S)}}}if(a.record?.layer!=="process"){e(`✗ not started: the gateway cannot be confined here (${a.record?.reason||a.record?.layer||"no sandbox"}). Nothing runs outside the sandbox when --confined is asked for.`),f?.stop?.(),F(1);return}const k=m(a.bin,a.argv,{...a.opts,stdio:"inherit"});s.child=k,s.startedAt=N(),k.on("exit",(S,G)=>{if(s.child=null,s.stopping)return;N()-s.startedAt>Z&&(s.backoff=0);const H=R[Math.min(s.backoff,R.length-1)];s.backoff+=1,e(` gateway : exited (${G||S}); restarting it in its sandbox in ${H/1e3}s`),l(j,H)})};let D=JSON.stringify(i(o()));const v=r.join(n,"gateway.config.json");if(I(v,{interval:2e3,persistent:!1},()=>{let c;try{c=JSON.stringify(i(o()))}catch{return}c!==D&&(D=c,f?.restart?.("sandbox settings changed"))}),d){const c=r.join(n,$);I(c,{interval:2e3,persistent:!1},async()=>{if(T(c)){try{x(c,{force:!0})}catch{return}e(" update : the gateway asked for an update — installing it from outside its sandbox");try{await d()}catch(E){const a=String(E?.message||E).slice(0,2400);e(` update : failed — ${a.slice(0,300)}`);try{A(r.join(n,U),JSON.stringify({at:N(),ok:!1,detail:a}))}catch{}}}})}const _=()=>{s.stopping=!0;try{s.child?.kill("SIGTERM")}catch{}f?.stop?.(),l(()=>F(0),300)};return L("SIGINT",_),L("SIGTERM",_),await j(),{stop:_,status:()=>({pid:s.child?.pid||null,bridge:f?.status?.()||null})}}export{$ as UPDATE_REQUEST,U as UPDATE_RESULT,ht as _resetConfinedStatus,et as codeDirsFor,ot as confinedAgentEnv,nt as confinedKit,yt as confinedLine,pt as confinedStatus,rt as confinementProbe,ut as confinementWanted,tt as loopbackPorts,Nt as requestUpdate,gt as runConfined,mt as systemCaFile,At as updateResult};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{searchEngines as $}from"./retrieval/search-apis.js";import{linkPaths as E}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const L=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const m=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function S({clock:e=L}={}){const t=new Map;return{record(a){const o=y(a);if(!o||!o.host)return;const u=`${o.scheme}://${o.host}:${o.port}`,n=e(),h=t.get(u);if(h){h.count+=1,h.lastAt=n;return}t.set(u,{host:o.host,port:o.port,scheme:o.scheme,local:m(o.host),count:1,firstAt:n,lastAt:n})},snapshot(){return[...t.values()].sort((a,o)=>a.local===o.local?o.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let b=null;function _(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=S();let o=t;a.setGate=c=>{o=c},a.blocked=[];const u=c=>{let r=null;try{r=y(c),a.record(c)}catch{}if(!o||!r?.host)return null;let i=!0;try{i=o(`${r.scheme}://${r.host}:${r.port}`,{local:m(r.host)})}catch{i=!0}if(i)return null;const p=`${r.host}:${r.port}`;a.blocked.includes(p)||a.blocked.push(p);const s=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return s.code="EGRESS_POLICY",s},n=e.fetch;typeof n=="function"&&(e.fetch=function(r,i){const p=u(r);return p?Promise.reject(p):n.call(this,r,i)});const h=e.WebSocket;return typeof h=="function"&&(e.WebSocket=new Proxy(h,{construct(c,r,i){const p=u(r[0]);if(p)throw p;return Reflect.construct(c,r,i)}})),e.__chatpanelEgress=a,e===globalThis&&(b=a),a}function P(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function A(e={},t=process.env,a=process.platform,o=process.arch){const u=[],n=(s,d,{when:l="always",off:w=null,local:v=!1,data:k=""}={})=>{s&&u.push({host:s,purpose:d,when:l,off:w,local:v,data:k})};n("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"}),n("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"}),n("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||n("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&o==="arm64"&&n("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const h=e.link?.enabled===!1?null:E(e.link||{}).relay;if(h){const s=new URL(h).host;n(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"})}n("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 s=c;try{s=new URL(c).host}catch{}n(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"){n("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"}),n("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"}),n("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 $(e).filter(d=>d.kind==="api"&&d.enabled!==!1))n(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{}n(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 r={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",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,d]of Object.entries(r)){const l=e.capabilities?.[s];if(!l?.url||l.provider==="embedded")continue;let w=l.url;try{w=new URL(l.url).host}catch{}n(w,`${d.what}${l.service?` (the ${l.service} container, started under Settings › Runtime)`:` (${l.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:l.service?`stop the ${l.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${d.data}${l.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(n("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"}),n("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,d]of Object.entries(e.upstreams||{}))d?.baseUrl&&n(f(d.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:m(f(d.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&n(f(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:m(f(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});n("(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&&n(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const i=e.tts||{};if(i.provider==="openai"||i.provider==="elevenlabs"){const s=i.remote?.baseUrl?f(i.remote.baseUrl):i.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";n(s,`remote read-aloud voice (${i.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:i.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&&n("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 p=e.bridge?.url||"http://127.0.0.1:4319";return n(f(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function C(e,{ledger:t=P(),version:a="",startedAt:o=null,env:u=process.env,managed:n=null,certificates:h=null}={}){return{ok:!0,version:a,since:o?new Date(o).toISOString():null,...h?{certificates:h}:{},...n?{managed:n,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:A(e,u)}}function I(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,o])=>o===!0?a:`${a}=${o}`).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{S as createEgressLedger,A as declaredEgress,C as egressAudit,P as egressLedger,I as formatAudit,_ as installEgressLedger};
1
+ import{confinedLine as $}from"./confine.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as S}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const L=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),n=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const m=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=L}={}){const t=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:m(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){t.clear()}}}let b=null;function N(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const n=A();let r=t;n.setGate=l=>{r=l},n.blocked=[];const u=l=>{let i=null;try{i=y(l),n.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:m(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;n.blocked.includes(o)||n.blocked.push(o);const a=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return a.code="EGRESS_POLICY",a},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=n,e===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function x(e={},t=process.env,n=process.platform,r=process.arch){const u=[],s=(a,p,{when:d="always",off:w=null,local:v=!1,data:k=""}={})=>{a&&u.push({host:a,purpose:p,when:d,off:w,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("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"}),s("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||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:S(e.link||{}).relay;if(c){const a=new URL(c).host;s(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let a=l;try{a=new URL(l).host}catch{}s(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"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(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{}s(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 i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",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,p]of Object.entries(i)){const d=e.capabilities?.[a];if(!d?.url||d.provider==="embedded")continue;let w=d.url;try{w=new URL(d.url).host}catch{}s(w,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:m(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(f(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:m(f(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const a=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function O(e,{ledger:t=P(),version:n="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=x(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(a=>a.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function _(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 n of e.observed||[])t.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const n of e.declared||[])t.push(` ${n.local?"[local] ":""}${n.host}`),t.push(` ${n.purpose}`),t.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&t.push(` sends: ${n.data}`);if(e.certificates){const n=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const n of e.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";t.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{A as createEgressLedger,x as declaredEgress,O as egressAudit,P as egressLedger,_ as formatAudit,N as installEgressLedger};
@@ -0,0 +1 @@
1
+ import{randomUUID as D}from"node:crypto";import{PERMISSION_TIMEOUT_MS as I,createPermissionDesk as M}from"@chatpanel/events/agent-permission.js";import{partnerDecisionForDesk as P}from"@chatpanel/events/link-scopes.js";function x({timeoutMs:d=I,now:f=()=>Date.now(),newId:g=()=>D().slice(0,12),log:y=()=>{}}={}){const r=new Map,s=new Set,i=new Map,S=M({memory:i}),l=()=>{const e=p();for(const t of s)try{t(e)}catch{}};function p(){return[...r.values()].map(e=>e.entry).sort((e,t)=>e.createdAt-t.createdAt)}function o(e,t){const n=r.get(e);return n?(r.delete(e),clearTimeout(n.timer),n.settle(P(t)),l(),!0):!1}function k(e,{partner:t,device:n,conversation:m,signal:v}={}){return S.ask(e,{convId:m,agentName:`${t||"A partner"}’s agent`,confirm:(w,{title:b})=>new Promise(A=>{const c=g(),a={id:c,partner:String(t||""),device:String(n||""),conversation:String(m||""),title:b,body:w,tool:String(e?.tool||""),createdAt:f(),expiresAt:f()+d},u=setTimeout(()=>o(c,"deny"),d);u.unref?.(),r.set(c,{entry:a,settle:A,timer:u}),v?.addEventListener?.("abort",()=>o(c,"deny"),{once:!0}),y(`link: ${a.partner}’s agent asks to use ${a.tool||"a tool"} — waiting for the owner`),l()})})}return{ask:k,list:p,answer:(e,t)=>o(String(e||""),t),cancelDevice(e){for(const[t,n]of[...r])n.entry.device===String(e)&&o(t,"deny");for(const t of[...i.keys()])String(t).startsWith(`partner.${e}.`)&&i.delete(t)},forget(e){i.delete(e)},subscribe(e){return s.add(e),()=>s.delete(e)},stop(){for(const e of[...r.keys()])o(e,"deny");s.clear()}}}export{x as createApprovalInbox};
@@ -0,0 +1,13 @@
1
+ const $=["usage: chatpanel-gateway link [list]"," chatpanel-gateway link pair --partner <name> [--scopes models,chat[,agents[,files]]] [--route link|relay|tailscale|cloudflare] [--relay <url>] [--folder <path, where its agents work>] [--yes]"," chatpanel-gateway link revoke <device id>"," chatpanel-gateway link approvals"," chatpanel-gateway link approve <id> [--for once|action|all] | link deny <id>"," chatpanel-gateway link route <link|relay|tailscale|cloudflare> [--relay <url>] [--gw <https tunnel address>] [--no-fallback]"].join(`
2
+ `);function g(t){const l={_:[]};for(let p=0;p<t.length;p++){const n=t[p];if(n==="--yes"||n==="-y")l.yes=!0;else if(n==="--no-fallback")l.fallback=!1;else if(n.startsWith("--")){const[h,i]=n.slice(2).split("=",2);l[h]=i!==void 0?i:t[++p]}else l._.push(n)}return l}const d=t=>t?new Date(t).toISOString().replace("T"," ").slice(0,16):"never";function w(t){return t.kind==="partner"?[` ${t.id} partner:${t.partner?.name||t.name} ${t.online?"online":"offline"} last seen ${d(t.lastSeen)}`,` scopes: ${(t.scopes||[]).join(", ")||"none"} · agents: ${(t.scopes||[]).includes("agents")?`yes${t.folder?`, in ${t.folder}`:""}`:"no"} · route: ${t.route||"?"}${t.host?` via ${t.host}`:""}${t.routeClosed?" — CLOSED: the gateway’s route moved off this tunnel; pair it again":""}`]:[` ${t.id} phone:${t.name} ${t.online?`online${t.via?` (${t.via})`:""}`:"offline"} last seen ${d(t.lastSeen)} · follows the gateway’s route`]}async function v(t,{call:l,ask:p=null,out:n=console.log,err:h=console.error}){const i=g(t),c=i._[0]||"list",s=r=>(h(r),1),u=r=>r.json?.error?.message||r.json?.error||`HTTP ${r.status}`;if(c==="list"){const r=await l("GET","/v1/link");if(r.status!==200)return s(`link: ${u(r)}`);const e=r.json;if(!e.enabled)return n("ChatPanel Link is off on this gateway (link.enabled: false)."),0;n(`route: ${e.route}${e.tunnel?` (tunnel ${new URL(e.tunnel).host})`:""}${e.relay?`${e.tunnel?", fallback":""} relay ${new URL(e.relay).host}`:""}`),e.devices?.length||n("no devices paired — nothing can reach this gateway over Link.");for(const a of e.devices||[])for(const o of w(a))n(o);return e.partnerPairing&&n(`a partner code for ${e.partnerPairing.partner?.name} is waiting (expires ${d(e.partnerPairing.expiresAt)})`),0}if(c==="pair"){if(!i.partner||i.partner===!0)return s(`link pair: name the partner server (--partner <name>). A phone pairs from Settings › Link › Phones; a server can also be connected from Settings › Link › Servers.
3
+ ${$}`);const r={kind:"partner",partner:{name:String(i.partner)},...i.scopes?{scopes:String(i.scopes)}:{},...i.route?{route:String(i.route)}:{},...i.relay?{relay:String(i.relay)}:{},...i.folder&&i.folder!==!0?{folder:String(i.folder)}:{}},e=await l("POST","/v1/link/pair",r);if(e.status===404)return s("link pair: this gateway predates partner devices (0.89.0) — update and restart it");if(e.status!==200||!e.json?.preview)return s(`link pair: ${u(e)}`);for(const o of e.json.preview.lines)n(o);if(!i.yes){if(!p)return s(`
4
+ Nothing was issued. Re-run with --yes to confirm (no terminal to ask in).`);if(!await p(`
5
+ Issue this code? [y/N] `))return n("Nothing was issued."),1}const a=await l("POST","/v1/link/pair",{...r,confirm:!0});return a.status!==200||!a.json?.code?s(`link pair: ${u(a)}`):(n(""),n(a.json.code),n(""),n(`One use, until ${d(a.json.expiresAt)}. Give it to ${a.json.partner.name} through a channel you trust; it pairs device ${a.json.room}.`),n(`Revoke any time: chatpanel-gateway link revoke ${a.json.room}`),0)}if(c==="revoke"||c==="remove"){const r=i._[1];if(!r)return s(`link revoke: which device? (\`chatpanel-gateway link\` lists them)
6
+ ${$}`);const e=await l("DELETE",`/v1/link/devices/${encodeURIComponent(r)}`);return e.status!==200?s(`link revoke: ${u(e)}`):(n(`Removed ${r}: its room is gone, its key forgotten, its connection closed.`),0)}if(c==="approvals"){const r=await l("GET","/v1/link/approvals");if(r.status!==200)return s(`link approvals: ${u(r)}`);const e=r.json?.pending||[];if(!e.length)return n("Nothing is waiting for your approval."),0;for(const a of e){n(` ${a.id} ${a.title}`);for(const o of String(a.body||"").split(`
7
+ `))n(` ${o}`);n(` chatpanel-gateway link approve ${a.id} [--for action|all] · link deny ${a.id} (until ${d(a.expiresAt)})`)}return 0}if(c==="approve"||c==="deny"){const r=i._[1];if(!r)return s(`link ${c}: which request? (\`chatpanel-gateway link approvals\` lists them)
8
+ ${$}`);const e=c==="deny"?null:String(i.for||"once"),a=c==="deny"?"deny":e==="once"?"allow":e==="action"?"allow_action":e==="all"?"allow_all":null;if(!a)return s(`link approve: --for once, action or all
9
+ ${$}`);const o=await l("POST",`/v1/link/approvals/${encodeURIComponent(r)}`,{decision:a});return o.status!==200?s(`link ${c}: ${u(o)}`):(n(a==="deny"?"Denied — the agent is told no.":a==="allow"?"Allowed, this once.":a==="allow_action"?"Allowed for the rest of this conversation.":"Everything is allowed for the rest of this conversation."),0)}if(c==="route"){const r=i._[1];if(!r)return s(`link route: which one?
10
+ ${$}`);const e=r==="relay"?i.relay:r==="tailscale"||r==="cloudflare"?i.gw:"",a=await l("POST","/v1/link/route",{route:r,url:e?String(e):"",fallback:i.fallback!==!1});if(a.status!==200)return s(`link route: ${u(a)}`);const o=a.json;n(`route: ${o.route}${o.tunnel?` — devices reach this computer at ${new URL(o.tunnel).host}`:""}${o.relay?`${o.tunnel?"; fallback":" —"} relay ${new URL(o.relay).host}`:""}`);for(const f of o.setup?.commands||[])n(` $ ${f}`);o.setup?.config&&n(o.setup.config.split(`
11
+ `).map(f=>` ${f}`).join(`
12
+ `));for(const f of o.setup?.notes||[])n(` ${f}`);const k=(o.devices||[]).filter(f=>f.kind==="partner"&&(f.routeClosed||f.route!==o.route));for(const f of k)n(` partner:${f.partner?.name} stays on its own route (${f.route}${f.routeClosed?", now closed":""}) — pair it again to move it.`);return 0}return s(`link: unknown command "${c}"
13
+ ${$}`)}export{v as linkCommand};
@@ -0,0 +1 @@
1
+ import{lstatSync as a,mkdirSync as y,readdirSync as S,renameSync as w,rmSync as k,unlinkSync as F,writeFileSync as g,createReadStream as $,chmodSync as b}from"node:fs";import{join as u,dirname as h,sep as x,resolve as d}from"node:path";import{randomUUID as z}from"node:crypto";import{partnerMayHold as M,checkPartnerFileText as P}from"@chatpanel/events/link-scopes.js";const l=(n,t=400)=>Object.assign(new Error(n),{status:t}),p=5e3;function f(n,t){const r=d(n),e=d(r,...String(t||"").split("/").filter(Boolean));if(e!==r&&!e.startsWith(r+x))throw l("outside the partner’s folder",403);let i=r;for(const s of String(t||"").split("/").filter(Boolean)){i=u(i,s);let o=null;try{o=a(i)}catch{break}if(o.isSymbolicLink())throw l(`${t}: a link in the folder is never followed`,403)}return e}function T(n,t=""){const r=[],e=i=>{if(r.length>=p)return;let s=[];try{s=S(f(n,i),{withFileTypes:!0})}catch{return}for(const o of s){if(r.length>=p)return;const c=i?`${i}/${o.name}`:o.name;if(!o.isSymbolicLink()){if(o.isDirectory()){(["data",".claude",".claude/skills",".claude/agents",".agents",".agents/skills"].includes(c)||/^(data|\.claude\/skills|\.agents\/skills)\//.test(c))&&e(c);continue}if(!(!o.isFile()||!M(c)))try{const m=a(u(n,...c.split("/")));r.push({path:c,size:m.size,modifiedAt:Math.round(m.mtimeMs)})}catch{}}}};return e(t),r.sort((i,s)=>i.path.localeCompare(s.path))}function j(n,t,r){/\.md$/i.test(t)&&P(t,Buffer.from(r).toString("utf8"));const e=f(n,t);y(h(e),{recursive:!0,mode:448}),f(n,t);try{if(a(e).isDirectory())throw l(`${t} is a folder`)}catch(o){if(o.status)throw o}const i=u(h(e),`.partner-${z().slice(0,8)}.tmp`);g(i,r,{mode:384});try{b(i,384)}catch{}try{w(i,e)}catch(o){throw k(i,{force:!0}),o}const s=a(e);return{path:t,size:s.size,modifiedAt:Math.round(s.mtimeMs)}}function D(n,t){const r=f(n,t);let e;try{e=a(r)}catch{throw l(`${t}: no such file`,404)}if(!e.isFile())throw l(`${t}: not a file`,404);return{size:e.size,stream:$(r)}}function E(n,t){const r=f(n,t);let e;try{e=a(r)}catch{return!1}if(!e.isFile())throw l(`${t}: not a file`);return F(r),!0}export{f as insideFolder,T as listPartnerFiles,D as readPartnerFile,E as removePartnerFile,j as writePartnerFile};
package/src/link-host.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as fe,writeFileSync as me,renameSync as ye,mkdirSync as he,chmodSync as ge}from"node:fs";import{dirname as ke,join as we}from"node:path";import X from"node:os";import{createLinkEndpoint as Se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Ee}from"@chatpanel/events/link-noise.js";import{pairingUri as Te,admissionToken as q,admissionVerifier as j,toB64url as O,fromB64url as J,coalesceChunks as ve}from"@chatpanel/events/link-protocol.js";import{linkPaths as ee,LINK_ROUTES as _e,LINK_TUNNEL_ROOM_PATH as be,tunnelSetup as $e}from"@chatpanel/events/link-routes.js";import{timingSafeEqual as Ae}from"node:crypto";import{acceptWebSocket as Ne,refuseUpgrade as H}from"./ws-accept.js";import{qrSvg as Le}from"@chatpanel/events/qr.js";import{verifyEntitlement as Pe,licenseFromPayload as xe,can as Ke,FEATURE_TIER as te}from"@chatpanel/events/entitlement.js";const qe="https://link.chatpanel.net",ne=10*6e4,Oe=3e4,G=[1e3,2e3,5e3,1e4,3e4,6e4],Re=30,R="chatpanel-link.v1",Ue=/(^|\n): ?ping\n\n/g,Ie=4,Ce=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],Me=u=>Ce.some(p=>p.test(String(u||""))),oe="x-chatpanel-entitlement",re="x-chatpanel-install",ae=(u,p)=>{for(const[h,v]of Object.entries(u||{}))if(h.toLowerCase()===p)return String(v||"");return""};async function Be(u,{now:p=Date.now()}={}){if(!te.link||te.link==="free")return!1;const h=ae(u,oe),v=ae(u,re);if(!h||!v)return!1;const N=await Pe(h,v,{now:p});return!!N&&Ke(xe(N,{at:p}),"link",0,p)}function De(){return we(X.homedir(),".chatpanel","link.json")}function Fe(u){try{const p=JSON.parse(fe(u,"utf8"));return{v:1,key:p.key||null,rooms:Array.isArray(p.rooms)?p.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function se(u,p){he(ke(u),{recursive:!0});const h=`${u}.tmp`;me(h,JSON.stringify(p,null,2),{mode:384});try{ge(h,384)}catch{}ye(h,u)}function et({settings:u={},relay:p=null,port:h=4320,name:v=X.hostname(),dispatch:N,path:U=De(),fetch:ie=globalThis.fetch,WebSocket:ce=globalThis.WebSocket,now:g=()=>Date.now(),random:z=w=>globalThis.crypto.getRandomValues(new Uint8Array(w)),crypto:I=Ee(),log:L=()=>{},mayLink:le=Be}={}){const w=p?new URL(p).origin:null;if(w&&!/^https:/.test(w)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(w))throw new Error("link: the relay must be https");const W=t=>{const e=ee(t);return w&&e.relay?{...e,relay:w}:e};let c=W(u);c.problem&&L(`link: ${c.problem} — using ChatPanel Link`);let l=Fe(U);const pe=w||ee({relayUrl:u?.relayUrl}).relay;for(const t of l.rooms)t.relay===void 0&&(t.relay=pe);const y=new Map,S=new Map;let E=null;async function b(){return E||(l.key?E=await I.keyPairFromPrivate(J(l.key)):(E=await I.generateKeyPair(),l.key=O(E.raw),se(U,l)),E)}const $=t=>l.rooms.find(e=>e.room===t)||null,C=()=>se(U,l),A=t=>!!t.relay&&t.relay===c.relay,M=async(t,e,n,o,s)=>{try{return await ie(`${s}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(r){const a=r?.cause?.code||"",f=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:r?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(s).host}: ${f}`)}};async function ue(t,e,n){if(t.lastSeen=g(),!Me(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await le(e.headers,{now:g()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:c.route,relay:A(t)?t.relay:null,gw:c.tunnel})),n.end();const o={};for(const[d,m]of Object.entries(e.headers||{}))d.toLowerCase()!==oe&&d.toLowerCase()!==re&&(o[d]=m);const s=e.method==="GET"?void 0:await e.body.bytes(),r=await N({method:e.method,path:e.path,headers:o,body:s,device:t.room}),a={};r.headers?.forEach?.((d,m)=>{a[m]=d});let f=!1;try{await n.head(r.status,a)}catch{f=!0}if(r.body){const d=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const m of ve(de(r.body,d))){if(n.cancelled)break;if(!f)try{await n.write(m)}catch{f=!0}}}if(!f)return n.end()}async function*de(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const s=new TextDecoder().decode(o);if(s.includes(": ping")){const r=s.replace(Ue,"$1");if(!r)continue;o=new TextEncoder().encode(r)}}yield o}}function Y(t,e,n,o,s){return Se({side:"laptop",keyPair:e,crypto:I,psk:t.phoneKey?null:J(n.psk),peerKey:t.phoneKey?J(t.phoneKey):null,sendBytes:s,onRequest:(r,a)=>ue(t,r,a),onSession:(r,a)=>{o.online=!0,o.attempts=0,t.lastSeen=g(),a.paired&&(t.phoneKey=O(a.peerKey),t.name=a.name||t.name||"Phone",t.pairedAt=g(),t.pending=null,L(`link: paired ${t.name}`)),C()},onEnd:()=>{o.online=!1}})}async function P(t){if(!A(t))return;const e=y.get(t.room)||{attempts:0,stopped:!1,online:!1};if(y.set(t.room,e),e.stopped)return;const n=await b(),o=t.pending&&t.pending.expiresAt>g()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const s=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let r;try{r=new ce(s,[R,t.token])}catch(a){Z(t,a?.message);return}r.binaryType="arraybuffer",e.ws=r,e.endpoint=Y(t,n,o,e,a=>{try{r.send(a)}catch{}}),r.onopen=()=>{if(e.stopped||y.get(t.room)!==e){try{r.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},Oe),e.keepalive.unref?.()},r.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),r.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){F(t.room,"the relay removed the room");return}Z(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?Ie:null)}},r.onerror=()=>{}}function Z(t,e,n=null){const o=y.get(t.room);if(!o||o.stopped)return;const s=n??Math.min(o.attempts,G.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>P(t),G[s]),o.timer.unref?.(),L(`link: ${e}; again in ${G[s]/1e3}s`)}function B(t){const e=y.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}y.delete(t)}}function x(t,e=1e3,n="stopped"){const o=S.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=$(t);n&&!n.phoneKey&&n.relay&&M(t,"DELETE",n.token,null,n.relay).catch(()=>{}),F(t,e)}function F(t,e){B(t),x(t,4004,"room removed"),S.delete(t),l.rooms=l.rooms.filter(n=>n.room!==t),C(),L(`link: ${e}`)}return{async pair({name:t=v}={}){const e=await b(),n=z(16),o=z(32),s=O(n),r=await q(o,n,"laptop"),a=await q(o,n,"phone"),f=await j(a);if(c.relay){const i=await M(s,"PUT",r,{laptop:await j(r),phone:f},c.relay);if(i.status!==200&&i.status!==201)throw new Error(`link: the relay refused the room (${i.status})`)}for(const i of l.rooms.filter(V=>!V.phoneKey))D(i.room,"a new pairing code replaced this one");const d=g()+ne,m={room:s,token:r,relay:c.relay,phoneVerifier:f,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:d}};l.rooms.push(m),C();const _=Te({relay:c.relay,gw:c.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return P(m),setTimeout(()=>{const i=$(s);i&&!i.phoneKey&&D(s,"the pairing code expired")},ne+1e3).unref?.(),{uri:_,svg:Le(_,{ecc:"M"}),expiresAt:d,room:s}},status(){const t=e=>!!y.get(e.room)?.online||!!S.get(e.room)?.online;return{route:c.route,relay:c.relay,tunnel:c.tunnel,...c.problem?{problem:c.problem}:{},routes:_e,setup:$e(c.route,{port:h,url:c.tunnel||""}),devices:l.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),via:S.get(e.room)?.online?"tunnel":y.get(e.room)?.online?"relay":null,...e.relay&&!A(e)?{staleRelay:e.relay}:{},...c.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:l.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>g()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null}},async applySettings(t={}){c=W(t);for(const e of[...y.keys()]){const n=$(e);(!n||!A(n))&&B(e)}if(!c.tunnel)for(const e of[...S.keys()])x(e,1001,"the tunnel was switched off");l.rooms.length&&await b();for(const e of l.rooms)A(e)&&!y.has(e.room)&&P(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(be.length));if(!c.tunnel)return H(e,404,"not found");const s=$(o),r=String(t.headers["sec-websocket-protocol"]||"").split(",").map(k=>k.trim()).filter(Boolean),f=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(r.length===2&&r.includes(R)?r.find(k=>k!==R):null),d=s&&!s.phoneKey&&s.pending?.expiresAt>g()?s.pending:null,m=f?Buffer.from(await j(f)):null,_=s?.phoneVerifier?Buffer.from(s.phoneVerifier):null;if(!s||!s.phoneKey&&!d||!m||!_||m.length!==_.length||!Ae(m,_))return H(e,403,"not admitted");const i=S.get(o)||{connects:[]};if(S.set(o,i),i.connects=i.connects.filter(k=>g()-k<6e4),i.connects.length>=Re)return H(e,429,"too many connects");i.connects.push(g());const V=await b(),T=Ne(t,e,n,{protocol:R});if(!T)return;x(o,4001,"replaced"),i.ws=T,i.online=!1;const K=Y(s,V,d,i,k=>{try{T.send(k)}catch{}});i.endpoint=K,T.onmessage=k=>{typeof k.data!="string"&&K.onBinary(new Uint8Array(k.data))},T.onclose=()=>{K.close("socket closed"),i.ws===T&&(i.ws=null,i.endpoint=null,i.online=!1)};const Q=JSON.stringify({t:"peer",up:!0});K.onText(Q),T.send(Q)},async remove(t){const e=$(t);if(!e)return!1;if(e.relay)try{await M(t,"DELETE",e.token,null,e.relay)}catch{}return F(t,"removed"),!0},async start(){if(l.rooms.length){await b();for(const t of l.rooms)P(t)}},stop(){for(const t of[...y.keys()])B(t);for(const t of[...S.keys()])x(t,1001,"going away")},get publicKey(){return E?.publicKey||null}}}export{Ce as COMPANION_PATHS,qe as DEFAULT_RELAY,oe as ENTITLEMENT_HEADER,re as INSTALL_HEADER,ne as PAIRING_TTL_MS,Me as companionMay,et as createLinkHost,De as defaultLinkPath,Be as phoneMayLink};
1
+ import{readFileSync as Oe,writeFileSync as Re,renameSync as Ue,mkdirSync as ee,chmodSync as Ce}from"node:fs";import{dirname as J,join as ue,resolve as de,sep as Ie}from"node:path";import te from"node:os";import{createLinkEndpoint as De}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Fe}from"@chatpanel/events/link-noise.js";import{pairingUri as fe,pairingCode as Me,admissionToken as G,admissionVerifier as F,toB64url as O,fromB64url as ne,coalesceChunks as je}from"@chatpanel/events/link-protocol.js";import{linkPaths as me,linkRoute as z,checkLinkRoute as Be,DEFAULT_LINK_RELAY as Ve,LINK_ROUTES as he,LINK_TUNNEL_ROOM_PATH as He,tunnelSetup as Je}from"@chatpanel/events/link-routes.js";import{linkDeviceKind as M,partnerMay as Ge,partnerHeaders as ze,withoutLinkMarks as We,linkMarkHeaders as Ye,checkPartnerName as Qe,checkPartnerScopes as Ze,describePartnerAccess as Xe,checkPartnerFolder as qe,partnerFolderSlug as et}from"@chatpanel/events/link-scopes.js";import{timingSafeEqual as tt}from"node:crypto";import{acceptWebSocket as nt,refuseUpgrade as oe}from"./ws-accept.js";import{qrSvg as ot}from"@chatpanel/events/qr.js";import{verifyEntitlement as rt,licenseFromPayload as at,can as st,FEATURE_TIER as ye}from"@chatpanel/events/entitlement.js";const bt="https://link.chatpanel.net",W=10*6e4,it=3e4,re=[1e3,2e3,5e3,1e4,3e4,6e4],lt=30,Y="chatpanel-link.v1",ct=/(^|\n): ?ping\n\n/g,pt=4,ut=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],dt=c=>ut.some(i=>i.test(String(c||""))),ge="x-chatpanel-entitlement",we="x-chatpanel-install",ke=(c,i)=>{for(const[g,k]of Object.entries(c||{}))if(g.toLowerCase()===i)return String(k||"");return""};async function Ee(c,{now:i=Date.now()}={}){if(!ye.link||ye.link==="free")return!1;const g=ke(c,ge),k=ke(c,we);if(!g||!k)return!1;const N=await rt(g,k,{now:i});return!!N&&st(at(N,{at:i}),"link",0,i)}const ft=!1;async function mt(c,i,{now:g=Date.now(),phoneCheck:k=Ee,ownerIsPro:N=async()=>!1}={}){return M(c)==="partner"?ft?!!await N():!0:k(i?.headers||{},{now:g})}const L=c=>Object.assign(new Error(c),{code:"bad_partner"}),R=c=>{try{return new URL(c).host}catch{return""}};function Lt(c=ae()){return Se(c).rooms.filter(i=>M(i)==="partner"&&i.phoneKey).map(i=>({id:i.room,kind:"partner",name:i.name,partner:{name:i.partner?.name||i.name},scopes:i.scopes||[],route:i.route||null,host:R(i.relay||i.gw||""),pairedAt:i.pairedAt||null,lastSeen:i.lastSeen||null,...(i.scopes||[]).includes("agents")?{folder:Q(i,c)}:{}}))}function Q(c,i=ae()){return c?.folder||ue(J(i),"partners",et(c?.partner?.name||c?.name))}const ht=(c,i)=>{const g=de(c),k=de(i);return g===k||g.startsWith(`${k}${Ie}`)};function ae(){return ue(te.homedir(),".chatpanel","link.json")}function Se(c){try{const i=JSON.parse(Oe(c,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function ve(c,i){ee(J(c),{recursive:!0});const g=`${c}.tmp`;Re(g,JSON.stringify(i,null,2),{mode:384});try{Ce(g,384)}catch{}Ue(g,c)}function Nt({settings:c={},relay:i=null,port:g=4320,name:k=te.hostname(),dispatch:N,path:T=ae(),fetch:$e=globalThis.fetch,WebSocket:Te=globalThis.WebSocket,now:w=()=>Date.now(),random:j=S=>globalThis.crypto.getRandomValues(new Uint8Array(S)),crypto:Z=Fe(),log:U=S=>{},mayLink:Pe=Ee,ownerIsPro:Ae=async()=>!1,home:_e=te.homedir(),confined:be=process.env.CHATPANEL_CONFINED==="1"}={}){const S=i?new URL(i).origin:null;if(S&&!/^https:/.test(S)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(S))throw new Error("link: the relay must be https");const se=t=>{const e=me(t);return S&&e.relay?{...e,relay:S}:e};let l=se(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let u=Se(T);const Le=S||me({relayUrl:c?.relayUrl}).relay;for(const t of u.rooms)t.relay===void 0&&(t.relay=Le);const E=new Map,P=new Map;let A=null;async function x(){return A||(u.key?A=await Z.keyPairFromPrivate(ne(u.key)):(A=await Z.generateKeyPair(),u.key=O(A.raw),ve(T,u)),A)}const _=t=>u.rooms.find(e=>e.room===t)||null,B=()=>ve(T,u),C=t=>M(t)==="partner"?!!t.relay:!!t.relay&&t.relay===l.relay,$=t=>M(t)==="partner",V=async(t,e,n,o,r)=>{try{return await $e(`${r}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(s){const a=s?.cause?.code||"",d=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(r).host}: ${d}`)}};async function Ne(t,e,n){t.lastSeen=w();const o=$(t);if(o?!Ge(t.scopes,e):!dt(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?`link: partner "${t.name}" may not call ${e.method} ${e.path.split("?")[0]} — its scopes are ${(t.scopes||[]).join(", ")||"none"}`:"link: a paired phone may not call this",type:"forbidden",...o?{code:"link_scope"}:{}}})),n.end();if(!await mt(t,e,{now:w(),phoneCheck:Pe,ownerIsPro:Ae}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?"ChatPanel Link partner devices need ChatPanel Pro on this computer":"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:l.route,relay:C(t)?t.relay:null,gw:l.tunnel})),n.end();let r={};if(o)r=ze(e.headers);else for(const[m,y]of Object.entries(e.headers||{}))m.toLowerCase()!==ge&&m.toLowerCase()!==we&&(r[m]=y);r={...We(r),...Ye(t)};const s=e.method==="GET"?void 0:await e.body.bytes(),a=await N({method:e.method,path:e.path,headers:r,body:s,device:t.room}),d={};a.headers?.forEach?.((m,y)=>{d[y]=m});let f=!1;try{await n.head(a.status,d)}catch{f=!0}if(a.body){const m=/event-stream/.test(String(a.headers?.get?.("content-type")||""));for await(const y of je(xe(a.body,m))){if(n.cancelled)break;if(!f)try{await n.write(y)}catch{f=!0}}}if(!f)return n.end()}async function*xe(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const r=new TextDecoder().decode(o);if(r.includes(": ping")){const s=r.replace(ct,"$1");if(!s)continue;o=new TextEncoder().encode(s)}}yield o}}function ie(t,e,n,o,r){return De({side:"laptop",keyPair:e,crypto:Z,psk:t.phoneKey?null:ne(n.psk),peerKey:t.phoneKey?ne(t.phoneKey):null,sendBytes:r,onRequest:(s,a)=>Ne(t,s,a),onSession:(s,a)=>{o.online=!0,o.attempts=0,t.lastSeen=w(),a.paired&&(t.phoneKey=O(a.peerKey),$(t)||(t.name=a.name||t.name||"Phone"),t.pairedAt=w(),t.pending=null,U(`link: paired ${t.name}`)),B()},onEnd:()=>{o.online=!1}})}async function I(t){if(!C(t))return;const e=E.get(t.room)||{attempts:0,stopped:!1,online:!1};if(E.set(t.room,e),e.stopped)return;const n=await x(),o=t.pending&&t.pending.expiresAt>w()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const r=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let s;try{s=new Te(r,[Y,t.token])}catch(a){le(t,a?.message);return}s.binaryType="arraybuffer",e.ws=s,e.endpoint=ie(t,n,o,e,a=>{try{s.send(a)}catch{}}),s.onopen=()=>{if(e.stopped||E.get(t.room)!==e){try{s.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{s.send("ping")}catch{}},it),e.keepalive.unref?.()},s.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),s.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){q(t.room,"the relay removed the room");return}le(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?pt:null)}},s.onerror=()=>{}}function le(t,e,n=null){const o=E.get(t.room);if(!o||o.stopped)return;const r=n??Math.min(o.attempts,re.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>I(t),re[r]),o.timer.unref?.(),U(`link: ${e}; again in ${re[r]/1e3}s`)}function X(t){const e=E.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}E.delete(t)}}function H(t,e=1e3,n="stopped"){const o=P.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=_(t);n&&!n.phoneKey&&n.relay&&V(t,"DELETE",n.token,null,n.relay).catch(()=>{}),q(t,e)}function q(t,e){X(t),H(t,4004,"room removed"),P.delete(t),u.rooms=u.rooms.filter(n=>n.room!==t),B(),U(`link: ${e}`)}function Ke({route:t=null,relay:e=""}={}){const n=t||(e?"relay":l.route);if(!z(n))throw L(`unknown route "${n}" — one of ${he.map(r=>r.id).join(", ")}`);if(z(n).kind==="tunnel"){if(l.route!==n||!l.tunnel)throw L(`this gateway's ${z(n).label} door is not open — set it as the route first (chatpanel-gateway link route ${n} --gw <https address>), then pair`);return{route:n,relay:null,gw:l.tunnel,host:R(l.tunnel)}}if(n==="relay"){const r=e||(l.route==="relay"?l.relay:"");if(!r)throw L('the relay route needs the relay’s https address (--relay <url>), or "Your own relay" set as the route');let s;try{s=Be({id:"relay",url:r})}catch(a){throw L(a.message)}return{route:s.id,relay:s.url,gw:null,host:R(s.url)}}const o=S||Ve;return{route:"link",relay:o,gw:null,host:R(o)}}function ce({partner:t,scopes:e,route:n=null,relay:o="",folder:r=""}={}){const s=Qe(t),a=Ze(e),d=Ke({route:n,relay:o});let f="";if(a.includes("agents")){try{f=String(r||"").trim()?qe(r,{name:s,home:_e}):Q({partner:{name:s}},T)}catch(m){throw L(m.message)}if(be&&!ht(f,J(T)))throw L(`this gateway runs confined and writes only ${J(T)} — leave the folder empty (the default is inside it), or run the gateway unconfined to use ${f}`)}return{via:d,folder:f,preview:Xe({partner:s,scopes:a,route:d.route,host:d.host,folder:f})}}return{previewPartner(t={}){return ce(t).preview},partnerFolderOf(t){const e=_(t);if(!e||!$(e)||!e.phoneKey||!(e.scopes||[]).includes("agents"))return null;const n=Q(e,T);try{ee(n,{recursive:!0,mode:448})}catch{return null}return n},async pairPartner(t={}){const{via:e,preview:n,folder:o}=ce(t);if(o)try{ee(o,{recursive:!0,mode:448})}catch(h){throw L(`could not create ${o}: ${h.message}`)}const r=await x(),s=j(16),a=j(32),d=O(s),f=await G(a,s,"laptop"),m=await F(await G(a,s,"phone"));if(e.relay){const h=await V(d,"PUT",f,{laptop:await F(f),phone:m},e.relay);if(h.status!==200&&h.status!==201)throw new Error(`link: the relay refused the room (${h.status})`)}for(const h of u.rooms.filter(b=>!b.phoneKey&&$(b)))D(h.room,"a new partner code replaced this one");const y=w()+W,p={room:d,token:f,relay:e.relay,phoneVerifier:m,phoneKey:null,name:n.partner,pairedAt:null,lastSeen:null,pending:{psk:O(a),expiresAt:y},kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,...o?{folder:o}:{}};u.rooms.push(p),B();const K=Me({uri:fe({relay:e.relay,gw:e.gw,room:s,key:r.publicKey,secret:a,name:""}),expiresAt:y,route:e.route});return I(p),setTimeout(()=>{const h=_(d);h&&!h.phoneKey&&D(d,"the partner code expired")},W+1e3).unref?.(),U(`link: partner code issued for ${n.partner} (${n.scopes.join(", ")}; route ${e.route} via ${e.host})`),{code:K,expiresAt:y,room:d,kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,host:e.host,...o?{folder:o}:{},preview:n}},async pair({name:t=k}={}){const e=await x(),n=j(16),o=j(32),r=O(n),s=await G(o,n,"laptop"),a=await G(o,n,"phone"),d=await F(a);if(l.relay){const p=await V(r,"PUT",s,{laptop:await F(s),phone:d},l.relay);if(p.status!==200&&p.status!==201)throw new Error(`link: the relay refused the room (${p.status})`)}for(const p of u.rooms.filter(K=>!K.phoneKey&&!$(K)))D(p.room,"a new pairing code replaced this one");const f=w()+W,m={room:r,token:s,relay:l.relay,phoneVerifier:d,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:f}};u.rooms.push(m),B();const y=fe({relay:l.relay,gw:l.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return I(m),setTimeout(()=>{const p=_(r);p&&!p.phoneKey&&D(r,"the pairing code expired")},W+1e3).unref?.(),{uri:y,svg:ot(y,{ecc:"M"}),expiresAt:f,room:r}},status(){const t=e=>!!E.get(e.room)?.online||!!P.get(e.room)?.online;return{route:l.route,relay:l.relay,tunnel:l.tunnel,...l.problem?{problem:l.problem}:{},routes:he,setup:Je(l.route,{port:g,url:l.tunnel||""}),devices:u.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,kind:M(e),name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),...$(e)?{partner:{name:e.partner?.name||e.name},scopes:e.scopes||[],route:e.route||null,host:R(e.relay||"")||R(e.route===l.route&&l.tunnel||""),...(e.scopes||[]).includes("agents")?{folder:Q(e,T)}:{},...e.route&&z(e.route)?.kind==="tunnel"&&e.route!==l.route?{routeClosed:!0}:{}}:{},via:P.get(e.room)?.online?"tunnel":E.get(e.room)?.online?"relay":null,...e.relay&&!C(e)?{staleRelay:e.relay}:{},...!$(e)&&l.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:u.rooms.filter(e=>!e.phoneKey&&!$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null,partnerPairing:u.rooms.filter(e=>!e.phoneKey&&$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,partner:{name:e.name},scopes:e.scopes||[],route:e.route||null}))[0]||null}},async applySettings(t={}){l=se(t);for(const e of[...E.keys()]){const n=_(e);(!n||!C(n))&&X(e)}if(!l.tunnel)for(const e of[...P.keys()])H(e,1001,"the tunnel was switched off");u.rooms.length&&await x();for(const e of u.rooms)C(e)&&!E.has(e.room)&&I(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(He.length));if(!l.tunnel)return oe(e,404,"not found");const r=_(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(v=>v.trim()).filter(Boolean),d=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(v=>v!==Y):null),f=r&&!r.phoneKey&&r.pending?.expiresAt>w()?r.pending:null,m=d?Buffer.from(await F(d)):null,y=r?.phoneVerifier?Buffer.from(r.phoneVerifier):null;if(!r||!r.phoneKey&&!f||!m||!y||m.length!==y.length||!tt(m,y))return oe(e,403,"not admitted");const p=P.get(o)||{connects:[]};if(P.set(o,p),p.connects=p.connects.filter(v=>w()-v<6e4),p.connects.length>=lt)return oe(e,429,"too many connects");p.connects.push(w());const K=await x(),h=nt(t,e,n,{protocol:Y});if(!h)return;H(o,4001,"replaced"),p.ws=h,p.online=!1;const b=ie(r,K,f,p,v=>{try{h.send(v)}catch{}});p.endpoint=b,h.onmessage=v=>{typeof v.data!="string"&&b.onBinary(new Uint8Array(v.data))},h.onclose=()=>{b.close("socket closed"),p.ws===h&&(p.ws=null,p.endpoint=null,p.online=!1)};const pe=JSON.stringify({t:"peer",up:!0});b.onText(pe),h.send(pe)},async remove(t){const e=_(t);if(!e)return!1;if(e.relay)try{await V(t,"DELETE",e.token,null,e.relay)}catch{}return q(t,"removed"),!0},async start(){if(u.rooms.length){await x();for(const t of u.rooms)I(t)}},stop(){for(const t of[...E.keys()])X(t);for(const t of[...P.keys()])H(t,1001,"going away")},get publicKey(){return A?.publicKey||null}}}export{ut as COMPANION_PATHS,bt as DEFAULT_RELAY,ge as ENTITLEMENT_HEADER,we as INSTALL_HEADER,W as PAIRING_TTL_MS,ft as PARTNER_DEVICES_REQUIRE_PRO,dt as companionMay,Nt as createLinkHost,ae as defaultLinkPath,mt as deviceMayLink,Lt as partnerDevicesOnDisk,Q as partnerFolderFor,Ee as phoneMayLink};