@chatpanel/gateway 0.85.5 → 0.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -0
- package/bin/chatpanel-gateway-bin.mjs +2 -2
- package/bin/chatpanel-gateway.js +3 -3
- package/package.json +2 -2
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/runtime.js +5 -5
- package/src/server.js +21 -21
- package/src/system-ca.js +1 -0
- package/src/update.js +6 -2
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -76,6 +76,26 @@ Windows:** stop the running gateway first, or npm fails with `EBUSY` on `onnxrun
|
|
|
76
76
|
(a loaded DLL cannot be overwritten) —
|
|
77
77
|
`chatpanel-gateway --stop; npm i -g @chatpanel/gateway --ignore-scripts; chatpanel-gateway --install`.
|
|
78
78
|
|
|
79
|
+
**On a company network.** The gateway is on the public npm registry. If `~/.npmrc` points npm at
|
|
80
|
+
a company mirror, the install can be slow, a version behind, or refused — name the registry on the
|
|
81
|
+
command: `npm i -g @chatpanel/gateway@latest --registry=https://registry.npmjs.org --ignore-scripts`.
|
|
82
|
+
If npm answers `UNABLE_TO_VERIFY_LEAF_SIGNATURE` or `SELF_SIGNED_CERT_IN_CHAIN`, a proxy is
|
|
83
|
+
re-signing HTTPS with a certificate Node does not know: prefix the command with
|
|
84
|
+
`NODE_OPTIONS=--use-system-ca` (Node 22.15+ — it then trusts what this computer trusts), or give
|
|
85
|
+
npm the company's certificate (`npm config set cafile /path/to/company-ca.pem`), or use the
|
|
86
|
+
standalone binary above. Do not set `strict-ssl=false`. The in-app Update does the first of these
|
|
87
|
+
by itself, and when an update fails it says which of these it was and the command to run.
|
|
88
|
+
|
|
89
|
+
**Whose certificates the gateway accepts.** Once installed, the gateway trusts the certificates
|
|
90
|
+
this computer trusts (the keychain, the Windows store, the distribution's bundle) as well as its
|
|
91
|
+
runtime's own list — so behind a proxy that re-signs HTTPS it reaches its models, its downloads
|
|
92
|
+
and its updates the way the browser on that machine does. Checks are never switched off: a
|
|
93
|
+
certificate nobody trusts is refused as before. The trade is the usual one on such a network: the
|
|
94
|
+
company's proxy can read what the gateway sends to a cloud model, after redaction has run. To
|
|
95
|
+
keep to the runtime's list alone, set `"tls": { "systemCa": false }` in
|
|
96
|
+
`~/.chatpanel/gateway.config.json` (or `CHATPANEL_SYSTEM_CA=off`) and restart;
|
|
97
|
+
`chatpanel-gateway --audit` says which is in effect. Needs Node 22.19+ for the npm install.
|
|
98
|
+
|
|
79
99
|
**Why `--ignore-scripts`.** The gateway itself has no install script, and the two in its tree — both
|
|
80
100
|
under `@huggingface/transformers`, the native model runtime — are ones it needs nothing from:
|
|
81
101
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{pathToFileURL as o}from"node:url";import{createRequire as l}from"node:module";import{existsSync as f,readFileSync as u}from"node:fs";import{join as g}from"node:path";import{homedir as
|
|
2
|
-
`)}catch{}};let s=null,c=!1;function
|
|
1
|
+
import{pathToFileURL as o}from"node:url";import{createRequire as l}from"node:module";import{existsSync as f,readFileSync as u}from"node:fs";import{join as g}from"node:path";import{homedir as d}from"node:os";import{normalizeRegistries as h}from"@chatpanel/events/registries.js";import p from"../assets/ort-wasm-simd-threaded.wasm";import _ from"../assets/ort-wasm-simd-threaded.mjs";import{findNativeBinding as v,ensureNativeOrt as a}from"../src/ort-native.js";import{trustSystemCertificates as w,systemCaWantedOnDisk as y}from"../src/system-ca.js";w({enabled:y()});function m(){try{const e=process.env.CHATPANEL_GATEWAY_CONFIG||g(d(),".chatpanel","gateway.config.json"),r=f(e)?JSON.parse(u(e,"utf8")):{},n={npm:process.env.CHATPANEL_REGISTRY_NPM,models:process.env.CHATPANEL_REGISTRY_MODELS};return h({...r.registries||{},...n.npm?{npm:n.npm}:{},...n.models?{models:n.models}:{}})}catch{return{}}}const t=e=>{try{process.stderr.write(`[ort] ${e}
|
|
2
|
+
`)}catch{}};let s=null,c=!1;function A(e){if(c)return s;c=!0;try{s=l(import.meta.url)(e),t(`native runtime loaded — ${e}`)}catch(r){t(`native runtime would not load (${String(r?.message||r).slice(0,120)}) — falling back to WASM`),s=null}return s}let i=v();const S=process.argv.includes("--install")||process.argv.includes("--fetch-runtime");if(!i&&S)try{i=await a({registries:m(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host}…`)}}),t(`native runtime ready — ${i}`)}catch(e){t(`no native runtime yet (${String(e?.message||e).slice(0,120)}) — the gateway will fetch it when it starts`)}process.argv.includes("--fetch-runtime")&&process.exit(i?0:1),i||a({registries:m(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host} — WASM answers until it lands`)}}).then(e=>t(`native runtime ready — ${e} (restart to use it)`)).catch(e=>t(`no native runtime (${String(e?.message||e).slice(0,120)}) — staying on WASM`)),i?globalThis.__CHATPANEL_ORT_BINDING__=()=>A(i):globalThis.__CHATPANEL_WASM_PATHS__={wasm:o(p).href,mjs:o(_).href},await import("./chatpanel-gateway.js");
|
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js")
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:
|
|
2
|
+
const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:t,systemCaWantedOnDisk:o}=await import("../src/system-ca.js");t({enabled:o()})}await import("@chatpanel/bridge/src/server.js")}else if(n==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(n==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(n==="tools"||n==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(n==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:c}=await import("../src/policy.js");try{const i=await t();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(o(i))}catch(i){throw i instanceof c&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(n==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:c}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:w}=await import("node:path"),g=await import("node:os"),p=c(),e=`http://127.0.0.1:${p.port||4320}`;let a=null,r=`no gateway running at ${e}`;try{const h=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(g.homedir(),".chatpanel","gateway-token"),"utf8").trim(),s=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(s.ok)a=await s.json();else if(s.status===404){const l=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);r=`the gateway running at ${e}${l?.version?` (${l.version})`:""} predates --audit (0.7.0) — restart it after updating`}else r=`the gateway at ${e} refused the audit (HTTP ${s.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js"),{systemCaWanted:s}=await import("../src/system-ca.js"),l=s(p);a={...t(p,{ledger:null,version:h,certificates:{on:!1,added:0,wanted:l,why:l?"no gateway is running; when one starts it adds this computer's list":"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"}}),observed:[]},console.log(`(${r}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:c}=await import("node:path"),i=await import("node:os"),g=`http://127.0.0.1:${t().port||4320}`,p=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||c(i.homedir(),".chatpanel","gateway-token");try{const e=o(p,"utf8").trim(),a=await fetch(`${g}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),r=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${g} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(r.error||`HTTP ${a.status}`);console.log(`Pairing code: ${r.display||r.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${g}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${p} — has the gateway started once?)`:""}`),process.exit(1)}}else if(n==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(n==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),c=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:c}),{dryRun:c}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:c,uninstallService:i,serviceReport:w,stopService:g,pathWithDir:p}=await import("../src/service.js");switch(n){case"--stop":g(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":{const e=await c({version:o,force:process.argv.includes("--force")}),a=e.health;if(e.newer){const r=a.managedBy&&a.managedBy!=="gateway"?` (run by the ${a.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${a.version} is already running at ${a.url}${r} — newer than this copy (v${o}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${o} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const r=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${a.version}) is the one answering right now; this install takes over at the next login`:"",h=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${a.version}: already running at ${a.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}${h}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${r}.`);let s=null;for(let l=0;l<30;l++){try{s=(await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),s?.version){const{staleBridgeCommands:l,staleBridgeLines:d}=await import("../src/service.js");for(const y of d(l({embedded:s.version}),{embedded:s.version}))console.log(y)}}else a.ok?(console.error(`ChatPanel Privacy Gateway: v${o} is registered to start at login, but v${a.version} still answers at ${a.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
|
|
4
4
|
${e.errLog.split(`
|
|
5
5
|
`).map(r=>` ${r}`).join(`
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:l=>console.error(l)}));s&&console.log(s)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&p(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await w());break;case void 0:await t();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${o}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
|
|
7
7
|
`));break;default:console.error(`unknown option: ${n}
|
|
8
8
|
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.87.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.44.2",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.354.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.0",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as
|
|
1
|
+
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,tls:{systemCa:!0},pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},mcp:{ask:{maxReach:"device",defaultModel:"",delegate:{roots:[],permissionMode:"acceptEdits"}}},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,diarizeModel:m,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function g(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,g as loadConfig};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
|
|
1
|
+
import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),s=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[s]||"",scheme:s}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(s){const r=g(s);if(!r||!r.host)return;const o=`${r.scheme}://${r.host}:${r.port}`,h=e(),c=t.get(o);if(c){c.count+=1,c.lastAt=h;return}t.set(o,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:h,lastAt:h})},snapshot(){return[...t.values()].sort((s,r)=>s.local===r.local?r.count-s.count:s.local?1:-1)},reset(){t.clear()}}}let y=null;function U(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const s=L();let r=t;s.setGate=d=>{r=d},s.blocked=[];const o=d=>{let n=null;try{n=g(d),s.record(d)}catch{}if(!r||!n?.host)return null;let u=!0;try{u=r(`${n.scheme}://${n.host}:${n.port}`,{local:w(n.host)})}catch{u=!0}if(u)return null;const a=`${n.host}:${n.port}`;s.blocked.includes(a)||s.blocked.push(a);const i=new Error(`egress to ${n.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},h=e.fetch;typeof h=="function"&&(e.fetch=function(n,u){const a=o(n);return a?Promise.reject(a):h.call(this,n,u)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(d,n,u){const a=o(n[0]);if(a)throw a;return Reflect.construct(d,n,u)}})),e.__chatpanelEgress=s,e===globalThis&&(y=s),s}function P(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function S(e={},t=process.env,s=process.platform){const r=[],o=(a,i,{when:l="always",off:f=null,local:b=!1,data:v=""}={})=>{a&&r.push({host:a,purpose:i,when:l,off:f,local:b,data:v})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const h=e.link?.enabled===!1?null:$(e.link||{}).relay;if(h){const a=new URL(h).host;o(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=e.search?.searxng?.url||"";if(c){let a=c;try{a=new URL(c).host}catch{}o(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(a.api.host,`web search: ${a.api.name} (search API${a.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${a.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}o(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,i]of Object.entries(d)){const l=e.capabilities?.[a];if(!l?.url||l.provider==="embedded")continue;let f=l.url;try{f=new URL(l.url).host}catch{}o(f,`${i.what}${l.service?` (the ${l.service} container, started under Settings › Runtime)`:` (${l.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:l.service?`stop the ${l.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${l.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(p(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:w(p(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const n=e.tts||{};if(n.provider==="openai"||n.provider==="elevenlabs"){const a=n.remote?.baseUrl?p(n.remote.baseUrl):n.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${n.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:n.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}s==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function q(e,{ledger:t=P(),version:s="",startedAt:r=null,env:o=process.env,managed:h=null}={}){return{ok:!0,version:s,since:r?new Date(r).toISOString():null,...h?{managed:h,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:S(e,o)}}function T(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const s of e.observed||[])t.push(` ${s.local?"[local] ":""}${s.scheme}://${s.host}:${s.port} ×${s.count} last ${s.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const s of e.declared||[])t.push(` ${s.local?"[local] ":""}${s.host}`),t.push(` ${s.purpose}`),t.push(` when: ${s.when}${s.off?` · off: ${s.off}`:""}`),s.data&&t.push(` sends: ${s.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,s])=>s).map(([s,r])=>r===!0?s:`${s}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
-
`)}export{L as createEgressLedger,
|
|
1
|
+
import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(a){const n=g(a);if(!n||!n.host)return;const o=`${n.scheme}://${n.host}:${n.port}`,l=e(),h=t.get(o);if(h){h.count+=1,h.lastAt=l;return}t.set(o,{host:n.host,port:n.port,scheme:n.scheme,local:w(n.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((a,n)=>a.local===n.local?n.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let y=null;function R(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=L();let n=t;a.setGate=d=>{n=d},a.blocked=[];const o=d=>{let r=null;try{r=g(d),a.record(d)}catch{}if(!n||!r?.host)return null;let u=!0;try{u=n(`${r.scheme}://${r.host}:${r.port}`,{local:w(r.host)})}catch{u=!0}if(u)return null;const s=`${r.host}:${r.port}`;a.blocked.includes(s)||a.blocked.push(s);const i=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},l=e.fetch;typeof l=="function"&&(e.fetch=function(r,u){const s=o(r);return s?Promise.reject(s):l.call(this,r,u)});const h=e.WebSocket;return typeof h=="function"&&(e.WebSocket=new Proxy(h,{construct(d,r,u){const s=o(r[0]);if(s)throw s;return Reflect.construct(d,r,u)}})),e.__chatpanelEgress=a,e===globalThis&&(y=a),a}function S(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function P(e={},t=process.env,a=process.platform){const n=[],o=(s,i,{when:c="always",off:f=null,local:b=!1,data:v=""}={})=>{s&&n.push({host:s,purpose:i,when:c,off:f,local:b,data:v})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const l=e.link?.enabled===!1?null:$(e.link||{}).relay;if(l){const s=new URL(l).host;o(s,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let s=h;try{s=new URL(h).host}catch{}o(s,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(s)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const s of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(s.api.host,`web search: ${s.api.name} (search API${s.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${s.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}o(s,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(s)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[s,i]of Object.entries(d)){const c=e.capabilities?.[s];if(!c?.url||c.provider==="embedded")continue;let f=c.url;try{f=new URL(c.url).host}catch{}o(f,`${i.what}${c.service?` (the ${c.service} container, started under Settings › Runtime)`:` (${c.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:c.service?`stop the ${c.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${i.data}${c.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[s,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&o(p(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:w(p(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const r=e.tts||{};if(r.provider==="openai"||r.provider==="elevenlabs"){const s=r.remote?.baseUrl?p(r.remote.baseUrl):r.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(s,`remote read-aloud voice (${r.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:r.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),n}function _(e,{ledger:t=S(),version:a="",startedAt:n=null,env:o=process.env,managed:l=null,certificates:h=null}={}){return{ok:!0,version:a,since:n?new Date(n).toISOString():null,...h?{certificates:h}:{},...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:P(e,o)}}function C(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,n])=>n===!0?a:`${a}=${n}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
+
`)}export{L as createEgressLedger,P as declaredEgress,_ as egressAudit,S as egressLedger,C as formatAudit,R as installEgressLedger};
|
package/src/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{promisify as Rn}from"node:util";import{execFile as In}from"node:child_process";import{existsSync as Ee,mkdirSync as ne,writeFileSync as oe,accessSync as Un,openSync as Fn,closeSync as Hn,constants as Dn}from"node:fs";import{randomBytes as jn,createHash as Xn}from"node:crypto";import Q from"node:os";import v from"node:path";import{modelsFor as Ze,isValidModelId as Wn,catalogFor as se,vllmTaskOf as te}from"./runtime-models.js";import{pickInferenceEngine as en,pickLlamaEngine as Jn,pickMlxEngine as zn,pickAppleEngine as Kn,recommendEngine as Qn,detectAccelerator as Vn,hostShape as qn}from"./inference-engines.js";import{tuningArgs as le,tuningRows as nn,patchTunings as Yn,profilesFor as tn,resolveTunings as rn,ENGINE_DOCS as Zn}from"./engine-tunings.js";import{IMAGE_RECIPES as et}from"./images.js";import{pullRepo as nt,pullGguf as tt,repoInstalled as rt,ggufInstalled as an}from"./model-pull.js";import{liveFit as it,kvCacheMB as at,cachedConfigPath as ot,needMB as st}from"./host-memory.js";import{APPLE_HELPER as Pe,APPLE_MODEL_ID as lt,APPLE_MIN_DARWIN as ut,appleHelperDirs as ct,appleInstallDoor as dt,darwinMajor as on}from"./apple-model.js";import{spawn as mt}from"node:child_process";import{readFileSync as sn,unlinkSync as ln}from"node:fs";const ft=Rn(In),ue=["podman","docker"],V="hf-cache",j=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(t,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>en({...t,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...te(t.model)==="embed"?["--task","embed"]:[],...le("vllm",t.tunings,{task:te(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.embed?.service==="vllm"?t.capabilities.embed.url.replace(/\/v1$/,""):t.capabilities?.stt?.service==="vllm"?t.capabilities.stt.url.replace(/\/v1$/,""):(t.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,P=te(f.model);un(t),P==="chat"?(t.destinations=(t.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),t.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>un(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>en(t),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...le("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),t.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>Jn(t),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:t=>/\.gguf$/i.test(t)?t.split(/[\\/]/).pop().replace(/\.gguf$/i,""):t.split("/").pop().split(":")[0],command:(t,l)=>["llama-server",[...t.file?["-m",t.file]:/\.gguf$/i.test(t.model)?["-m",t.model]:["-hf",t.model],"--host","127.0.0.1","--port",String(t.port),"--alias",t.alias(t.model),"--jinja",...le("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>zn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...le("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Pe,engineOf:t=>Kn(t),only:{platform:"darwin",arch:"arm64",minDarwin:ut,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:t=>[Pe,["serve","--port",String(t.port)]],answers:async(t,l)=>{try{const f=await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l)=>{t.destinations=(t.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),t.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[lt],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),re=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function un(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const x=t=>j.find(l=>l.id===t)||null,pt=({answers:t,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:U,caps:ce,command:de,engineOf:Ne,alias:N,..._})=>_,ht=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),gt=Object.freeze(["brave","qwant"]);function kt(t=[]){const l=t.length?t:ht,f=gt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
|
|
2
|
-
`)}function Oe(t=process.platform){return t==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:t==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function cn(t,l){const f=l==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=l==="podman"?Array.isArray(t.Ports)?t.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(t.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),P=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:P,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function Lt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,
|
|
3
|
-
`).filter(
|
|
4
|
-
`)[0]);return e.ok&&Number.isInteger(r)&&r>1?r:0}function Ge(n){const e=
|
|
1
|
+
import{promisify as Rn}from"node:util";import{execFile as In}from"node:child_process";import{existsSync as Ee,mkdirSync as ne,writeFileSync as oe,accessSync as Un,openSync as Fn,closeSync as Hn,constants as Dn}from"node:fs";import{randomBytes as jn,createHash as Xn}from"node:crypto";import Q from"node:os";import v from"node:path";import{modelsFor as Ze,isValidModelId as Wn,catalogFor as se,vllmTaskOf as te}from"./runtime-models.js";import{pickInferenceEngine as en,pickLlamaEngine as Jn,pickMlxEngine as zn,pickAppleEngine as Kn,recommendEngine as Qn,detectAccelerator as Vn,hostShape as qn}from"./inference-engines.js";import{tuningArgs as le,tuningRows as nn,patchTunings as Yn,profilesFor as tn,resolveTunings as rn,ENGINE_DOCS as Zn}from"./engine-tunings.js";import{IMAGE_RECIPES as et}from"./images.js";import{pullRepo as nt,pullGguf as tt,repoInstalled as rt,ggufInstalled as an}from"./model-pull.js";import{liveFit as it,kvCacheMB as at,cachedConfigPath as ot,needMB as st}from"./host-memory.js";import{APPLE_HELPER as Pe,APPLE_MODEL_ID as lt,APPLE_MIN_DARWIN as ut,appleHelperDirs as ct,appleInstallDoor as dt,darwinMajor as on}from"./apple-model.js";import{spawn as mt}from"node:child_process";import{readFileSync as sn,unlinkSync as ln}from"node:fs";const ft=Rn(In),ue=["podman","docker"],V="hf-cache",X=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],helper:!0,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(t,l)=>{try{return(await l(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,l)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:l}},unconfigure:(t,l)=>{t.search?.searxng?.url===l&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],helper:!0,adapter:"tei",model:"BAAI/bge-reranker-base",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. The gateway already reranks in-process by default (a small model, no container); start this to run a multilingual cross-encoder (bge-reranker base by default) in a container instead, behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:l,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,l)=>{t.capabilities?.rerank?.url===l&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],helper:!0,adapter:"systemone",model:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. The gateway already decides in-process by default with the same algorithm and model; start this to run it in a container instead. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,l,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:l,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,l)=>{t.capabilities?.decide?.url===l&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>en({...t,containerOnly:!0}),container:"chatpanel-vllm",port:8891,containerPort:8e3,provides:["chat","embed","stt"],adapter:"openai",model:"Qwen/Qwen3-0.6B",pull:!0,blurb:"Your own model, served by vLLM on this machine’s accelerator (CUDA, ROCm, XPU — or CPU): a chat model the router can send turns to, an embedding model for semantic search, or a transcriber for every ear. OpenAI-shaped, loopback only.",caps:[],volumes:t=>[`${v.join(t,V)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,l)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...te(t.model)==="embed"?["--task","embed"]:[],...le("vllm",t.tunings,{task:te(t.model),model:t.model,backend:l?.backend||null})],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.embed?.service==="vllm"?t.capabilities.embed.url.replace(/\/v1$/,""):t.capabilities?.stt?.service==="vllm"?t.capabilities.stt.url.replace(/\/v1$/,""):(t.destinations||[]).find(l=>l?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{const h=`${l}/v1`,P=te(f.model);un(t),P==="chat"?(t.destinations=(t.destinations||[]).filter(p=>p?.service!=="vllm"&&p?.id!=="vllm"),t.destinations.push({id:"vllm",type:"api",protocol:"openai",baseUrl:h,models:[f.model],service:"vllm"})):P==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):P==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>un(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>en(t),only:{platform:"darwin",arch:"arm64"},port:8892,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU, served by vLLM-Metal: a chat model the router can send turns to. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...le("vllm-metal",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="vllm-metal"&&h?.id!=="vllm-metal"),t.destinations.push({id:"vllm-metal",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm-metal"&&l?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>Jn(t),port:8893,provides:["chat"],adapter:"openai",model:"unsloth/Qwen3-4B-GGUF:Q4_K_M",blurb:"Your own GGUF model on this machine, served by llama.cpp: the Metal GPU on a Mac, CUDA or Vulkan elsewhere, CPU otherwise — a chat model the router can send turns to, with the flags that make it fast set for this machine. A process on this machine behind the gateway, loopback only.",alias:t=>/\.gguf$/i.test(t)?t.split(/[\\/]/).pop().replace(/\.gguf$/i,""):t.split("/").pop().split(":")[0],command:(t,l)=>["llama-server",[...t.file?["-m",t.file]:/\.gguf$/i.test(t.model)?["-m",t.model]:["-hf",t.model],"--host","127.0.0.1","--port",String(t.port),"--alias",t.alias(t.model),"--jinja",...le("llama",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="llama"&&l?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>zn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-1.7B-4bit",blurb:"Your own model on the Apple Silicon GPU through MLX — Apple’s framework, the lightest way to run a chat model on a Mac. A process on this machine behind the gateway, loopback only.",command:(t,l)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...le("mlx",t.tunings,l)]],answers:async(t,l)=>{try{return(await l(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="mlx"&&l?.id!=="mlx"))}},{id:"apple",label:"Apple on-device",kind:"native",auto:!0,runner:Pe,engineOf:t=>Kn(t),only:{platform:"darwin",arch:"arm64",minDarwin:ut,label:"macOS 26 or later on Apple Silicon"},port:8895,provides:["chat"],adapter:"openai",window:4096,card:{engine:"apple",backend:"apple",where:"this machine",egress:"none",cost:"free",task:"chat",window:4096,vision:!1,tools:!1,reasoning:!1,label:"Apple on-device",licence:"Apple",draft:!1},blurb:"Apple’s own model, on this Mac (macOS 26 with Apple Intelligence on): the system loads it when asked and frees it when idle, so nothing stays loaded and nothing runs hot — the lightest choice for titles, topics and short answers. Text only, 4,096 tokens at a time. A small helper on this machine behind the gateway, loopback only.",command:t=>[Pe,["serve","--port",String(t.port)]],answers:async(t,l)=>{try{const f=await l(`${t}/health`,{signal:AbortSignal.timeout(4e3)});return f.ok&&(await f.json())?.ok===!0}catch{return!1}},configured:t=>String((t.destinations||[]).find(l=>l?.service==="apple")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,l)=>{t.destinations=(t.destinations||[]).filter(f=>f?.service!=="apple"&&f?.id!=="apple"),t.destinations.push({id:"apple",type:"api",protocol:"openai",baseUrl:`${l}/v1`,models:[lt],service:"apple"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="apple"&&l?.id!=="apple"))}}]),re=t=>t.only?.label||`${t.only?.platform||"this platform"} ${t.only?.arch||""}`.trim();function un(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(l=>l?.service!=="vllm"&&l?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const x=t=>X.find(l=>l.id===t)||null,pt=({answers:t,configured:l,configure:f,unconfigure:h,volumes:P,args:p,env:H,caps:ce,command:de,engineOf:Ne,alias:B,..._})=>_,ht=Object.freeze(["google","yahoo","yep","duckduckgo","bing","wikipedia"]),gt=Object.freeze(["brave","qwant"]);function kt(t=[]){const l=t.length?t:ht,f=gt.filter(h=>!l.includes(h));return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...l.flatMap(h=>[` - name: ${h}`," disabled: false"]),...f.flatMap(h=>[` - name: ${h}`," disabled: true"]),""].join(`
|
|
2
|
+
`)}function Oe(t=process.platform){return t==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:t==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function cn(t,l){const f=l==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=l==="podman"?Array.isArray(t.Ports)?t.Ports.map(p=>`${p.host_ip||""}:${p.host_port}->${p.container_port}/${p.protocol||"tcp"}`):[]:String(t.Ports||"").split(",").map(p=>p.trim()).filter(Boolean),P=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:P,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:l}}function Lt({cfg:t,bridgeHealth:l,workers:f=()=>[],persist:h=()=>{},exec:P=(S,D,C={})=>ft(S,D,{timeout:6e4,killSignal:"SIGKILL",...C}),platform:p=process.platform,arch:H=process.arch,osRelease:ce=Q.release(),spawn:de=mt,lookup:Ne=null,fetchImpl:B=globalThis.fetch,stateDir:_=v.join(Q.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:me=S=>new Promise(D=>setTimeout(D,S)),totalMem:Be=()=>Q.totalmem(),memoryProbe:dn=S=>p==="darwin"&&t?.runtime?.heatwatch!==!1?it(S,{fetchImpl:B}):Promise.resolve(null),now:fe=()=>Date.now(),autoEnv:mn=process.env.CHATPANEL_RUNTIME_AUTO,every:Ce=(S,D)=>{const C=setInterval(S,D);return C.unref?.(),C}}={}){const S=Q.homedir(),D=p==="win32"?[v.join(S,"AppData","Local","Microsoft","WinGet","Links"),v.join(S,".local","bin"),v.join(S,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",v.join(S,".local","bin"),v.join(S,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin",...p==="darwin"?ct({home:S}):[]],C=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=D.filter(s=>!r.split(e).includes(s));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},k=async(n,e,r={})=>{try{const i=await P(n,e,{...r,env:C(r.env)});return{ok:!0,out:String(i.stdout||"").trim(),err:String(i.stderr||"").trim()}}catch(i){return{ok:!1,out:String(i?.stdout||"").trim(),err:String(i?.stderr||i?.message||i).trim(),code:i?.code}}},y=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let pe=null;const fn=async()=>(pe===null&&(pe=await Vn({exec:P,platform:p,arch:H})),pe),q={},pn=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of C().PATH.split(e).filter(Boolean))for(const s of r)try{return Un(v.join(i,n+s),Dn.X_OK),!0}catch{}return!1},L=async(n,e=["--version"])=>(q[n]===void 0&&(q[n]=(Ne||pn)(n)||(await k(n,e,{timeout:8e3})).ok),q[n]);let he=null;const ge=async()=>(he||(he=await qn({exec:P,platform:p,totalmem:Be,cpus:()=>Q.cpus()})),he),G=async n=>({platform:p,arch:H,accelerator:await fn(),engine:n,vllmOnPath:await L("vllm"),llamaOnPath:await L("llama-server"),mlxOnPath:p==="darwin"&&H==="arm64"?await L("mlx_lm.server",["--help"]):!1,osMajor:p==="darwin"?on(ce):0,appleOnPath:p==="darwin"&&H==="arm64"?await L(Pe):!1,appleInstall:p==="darwin"?dt({home:S}):null,...await ge()}),R=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===H)&&(!n.only.minDarwin||on(ce)>=n.only.minDarwin),Y=n=>v.join(_,`${n.id}.pid`),W=n=>{try{const e=Number(sn(Y(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},ke=n=>R(n)?W(n)?"running":"stopped":"unsupported",j={};async function ie(n){const e=Z(n);if(!R(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};if(W(e))return e.auto&&!e.configured(t)&&(e.configure(t,A(e),e),h()),{ok:!0,already:!0,url:A(e)};if(e.auto&&await e.answers(A(e),B)){const $=await wn(e.port);if($)return ne(_,{recursive:!0,mode:448}),oe(Y(e),String($),{mode:384}),j[e.id]={layer:"none",reason:"a model engine runs on the hardware, behind the gateway"},e.configure(t,A(e),e),h(),E(`[runtime] ${e.label} was already answering on ${A(e)} (pid ${$}) — adopted`),{ok:!0,adopted:!0,url:A(e),answering:!0,provides:e.provides}}const r=await G(null),i=e.engineOf(r);if(!await L(e.runner,e.runnerCheck))return{ok:!1,error:`\`${e.runner}\` is not on PATH — install it first (${i.install?.command||""}), or click Install`,install:i.install};if(e.id==="llama"&&/\.gguf$/i.test(e.model)&&!Ee(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[s,o]=e.command(e,I(e,e.model,i,r)),a=v.join(_,V);ne(a,{recursive:!0,mode:448});const d={bin:s,argv:o,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:a,LLAMA_CACHE:a,...e.installed?{HF_HUB_OFFLINE:"1"}:{}}},record:{layer:"none",reason:"a model engine runs on the hardware directly, behind the gateway (loopback only) — the sandbox is for agents and tools"}};j[e.id]=d.record;const u=v.join(_,`${e.id}.log`);let c,m=null;try{try{m=Fn(u,"w",384)}catch{m=null}c=de(d.bin,d.argv,{...d.opts,env:C(d.opts?.env),detached:!0,stdio:["ignore",m??"ignore",m??"ignore"]}),c.unref?.()}catch($){return{ok:!1,error:`${d.bin}: ${$.message}`,install:i.install}}finally{if(m!==null)try{Hn(m)}catch{}}if(!c?.pid)return{ok:!1,error:`${d.bin} did not start`,install:i.install};oe(Y(e),String(c.pid),{mode:384});const w=A(e);let g=!1;for(let $=0;$<120&&!g&&W(e);$++)g=await e.answers(w,B),g||await me(1e3);if(!W(e)){try{ln(Y(e))}catch{}let $="";try{$=sn(u,"utf8").trim().split(`
|
|
3
|
+
`).filter(U=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(U)).slice(-3).map(U=>U.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{$=""}return{ok:!1,error:`${e.label} exited on start${$?` — ${$}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:u}}return e.configure(t,w,e),h(),E(`[runtime] ${e.label} started (pid ${c.pid}) on ${w}, sandbox ${j[e.id].layer}${g?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:w,answering:g,provides:e.provides,model:y(e),sandbox:j[e.id]}}const we=n=>t.runtime?.services?.[n.id]?.off===!0,Le=(n,e)=>{t.runtime=t.runtime||{},t.runtime.services=t.runtime.services||{};const r={...t.runtime.services[n.id]||{}};e?r.off=!0:delete r.off,t.runtime.services[n.id]=r},hn=()=>t.runtime?.auto!==!1&&String(mn||"").toLowerCase()!=="off",O={};async function Te(n){if(!n?.auto)return{ok:!1,skipped:"not a service that starts by itself"};if(!hn())return{ok:!1,skipped:"automatic start is switched off"};if(!R(n))return{ok:!1,skipped:`runs on ${re(n)} only`};if(we(n))return{ok:!1,skipped:"stopped by the person"};if(!await L(n.runner,n.runnerCheck))return{ok:!1,skipped:"its helper is not in this install"};if(!W(n)){const r=await k(n.runner,["check"],{timeout:8e3});if(!r.ok){let i="";try{i=JSON.parse(r.out||"{}").message||""}catch{i=""}return O[n.id]=i||"not available on this Mac right now",{ok:!1,skipped:O[n.id]}}}const e=await ie(n);return e.ok?(delete O[n.id],{ok:!0,...e.already?{already:!0}:e.adopted?{adopted:!0}:{started:!0}}):(O[n.id]=e.error,{ok:!1,skipped:e.error})}async function gn(){const n=[];for(const e of X.filter(r=>r.auto))n.push({id:e.id,label:e.label,...await Te(e).catch(r=>({ok:!1,skipped:r.message}))});return n}async function kn(n){const e=x(n);return e?.auto?Te(e):{ok:!1,skipped:"not a service that starts by itself"}}async function wn(n){if(p==="win32")return 0;const e=await k("lsof",["-nP",`-iTCP:${n}`,"-sTCP:LISTEN","-t"],{timeout:4e3}),r=Number(String(e.out||"").split(`
|
|
4
|
+
`)[0]);return e.ok&&Number.isInteger(r)&&r>1?r:0}function Ge(n){const e=W(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{ln(Y(n))}catch{}return n.unconfigure(t,A(n)),h(),{ok:!0}}const Z=n=>n.model?{...n,model:y(n),installed:K(n,y(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:yn(y(n))}:{}}:n,J=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function bn(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},s=se(n.id).filter(d=>!d.minRamMB||r>0&&r>=d.minRamMB);if(!s.length||!r)return null;const o=s.slice().sort((d,u)=>(i[u.tier]??-1)-(i[d.tier]??-1)||d.ramMB-u.ramMB)[0],a=Math.round(o.ramMB/1024*10)/10;return{model:o.id,label:o.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${o.label} well — about ${a} GB while loaded${o.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:y(n)===o.id}}async function Re(n,{model:e,ctx:r,needMB:i}={}){const s=x(n);if(!s||!s.model)return{ok:!1,error:s?`${s.label} takes no model`:`unknown service ${n}`};const o=String(e||y(s)),a=se(n).find(_e=>_e.id===o)||null,d=Number(i)>0?Number(i):a?.ramMB||null;if(!d)return{ok:!1,error:`${o} is not in the catalogue — pass need_mb (its peak memory while serving)`};const u=Number(r)>0?Number(r):Ve(n),c=/\.gguf$/i.test(o)||s.id==="llama"?null:ot(z(),o),m=u&&c?at(c,u):null,w=st({ramMB:d,kvMB:m||0}),g=s.kind==="native"?await dn(w):null,$=((await ge()).ramGB||0)*1024,U=g?g.fits:$>0&&w<=$,F=_e=>`${Math.round(_e/102.4)/10} GB`,Gn=g?g.fits?`${o} fits: needs about ${F(w)}, ${F(g.availableMB)} is free now${g.fitsGPULimit===!1?` — but it is above the GPU wired limit (${F(g.gpuWiredLimitMB)}); raise iogpu.wired_limit_mb`:""}.`:`${o} needs about ${F(w)} and ${F(g.availableMB)} is free now — ${F(g.shortfallMB)} short.${g.close.length?` Close ${g.close.join(", ")} to make room, or pick a smaller model.`:" Pick a smaller model."}`:`${o} needs about ${F(w)} of the machine's ${F($)} — ${U?"fits":"does not fit"} (total memory; install Heatwatch to check what is free now).`;return{ok:!0,service:s.id,model:o,needMB:w,weightsMB:d,kvMB:m,context:u||null,contextCounted:m!==null||!u,source:g?"heatwatch":"total-memory",fits:U,live:g,advice:Gn}}const I=(n,e,r,i={})=>({task:n.id==="vllm"?te(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),z=()=>v.join(_,V),K=(n,e)=>/\.gguf$/i.test(e)?Ee(e):n.id==="llama"?!!an(z(),e):rt(z(),e),yn=n=>/\.gguf$/i.test(n)?n:an(z(),n),b={},wt=n=>b[n.id]||null;function be(n,e,r={}){return b[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},b[n.id]}function N(n,e){const r=String(e||"").trim();if(!r)return;n.lines.push(r.slice(0,200)),n.lines.length>8&&n.lines.shift();const i=/^STEP (\d+)\/(\d+)/.exec(r);i&&(n.step={n:Number(i[1]),of:Number(i[2])})}const ae=(n,e,r,{timeout:i=36e5*4}={})=>new Promise(s=>{if(n.cancelled)return s({ok:!1,code:-1,error:"cancelled"});let o;try{o=de(e,r,{stdio:["ignore","pipe","pipe"],env:C()})}catch(c){return s({ok:!1,code:-1,error:c.message})}n.child=o;let a="";const d=c=>{a+=String(c);const m=a.split(/\r?\n|\r/);a=m.pop();for(const w of m)N(n,w)};o.stdout?.on("data",d),o.stderr?.on("data",d);const u=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}},i);u.unref?.(),o.on("error",c=>{clearTimeout(u),n.child=null,s({ok:!1,code:-1,error:c.message})}),o.on("exit",c=>{clearTimeout(u),n.child=null,a&&N(n,a),s({ok:c===0&&!n.cancelled,code:c,...n.cancelled?{error:"cancelled"}:{}})})}),Ie={install:Promise.resolve(),build:Promise.resolve()},ye={install:0,build:0},Ue=(n,e,r)=>{ye[n]>0&&(e.waiting=!0,N(e,`waiting for the other ${n} to finish first — one at a time`)),ye[n]++;const i=Ie[n];let s;const o=new Promise(a=>{s=a});return Ie[n]=i.then(()=>o),i.then(async()=>{e.waiting&&(N(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{ye[n]--,s()}})},Fe=async(n,e)=>(await k(n,["image","exists",e],{timeout:2e4})).ok;async function $n(n,e,r,i){const s=e?.image||r.image;if(await Fe(n,s))return{ok:!0};const o=e?.sources?.length?e.sources:[s],a=[];for(const m of o){if(i.kind="pull-image",i.detail=m,N(i,`pulling ${m}`),(await ae(i,n,["pull",m])).ok)return m!==s&&await k(n,["tag",m,s],{timeout:2e4}),{ok:!0,pulled:m};a.push(m)}const d=e?.recipe?et[e.recipe]:null;if(!d)return{ok:!1,error:`no image to pull (${a.join(", ")} — ${i.lines.at(-1)||"refused"})`};const u=v.join(_,"images",e.recipe);return ne(u,{recursive:!0,mode:448}),oe(v.join(u,"Dockerfile"),d.dockerfile,{mode:384}),i.kind="build-image",i.detail=s,i.minutes=d.minutes,N(i,`no registry has ${s} for this machine — building it here (about ${d.minutes} minutes)`),E(`[runtime] building ${s} from the ${e.recipe} recipe in ${u}`),(await Ue("build",i,()=>ae(i,n,["build","-t",s,"-f",v.join(u,"Dockerfile"),u]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function He(n,e){const r=y(n);if(!r||K(n,r))return{ok:!0};if(/\.gguf$/i.test(r))return{ok:!1,error:`no such file: ${r}`};e.kind="pull-model",e.detail=r;const i=s=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:s.bytes,total:s.total,file:s.file}};try{return n.id==="llama"?await tt(r,{root:z(),fetchImpl:B,onProgress:i}):await nt(r,{root:z(),fetchImpl:B,onProgress:i}),{ok:!0}}catch(s){return{ok:!1,error:`pull ${r}: ${s.message}`}}}async function vn(n,e,r){const i=[];return n.kind!=="native"&&e&&!await Fe(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!K(n,y(n))&&i.push("model"),i}async function De(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await k("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?i:0}if(n==="docker"&&p!=="linux"){const r=await k("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(Be()/1048576)}async function M(){const n={};for(const r of ue){const i=await k(r,["--version"],{timeout:5e3});if(!i.ok){n[r]={installed:!1};continue}const s=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let o=!1,a=null;if(r==="podman")if(p==="linux")o=(await k("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const d=await k("podman",["machine","list","--format","json"],{timeout:8e3});try{const c=JSON.parse(d.out||"[]")[0]||null;a=c?{name:c.Name,running:!!c.Running}:null,o=!!c?.Running}catch{a=null}}else o=(await k("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:s,running:o,...r==="podman"&&p!=="linux"?{machine:a}:{}}}const e=ue.find(r=>n[r]?.installed&&n[r].running)||ue.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:Oe(p)}}}async function $e(n="podman"){if(!ue.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await M())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:Oe(p)};if(e.running)return{ok:!0,already:!0};if(n==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(p!=="linux"){if(!e.machine){const i=await k("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await k("podman",["machine","start"],{timeout:3e5});if(!r.ok&&!/already running/i.test(r.err))return{ok:!1,error:`podman machine start: ${r.err||r.out}`}}return{ok:!0}}async function je(){const n=await M(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await k("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(s=>cn(s,"podman"))}catch{return[]}}const r=await k("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
|
|
5
5
|
`).filter(Boolean).map(i=>{try{return cn(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function Xe(n,e){const r=await k(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function ve(n,e){const r=await k(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const o of e)i[o]="absent";return i}const s=new Map(r.out.split(`
|
|
6
|
-
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function We(){const n=await M(),e=n.preferred,r=await De(e,n),i={},s=await T(e),o=e&&n[e].running?await ve(e,j.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of j){const c=A(a);let u="no-engine";a.kind==="native"?u=ke(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const d=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...pt(a),engine:a.kind==="native"?"host":e,state:u,url:c,configured:a.configured(t),answering:u==="running"?await a.answers(c,N):!1,...a.helper?{asleep:L.has(a.id),idleMinutes:qe()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!H(a)?{why:`${a.label} runs on ${re(a)} only`}:{},...a.auto&&u!=="running"&&H(a)?{auto:!0,...we(a)?{why:"Stopped here — Start turns it back on"}:W[a.id]?{why:W[a.id]}:{}}:a.auto?{auto:!0}:{},...a.kind==="native"&&D[a.id]?{sandbox:D[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...J(a)?{profiles:tn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s)),docs:Zn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:bn(a,s)}:{},...a.model?{model:d,default:a.model,models:Ze(a.id,{active:d,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>K(a,g)}),machine:{engineRamMB:w}}:{},...J(a)?{tunings:nn(a.id,t.runtime?.services?.[a.id]?.tunings,G(a,d,m,s))}:{}}}return i}async function Sn(){const n=await M(),e=await T(n.preferred);return{platform:p,arch:U,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Qn(e)}}function Je(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Z(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(_):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const c=Xn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${c}`),{args:a,hash:c}}const Se={};async function An(n){if(Se[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);Se[n]=Number.isFinite(r)&&r>0?r:Q.cpus()?.length||2}return Math.max(1,Math.floor(Se[n]/2))}async function ze(n,{force:e=!1}={}){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};L.delete(r.id),xe(r.id),r.auto&&we(r)&&Le(r,!1);const i=b[r.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(r.kind!=="native"){const d=await M();if(s=d.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Oe(p)};if(!d[s].running){const m=await $e(s);if(!m.ok)return m}}else if(!H(r))return{ok:!1,error:`${r.label} runs on ${re(r)} only`};const o=await T(s),a=r.engineOf?r.engineOf(o):null;if(r.kind==="native"&&!await C(r.runner,r.runnerCheck))return{ok:!1,error:`\`${r.runner}\` is not on PATH — install it first (${a?.install?.command||""}), or click Install`,install:a?.install};if(r.model&&/\.gguf$/i.test(y(r))&&!Ee(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!e){const d=await Re(r.id);if(d.live&&!d.fits)return{ok:!1,error:d.advice,plan:d}}const c=await vn(r,s,a);if(!c.length)return delete b[r.id],r.kind==="native"?ie(r):Ae(r,s);const u=be(r,c[0]==="image"?"pull-image":"pull-model",{detail:c[0]==="image"?a?.image||r.image:y(r)});return u.then=(async()=>{try{if(c.includes("image")){const m=await $n(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(c.includes("model")){const m=await He(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const d=r.kind==="native"?await ie(r):await Ae(r,s);if(!d.ok)throw new Error(d.error);u.done=!0,u.result=d,E(`[runtime] ${r.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(d){u.done=!0,u.error=u.cancelled?"cancelled":d.message,E(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Mn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=b[e.id];if(!r||r.done)return{ok:!0,nothing:!0};if(r.cancelled=!0,r.child){try{r.child.kill("SIGTERM")}catch{}const i=r.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return O(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Ae(n,e){let r=await Xe(e,n.container);const i=n.helper?await An(e):null,s=n.engineOf?n.engineOf(await T(e)):null,o=n.id==="searxng"?v.join(_,"searxng-settings.yml"):null,a=Je(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const d=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!d.ok||d.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const d=await k(e,["start",n.container],{timeout:6e4});if(!d.ok)return{ok:!1,error:`${e} start: ${d.err||d.out}`}}else{ne(_,{recursive:!0,mode:448});let d=null;n.id==="searxng"&&(oe(o,kt(String(t.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),d=jn(32).toString("hex")),n.volumes&&ne(v.join(_,V),{recursive:!0,mode:448});const{args:m}=Je(n,{settingsFile:o,secret:d,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const c=A(n);let u=!1;for(let d=0;d<30&&!u;d++)u=await n.answers(c,N),u||await me(1e3);return n.configure(t,c,Z(n)),h(),{ok:!0,url:c,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function xn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(L.delete(e.id),delete Me[e.id],e.auto&&Le(e,!0),e.kind==="native")return Ge(e);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,A(e)),h(),{ok:!0}}async function _n(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(e||"").trim();if(!Wn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=r.kind==="native"?((await ge()).ramGB||0)*1024:await De(o,s),c=Ze(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>K(r,m)}).find(m=>m.id===i);if(c?.unavailable)return{ok:!1,error:`${i} ${c.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const u=A(r);r.configured(t)===u&&r.configure(t,u,Z(r)),h();const d=await Ke(r,o,s);return d.ok?{ok:!0,model:i,restarted:d.restarted,...c?.ramNote?{note:c.ramNote}:{}}:d}async function Ke(n,e,r){if(n.kind==="native"){if(ke(n)!=="running")return{ok:!0,restarted:!1};Ge(n);const o=await ie(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await Xe(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await ze(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function En(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await T(i.preferred),o=r.engineOf?r.engineOf(s):null,a=tn(r.id,t.runtime?.services?.[n]?.tunings,G(r,y(r),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const c=await Qe(n,a.patch);return c.ok?{...c,profile:a.id}:c}async function Pn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!H(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete q[e.runner],await C(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await T(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=be(e,"install",{detail:e.runner});return o.then=Ue("install",o,async()=>{const a=async d=>{for(const[m,...w]of d){O(o,`$ ${m} ${w.join(" ")}`);let g=await ae(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(R=>/already locked|Please wait for it to finish/i.test(R));$++)O(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await me(2e4),g=await ae(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let c=await a(s.steps);!c.ok&&!o.cancelled&&s.fallback?.length&&(O(o,`${c.error} — trying the other way`),c=await a(s.fallback)),delete q[e.runner];const u=c.ok&&await C(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":c.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${c.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function On(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(K(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=be(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await He(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Qe(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(r),a=await T(s),c=r.engineOf?r.engineOf(a):null,u=Yn(r.id,t.runtime?.services?.[n]?.tunings,e,G(r,o,c,a));if(u.error)return{ok:!1,error:u.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:u},h();const d=await Ke(r,s,i);return d.ok?{ok:!0,tunings:nn(r.id,u,G(r,o,c,a)),restarted:d.restarted}:d}async function Nn(){const n=await M(),e=n.preferred,r=e&&n[e].running?await ve(e,j.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(j.map(async o=>{const a=o.kind==="native"?ke(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),N)?"up":"down";const c=(o.provides||[]).some(u=>["embedded","none"].includes(t.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!c&&o.configured(t)!==A(o)&&(o.configure(t,A(o),Z(o)),s=!0)})),s&&h(),i}function Ve(n){const e=x(n);if(e?.window)return e.window;if(!e||!J(e))return null;const r=Number(rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,y(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Bn(n){const e=x(n);if(e?.card)return e.card;if(!e||!J(e))return null;const r=y(e),i=rn(e.id,t.runtime?.services?.[n]?.tunings,G(e,r,null,{})),s=se(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?te(r):"chat";return{engine:e.id,backend:D[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Cn=10,qe=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Cn)*6e4},Ln=fe(),Me={},L=new Set,ee={};function xe(n){Me[n]=fe()}async function Tn(n,{force:e=!1}={}){const r=x(n);if(!r||!r.helper)return{ok:!0};if(xe(r.id),!L.has(r.id)&&!e){const i=r.container&&r.configured?.(t)?(await je()).find(s=>s.name===r.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};L.add(r.id)}return ee[r.id]||(ee[r.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await $e(s);if(!a.ok)return a}const o=await Ae(r,s);return o.ok&&(L.delete(r.id),E(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete ee[r.id]})),ee[r.id]}async function Ye(){const n=qe();if(!n)return[];const e=j.filter(a=>a.helper&&a.configured(t)&&!L.has(a.id)&&!ee[a.id]&&!(b[a.id]&&!b[a.id].done)&&fe()-(Me[a.id]??Ln)>=n);if(!e.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of e)L.add(a.id);return e.map(a=>a.id)}const s=await ve(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}L.add(a.id),o.push(a.id)}return o}return Ce&&Ce(()=>{Ye().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Tn,sweepIdle:Ye,health:Nn,contextWindow:Ve,modelCard:Bn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),M(),We(),je(),Sn()]);return{machine:s,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:r}},startEngine:$e,startService:ze,stopService:xn,ensureDefaults:gn,revive:kn,plan:Re,setModel:_n,setTunings:Qe,setProfile:En,pullModel:On,installRunner:Pn,cancelJob:Mn,services:We,catalogFor:se}}export{ht as SEARXNG_DEFAULT_ENGINES,j as SERVICES,cn as containerRow,Lt as createRuntime,Oe as installDoor,kt as searxngSettings};
|
|
6
|
+
`).map(o=>o.split(" ")).filter(o=>o[0]).map(([o,a])=>[o,/running/i.test(a||"")?"running":"stopped"]));for(const o of e)i[o]=s.get(o)||"absent";return i}const A=n=>`http://127.0.0.1:${n.port}`;async function We(){const n=await M(),e=n.preferred,r=await De(e,n),i={},s=await G(e),o=e&&n[e].running?await ve(e,X.filter(a=>a.kind!=="native").map(a=>a.container)):{};for(const a of X){const d=A(a);let u="no-engine";a.kind==="native"?u=ke(a):e&&n[e].running?u=o[a.container]||"absent":e&&(u="engine-stopped");const c=a.model?y(a):null,m=a.engineOf?a.engineOf(s):null,w=a.kind==="native"?(s.ramGB||0)*1024:r;i[a.id]={...pt(a),engine:a.kind==="native"?"host":e,state:u,url:d,configured:a.configured(t),answering:u==="running"?await a.answers(d,B):!1,...a.helper?{asleep:T.has(a.id),idleMinutes:qe()/6e4}:{},...m?{engineFor:{backend:m.backend,kind:m.kind,image:m.image||null,...m.runner?{runner:m.runner}:{},why:m.why,...m.for?{for:m.for}:{},...m.speed?{speed:m.speed}:{},...m.notFor?{notFor:m.notFor}:{},...m.warn?{warn:m.warn}:{},...m.install?{install:m.install}:{}}}:{},...a.kind==="native"&&!R(a)?{why:`${a.label} runs on ${re(a)} only`}:{},...a.auto&&u!=="running"&&R(a)?{auto:!0,...we(a)?{why:"Stopped here — Start turns it back on"}:O[a.id]?{why:O[a.id]}:{}}:a.auto?{auto:!0}:{},...!a.auto&&a.kind==="native"&&u!=="running"&&R(a)&&O[a.id]?{why:O[a.id]}:{},...a.kind==="native"&&j[a.id]?{sandbox:j[a.id]}:{},...b[a.id]?{job:{kind:b[a.id].kind,since:b[a.id].since,detail:b[a.id].detail||null,step:b[a.id].step||null,minutes:b[a.id].minutes||null,progress:b[a.id].progress,lines:b[a.id].lines.slice(-4),done:b[a.id].done,error:b[a.id].error,waiting:!!b[a.id].waiting,cancelled:!!b[a.id].cancelled}}:{},...J(a)?{profiles:tn(a.id,t.runtime?.services?.[a.id]?.tunings,I(a,c,m,s)),docs:Zn[a.id]||null}:{},...a.model&&a.kind==="native"?{recommend:bn(a,s)}:{},...a.model?{model:c,default:a.model,models:Ze(a.id,{active:c,engineRamMB:w,engine:a.kind==="native"?"host":e,platform:p,installed:g=>K(a,g)}),machine:{engineRamMB:w}}:{},...J(a)?{tunings:nn(a.id,t.runtime?.services?.[a.id]?.tunings,I(a,c,m,s))}:{}}}return i}async function Sn(){const n=await M(),e=await G(n.preferred);return{platform:p,arch:H,accelerator:e.accelerator,vllmOnPath:e.vllmOnPath,llamaOnPath:e.llamaOnPath,mlxOnPath:e.mlxOnPath,ramGB:e.ramGB,cores:e.cores,perfCores:e.perfCores,recommend:Qn(e)}}function Je(n,{settingsFile:e=null,secret:r=null,pick:i=null,cpus:s=null}={}){const o=Z(n),a=["run","-d","--name",o.container,"--restart","no","-p",`127.0.0.1:${o.port}:${o.containerPort}`];o.helper&&s&&a.push("--cpus",String(s));for(const u of o.volumes?o.volumes(_):[])a.push("-v",u);e&&a.push("-v",`${e}:/etc/searxng/settings.yml:ro`);for(const u of o.env?o.env(o):[])a.push("-e",u);o.helper&&s&&a.push("-e",`THREADS=${s}`),r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${o.port}/`),a.push("--cap-drop","ALL");for(const u of o.caps||[])a.push("--cap-add",u);i?.devices?.length&&a.push(...i.devices),a.push(i?.image||o.image,...o.args?o.args(o,i):[]);const d=Xn("sha1").update(JSON.stringify(a.filter(u=>!String(u).startsWith("SEARXNG_SECRET=")))).digest("hex").slice(0,12);return a.splice(2,0,"--label",`chatpanel.run=${d}`),{args:a,hash:d}}const Se={};async function An(n){if(Se[n]==null){const e=await k(n,["info","--format",n==="docker"?"{{.NCPU}}":"{{.Host.CPUs}}"],{timeout:8e3}),r=Number.parseInt(e.out,10);Se[n]=Number.isFinite(r)&&r>0?r:Q.cpus()?.length||2}return Math.max(1,Math.floor(Se[n]/2))}async function ze(n,{force:e=!1}={}){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};T.delete(r.id),xe(r.id),r.auto&&we(r)&&Le(r,!1);const i=b[r.id];if(i&&!i.done)return{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail||null}};let s=null;if(r.kind!=="native"){const c=await M();if(s=c.preferred,!s)return{ok:!1,error:"no container engine — install Podman first",install:Oe(p)};if(!c[s].running){const m=await $e(s);if(!m.ok)return m}}else if(!R(r))return{ok:!1,error:`${r.label} runs on ${re(r)} only`};const o=await G(s),a=r.engineOf?r.engineOf(o):null;if(r.kind==="native"&&!await L(r.runner,r.runnerCheck))return{ok:!1,error:`\`${r.runner}\` is not on PATH — install it first (${a?.install?.command||""}), or click Install`,install:a?.install};if(r.model&&/\.gguf$/i.test(y(r))&&!Ee(y(r)))return{ok:!1,error:`no such file: ${y(r)}`};if(r.kind==="native"&&r.model&&!e){const c=await Re(r.id);if(c.live&&!c.fits)return{ok:!1,error:c.advice,plan:c}}const d=await vn(r,s,a);if(!d.length){if(delete b[r.id],r.kind!=="native")return Ae(r,s);const c=await ie(r);return c.ok?delete O[r.id]:O[r.id]=c.error,c}const u=be(r,d[0]==="image"?"pull-image":"pull-model",{detail:d[0]==="image"?a?.image||r.image:y(r)});return u.then=(async()=>{try{if(d.includes("image")){const m=await $n(s,a,r,u);if(!m.ok)throw new Error(m.error)}if(d.includes("model")){const m=await He(r,u);if(!m.ok)throw new Error(m.error)}u.kind="starting",u.detail=r.label;const c=r.kind==="native"?await ie(r):await Ae(r,s);if(!c.ok)throw new Error(c.error);u.done=!0,u.result=c,E(`[runtime] ${r.label}: ready after ${Math.round((Date.now()-u.since)/1e3)} s`)}catch(c){u.done=!0,u.error=u.cancelled?"cancelled":c.message,E(`[runtime] ${r.label}: ${u.error}`)}})(),{ok:!0,pending:{kind:u.kind,since:u.since,detail:u.detail}}}function Mn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};const r=b[e.id];if(!r||r.done)return{ok:!0,nothing:!0};if(r.cancelled=!0,r.child){try{r.child.kill("SIGTERM")}catch{}const i=r.child;setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},5e3).unref?.()}return N(r,"cancelled"),E(`[runtime] ${e.label}: job cancelled (${r.kind})`),{ok:!0,cancelled:r.kind}}async function Ae(n,e){let r=await Xe(e,n.container);const i=n.helper?await An(e):null,s=n.engineOf?n.engineOf(await G(e)):null,o=n.id==="searxng"?v.join(_,"searxng-settings.yml"):null,a=Je(n,{settingsFile:o,secret:n.id==="searxng"?"x":null,pick:s,cpus:i});if(r!=="absent"){const c=await k(e,["inspect","--format",'{{index .Config.Labels "chatpanel.run"}}',n.container],{timeout:8e3});(!c.ok||c.out!==a.hash)&&(E(`[runtime] ${n.label}: made with older settings — re-creating it`),await k(e,["rm","-f",n.container],{timeout:6e4}),r="absent")}if(r!=="running")if(r==="stopped"){const c=await k(e,["start",n.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${e} start: ${c.err||c.out}`}}else{ne(_,{recursive:!0,mode:448});let c=null;n.id==="searxng"&&(oe(o,kt(String(t.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),c=jn(32).toString("hex")),n.volumes&&ne(v.join(_,V),{recursive:!0,mode:448});const{args:m}=Je(n,{settingsFile:o,secret:c,pick:s,cpus:i});E(`[runtime] ${e} ${m.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const w=await k(e,m,{timeout:6e5});if(!w.ok)return{ok:!1,error:`${e} run: ${w.err||w.out}`}}const d=A(n);let u=!1;for(let c=0;c<30&&!u;c++)u=await n.answers(d,B),u||await me(1e3);return n.configure(t,d,Z(n)),h(),{ok:!0,url:d,answering:u,...n.provides.length?{provides:n.provides}:{},...n.model?{model:y(n)}:{}}}async function xn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(T.delete(e.id),delete Me[e.id],e.auto&&Le(e,!0),e.kind==="native")return Ge(e);const r=await M(),i=r.preferred;if(i&&r[i].running){const s=await k(i,["stop",e.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${i} stop: ${s.err||s.out}`}}return e.unconfigure(t,A(e)),h(),{ok:!0}}async function _n(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const i=String(e||"").trim();if(!Wn(n,i))return{ok:!1,error:`not a model id: ${JSON.stringify(e)} — pick one from the list, or a Hugging Face id like owner/name`};const s=await M(),o=s.preferred,a=r.kind==="native"?((await ge()).ramGB||0)*1024:await De(o,s),d=Ze(n,{active:i,engineRamMB:a,engine:r.kind==="native"?"host":o,platform:p,installed:m=>K(r,m)}).find(m=>m.id===i);if(d?.unavailable)return{ok:!1,error:`${i} ${d.unavailable}`};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},model:i};const u=A(r);r.configured(t)===u&&r.configure(t,u,Z(r)),h();const c=await Ke(r,o,s);return c.ok?{ok:!0,model:i,restarted:c.restarted,...d?.ramNote?{note:d.ramNote}:{}}:c}async function Ke(n,e,r){if(n.kind==="native"){if(ke(n)!=="running")return{ok:!0,restarted:!1};Ge(n);const o=await ie(n);return o.ok?{ok:!0,restarted:!0}:o}if(!e||!r[e].running)return{ok:!0,restarted:!1};const i=await Xe(e,n.container);if(i==="absent")return{ok:!0,restarted:!1};const s=await k(e,["rm","-f",n.container],{timeout:6e4});if(!s.ok&&!/no such container/i.test(s.err))return{ok:!1,error:`${e} rm: ${s.err||s.out}`};if(i==="running"){const o=await ze(n.id);return o.ok?{ok:!0,restarted:!0}:o}return{ok:!0,restarted:!1}}async function En(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no profile`};const i=await M(),s=await G(i.preferred),o=r.engineOf?r.engineOf(s):null,a=tn(r.id,t.runtime?.services?.[n]?.tunings,I(r,y(r),o,s)).find(u=>u.id===e);if(!a)return{ok:!1,error:`no profile ${JSON.stringify(e)} — one of speed, coding, long, xl`};if(!a.fits)return{ok:!1,error:`${a.label}: ${a.why}`};const d=await Qe(n,a.patch);return d.ok?{...d,profile:a.id}:d}async function Pn(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(e.kind!=="native")return{ok:!1,error:`${e.label} is a container — its image is pulled or built on Start`};if(!R(e))return{ok:!1,error:`${e.label} runs on ${re(e)} only`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(delete q[e.runner],await L(e.runner,e.runnerCheck))return{ok:!0,installed:!0};const s=e.engineOf(await G(null))?.install;if(!s?.steps?.length)return{ok:!1,error:`no installer for ${e.label} on this platform${s?.url?` — see ${s.url}`:""}`,install:s||null};const o=be(e,"install",{detail:e.runner});return o.then=Ue("install",o,async()=>{const a=async c=>{for(const[m,...w]of c){N(o,`$ ${m} ${w.join(" ")}`);let g=await ae(o,m,w,{timeout:36e5});for(let $=0;!g.ok&&!o.cancelled&&$<6&&o.lines.some(U=>/already locked|Please wait for it to finish/i.test(U));$++)N(o,`another ${m} holds the lock — waiting 20 s (${$+1}/6)`),await me(2e4),g=await ae(o,m,w,{timeout:36e5});if(!g.ok)return{ok:!1,error:g.error||`${m} exited ${g.code}`}}return{ok:!0}};let d=await a(s.steps);!d.ok&&!o.cancelled&&s.fallback?.length&&(N(o,`${d.error} — trying the other way`),d=await a(s.fallback)),delete q[e.runner];const u=d.ok&&await L(e.runner,e.runnerCheck);o.done=!0,o.cancelled?o.error="cancelled":d.ok?u||(o.error=`${e.runner} still not found after the install — open a new terminal and run \`${s.command}\` by hand`):o.error=`install failed: ${d.error}${o.lines.length?` (${o.lines.slice(-2).join(" | ")})`:""}`,E(`[runtime] install ${e.runner}: ${o.error||"ok"}`)}),{ok:!0,pending:{kind:o.kind,since:o.since,detail:o.detail}}}async function On(n){const e=x(n);if(!e)return{ok:!1,error:`unknown service ${n}`};if(!e.pull)return{ok:!1,error:`${e.label} fetches its own model on the first start`};const r=b[e.id];if(r&&!r.done)return{ok:!0,pending:{kind:r.kind,since:r.since,detail:r.detail||null}};if(K(e,y(e)))return{ok:!0,installed:!0,model:y(e)};const i=be(e,"pull-model",{detail:y(e)});return i.then=(async()=>{const s=await He(e,i);i.done=!0,s.ok||(i.error=s.error)})(),{ok:!0,pending:{kind:i.kind,since:i.since,detail:i.detail}}}async function Qe(n,e){const r=x(n);if(!r)return{ok:!1,error:`unknown service ${n}`};if(!J(r))return{ok:!1,error:`${r.label} takes no tunings`};if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"tunings: an object of { id: value }"};const i=await M(),s=i.preferred,o=y(r),a=await G(s),d=r.engineOf?r.engineOf(a):null,u=Yn(r.id,t.runtime?.services?.[n]?.tunings,e,I(r,o,d,a));if(u.error)return{ok:!1,error:u.error};t.runtime=t.runtime||{services:{}},t.runtime.services=t.runtime.services||{},t.runtime.services[n]={...t.runtime.services[n]||{},tunings:u},h();const c=await Ke(r,s,i);return c.ok?{ok:!0,tunings:nn(r.id,u,I(r,o,d,a)),restarted:c.restarted}:c}async function Nn(){const n=await M(),e=n.preferred,r=e&&n[e].running?await ve(e,X.filter(o=>o.kind!=="native").map(o=>o.container)):{},i={};let s=!1;return await Promise.all(X.map(async o=>{const a=o.kind==="native"?ke(o):e&&n[e].running?r[o.container]||"absent":"no-engine";i[o.id]=a==="running"&&await o.answers(A(o),B)?"up":"down";const d=(o.provides||[]).some(u=>["embedded","none"].includes(t.capabilities?.[u]?.provider));i[o.id]==="up"&&o.configure&&!d&&o.configured(t)!==A(o)&&(o.configure(t,A(o),Z(o)),s=!0)})),s&&h(),i}function Ve(n){const e=x(n);if(e?.window)return e.window;if(!e||!J(e))return null;const r=Number(rn(e.id,t.runtime?.services?.[n]?.tunings,I(e,y(e),null,{})).maxModelLen);return Number.isFinite(r)&&r>0?r:null}function Bn(n){const e=x(n);if(e?.card)return e.card;if(!e||!J(e))return null;const r=y(e),i=rn(e.id,t.runtime?.services?.[n]?.tunings,I(e,r,null,{})),s=se(e.id).find(a=>a.id===r)||null,o=e.id==="vllm"?te(r):"chat";return{engine:e.id,backend:j[e.id]?.backend||null,where:"this machine",egress:"none",cost:"free",task:o,window:Number(i.maxModelLen)>0?Number(i.maxModelLen):null,vision:o==="chat"&&!!i.vision,tools:!!(o==="chat"&&(e.id==="llama"||i.toolCalls&&i.toolCalls!=="off")),reasoning:o==="chat"&&!!i.reasoning&&i.reasoning!=="off",...s?{tier:s.tier||null,licence:s.licence||null,languages:s.lang||null,label:s.label||null}:{},draft:!!(i.speculative&&i.speculative!=="off")}}const Cn=10,qe=()=>{const n=Number(t.runtime?.idleMinutes);return(Number.isFinite(n)&&n>=0?n:Cn)*6e4},Ln=fe(),Me={},T=new Set,ee={};function xe(n){Me[n]=fe()}async function Tn(n,{force:e=!1}={}){const r=x(n);if(!r||!r.helper)return{ok:!0};if(xe(r.id),!T.has(r.id)&&!e){const i=r.container&&r.configured?.(t)?(await je()).find(s=>s.name===r.container):null;if(!i||i.state==="running")return{ok:!0,awake:!0};T.add(r.id)}return ee[r.id]||(ee[r.id]=(async()=>{const i=await M(),s=i.preferred;if(!s)return{ok:!1,error:"no container engine"};if(!i[s].running){const a=await $e(s);if(!a.ok)return a}const o=await Ae(r,s);return o.ok&&(T.delete(r.id),E(`[runtime] ${r.label}: woken for a request`)),o})().finally(()=>{delete ee[r.id]})),ee[r.id]}async function Ye(){const n=qe();if(!n)return[];const e=X.filter(a=>a.helper&&a.configured(t)&&!T.has(a.id)&&!ee[a.id]&&!(b[a.id]&&!b[a.id].done)&&fe()-(Me[a.id]??Ln)>=n);if(!e.length)return[];const r=await M(),i=r.preferred;if(!i||!r[i].running){for(const a of e)T.add(a.id);return e.map(a=>a.id)}const s=await ve(i,e.map(a=>a.container)),o=[];for(const a of e){if(s[a.container]==="running"){if(!(await k(i,["stop",a.container],{timeout:6e4})).ok)continue;E(`[runtime] ${a.label}: asleep after ${Math.round(n/6e4)} min without a request — the next one starts it`)}T.add(a.id),o.push(a.id)}return o}return Ce&&Ce(()=>{Ye().catch(n=>E(`[runtime] idle sweep: ${n.message}`))},6e4),{touch:xe,wake:Tn,sweepIdle:Ye,health:Nn,contextWindow:Ve,modelCard:Bn,async status(){const[n,e,r,i,s]=await Promise.all([l().catch(()=>null),M(),We(),je(),Sn()]);return{machine:s,sandbox:n?.sandbox||null,processes:{all:[...Array.isArray(n?.processes)?n.processes:[],...f()],localMcp:Array.isArray(n?.localMcp)?n.localMcp:[],warm:n?.warm||null},containers:i,refused:Array.isArray(n?.sandbox?.refused)?n.sandbox.refused:[],bridge:n?{ok:!0,version:n.version||""}:{ok:!1},engines:e,services:r}},startEngine:$e,startService:ze,stopService:xn,ensureDefaults:gn,revive:kn,plan:Re,setModel:_n,setTunings:Qe,setProfile:En,pullModel:On,installRunner:Pn,cancelJob:Mn,services:We,catalogFor:se}}export{ht as SEARXNG_DEFAULT_ENGINES,X as SERVICES,cn as containerRow,Lt as createRuntime,Oe as installDoor,kt as searxngSettings};
|