@chatpanel/gateway 0.87.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:t,systemCaWantedOnDisk:o}=await import("../src/system-ca.js");t({enabled:o()})}await import("@chatpanel/bridge/src/server.js")}else if(n==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(n==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(n==="tools"||n==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(n==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:c}=await import("../src/policy.js");try{const i=await t();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(o(i))}catch(i){throw i instanceof c&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(n==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:c}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:w}=await import("node:path"),g=await import("node:os"),p=c(),e=`http://127.0.0.1:${p.port||4320}`;let a=null,r=`no gateway running at ${e}`;try{const h=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(g.homedir(),".chatpanel","gateway-token"),"utf8").trim(),s=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(s.ok)a=await s.json();else if(s.status===404){const l=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);r=`the gateway running at ${e}${l?.version?` (${l.version})`:""} predates --audit (0.7.0) — restart it after updating`}else r=`the gateway at ${e} refused the audit (HTTP ${s.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js"),{systemCaWanted:s}=await import("../src/system-ca.js"),l=s(p);a={...t(p,{ledger:null,version:h,certificates:{on:!1,added:0,wanted:l,why:l?"no gateway is running; when one starts it adds this computer's list":"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"}}),observed:[]},console.log(`(${r}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:c}=await import("node:path"),i=await import("node:os"),g=`http://127.0.0.1:${t().port||4320}`,p=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||c(i.homedir(),".chatpanel","gateway-token");try{const e=o(p,"utf8").trim(),a=await fetch(`${g}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),r=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${g} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(r.error||`HTTP ${a.status}`);console.log(`Pairing code: ${r.display||r.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${g}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${p} — has the gateway started once?)`:""}`),process.exit(1)}}else if(n==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(n==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),c=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:c}),{dryRun:c}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:c,uninstallService:i,serviceReport:w,stopService:g,pathWithDir:p}=await import("../src/service.js");switch(n){case"--stop":g(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":{const e=await c({version:o,force:process.argv.includes("--force")}),a=e.health;if(e.newer){const r=a.managedBy&&a.managedBy!=="gateway"?` (run by the ${a.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${a.version} is already running at ${a.url}${r} — newer than this copy (v${o}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${o} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const r=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${a.version}) is the one answering right now; this install takes over at the next login`:"",h=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${a.version}: already running at ${a.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}${h}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${r}.`);let s=null;for(let l=0;l<30;l++){try{s=(await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),s?.version){const{staleBridgeCommands:l,staleBridgeLines:d}=await import("../src/service.js");for(const y of d(l({embedded:s.version}),{embedded:s.version}))console.log(y)}}else a.ok?(console.error(`ChatPanel Privacy Gateway: v${o} is registered to start at login, but v${a.version} still answers at ${a.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
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:
4
4
  ${e.errLog.split(`
5
- `).map(r=>` ${r}`).join(`
6
- `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:l=>console.error(l)}));s&&console.log(s)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&p(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await w());break;case void 0:await t();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${o}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
7
- `));break;default:console.error(`unknown option: ${n}
8
- Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
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(`
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)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.87.0",
3
+ "version": "0.88.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,8 +23,8 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
- "@chatpanel/bridge": "^0.44.2",
27
- "@chatpanel/events": "^0.354.0",
26
+ "@chatpanel/bridge": "^0.45.2",
27
+ "@chatpanel/events": "^0.356.1",
28
28
  "@chatpanel/pii": "^0.15.0",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
@@ -0,0 +1 @@
1
+ import{mirrorUrl as A}from"@chatpanel/events/registries.js";import{createHash as k}from"node:crypto";import{gunzipSync as b}from"node:zlib";import{mkdirSync as H,writeFileSync as j,renameSync as x,rmSync as P,chmodSync as B,existsSync as L}from"node:fs";import{join as d}from"node:path";import{homedir as S}from"node:os";import{readTar as N}from"./ort-native.js";import{APPLE_HELPER as u,APPLE_MIN_DARWIN as R,appleHelperDirs as _,darwinMajor as z}from"./apple-model.js";const t="@chatpanel/gateway",D=`package/native/darwin-arm64/${u}`;function M({home:e=S(),dirs:n=_({home:e}),exists:o=L}={}){for(const i of n){const a=d(i,u);if(o(a))return a}return""}function Y({platform:e=process.platform,arch:n=process.arch,release:o=""}={}){return e==="darwin"&&n==="arm64"&&z(o)>=R}async function q({home:e=S(),version:n,fetchImpl:o=fetch,registries:i={},onProgress:a=()=>{},found:w=M({home:e})}={}){if(w)return w;const y=async p=>{const h=A("npm",`https://registry.npmjs.org/${t}/${p}`,i),m=await o(h,{headers:{accept:"application/json"}});if(m.status===404)return null;if(!m.ok)throw new Error(`the npm registry answered ${m.status} for ${t}@${p}`);return m.json()},r=n&&await y(n)||await y("latest");if(!r?.dist?.tarball)throw new Error(`${t} is not on the npm registry this gateway uses`);const $=A("npm",r.dist.tarball,i);a({phase:"download",url:$,version:r.version});const l=await o($);if(!l.ok)throw new Error(`the npm registry answered ${l.status} for ${t}@${r.version}'s package`);const g=Buffer.from(await l.arrayBuffer()),E=/^sha512-(.+)$/.exec(String(r.dist.integrity||""))?.[1];if(!E)throw new Error(`${t}@${r.version} has no sha512 on the registry — not installing an unchecked helper`);if(k("sha512").update(g).digest("base64")!==E)throw new Error(`${t}@${r.version}: the download does not match the registry's checksum — nothing was installed`);let f=null;for(const p of N(Buffer.from(b(g)),h=>h===D))f=p.data;if(!f)throw new Error(`${t}@${r.version} carries no Apple helper (it is built into the package on Apple Silicon)`);const v=d(e,".chatpanel","bin");H(v,{recursive:!0,mode:448});const s=d(v,u),c=`${s}.incoming-${process.pid}`;P(c,{force:!0}),j(c,f,{mode:493});try{B(c,493)}catch{}return x(c,s),a({phase:"ready",path:s,version:r.version}),s}export{Y as appleHelperWanted,q as ensureAppleHelper,M as findAppleHelper};
@@ -1 +1 @@
1
- import{readdirSync as s}from"node:fs";import n from"node:path";import{fileURLToPath as l}from"node:url";const c="chatpanel-apple-model",A="apple-on-device",w=25,m="arm64-apple-macos26.0",p=n.dirname(l(import.meta.url));function x(t){const e=Number.parseInt(String(t||""),10);return Number.isFinite(e)?e:0}function P({home:t,execPath:e=process.execPath,moduleDir:o=p}={}){const i=[n.join(o,"..","native","darwin-arm64")];return/^node(\.exe)?$/i.test(n.basename(e||""))||i.push(n.dirname(e)),t&&i.push(n.join(t,".chatpanel","bin")),i}function d(t=p){const e=n.join(t,"..","native","apple-model");try{return s(e).filter(o=>o.endsWith(".swift")).sort().map(o=>n.join(e,o))}catch{return[]}}function a(t,e){return["-O","-target",m,"-o",t,...e]}function S({home:t,sources:e=d()}={}){const o="https://developer.apple.com/documentation/foundationmodels";if(!e.length||!t)return{command:"comes with the gateway from npm and the desktop app on Apple Silicon",steps:[],url:o,note:"Needs macOS 26 on Apple Silicon with Apple Intelligence turned on (System Settings › Apple Intelligence & Siri)."};const i=n.join(t,".chatpanel","bin"),r=n.join(i,c);return{command:`swiftc ${a(r,["native/apple-model/*.swift"]).join(" ")}`,steps:[["mkdir","-p",i],["swiftc",...a(r,e)]],url:o,note:"A source checkout: builds the helper with the Command Line Tools. Needs Apple Intelligence turned on."}}export{c as APPLE_HELPER,w as APPLE_MIN_DARWIN,A as APPLE_MODEL_ID,m as APPLE_SWIFT_TARGET,a as appleBuildArgs,P as appleHelperDirs,S as appleInstallDoor,d as appleSources,x as darwinMajor};
1
+ import{readdirSync as u,existsSync as d}from"node:fs";import n from"node:path";import{fileURLToPath as f}from"node:url";const h="chatpanel-apple-model",I="apple-on-device",S=25,g="arm64-apple-macos26.0",p=n.dirname(f(import.meta.url));function P(e){const t=Number.parseInt(String(e||""),10);return Number.isFinite(t)?t:0}function w({home:e,execPath:t=process.execPath,moduleDir:o=p}={}){const i=[n.join(o,"..","native","darwin-arm64")];return/^node(\.exe)?$/i.test(n.basename(t||""))||i.push(n.dirname(t)),e&&i.push(n.join(e,".chatpanel","bin")),i}function b(e=p){const t=n.join(e,"..","native","apple-model");try{return u(t).filter(o=>o.endsWith(".swift")).sort().map(o=>n.join(t,o))}catch{return[]}}function m(e,t){return["-O","-target",g,"-o",e,...t]}function j({execPath:e=process.execPath,moduleDir:t=p,exists:o=d}={}){if(!/^(node|bun)(\.exe)?$/i.test(n.basename(e||"")))return[e];const i=n.join(t,"..","bin","chatpanel-gateway.js");return o(i)?[e,i]:null}function $({home:e,sources:t=b(),self:o=j(),dirs:i=w({home:e})}={}){const r="https://developer.apple.com/documentation/foundationmodels",a="Needs macOS 26 on Apple Silicon with Apple Intelligence turned on (System Settings › Apple Intelligence & Siri).";if(!t.length||!e){const c=`\`${h}\` is not in this install — it was looked for in ${i.join(", ")}`;return!e||!o?{command:"chatpanel-gateway --fetch-apple-helper",steps:[],url:r,note:a,missing:`${c}. Run \`chatpanel-gateway --fetch-apple-helper\` to fetch it.`}:{command:"chatpanel-gateway --fetch-apple-helper",steps:[[...o,"--fetch-apple-helper"]],url:r,note:`Fetches the helper this gateway version ships with (about 200 KB, from the npm registry) into ${n.join(e,".chatpanel","bin")}. ${a}`,missing:`${c}. Click Install to fetch it, or run \`chatpanel-gateway --fetch-apple-helper\`.`}}const s=n.join(e,".chatpanel","bin"),l=n.join(s,h);return{command:`swiftc ${m(l,["native/apple-model/*.swift"]).join(" ")}`,steps:[["mkdir","-p",s],["swiftc",...m(l,t)]],url:r,note:"A source checkout: builds the helper with the Command Line Tools. Needs Apple Intelligence turned on."}}export{h as APPLE_HELPER,S as APPLE_MIN_DARWIN,I as APPLE_MODEL_ID,g as APPLE_SWIFT_TARGET,m as appleBuildArgs,w as appleHelperDirs,$ as appleInstallDoor,b as appleSources,P as darwinMajor,j as selfCommand};
@@ -1 +1 @@
1
- import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
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};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(a){const n=g(a);if(!n||!n.host)return;const o=`${n.scheme}://${n.host}:${n.port}`,l=e(),h=t.get(o);if(h){h.count+=1,h.lastAt=l;return}t.set(o,{host:n.host,port:n.port,scheme:n.scheme,local:w(n.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((a,n)=>a.local===n.local?n.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let y=null;function R(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=L();let n=t;a.setGate=d=>{n=d},a.blocked=[];const o=d=>{let r=null;try{r=g(d),a.record(d)}catch{}if(!n||!r?.host)return null;let u=!0;try{u=n(`${r.scheme}://${r.host}:${r.port}`,{local:w(r.host)})}catch{u=!0}if(u)return null;const s=`${r.host}:${r.port}`;a.blocked.includes(s)||a.blocked.push(s);const i=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},l=e.fetch;typeof l=="function"&&(e.fetch=function(r,u){const s=o(r);return s?Promise.reject(s):l.call(this,r,u)});const h=e.WebSocket;return typeof h=="function"&&(e.WebSocket=new Proxy(h,{construct(d,r,u){const s=o(r[0]);if(s)throw s;return Reflect.construct(d,r,u)}})),e.__chatpanelEgress=a,e===globalThis&&(y=a),a}function S(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function P(e={},t=process.env,a=process.platform){const n=[],o=(s,i,{when:c="always",off:f=null,local:b=!1,data:v=""}={})=>{s&&n.push({host:s,purpose:i,when:c,off:f,local:b,data:v})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const l=e.link?.enabled===!1?null:$(e.link||{}).relay;if(l){const s=new URL(l).host;o(s,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let s=h;try{s=new URL(h).host}catch{}o(s,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(s)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const s of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(s.api.host,`web search: ${s.api.name} (search API${s.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${s.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}o(s,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(s)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[s,i]of Object.entries(d)){const c=e.capabilities?.[s];if(!c?.url||c.provider==="embedded")continue;let f=c.url;try{f=new URL(c.url).host}catch{}o(f,`${i.what}${c.service?` (the ${c.service} container, started under Settings › Runtime)`:` (${c.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:c.service?`stop the ${c.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${i.data}${c.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[s,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&o(p(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:w(p(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const r=e.tts||{};if(r.provider==="openai"||r.provider==="elevenlabs"){const s=r.remote?.baseUrl?p(r.remote.baseUrl):r.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(s,`remote read-aloud voice (${r.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:r.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),n}function _(e,{ledger:t=S(),version:a="",startedAt:n=null,env:o=process.env,managed:l=null,certificates:h=null}={}){return{ok:!0,version:a,since:n?new Date(n).toISOString():null,...h?{certificates:h}:{},...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:P(e,o)}}function C(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,n])=>n===!0?a:`${a}=${n}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{L as createEgressLedger,P as declaredEgress,_ as egressAudit,S as egressLedger,C as formatAudit,R as installEgressLedger};
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 +1 @@
1
- const s="0.29.0",i=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm-cpu:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,i.cpu]:[i.cpu]}const y=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function L({exec:e,platform:t=process.platform,arch:n=process.arch}={}){const a=async(l,o)=>{try{const r=await e(l,o,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return t==="darwin"&&n==="arm64"?"apple":await a("nvidia-smi",["-L"])?"cuda":t==="linux"&&await a("rocm-smi",["--showid"])?"rocm":t==="linux"&&await a("sycl-ls",[])?"xpu":null}function x({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:a=null,vllmOnPath:l=!1,containerOnly:o=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&o?{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:y,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...l?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:a?n==="cuda"?{backend:"cuda",kind:"container",image:i.cuda,devices:m("cuda",a),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...a==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:n==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:i.rocm,devices:m("rocm",a),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:n==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:i.xpu,devices:m("xpu",a),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:a=!1}={}){const l=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"vulkan":"cpu",o=l==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":l==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${l.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:l,kind:"native",runner:"llama-server",install:r,why:o,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:l==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${l==="metal"?"Apple":l.toUpperCase()} GPU`,...a?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function k({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:a=()=>[]}={}){const l=Math.round(n()/1073741824),o=a().length||0;let r=Math.max(1,Math.floor(o/2))||1,c=r;if(t==="darwin"&&e){const p=async w=>{try{const b=await e("sysctl",["-n",w]),u=Number(String(b?.stdout||"").trim());return u>0?u:0}catch{return 0}},[d,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);d&&(r=d),c=g||r}else o&&(r=o,c=Math.min(o,8));return{ramGB:l,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function P({platform:e=process.platform,arch:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function U({platform:e=process.platform,arch:t=process.arch,osMajor:n=0,appleOnPath:a=!1,appleInstall:l=null}={}){const o={kind:"native",runner:"chatpanel-apple-model",...l?{install:l}:{}};return e==="darwin"&&t==="arm64"?n<25?{...o,backend:"none",why:"Apple’s on-device model needs macOS 26 or later."}:{...o,backend:"apple",for:"titles, topics, short answers — the system keeps the model, nothing stays loaded",speed:"quick for short text; the Mac decides when the model is in memory",notFor:"long chats (a 4,096-token window), images, tools",why:"Apple Silicon on macOS 26: Apple’s own model, which the system loads when asked and frees when not — the lightest way to run a model on a Mac.",...a?{}:{warn:l?.steps?.length?"The helper is not built in this checkout yet — Install builds it.":"The helper is not in this install — it comes with the gateway from npm and the desktop app."}}:{...o,backend:"none",why:"Apple’s on-device model runs on Apple Silicon Macs only."}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,i as VLLM_IMAGES,y as VLLM_METAL_INSTALL,s as VLLM_VERSION,L as detectAccelerator,m as deviceArgs,k as hostShape,U as pickAppleEngine,x as pickInferenceEngine,M as pickLlamaEngine,P as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
1
+ const s="0.29.0",i=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm-cpu:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,i.cpu]:[i.cpu]}const y=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function p(e,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function L({exec:e,platform:t=process.platform,arch:n=process.arch}={}){const a=async(l,r)=>{try{const o=await e(l,r,{timeout:8e3});return o&&!/error|not found|no devices/i.test(String(o.stdout||"")+String(o.stderr||""))}catch{return!1}};return t==="darwin"&&n==="arm64"?"apple":await a("nvidia-smi",["-L"])?"cuda":t==="linux"&&await a("rocm-smi",["--showid"])?"rocm":t==="linux"&&await a("sycl-ls",[])?"xpu":null}function x({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:a=null,vllmOnPath:l=!1,containerOnly:r=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&r?{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:y,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...l?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:a?n==="cuda"?{backend:"cuda",kind:"container",image:i.cuda,devices:p("cuda",a),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...a==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:n==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:i.rocm,devices:p("rocm",a),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:n==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:i.xpu,devices:p("xpu",a),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:a=!1}={}){const l=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"vulkan":"cpu",r=l==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":l==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${l.toUpperCase()} build, all layers offloaded`,o=f[e]||f.linux;return{backend:l,kind:"native",runner:"llama-server",install:o,why:r,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:l==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${l==="metal"?"Apple":l.toUpperCase()} GPU`,...a?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function k({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:a=()=>[]}={}){const l=Math.round(n()/1073741824),r=a().length||0;let o=Math.max(1,Math.floor(r/2))||1,c=o;if(t==="darwin"&&e){const m=async w=>{try{const b=await e("sysctl",["-n",w]),u=Number(String(b?.stdout||"").trim());return u>0?u:0}catch{return 0}},[d,g]=await Promise.all([m("hw.physicalcpu"),m("hw.perflevel0.physicalcpu")]);d&&(o=d),c=g||o}else r&&(o=r,c=Math.min(r,8));return{ramGB:l,cores:o,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function P({platform:e=process.platform,arch:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function U({platform:e=process.platform,arch:t=process.arch,osMajor:n=0,appleOnPath:a=!1,appleInstall:l=null}={}){const r={kind:"native",runner:"chatpanel-apple-model",...l?{install:l}:{}};return e==="darwin"&&t==="arm64"?n<25?{...r,backend:"none",why:"Apple’s on-device model needs macOS 26 or later."}:{...r,backend:"apple",for:"titles, topics, short answers — the system keeps the model, nothing stays loaded",speed:"quick for short text; the Mac decides when the model is in memory",notFor:"long chats (a 4,096-token window), images, tools",why:"Apple Silicon on macOS 26: Apple’s own model, which the system loads when asked and frees when not — the lightest way to run a model on a Mac.",...a?{}:{warn:l?.steps?.length?l.steps[0][0]==="mkdir"?"The helper is not built in this checkout yet — Install builds it.":"The helper is not in this install — Install fetches it.":"The helper is not in this install — run `chatpanel-gateway --fetch-apple-helper` to fetch it."}}:{...r,backend:"none",why:"Apple’s on-device model runs on Apple Silicon Macs only."}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,i as VLLM_IMAGES,y as VLLM_METAL_INSTALL,s as VLLM_VERSION,L as detectAccelerator,p as deviceArgs,k as hostShape,U as pickAppleEngine,x as pickInferenceEngine,M as pickLlamaEngine,P as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};