@chatpanel/gateway 0.39.4 → 0.39.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,7 +53,7 @@ curl -fsSL https://dl.chatpanel.net/install.sh | bash # macOS / Linux
53
53
  # Windows (PowerShell): irm https://dl.chatpanel.net/gateway/install.ps1 | iex
54
54
 
55
55
  # Or via npm (needs Node):
56
- npm install -g @chatpanel/gateway
56
+ npm install -g @chatpanel/gateway --ignore-scripts
57
57
  chatpanel-gateway
58
58
  # → ChatPanel Privacy Gateway on http://127.0.0.1:4320
59
59
  # backend : bridge (agent: codex, via http://127.0.0.1:4319)
@@ -65,10 +65,24 @@ folder is not on that shell's PATH yet: open a new PowerShell, or run it by path
65
65
  `node "$(npm root -g)/@chatpanel/gateway/bin/chatpanel-gateway.js" --install`. **Updating on
66
66
  Windows:** stop the running gateway first, or npm fails with `EBUSY` on `onnxruntime_binding.node`
67
67
  (a loaded DLL cannot be overwritten) —
68
- `chatpanel-gateway --stop; npm i -g @chatpanel/gateway; chatpanel-gateway --install`. npm may also warn
69
- that `boolean@3.2.0` is deprecated and that `onnxruntime-node` / `sharp` / `protobufjs` run install
70
- scripts: all three come through `@huggingface/transformers` (the native model runtime) and are
71
- expected.
68
+ `chatpanel-gateway --stop; npm i -g @chatpanel/gateway --ignore-scripts; chatpanel-gateway --install`.
69
+
70
+ **Why `--ignore-scripts`.** The gateway itself has no install script, and the two in its tree — both
71
+ under `@huggingface/transformers`, the native model runtime — are ones it needs nothing from:
72
+
73
+ | Script | What it does | What skipping it costs |
74
+ |---|---|---|
75
+ | `onnxruntime-node` | Downloads the **CUDA / TensorRT** execution providers on linux/x64 (225 MB from NuGet). The prebuilt CPU bindings for macOS arm64, Linux x64/arm64 and Windows x64/arm64 are already inside the npm tarball. | Nothing. The gateway asks ORT for `['cpu']` on every engine (`src/ort.js`), so those providers were never loaded. |
76
+ | `protobufjs` | Prints a caret-vs-tilde advisory about the range its own parent declared. | Nothing. |
77
+
78
+ So the flag is not a workaround — it is the install. It also means `npm i -g` never runs code from
79
+ 114 transitive packages on your machine, which is the posture the rest of this gateway is built for.
80
+
81
+ **npm 12 and newer blocks unlisted install scripts by default** and prints a four-line warning
82
+ naming those two packages. That warning is not a broken install: `onnxruntime-node` still loads and
83
+ the native runtime is still the fast one. Passing `--ignore-scripts` says the same thing
84
+ deliberately and installs quietly. Do **not** take npm's suggested
85
+ `--allow-scripts=onnxruntime-node,protobufjs` — on Linux x64 it starts the 225 MB CUDA download.
72
86
 
73
87
  `GET /health` says which bridge it runs: `bridge.mode` is `embedded`, `standalone`,
74
88
  `adopted` or `off`. `CHATPANEL_BRIDGE_MANAGED=off` (or `bridge.managed: false`) turns the
@@ -76,6 +90,28 @@ supervision off for a host that runs its own bridge — the desktop app does. A
76
90
  `bridge.url` that is not on this machine is left alone: nothing is started for a remote
77
91
  bridge.
78
92
 
93
+ > **Size.** A fresh `npm i -g` is ~669 MB on disk (~16 s on a warm connection), and
94
+ > `chatpanel-gateway --install` takes it to **~327 MB**, down from 798 MB:
95
+ > - `onnxruntime-web` is a **devDependency**, not a dependency (0.39.7) — only the standalone
96
+ > binary's build reads it, to embed the WASM runtime a compiled binary needs because it
97
+ > cannot carry a native addon. −129 MB.
98
+ > - `--install` **prunes what this install cannot reach** (0.39.8, 0.39.9): the onnxruntime
99
+ > prebuilds for the other four platforms (`onnxruntime-node` ships one tarball for all five
100
+ > and `dist/binding.js` loads exactly one), and the copy of `onnxruntime-web` npm hoists from
101
+ > `@huggingface/transformers`. −340 MB. A reinstall puts them back and the next `--install`
102
+ > takes them off again.
103
+ >
104
+ > **That WASM copy is not a fallback.** Hide the native binding and transformers throws at
105
+ > import rather than switching backends — it never reaches WASM — and `src/ort.js` only looks
106
+ > at the WASM runtime when the compiled binary sets `__CHATPANEL_WASM_PATHS__`, which no npm
107
+ > install does. So nothing degrades; there was nothing there to degrade to.
108
+ >
109
+ > Speed is untouched: what is kept is the *native* runtime, which is the whole reason to
110
+ > install via npm rather than take the binary. The prune refuses unless your platform's binding
111
+ > is present **and** the addon loads, never touches that one, is idempotent, and does nothing at
112
+ > all when run from a checkout. `tests/install-weight.test.js` and `tests/prune-install.test.js`
113
+ > guard it.
114
+
79
115
  > **Binary vs. npm — same features, very different local-AI speed.** Both run
80
116
  > identical redaction/routing. But the standalone binary runs the local models
81
117
  > (speech-to-text, diarization, NER) on the **WASM** runtime — **fp32-only,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- const o=process.argv[2];try{process.title=o==="--bridge"?"chatpanel-bridge":o==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(o==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(o==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(o==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(o==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(o==="tools"||o==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(o==="policy"){const{loadPolicy:e,formatPolicy:s,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(s(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(o==="--audit"){const{egressAudit:e,formatAudit:s}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:p}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let a=null,i=`no gateway running at ${t}`;try{const h=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(g.ok)a=await g.json();else if(g.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js");a={...e(c,{ledger:null,version:h}),observed:[]},console.log(`(${i}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(s(a))}else if(o==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await s(process.argv.slice(3)))}else if(o==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=s(c,"utf8").trim(),a=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(i.error||`HTTP ${a.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(o==="local"){const{localStatus:e,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await e()))}else if(o==="connect"){const{connectAgents:e,formatConnect:s}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:s}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:p,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(o){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--install":{const t=await n(),a=t.health;if(a.ok){const i=a.managedBy&&a.managedBy!=="gateway"?` — the ${a.managedBy} app's gateway is the one answering right now; this install takes over at the next login`:"";console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
2
+ const a=process.argv[2];try{process.title=a==="--bridge"?"chatpanel-bridge":a==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(a==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(a==="tools"||a==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:e,formatPolicy:s,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(s(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(a==="--audit"){const{egressAudit:e,formatAudit:s}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let o=null,i=`no gateway running at ${t}`;try{const g=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),p=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${g}`},signal:AbortSignal.timeout(2500)});if(p.ok)o=await p.json();else if(p.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${p.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!o){const{VERSION:g}=await import("../src/server.js");o={...e(c,{ledger:null,version:g}),observed:[]},console.log(`(${i}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(o,null,2)):console.log(s(o))}else if(a==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await s(process.argv.slice(3)))}else if(a==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=s(c,"utf8").trim(),o=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(o.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(a==="local"){const{localStatus:e,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await e()))}else if(a==="connect"){const{connectAgents:e,formatConnect:s}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:s}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:h,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(a){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--install":{const t=await n(),o=t.health;if(o.ok){const i=o.managedBy&&o.managedBy!=="gateway"?` — the ${o.managedBy} app's gateway is the one answering right now; this install takes over at the next login`:"";console.log(`ChatPanel Privacy Gateway v${o.version}: running at ${o.url}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${o.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
4
4
  ${t.errLog.split(`
5
5
  `).map(i=>` ${i}`).join(`
6
- `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await p());break;case void 0:await e();break;default:console.error(`unknown option: ${o}
6
+ `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");try{const{pruneForeignPrebuilds:i,pruneLine:g}=await import("../src/prune-install.js"),p=g(i({log:d=>console.error(d)}));p&&console.log(p)}catch{}t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),o.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await h());break;case void 0:await e();break;default:console.error(`unknown option: ${a}
7
7
  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(e){console.error(`error: ${e.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.39.4",
3
+ "version": "0.39.11",
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": {
@@ -30,7 +30,6 @@
30
30
  "fflate": "^0.8.3",
31
31
  "linkedom": "^0.18.13",
32
32
  "mammoth": "^1.12.3",
33
- "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c",
34
33
  "pdfjs-dist": "^6.3.289",
35
34
  "phonemizer": "^1.2.1"
36
35
  },
package/src/images.js CHANGED
@@ -1,4 +1,4 @@
1
- const e=Object.freeze({"vllm-cpu":{tag:"ghcr.io/chatpanel/vllm:latest",what:"vLLM’s CPU build (arm64 and amd64) with the audio extras — a chat, embedding or whisper model on a machine without a GPU",minutes:90,dockerfile:`ARG VLLM_VERSION=v0.29.0
1
+ const e=Object.freeze({"vllm-cpu":{tag:"ghcr.io/chatpanel/vllm-cpu:latest",what:"vLLM’s CPU build (arm64 and amd64) with the audio extras — a chat, embedding or whisper model on a machine without a GPU",minutes:90,dockerfile:`ARG VLLM_VERSION=v0.29.0
2
2
  FROM python:3.12-slim AS build
3
3
  ARG VLLM_VERSION
4
4
  RUN apt-get update && apt-get install -y --no-install-recommends git build-essential cmake ninja-build libnuma-dev curl ca-certificates \\
@@ -1 +1 @@
1
- const s="0.29.0",o=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,o.cpu]:[o.cpu]}const L=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,n){return e==="cuda"?n==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function x({exec:e,platform:n=process.platform,arch:t=process.arch}={}){const l=async(a,i)=>{try{const r=await e(a,i,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return n==="darwin"&&t==="arm64"?"apple":await l("nvidia-smi",["-L"])?"cuda":n==="linux"&&await l("rocm-smi",["--showid"])?"rocm":n==="linux"&&await l("sycl-ls",[])?"xpu":null}function M({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,engine:l=null,vllmOnPath:a=!1,containerOnly:i=!1}={}){return e==="darwin"&&(n==="arm64"||t==="apple")&&i?{backend:"cpu",kind:"container",image:o.cpu,sources:h(n),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(n==="arm64"||t==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:L,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...a?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:l?t==="cuda"?{backend:"cuda",kind:"container",image:o.cuda,devices:m("cuda",l),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...l==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:t==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:o.rocm,devices:m("rocm",l),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:t==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:o.xpu,devices:m("xpu",l),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:o.cpu,sources:h(n),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${n==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${n}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function P({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,llamaOnPath:l=!1}={}){const a=e==="darwin"&&n==="arm64"?"metal":t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"vulkan":"cpu",i=a==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":a==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${a.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:a,kind:"native",runner:"llama-server",install:r,why:i,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:a==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${a==="metal"?"Apple":a.toUpperCase()} GPU`,...l?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function y({exec:e,platform:n=process.platform,totalmem:t=()=>0,cpus:l=()=>[]}={}){const a=Math.round(t()/1073741824),i=l().length||0;let r=Math.max(1,Math.floor(i/2))||1,c=r;if(n==="darwin"&&e){const p=async b=>{try{const w=await e("sysctl",["-n",b]),d=Number(String(w?.stdout||"").trim());return d>0?d:0}catch{return 0}},[u,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);u&&(r=u),c=g||r}else i&&(r=i,c=Math.min(i,8));return{ramGB:a,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function U({platform:e=process.platform,arch:n=process.arch,mlxOnPath:t=!1}={}){return e==="darwin"&&n==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...t?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function k({platform:e=process.platform,arch:n=process.arch,accelerator:t=null}={}){return e==="darwin"&&n==="arm64"?{engine:"llama",why:"Apple Silicon: llama.cpp on Metal is the mature path — the largest choice of models (GGUF), vision, and the MTP draft that makes a big model fast. MLX is the lighter alternative."}:t==="cuda"||t==="rocm"||t==="xpu"?{engine:"vllm",why:`${t.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,o as VLLM_IMAGES,L as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,m as deviceArgs,y as hostShape,M as pickInferenceEngine,P as pickLlamaEngine,U as pickMlxEngine,k as recommendEngine,h as vllmCpuSources};
1
+ const s="0.29.0",o=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm-cpu:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,o.cpu]:[o.cpu]}const L=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,n){return e==="cuda"?n==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function x({exec:e,platform:n=process.platform,arch:t=process.arch}={}){const l=async(a,i)=>{try{const r=await e(a,i,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return n==="darwin"&&t==="arm64"?"apple":await l("nvidia-smi",["-L"])?"cuda":n==="linux"&&await l("rocm-smi",["--showid"])?"rocm":n==="linux"&&await l("sycl-ls",[])?"xpu":null}function M({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,engine:l=null,vllmOnPath:a=!1,containerOnly:i=!1}={}){return e==="darwin"&&(n==="arm64"||t==="apple")&&i?{backend:"cpu",kind:"container",image:o.cpu,sources:h(n),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(n==="arm64"||t==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:L,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...a?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:l?t==="cuda"?{backend:"cuda",kind:"container",image:o.cuda,devices:m("cuda",l),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...l==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:t==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:o.rocm,devices:m("rocm",l),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:t==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:o.xpu,devices:m("xpu",l),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:o.cpu,sources:h(n),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${n==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${n}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function P({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,llamaOnPath:l=!1}={}){const a=e==="darwin"&&n==="arm64"?"metal":t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"vulkan":"cpu",i=a==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":a==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${a.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:a,kind:"native",runner:"llama-server",install:r,why:i,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:a==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${a==="metal"?"Apple":a.toUpperCase()} GPU`,...l?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function y({exec:e,platform:n=process.platform,totalmem:t=()=>0,cpus:l=()=>[]}={}){const a=Math.round(t()/1073741824),i=l().length||0;let r=Math.max(1,Math.floor(i/2))||1,c=r;if(n==="darwin"&&e){const p=async b=>{try{const w=await e("sysctl",["-n",b]),d=Number(String(w?.stdout||"").trim());return d>0?d:0}catch{return 0}},[u,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);u&&(r=u),c=g||r}else i&&(r=i,c=Math.min(i,8));return{ramGB:a,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function U({platform:e=process.platform,arch:n=process.arch,mlxOnPath:t=!1}={}){return e==="darwin"&&n==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...t?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function k({platform:e=process.platform,arch:n=process.arch,accelerator:t=null}={}){return e==="darwin"&&n==="arm64"?{engine:"llama",why:"Apple Silicon: llama.cpp on Metal is the mature path — the largest choice of models (GGUF), vision, and the MTP draft that makes a big model fast. MLX is the lighter alternative."}:t==="cuda"||t==="rocm"||t==="xpu"?{engine:"vllm",why:`${t.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,o as VLLM_IMAGES,L as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,m as deviceArgs,y as hostShape,M as pickInferenceEngine,P as pickLlamaEngine,U as pickMlxEngine,k as recommendEngine,h as vllmCpuSources};
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import nt from"node:os";import{join as S}from"node:path";import{existsSync as B,mkdirSync as rt,readdirSync as Y,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{makeWarmTimer as Q}from"./warm-timer.js";import{makeModelFileCache as pt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function dt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return E;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${E}`),E);let n;try{n=new URL(t)}catch{return e("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return e(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return e("points at cloud metadata");const o=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!o?e("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${E}`),t.replace(/\/*$/,"/"))}const mt=dt();let d="off",h=null,g=null,x=null,L=null,v=null,M=null,T=null,w=null,N=0,A=null;const m=new Map;function C(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function H(t=h||J){const e=S(C(),...t.split("/"));return B(S(e,"onnx","model_quantized.onnx"))||B(S(e,"onnx","model.onnx"))}function jt(){const t=C(),e=[];try{for(const n of Y(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of Y(S(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;H(r)&&ht(S(t,n.name,o.name))&&e.push(r)}}catch{}return e}function ht(t){try{return(JSON.parse(ot(S(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function qt(){return d}function k(){return d==="ready"&&!!g}function zt(){return{configured:d!=="off",ok:k(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:kt(),companions:Mt(),warmMs:w?.warmMs??null}}async function gt(t,{signal:e}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[];for(const i of o||[]){let f=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(f.startsWith("##")&&r.length&&r[r.length-1].type===a){r[r.length-1].value+=f.slice(2);continue}f=f.replace(/##/g,"").trim(),f&&r.push({value:f,type:a})}const s=new Set,u=[];for(const i of r){const f=vt(n,$t(n,i.value.trim()));if(f.length<=1)continue;const a=`${i.type}:${f.toLowerCase()}`;s.has(a)||(s.add(a),u.push({value:f,type:i.type}))}return u}async function G(t,e){N++;try{return await yt(t,e)}finally{N--,$()||w?.arm()}}async function yt(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(P){const s=ct(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:u}of V())for(const i of r){let f=0;for(const a of Ot(i.text,u.tokenizer)){if(e?.aborted)return null;const l=i.text.indexOf(a,f),c=await u(a,{aggregation_strategy:"simple"});for(const p of c||[])o.push({...p,_win:l<0?f:l,_winText:a,_model:s,_pass:i.key,_passText:i.text});l>=0&&(f=Math.max(f,l+1))}}return Tt(performance.now()-n,t.length,o.length),o}let P=!0;function Bt(t){P=t!==!1}async function Yt(t,{signal:e}={}){if(!k())return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[],s=new Set;let u=-1,i=-1,f=null,a=null;for(const c of o){const p=String(c.word??"").replace(/##/g,"").trim();if(!p)continue;(c._win!==i||c._model!==f||c._pass!==a)&&(i=c._win,f=c._model,a=c._pass,u=c._win);const b=c._passText||n;let _=b.indexOf(p,u);if(_<0&&(_=b.indexOf(p,c._win)),_<0)continue;let O=_+p.length;u=O;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;_>0&&W(n[_-1]);)_--;for(;O<n.length&&W(n[O]);)O++;const U=String(c.entity_group??c.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(c.score);r.push({value:n.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:c._model})}r.sort((c,p)=>c.start-p.start||c.end-p.end);const l=[];for(const c of r){const p=l[l.length-1];if(p&&p.type===c.type&&p.end===c.start){p.end=c.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,c.score);continue}l.push({...c})}return m.size||P?xt(l):l}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function wt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function R(t){const e=K.indexOf(wt(t.type));return e<0?K.length:e}let D=[];function _t(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function xt(t){const e=[...t].sort((o,r)=>o.start-r.start||r.end-o.end),n=[];for(const o of e){const r=n[n.length-1];if(r&&o.start<r.end){const s=i=>i.end-i.start;(R(o)<R(r)||R(o)===R(r)&&(s(o)>s(r)||s(o)===s(r)&&(F(o)<F(r)||F(o)===F(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Jt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const n of Object.values(t)){const o=String(n).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Qt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Mt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function bt(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:r}=await I(t,{log:e,allowDownload:n});return m.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return m.set(t,{pipe:null,state:"error",error:r.message}),e(`[ner] companion ${t} failed to load (${r.message}) — the union runs without it`),!1}}async function Gt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,n]of m)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const Lt=160,X=256;function Ot(t,e){if(!t||typeof e!="function")return[t];const n=Number(e.model_max_length),r=Math.min(X,Number.isFinite(n)&&n>0?n:X)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=r)return[t];const u=[];let i=0,f=Math.max(64,Math.floor(r*3));for(;i<t.length;){let a=Math.min(t.length,i+f);if(a<t.length){const b=t.lastIndexOf(" ",a);b>i+f/2&&(a=b)}let l=t.slice(i,a);for(;s(l)>r&&l.length>32;){f=Math.max(32,Math.floor(l.length/2)),a=i+f;const b=t.lastIndexOf(" ",a);b>i+f/2&&(a=b),l=t.slice(i,a)}if(u.push(l),a>=t.length)break;const c=Math.max(i+1,a-Lt),p=t.indexOf(" ",c);i=p>0&&p<a?p+1:a}return u}const St=200,y=[];function Tt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>St&&y.shift()}function kt(){if(!y.length)return{calls:0};const t=y.map(r=>r.ms).sort((r,s)=>r-s),e=r=>t[Math.min(t.length-1,Math.floor(r*t.length))],n=y.reduce((r,s)=>r+s.chars,0),o=y.reduce((r,s)=>r+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(n/(o/1e3)):null}}function $t(t,e){if(!e||t.includes(e))return e;const n=t.toLowerCase().indexOf(e.toLowerCase());return n<0?e:t.slice(n,n+e.length)}function vt(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);let r=n,s=n+e.length;for(;r>0&&o(t[r-1]);)r--;for(;s<t.length&&o(t[s]);)s++;return t.slice(r,s)}async function Kt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await gt(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Vt(){return M}async function Z(){if(v)return v;const t=C();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}const{env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:u,LogLevel:i}=await import("@huggingface/transformers");if(n.cacheDir=t,e&&i)try{n.logLevel=i.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=pt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=mt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return v={env:n,pipeline:(a,l,c={})=>o(a,l,c.progress_callback&&n.allowRemoteModels===!1?{...c,progress_callback:void 0}:c),Tensor:r,AutoModel:s,AutoProcessor:u},v}async function I(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await Z(),s=H(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const u=r.env.remoteHost,i=!st(t);if(!s&&i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const f=l=>{l&&(l.status==="progress"||l.status==="download"||l.status==="initiate"?o(l):l.status==="done"&&l.file&&e(`[ner] fetched ${l.file}`))};let a;try{a=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}catch(l){if(s||i||!n)throw l;e(`[ner] mirror fetch failed (${String(l.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,a=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}if(!s)try{ut(t,{modelsDir:C(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{r.env.remoteHost=u}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=g,r=h;try{await Z()}catch(u){return d="error",x=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!n)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:u}=await I(t,{log:e,allowDownload:n,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=u,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==u)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||w?.arm(),!0}catch(u){return x=u.message,M=null,o?(g=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${u.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function At(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const n=t.allowDownload!==!1;return w=Q({warmMs:t.warmMs,busy:$,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];_t(r);for(const s of r)await bt(s,{log:e,allowDownload:n});return k()&&!$()&&w?.arm(),o}),L}function $(){if(N>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if($())return!1;w?.disarm();const e=V().map(n=>n.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const n of e)try{await n.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Xt(){try{d==="idle"&&(A||T)?await(A?A():At(T)):L&&await L}catch{}return k()}async function Zt(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&k())return!0;const r=m.get(t);if(r?.pipe){const s=g;if(g=r.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:n,allowDownload:o})}function It(){d="off",h=null,g=null,x=null,L=null,v=null,M=null,y.length=0,m.clear(),P=!0,D=[],w?.disarm(),w=null,T=null,N=0,A=null}function te(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function ee(t,{model:e="test/model",warmMs:n=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(A=o),n!==null&&(w=Q({warmMs:n,busy:$,unload:()=>et()}),t&&w.arm())}export{It as _reset,te as _setCompanionForTest,ee as _setForTest,bt as addCompanion,Mt as companions,gt as detect,Yt as detectSpans,Xt as ensure,Z as ensureLib,Kt as fetchAdapter,zt as health,At as init,k as isReady,Jt as labels,Qt as maxTokens,H as modelOnDisk,C as modelRoot,jt as modelsOnDisk,Vt as progress,Gt as removeCompanion,dt as resolveModelHost,Bt as setCaseRecovery,Zt as setModel,_t as setUnionOrder,qt as state,kt as stats,xt as unionSpans,et as unload,Ot as windowsFor};
1
+ import nt from"node:os";import{join as S}from"node:path";import{existsSync as B,mkdirSync as rt,readdirSync as Y,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as Q}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return E;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${E}`),E);let n;try{n=new URL(t)}catch{return e("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return e(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return e("points at cloud metadata");const o=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!o?e("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${E}`),t.replace(/\/*$/,"/"))}const ht=mt();let d="off",h=null,g=null,x=null,L=null,v=null,M=null,T=null,w=null,N=0,A=null;const m=new Map;function C(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function H(t=h||J){const e=S(C(),...t.split("/"));return B(S(e,"onnx","model_quantized.onnx"))||B(S(e,"onnx","model.onnx"))}function zt(){const t=C(),e=[];try{for(const n of Y(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of Y(S(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;H(r)&&gt(S(t,n.name,o.name))&&e.push(r)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(S(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function Bt(){return d}function k(){return d==="ready"&&!!g}function Yt(){return{configured:d!=="off",ok:k(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:$t(),companions:bt(),warmMs:w?.warmMs??null}}async function yt(t,{signal:e}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[];for(const i of o||[]){let c=String(i.word??"");const l=i.entity_group??i.entity??"ENTITY";if(c.startsWith("##")&&r.length&&r[r.length-1].type===l){r[r.length-1].value+=c.slice(2);continue}c=c.replace(/##/g,"").trim(),c&&r.push({value:c,type:l})}const s=new Set,u=[];for(const i of r){const c=At(n,vt(n,i.value.trim()));if(c.length<=1)continue;const l=`${i.type}:${c.toLowerCase()}`;s.has(l)||(s.add(l),u.push({value:c,type:i.type}))}return u}async function G(t,e){N++;try{return await wt(t,e)}finally{N--,$()||w?.arm()}}async function wt(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(P){const s=ct(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:u}of V())for(const i of r){let c=0;for(const l of St(i.text,u.tokenizer)){if(e?.aborted)return null;const a=i.text.indexOf(l,c),f=await u(l,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:a<0?c:a,_winText:l,_model:s,_pass:i.key,_passText:i.text});a>=0&&(c=Math.max(c,a+1))}}return kt(performance.now()-n,t.length,o.length),o}let P=!0;function Jt(t){P=t!==!1}async function Qt(t,{signal:e}={}){if(!k())return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[],s=new Set;let u=-1,i=-1,c=null,l=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==c||f._pass!==l)&&(i=f._win,c=f._model,l=f._pass,u=f._win);const b=f._passText||n;let _=b.indexOf(p,u);if(_<0&&(_=b.indexOf(p,f._win)),_<0)continue;let O=_+p.length;u=O;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;_>0&&W(n[_-1]);)_--;for(;O<n.length&&W(n[O]);)O++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);r.push({value:n.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}r.sort((f,p)=>f.start-p.start||f.end-p.end);const a=[];for(const f of r){const p=a[a.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}a.push({...f})}return m.size||P?Mt(a):a}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function R(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,r)=>o.start-r.start||r.end-o.end),n=[];for(const o of e){const r=n[n.length-1];if(r&&o.start<r.end){const s=i=>i.end-i.start;(R(o)<R(r)||R(o)===R(r)&&(s(o)>s(r)||s(o)===s(r)&&(F(o)<F(r)||F(o)===F(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Gt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const n of Object.values(t)){const o=String(n).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:r}=await I(t,{log:e,allowDownload:n});return m.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return m.set(t,{pipe:null,state:"error",error:r.message}),e(`[ner] companion ${t} failed to load (${r.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,n]of m)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const Ot=160,X=256;function St(t,e){if(!t||typeof e!="function")return[t];const n=Number(e.model_max_length),r=Math.min(X,Number.isFinite(n)&&n>0?n:X)-8,s=l=>{try{return e(l).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=r)return[t];const u=[];let i=0,c=Math.max(64,Math.floor(r*3));for(;i<t.length;){let l=Math.min(t.length,i+c);if(l<t.length){const b=t.lastIndexOf(" ",l);b>i+c/2&&(l=b)}let a=t.slice(i,l);for(;s(a)>r&&a.length>32;){c=Math.max(32,Math.floor(a.length/2)),l=i+c;const b=t.lastIndexOf(" ",l);b>i+c/2&&(l=b),a=t.slice(i,l)}if(u.push(a),l>=t.length)break;const f=Math.max(i+1,l-Ot),p=t.indexOf(" ",f);i=p>0&&p<l?p+1:l}return u}const Tt=200,y=[];function kt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>Tt&&y.shift()}function $t(){if(!y.length)return{calls:0};const t=y.map(r=>r.ms).sort((r,s)=>r-s),e=r=>t[Math.min(t.length-1,Math.floor(r*t.length))],n=y.reduce((r,s)=>r+s.chars,0),o=y.reduce((r,s)=>r+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(n/(o/1e3)):null}}function vt(t,e){if(!e||t.includes(e))return e;const n=t.toLowerCase().indexOf(e.toLowerCase());return n<0?e:t.slice(n,n+e.length)}function At(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);let r=n,s=n+e.length;for(;r>0&&o(t[r-1]);)r--;for(;s<t.length&&o(t[s]);)s++;return t.slice(r,s)}async function Xt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return M}async function Z(){if(v)return v;const t=C();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let n;try{n=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(pt(a))}const{env:o,pipeline:r,Tensor:s,AutoModel:u,AutoProcessor:i,LogLevel:c}=n;if(o.cacheDir=t,e&&c)try{o.logLevel=c.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return v={env:o,pipeline:(a,f,p={})=>r(a,f,p.progress_callback&&o.allowRemoteModels===!1?{...p,progress_callback:void 0}:p),Tensor:s,AutoModel:u,AutoProcessor:i},v}async function I(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await Z(),s=H(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const u=r.env.remoteHost,i=!st(t);if(!s&&i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const c=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?o(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let l;try{l=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:c})}catch(a){if(s||i||!n)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,l=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:c})}if(!s)try{ut(t,{modelsDir:C(),log:e})}catch(a){try{await l.dispose?.()}catch{}throw a}return{pipe:l,haveLocal:s}}finally{try{r.env.remoteHost=u}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=g,r=h;try{await Z()}catch(u){return d="error",x=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!n)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:u}=await I(t,{log:e,allowDownload:n,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=u,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==u)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||w?.arm(),!0}catch(u){return x=u.message,M=null,o?(g=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${u.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const n=t.allowDownload!==!1;return w=Q({warmMs:t.warmMs,busy:$,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];xt(r);for(const s of r)await Lt(s,{log:e,allowDownload:n});return k()&&!$()&&w?.arm(),o}),L}function $(){if(N>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if($())return!1;w?.disarm();const e=V().map(n=>n.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const n of e)try{await n.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(A||T)?await(A?A():Et(T)):L&&await L}catch{}return k()}async function te(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&k())return!0;const r=m.get(t);if(r?.pipe){const s=g;if(g=r.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:n,allowDownload:o})}function ee(){d="off",h=null,g=null,x=null,L=null,v=null,M=null,y.length=0,m.clear(),P=!0,D=[],w?.disarm(),w=null,T=null,N=0,A=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:n=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(A=o),n!==null&&(w=Q({warmMs:n,busy:$,unload:()=>et()}),t&&w.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Qt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Yt as health,Et as init,k as isReady,Gt as labels,Kt as maxTokens,H as modelOnDisk,C as modelRoot,zt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,Bt as state,$t as stats,Mt as unionSpans,et as unload,St as windowsFor};
package/src/ort.js CHANGED
@@ -1 +1,2 @@
1
- let n=null;function r(){return!globalThis.__CHATPANEL_WASM_PATHS__}function a(){return globalThis.__CHATPANEL_WASM_PATHS__?"wasm":"native"}function o(){return globalThis.__CHATPANEL_WASM_PATHS__?["wasm"]:["cpu"]}function i(){return n||(n=(async()=>{if(!(globalThis.__CHATPANEL_WASM_PATHS__||null)){const t=await import("onnxruntime-node");return t.InferenceSession?t:t.default||t}throw new Error("this model needs the native onnxruntime, which the standalone binary does not carry — install the npm gateway instead (npm i -g @chatpanel/gateway), or pick a model that runs on the bundled runtime")})(),n)}export{i as getOrt,o as ortProviders,a as ortRuntimeName,r as rawOrtAvailable};
1
+ let e=null;function i(){return!globalThis.__CHATPANEL_WASM_PATHS__}function o(){return globalThis.__CHATPANEL_WASM_PATHS__?"wasm":"native"}function s(){return globalThis.__CHATPANEL_WASM_PATHS__?["wasm"]:["cpu"]}function r(n){const t=n?.message?` (${String(n.message).split(`
2
+ `)[0]})`:"",a=process.platform==="win32"?"chatpanel-gateway --stop; ":"";return`the native onnxruntime could not be loaded${t} — reinstall with \`${a}npm i -g @chatpanel/gateway@latest --ignore-scripts\``+(process.platform==="win32"?" (Windows cannot overwrite a loaded DLL, so the gateway must be stopped first)":"")+". Blocked install scripts are NOT the cause: the bindings ship inside the package."}function l(){return e||(e=(async()=>{if(!(globalThis.__CHATPANEL_WASM_PATHS__||null)){let t;try{t=await import("onnxruntime-node")}catch(a){throw new Error(`${r(a)}`)}return t.InferenceSession?t:t.default||t}throw new Error("this model needs the native onnxruntime, which the standalone binary does not carry — install the npm gateway instead (npm i -g @chatpanel/gateway --ignore-scripts), or pick a model that runs on the bundled runtime")})(),e)}export{l as getOrt,r as nativeOrtFailure,s as ortProviders,o as ortRuntimeName,i as rawOrtAvailable};
@@ -0,0 +1,2 @@
1
+ import{createRequire as j}from"node:module";import{rmSync as k,existsSync as $,readdirSync as y,statSync as z}from"node:fs";import{join as u,dirname as b,sep as i}from"node:path";import{fileURLToPath as T}from"node:url";const d=j(import.meta.url);function D(){return T(import.meta.url).includes(`${i}node_modules${i}@chatpanel${i}gateway${i}`)}function g(n){let t=0;for(const s of y(n,{withFileTypes:!0})){const o=u(n,s.name);try{t+=s.isDirectory()?g(o):z(o).size}catch{}}return t}const P=n=>`${Math.round(n/1e6)} MB`;function R({log:n=()=>{},dryRun:t=!1,packageRoot:s=null,platform:o=process.platform,arch:v=process.arch,verify:F=null,webRoot:x=void 0}={}){const c=e=>({pruned:[],freed:0,skipped:e});let f=s;if(!f){if(!D())return c("running from a checkout, not an install");let e;try{e=d.resolve("onnxruntime-node/dist/binding.js")}catch{return c("onnxruntime-node is not installed")}if(f=b(b(e)),!f.split(i).includes("node_modules"))return c("not an installed package")}const a=u(f,"bin","napi-v6");if(!$(a))return c("no prebuild directory");const w=u(a,o,v);if(!$(u(w,"onnxruntime_binding.node")))return c(`no prebuild for ${o}/${v} — leaving every platform in place`);try{(F||(()=>d("onnxruntime-node")))()}catch(e){return c(`the native runtime does not load (${e.message.split(`
2
+ `)[0]}) — leaving every platform in place`)}const l=[];let m=0;for(const e of y(a,{withFileTypes:!0}))if(e.isDirectory())for(const r of y(u(a,e.name),{withFileTypes:!0})){if(!r.isDirectory())continue;const p=u(a,e.name,r.name);if(p===w)continue;let h=0;try{h=g(p)}catch{}if(t){l.push(`${e.name}/${r.name}`),m+=h;continue}try{k(p,{recursive:!0,force:!0}),l.push(`${e.name}/${r.name}`),m+=h}catch(S){n(`[prune] could not remove ${e.name}/${r.name}: ${S.message}`)}}if(x!==!1){const e=x||_();if(e&&$(e)){let r=0;try{r=g(e)}catch{}if(t)l.push("onnxruntime-web"),m+=r;else try{k(e,{recursive:!0,force:!0}),l.push("onnxruntime-web"),m+=r}catch(p){n(`[prune] could not remove onnxruntime-web: ${p.message}`)}}}return{pruned:l,freed:m,skipped:""}}function _(){try{return b(d.resolve("onnxruntime-web/package.json"))}catch{}try{const n=d.resolve("onnxruntime-web"),t=n.lastIndexOf(`${i}onnxruntime-web${i}`);return t===-1?"":n.slice(0,t+`${i}onnxruntime-web`.length)}catch{return""}}function B({pruned:n,freed:t},{platform:s=process.platform,arch:o=process.arch}={}){return n.length?` Freed ${P(t)} — removed ${n.join(", ")}: runtimes this install cannot reach (the native ${s}/${o} one it does use is kept).`:""}export{R as pruneForeignPrebuilds,B as pruneLine};
package/src/runtime.js CHANGED
@@ -1,4 +1,4 @@
1
- import{promisify as on}from"node:util";import{execFile as ln}from"node:child_process";import{existsSync as ce,mkdirSync as q,writeFileSync as de,accessSync as sn,openSync as un,closeSync as cn,constants as dn}from"node:fs";import{randomBytes as mn}from"node:crypto";import Z from"node:os";import b from"node:path";import{modelsFor as Be,isValidModelId as fn,catalogFor as me,vllmTaskOf as V}from"./runtime-models.js";import{pickInferenceEngine as Le,pickLlamaEngine as pn,pickMlxEngine as hn,recommendEngine as gn,detectAccelerator as kn,hostShape as wn}from"./inference-engines.js";import{tuningArgs as ee,tuningRows as Ce,patchTunings as bn,profilesFor as Re,resolveTunings as Ge,ENGINE_DOCS as yn}from"./engine-tunings.js";import{IMAGE_RECIPES as $n}from"./images.js";import{pullRepo as vn,pullGguf as Sn,repoInstalled as xn,ggufInstalled as Ne}from"./model-pull.js";import{spawn as An}from"node:child_process";import{readFileSync as Te,unlinkSync as Fe}from"node:fs";const _n=on(ln),ne=["podman","docker"],I="hf-cache",z=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],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,s)=>{try{return(await s(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,s)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:s}},unconfigure:(t,s)=>{t.search?.searxng?.url===s&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],adapter:"tei",model:"BAAI/bge-reranker-v2-m3",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. A cross-encoder (bge-reranker-v2-m3, multilingual) behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:s,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,s)=>{t.capabilities?.rerank?.url===s&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],adapter:"systemone",model:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:s,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,s)=>{t.capabilities?.decide?.url===s&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm:latest",engineOf:t=>Le({...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=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,s)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...V(t.model)==="embed"?["--task","embed"]:[],...ee("vllm",t.tunings,{task:V(t.model),model:t.model,backend:s?.backend||null})],answers:async(t,s)=>{try{return(await s(`${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(s=>s?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{const h=`${s}/v1`,x=V(f.model);He(t),x==="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"})):x==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):x==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>He(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>Le(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,s)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("vllm-metal",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,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:`${s}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm-metal"&&s?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>pn(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,s)=>["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",...ee("llama",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="llama"&&s?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>hn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-4B-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,s)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("mlx",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="mlx"&&s?.id!=="mlx"))}}]);function He(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm"&&s?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const P=t=>z.find(s=>s.id===t)||null,Mn=({answers:t,configured:s,configure:f,unconfigure:h,volumes:x,args:p,env:G,caps:te,command:pe,engineOf:C,alias:A,...E})=>E;function Pn(t=[]){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:",...(t.length?t:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(f=>[` - name: ${f}`," disabled: false"])," - name: google"," disabled: true",""].join(`
1
+ import{promisify as on}from"node:util";import{execFile as ln}from"node:child_process";import{existsSync as ce,mkdirSync as q,writeFileSync as de,accessSync as sn,openSync as un,closeSync as cn,constants as dn}from"node:fs";import{randomBytes as mn}from"node:crypto";import Z from"node:os";import b from"node:path";import{modelsFor as Be,isValidModelId as fn,catalogFor as me,vllmTaskOf as V}from"./runtime-models.js";import{pickInferenceEngine as Le,pickLlamaEngine as pn,pickMlxEngine as hn,recommendEngine as gn,detectAccelerator as kn,hostShape as wn}from"./inference-engines.js";import{tuningArgs as ee,tuningRows as Ce,patchTunings as bn,profilesFor as Re,resolveTunings as Ge,ENGINE_DOCS as yn}from"./engine-tunings.js";import{IMAGE_RECIPES as $n}from"./images.js";import{pullRepo as vn,pullGguf as Sn,repoInstalled as xn,ggufInstalled as Ne}from"./model-pull.js";import{spawn as An}from"node:child_process";import{readFileSync as Te,unlinkSync as Fe}from"node:fs";const _n=on(ln),ne=["podman","docker"],I="hf-cache",z=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],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,s)=>{try{return(await s(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.search?.searxng?.url||""),configure:(t,s)=>{t.search=t.search||{},t.search.searxng={...t.search.searxng||{},url:s}},unconfigure:(t,s)=>{t.search?.searxng?.url===s&&(t.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker-cpu:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],adapter:"tei",model:"BAAI/bge-reranker-v2-m3",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. A cross-encoder (bge-reranker-v2-m3, multilingual) behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.rerank?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.rerank={url:s,adapter:f.adapter,model:f.model,service:f.id}},unconfigure:(t,s)=>{t.capabilities?.rerank?.url===s&&delete t.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision-cpu:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],adapter:"systemone",model:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:t=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data",`MODEL_ID=${t.model}`],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String(t.capabilities?.decide?.url||""),configure:(t,s,f)=>{t.capabilities=t.capabilities||{},t.capabilities.decide={url:s,adapter:f.adapter,model:f.model,service:f.id,calibrated:f.calibrated}},unconfigure:(t,s)=>{t.capabilities?.decide?.url===s&&delete t.capabilities.decide}},{id:"vllm",label:"vLLM",image:"ghcr.io/chatpanel/vllm-cpu:latest",engineOf:t=>Le({...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=>[`${b.join(t,I)}:/data`],env:t=>["HF_HOME=/data","VLLM_CPU_KVCACHE_SPACE=4",`MODEL_ID=${t.model}`,...t.installed?["HF_HUB_OFFLINE=1"]:[]],args:(t,s)=>["--model",t.model,"--host","0.0.0.0","--port","8000",...V(t.model)==="embed"?["--task","embed"]:[],...ee("vllm",t.tunings,{task:V(t.model),model:t.model,backend:s?.backend||null})],answers:async(t,s)=>{try{return(await s(`${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(s=>s?.service==="vllm")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{const h=`${s}/v1`,x=V(f.model);He(t),x==="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"})):x==="embed"?(t.capabilities=t.capabilities||{},t.capabilities.embed={url:h,adapter:"openai",model:f.model,service:"vllm"}):x==="transcription"&&(t.capabilities=t.capabilities||{},t.capabilities.stt={provider:"container",url:h,adapter:"openai",model:f.model,service:"vllm"})},unconfigure:t=>He(t)},{id:"vllm-metal",label:"vLLM (Metal, Apple Silicon)",kind:"native",runner:"vllm",pull:!0,engineOf:t=>Le(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,s)=>["vllm",["serve",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("vllm-metal",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="vllm-metal")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,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:`${s}/v1`,models:[f.model],service:"vllm-metal"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm-metal"&&s?.id!=="vllm-metal"))}},{id:"llama",label:"llama.cpp",kind:"native",runner:"llama-server",pull:!0,engineOf:t=>pn(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,s)=>["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",...ee("llama",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="llama")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="llama"&&h?.id!=="llama"),t.destinations.push({id:"llama",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.alias(f.model)],service:"llama"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="llama"&&s?.id!=="llama"))}},{id:"mlx",label:"MLX",kind:"native",runner:"mlx_lm.server",runnerCheck:["--help"],pull:!0,engineOf:t=>hn(t),only:{platform:"darwin",arch:"arm64"},port:8894,provides:["chat"],adapter:"openai",model:"mlx-community/Qwen3-4B-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,s)=>["mlx_lm.server",["--model",t.model,"--host","127.0.0.1","--port",String(t.port),...ee("mlx",t.tunings,s)]],answers:async(t,s)=>{try{return(await s(`${t}/v1/models`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:t=>String((t.destinations||[]).find(s=>s?.service==="mlx")?.baseUrl?.replace(/\/v1$/,"")||""),configure:(t,s,f)=>{t.destinations=(t.destinations||[]).filter(h=>h?.service!=="mlx"&&h?.id!=="mlx"),t.destinations.push({id:"mlx",type:"api",protocol:"openai",baseUrl:`${s}/v1`,models:[f.model],service:"mlx"})},unconfigure:t=>{Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="mlx"&&s?.id!=="mlx"))}}]);function He(t){Array.isArray(t.destinations)&&(t.destinations=t.destinations.filter(s=>s?.service!=="vllm"&&s?.id!=="vllm")),t.capabilities?.embed?.service==="vllm"&&delete t.capabilities.embed,t.capabilities?.stt?.service==="vllm"&&delete t.capabilities.stt}const P=t=>z.find(s=>s.id===t)||null,Mn=({answers:t,configured:s,configure:f,unconfigure:h,volumes:x,args:p,env:G,caps:te,command:pe,engineOf:C,alias:A,...E})=>E;function Pn(t=[]){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:",...(t.length?t:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(f=>[` - name: ${f}`," disabled: false"])," - name: google"," disabled: true",""].join(`
2
2
  `)}function fe(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 Ie(t,s){const f=s==="podman"?Array.isArray(t.Names)?t.Names[0]:String(t.Names||""):String(t.Names||t.Name||""),h=s==="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),x=String(t.State||"").toLowerCase()||(/^up/i.test(String(t.Status||""))?"running":"exited");return{name:f,image:String(t.Image||""),state:x,status:String(t.Status||""),ports:h,ours:f.startsWith("chatpanel-"),engine:s}}function Dn({cfg:t,bridgeHealth:s,workers:f=()=>[],persist:h=()=>{},exec:x=(O,U,N={})=>_n(O,U,{timeout:6e4,killSignal:"SIGKILL",...N}),platform:p=process.platform,arch:G=process.arch,spawn:te=An,lookup:pe=null,fetchImpl:C=globalThis.fetch,stateDir:A=b.join(Z.homedir(),".chatpanel","runtime"),log:E=()=>{},sleep:re=O=>new Promise(U=>setTimeout(U,O)),totalMem:he=()=>Z.totalmem()}={}){const O=Z.homedir(),U=p==="win32"?[b.join(O,"AppData","Local","Microsoft","WinGet","Links"),b.join(O,".local","bin"),b.join(O,".cargo","bin")]:["/opt/homebrew/bin","/usr/local/bin",b.join(O,".local","bin"),b.join(O,".cargo","bin"),"/home/linuxbrew/.linuxbrew/bin"],N=(n=process.env)=>{const e=p==="win32"?";":":",r=String(n.PATH||n.Path||""),i=U.filter(l=>!r.split(e).includes(l));return{...n,PATH:[...r.split(e).filter(Boolean),...i].join(e)}},w=async(n,e,r={})=>{try{const i=await x(n,e,{...r,env:N(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}}},g=n=>String(t.runtime?.services?.[n.id]?.model||n.model||"");let ie=null;const Ue=async()=>(ie===null&&(ie=await kn({exec:x,platform:p,arch:G})),ie),j={},je=n=>{const e=p==="win32"?";":":",r=p==="win32"?[".exe",".cmd",".bat",""]:[""];for(const i of N().PATH.split(e).filter(Boolean))for(const l of r)try{return sn(b.join(i,n+l),dn.X_OK),!0}catch{}return!1},R=async(n,e=["--version"])=>(j[n]===void 0&&(j[n]=(pe||je)(n)||(await w(n,e,{timeout:8e3})).ok),j[n]);let ae=null;const ge=async()=>(ae||(ae=await wn({exec:x,platform:p,totalmem:he,cpus:()=>Z.cpus()})),ae),B=async n=>({platform:p,arch:G,accelerator:await Ue(),engine:n,vllmOnPath:await R("vllm"),llamaOnPath:await R("llama-server"),mlxOnPath:p==="darwin"&&G==="arm64"?await R("mlx_lm.server",["--help"]):!1,...await ge()}),D=n=>!n.only||(!n.only.platform||n.only.platform===p)&&(!n.only.arch||n.only.arch===G),K=n=>b.join(A,`${n.id}.pid`),X=n=>{try{const e=Number(Te(K(n),"utf8"));if(e>0)return process.kill(e,0),e}catch{}return null},oe=n=>D(n)?X(n)?"running":"stopped":"unsupported",T={};async function le(n){const e=J(n);if(!D(e))return{ok:!1,error:`${e.label} runs on ${e.only?.platform||"this platform"} ${e.only?.arch||""} only`};if(X(e))return{ok:!0,already:!0,url:M(e)};const r=await B(null),i=e.engineOf(r);if(!await R(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)&&!ce(e.model))return{ok:!1,error:`no such file: ${e.model}`};const[l,a]=e.command(e,L(e,e.model,i,r)),o=b.join(A,I);q(o,{recursive:!0,mode:448});const u={bin:l,argv:a,opts:{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,HF_HOME:o,LLAMA_CACHE:o,...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"}};T[e.id]=u.record;const m=b.join(A,`${e.id}.log`);let d,c=null;try{try{c=un(m,"w",384)}catch{c=null}d=te(u.bin,u.argv,{...u.opts,env:N(u.opts?.env),detached:!0,stdio:["ignore",c??"ignore",c??"ignore"]}),d.unref?.()}catch(v){return{ok:!1,error:`${u.bin}: ${v.message}`,install:i.install}}finally{if(c!==null)try{cn(c)}catch{}}if(!d?.pid)return{ok:!1,error:`${u.bin} did not start`,install:i.install};de(K(e),String(d.pid),{mode:384});const y=M(e);let $=!1;for(let v=0;v<120&&!$&&X(e);v++)$=await e.answers(y,C),$||await re(1e3);if(!X(e)){try{Fe(K(e))}catch{}let v="";try{v=Te(m,"utf8").trim().split(`
3
3
  `).filter(Q=>/\b(E |error|Error|couldn't|cannot|failed|not found|No such)\b/.test(Q)).slice(-3).map(Q=>Q.replace(/^[\d.]+ [A-Z] \S+\s+/,"").trim()).join(" | ")}catch{v=""}return{ok:!1,error:`${e.label} exited on start${v?` — ${v}`:` — a model it cannot load, a draft or projector file that is not there, or ${e.runner} not installed (${i.install?.command})`}`,log:m}}return e.configure(t,y,e),h(),E(`[runtime] ${e.label} started (pid ${d.pid}) on ${y}, sandbox ${T[e.id].layer}${$?"":" — not answering yet (downloading the model?)"}`),{ok:!0,url:y,answering:$,provides:e.provides,model:g(e),sandbox:T[e.id]}}function ke(n){const e=X(n);if(e)try{process.kill(e,"SIGTERM")}catch{}try{Fe(K(n))}catch{}return n.unconfigure(t,M(n)),h(),{ok:!0}}const J=n=>n.model?{...n,model:g(n),installed:H(n,g(n)),tunings:t.runtime?.services?.[n.id]?.tunings||{},...n.id==="llama"?{file:Xe(g(n))}:{}}:n,F=n=>n.id==="vllm"||n.id==="vllm-metal"||n.id==="llama"||n.id==="mlx";function De(n,e){const r=(e.ramGB||0)*1024,i={light:0,balanced:1,accurate:2,max:3},l=me(n.id).filter(u=>!u.minRamMB||r>0&&r>=u.minRamMB);if(!l.length||!r)return null;const a=l.slice().sort((u,m)=>(i[m.tier]??-1)-(i[u.tier]??-1)||u.ramMB-m.ramMB)[0],o=Math.round(a.ramMB/1024*10)/10;return{model:a.id,label:a.label,why:`This machine (${e.ramGB} GB${e.accelerator==="apple"?", Apple Silicon":e.accelerator?`, ${e.accelerator.toUpperCase()} GPU`:", no GPU"}) runs ${a.label} well — about ${o} GB while loaded${a.tier==="max"?"; the strongest in the list":""}.`,profile:"coding",current:g(n)===a.id}}const L=(n,e,r,i={})=>({task:n.id==="vllm"?V(e):"chat",model:e,backend:r?.backend||null,ramGB:i.ramGB||0,cores:i.cores||0,perfCores:i.perfCores||0}),W=()=>b.join(A,I),H=(n,e)=>/\.gguf$/i.test(e)?ce(e):n.id==="llama"?!!Ne(W(),e):xn(W(),e),Xe=n=>/\.gguf$/i.test(n)?n:Ne(W(),n),k={},En=n=>k[n.id]||null;function se(n,e,r={}){return k[n.id]={kind:e,since:Date.now(),lines:[],progress:null,done:!1,error:null,...r},k[n.id]}function _(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 Y=(n,e,r,{timeout:i=36e5*4}={})=>new Promise(l=>{if(n.cancelled)return l({ok:!1,code:-1,error:"cancelled"});let a;try{a=te(e,r,{stdio:["ignore","pipe","pipe"],env:N()})}catch(d){return l({ok:!1,code:-1,error:d.message})}n.child=a;let o="";const u=d=>{o+=String(d);const c=o.split(/\r?\n|\r/);o=c.pop();for(const y of c)_(n,y)};a.stdout?.on("data",u),a.stderr?.on("data",u);const m=setTimeout(()=>{try{a.kill("SIGTERM")}catch{}},i);m.unref?.(),a.on("error",d=>{clearTimeout(m),n.child=null,l({ok:!1,code:-1,error:d.message})}),a.on("exit",d=>{clearTimeout(m),n.child=null,o&&_(n,o),l({ok:d===0&&!n.cancelled,code:d,...n.cancelled?{error:"cancelled"}:{}})})}),we={install:Promise.resolve(),build:Promise.resolve()},ue={install:0,build:0},be=(n,e,r)=>{ue[n]>0&&(e.waiting=!0,_(e,`waiting for the other ${n} to finish first — one at a time`)),ue[n]++;const i=we[n];let l;const a=new Promise(o=>{l=o});return we[n]=i.then(()=>a),i.then(async()=>{e.waiting&&(_(e,"the other one finished — going"),e.waiting=!1);try{return await r()}finally{ue[n]--,l()}})},ye=async(n,e)=>(await w(n,["image","exists",e],{timeout:2e4})).ok;async function Je(n,e,r,i){const l=e?.image||r.image;if(await ye(n,l))return{ok:!0};const a=e?.sources?.length?e.sources:[l],o=[];for(const c of a){if(i.kind="pull-image",i.detail=c,_(i,`pulling ${c}`),(await Y(i,n,["pull",c])).ok)return c!==l&&await w(n,["tag",c,l],{timeout:2e4}),{ok:!0,pulled:c};o.push(c)}const u=e?.recipe?$n[e.recipe]:null;if(!u)return{ok:!1,error:`no image to pull (${o.join(", ")} — ${i.lines.at(-1)||"refused"})`};const m=b.join(A,"images",e.recipe);return q(m,{recursive:!0,mode:448}),de(b.join(m,"Dockerfile"),u.dockerfile,{mode:384}),i.kind="build-image",i.detail=l,i.minutes=u.minutes,_(i,`no registry has ${l} for this machine — building it here (about ${u.minutes} minutes)`),E(`[runtime] building ${l} from the ${e.recipe} recipe in ${m}`),(await be("build",i,()=>Y(i,n,["build","-t",l,"-f",b.join(m,"Dockerfile"),m]))).ok?{ok:!0,built:!0}:{ok:!1,error:`build failed: ${i.lines.slice(-3).join(" | ")}`}}async function $e(n,e){const r=g(n);if(!r||H(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=l=>{if(e.cancelled)throw new Error("cancelled");e.progress={bytes:l.bytes,total:l.total,file:l.file}};try{return n.id==="llama"?await Sn(r,{root:W(),fetchImpl:C,onProgress:i}):await vn(r,{root:W(),fetchImpl:C,onProgress:i}),{ok:!0}}catch(l){return{ok:!1,error:`pull ${r}: ${l.message}`}}}async function We(n,e,r){const i=[];return n.kind!=="native"&&e&&!await ye(e,r?.image||n.image)&&i.push("image"),n.pull&&n.model&&!H(n,g(n))&&i.push("model"),i}async function ve(n,e){if(!n||!e?.[n]?.running)return 0;if(n==="podman"&&p!=="linux"){const r=await w("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 w("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),i=parseInt(r.out,10);return r.ok&&i>0?Math.round(i/1048576):0}return Math.round(he()/1048576)}async function S(){const n={};for(const r of ne){const i=await w(r,["--version"],{timeout:5e3});if(!i.ok){n[r]={installed:!1};continue}const l=(i.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||i.out;let a=!1,o=null;if(r==="podman")if(p==="linux")a=(await w("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const u=await w("podman",["machine","list","--format","json"],{timeout:8e3});try{const d=JSON.parse(u.out||"[]")[0]||null;o=d?{name:d.Name,running:!!d.Running}:null,a=!!d?.Running}catch{o=null}}else a=(await w("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;n[r]={installed:!0,version:l,running:a,...r==="podman"&&p!=="linux"?{machine:o}:{}}}const e=ne.find(r=>n[r]?.installed&&n[r].running)||ne.find(r=>n[r]?.installed)||null;return{...n,preferred:e,...e?{}:{install:fe(p)}}}async function Se(n="podman"){if(!ne.includes(n))return{ok:!1,error:`unknown engine ${n}`};const e=(await S())[n];if(!e?.installed)return{ok:!1,error:`${n} is not installed`,install:fe(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 w("podman",["machine","init"],{timeout:6e5});if(!i.ok)return{ok:!1,error:`podman machine init: ${i.err||i.out}`}}const r=await w("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 Qe(){const n=await S(),e=n.preferred;if(!e||!n[e].running)return[];if(e==="podman"){const i=await w("podman",["ps","-a","--format","json"],{timeout:1e4});if(!i.ok)return[];try{return JSON.parse(i.out||"[]").map(l=>Ie(l,"podman"))}catch{return[]}}const r=await w("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
4
4
  `).filter(Boolean).map(i=>{try{return Ie(JSON.parse(i),"docker")}catch{return null}}).filter(Boolean):[]}async function xe(n,e){const r=await w(n,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}async function Ae(n,e){const r=await w(n,["ps","-a","--format","{{.Names}} {{.State}}"],{timeout:8e3}),i={};if(!r.ok){for(const a of e)i[a]="absent";return i}const l=new Map(r.out.split(`
package/src/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createServer as Ft}from"node:http";import{loadConfig as rt}from"./config.js";import{startEntitlementRefresh as Wt,maybeRevalidate as Kt}from"./entitlement-refresh.js";import{redactSegments as Oe,segment as je}from"./redact.js";import{pipeRestoredStream as Qt,pipeRestoredOpenAIStream as Zt,makeTokenRestorer as nt,restoreDeep as Yt}from"./stream.js";import{restoreText as Xt,gatedDictionary as qt,narrowSpecs as eo,makeToolHarness as to,placeholderToolNote as oo,placeholderNote as ro,assertEndpointUrl as no,capRunOptions as so,isPaired as ao}from"@chatpanel/pii";import{ensureGatewayToken as Re,currentGatewayToken as io,isAdminAuthorized as X,callerTrustOf as $e,setPinnedExtensionIds as lo,issuePairingCode as co,claimPairingCode as uo}from"./gateway-token.js";import{installEgressLedger as mo,egressAudit as po}from"./egress.js";import{initPolicy as ho,activePolicy as yo,applyPolicyToConfig as st,managedSummary as ke,PolicyLoadError as fo}from"./policy.js";import{routeAllowed as at,agentAllowed as go,egressAllowed as wo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ye}from"./bridge.js";import{secureFetch as Pe}from"./secure-fetch.js";import{streamBridgeChat as it,readBridgeToken as de,openBridgeChat as bo}from"./bridge.js";import{createRelaySession as vo,getRelaySession as lt,endRelaySession as Se,pumpBridgeStream as ko,deliverToolResult as So,toolsToSpecs as To,wantsApprovals as xo,parseToolCallId as ct,touchRelaySession as Ie}from"./toolrelay.js";import{shaperFor as Le}from"./shape.js";import{startNer as _o,ensureNer as Ee,unionForThisMachine as Oo,skippedCompanions as $o}from"./ner.js";import{recommendDetector as dt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Po}from"./log.js";import{saveBackupSecret as Eo,clearBackupSecret as Ao,loadBackupSecret as Je,hasBackupSecret as ut}from"./history-store.js";import{createMemoryStore as No}from"./memory-store.js";import{createPrefsStore as Bo}from"./prefs-store.js";import{createTeamStore as Do,loadOrCreateKey as ze}from"./team-store.js";import{createScorecardStore as Mo}from"./scorecard-store.js";import{createEngineLedgerStore as Co}from"./engine-ledger-store.js";import{createProjectStore as jo}from"./project-store.js";import{applicationsFor as Ro,recruitPass as Io}from"./recruiting.js";import{ensureBridge as Lo}from"./bridge-supervisor.js";import{checkForUpdate as Jo,updateStatus as zo,startUpdate as Go,updateJob as Ho}from"./update.js";import{createHistoryStore as Vo}from"./sqlite-store.js";import{createEventStore as Uo}from"./event-store.js";import{ingestCloudEvents as Fo,cursorOf as mt}from"./event-sync.js";import{eventStats as Wo,projectYear as Ko}from"./event-stats.js";import{toCloudEvent as Ge}from"./cloudevents.js";import{fusionsDocument as Qo,resolveFusionModel as Zo}from"./fusions.js";import{ingestBackups as He}from"./backup-ingest.js";import{toSearchRecord as Yo}from"@chatpanel/events/library.js";import{deriveBackupKey as Xo,openRecord as qo,keyCache as er,nodeCodec as tr}from"@chatpanel/events/backup-envelope.js";import or from"node:zlib";import*as E from"./ner-engine.js";import pt from"node:os";import{capabilitiesDocument as rr,handleDetect as nr}from"./capabilities.js";import{createExtractService as sr}from"./extract/service.js";import{workerSandbox as ar,disposeWorkerSandbox as ir}from"./worker-sandbox.js";import{createRuntime as lr}from"./runtime.js";import{createCapabilityProxy as cr}from"./capability-proxy.js";import{handleExtract as dr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as ur}from"./extract-capability.js";import{createReader as mr}from"./retrieval/read.js";import{createSearcher as pr,toJinaSearch as hr,SEARCH_DEFAULTS as yr}from"./retrieval/search.js";import{createSearxng as fr}from"./retrieval/search-searxng.js";import{toJinaText as gr}from"./read-document.js";import*as A from"./stt-engine.js";import*as j from"./diarize-engine.js";import{providerOf as ht}from"./providers.js";import{createRemoteTranscriber as yt}from"./stt-remote.js";import{parseMultipart as wr,decodeAudioFile as br}from"./audio-file.js";import{MODEL_CATALOG as ft,isKnownModel as gt,isValidCustomModelId as wt,recommendFor as vr}from"./models.js";import{STT_MODEL_CATALOG as kr,isKnownSttModel as Sr,isValidCustomSttId as Tr,DEFAULT_STT_MODEL as Ae,STT_DTYPES as xr,isValidDtype as _r}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as bt,TTS_VOICES as Or,isKnownTtsModel as $r,isValidCustomTtsId as Pr,isKnownVoice as vt,isValidVoiceId as kt,DEFAULT_TTS_MODEL as St,DEFAULT_TTS_VOICE as ue,TTS_DTYPES as Er,isValidTtsDtype as Ar,MAX_TTS_CHARS as Tt,ttsModelHasCustomVoices as Nr,resolveDefaultModel as xt,POCKET_VOICES as Br,DEFAULT_POCKET_VOICE as Ne,isPocketVoice as Be,ttsModelEngine as De}from"./tts-models.js";import{ttsDestination as Dr,synthesizeRemote as Mr,isValidRemoteVoice as Cr}from"./tts-remote.js";import{rawOrtAvailable as Ve}from"./ort.js";import*as K from"./tts-voices.js";import{resolveTtsVoice as jr}from"./tts-voice-resolve.js";import{resolvePro as fe,checkQuota as Rr,consume as Ir,usage as Lr}from"./freegate.js";import{publicConfig as _t,applyConfigPatch as Jr,applyNerModelSelection as Ot,persistConfig as me,configPath as se,bridgeAgentOptions as $t,PERMISSION_MODES as zr,sandboxEnvFor as Gr}from"./configstore.js";import Pt from"node:path";import{resolveDestination as Et,aggregateModelsAsync as Hr,listDestinations as Vr}from"./router.js";import{makeAccessEvent as At}from"./observability.js";import{createPersistentAccessLog as Ur}from"./access-log-store.js";import{planQueries as Fr,multiSearch as Wr}from"./rrf.js";import*as Ue from"./openai.js";import*as Nt from"./responses.js";import*as Fe from"./anthropic.js";import{closeAndExit as Kr}from"./shutdown.js";const ee="0.39.4",N=await Vo(),ae=new Set;function Me({ids:t=[]}={}){const c=N.lossless;if(!c||!ae.size)return;const d=JSON.stringify({newest:c.newest,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of ae)try{m.write(`event: records
1
+ import{createServer as Ft}from"node:http";import{loadConfig as rt}from"./config.js";import{startEntitlementRefresh as Wt,maybeRevalidate as Kt}from"./entitlement-refresh.js";import{redactSegments as Oe,segment as je}from"./redact.js";import{pipeRestoredStream as Qt,pipeRestoredOpenAIStream as Zt,makeTokenRestorer as nt,restoreDeep as Yt}from"./stream.js";import{restoreText as Xt,gatedDictionary as qt,narrowSpecs as eo,makeToolHarness as to,placeholderToolNote as oo,placeholderNote as ro,assertEndpointUrl as no,capRunOptions as so,isPaired as ao}from"@chatpanel/pii";import{ensureGatewayToken as Re,currentGatewayToken as io,isAdminAuthorized as X,callerTrustOf as $e,setPinnedExtensionIds as lo,issuePairingCode as co,claimPairingCode as uo}from"./gateway-token.js";import{installEgressLedger as mo,egressAudit as po}from"./egress.js";import{initPolicy as ho,activePolicy as yo,applyPolicyToConfig as st,managedSummary as ke,PolicyLoadError as fo}from"./policy.js";import{routeAllowed as at,agentAllowed as go,egressAllowed as wo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ye}from"./bridge.js";import{secureFetch as Pe}from"./secure-fetch.js";import{streamBridgeChat as it,readBridgeToken as de,openBridgeChat as bo}from"./bridge.js";import{createRelaySession as vo,getRelaySession as lt,endRelaySession as Se,pumpBridgeStream as ko,deliverToolResult as So,toolsToSpecs as To,wantsApprovals as xo,parseToolCallId as ct,touchRelaySession as Ie}from"./toolrelay.js";import{shaperFor as Le}from"./shape.js";import{startNer as _o,ensureNer as Ee,unionForThisMachine as Oo,skippedCompanions as $o}from"./ner.js";import{recommendDetector as dt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Po}from"./log.js";import{saveBackupSecret as Eo,clearBackupSecret as Ao,loadBackupSecret as Je,hasBackupSecret as ut}from"./history-store.js";import{createMemoryStore as No}from"./memory-store.js";import{createPrefsStore as Bo}from"./prefs-store.js";import{createTeamStore as Do,loadOrCreateKey as ze}from"./team-store.js";import{createScorecardStore as Mo}from"./scorecard-store.js";import{createEngineLedgerStore as Co}from"./engine-ledger-store.js";import{createProjectStore as jo}from"./project-store.js";import{applicationsFor as Ro,recruitPass as Io}from"./recruiting.js";import{ensureBridge as Lo}from"./bridge-supervisor.js";import{checkForUpdate as Jo,updateStatus as zo,startUpdate as Go,updateJob as Ho}from"./update.js";import{createHistoryStore as Vo}from"./sqlite-store.js";import{createEventStore as Uo}from"./event-store.js";import{ingestCloudEvents as Fo,cursorOf as mt}from"./event-sync.js";import{eventStats as Wo,projectYear as Ko}from"./event-stats.js";import{toCloudEvent as Ge}from"./cloudevents.js";import{fusionsDocument as Qo,resolveFusionModel as Zo}from"./fusions.js";import{ingestBackups as He}from"./backup-ingest.js";import{toSearchRecord as Yo}from"@chatpanel/events/library.js";import{deriveBackupKey as Xo,openRecord as qo,keyCache as er,nodeCodec as tr}from"@chatpanel/events/backup-envelope.js";import or from"node:zlib";import*as E from"./ner-engine.js";import pt from"node:os";import{capabilitiesDocument as rr,handleDetect as nr}from"./capabilities.js";import{createExtractService as sr}from"./extract/service.js";import{workerSandbox as ar,disposeWorkerSandbox as ir}from"./worker-sandbox.js";import{createRuntime as lr}from"./runtime.js";import{createCapabilityProxy as cr}from"./capability-proxy.js";import{handleExtract as dr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as ur}from"./extract-capability.js";import{createReader as mr}from"./retrieval/read.js";import{createSearcher as pr,toJinaSearch as hr,SEARCH_DEFAULTS as yr}from"./retrieval/search.js";import{createSearxng as fr}from"./retrieval/search-searxng.js";import{toJinaText as gr}from"./read-document.js";import*as A from"./stt-engine.js";import*as j from"./diarize-engine.js";import{providerOf as ht}from"./providers.js";import{createRemoteTranscriber as yt}from"./stt-remote.js";import{parseMultipart as wr,decodeAudioFile as br}from"./audio-file.js";import{MODEL_CATALOG as ft,isKnownModel as gt,isValidCustomModelId as wt,recommendFor as vr}from"./models.js";import{STT_MODEL_CATALOG as kr,isKnownSttModel as Sr,isValidCustomSttId as Tr,DEFAULT_STT_MODEL as Ae,STT_DTYPES as xr,isValidDtype as _r}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as bt,TTS_VOICES as Or,isKnownTtsModel as $r,isValidCustomTtsId as Pr,isKnownVoice as vt,isValidVoiceId as kt,DEFAULT_TTS_MODEL as St,DEFAULT_TTS_VOICE as ue,TTS_DTYPES as Er,isValidTtsDtype as Ar,MAX_TTS_CHARS as Tt,ttsModelHasCustomVoices as Nr,resolveDefaultModel as xt,POCKET_VOICES as Br,DEFAULT_POCKET_VOICE as Ne,isPocketVoice as Be,ttsModelEngine as De}from"./tts-models.js";import{ttsDestination as Dr,synthesizeRemote as Mr,isValidRemoteVoice as Cr}from"./tts-remote.js";import{rawOrtAvailable as Ve}from"./ort.js";import*as K from"./tts-voices.js";import{resolveTtsVoice as jr}from"./tts-voice-resolve.js";import{resolvePro as fe,checkQuota as Rr,consume as Ir,usage as Lr}from"./freegate.js";import{publicConfig as _t,applyConfigPatch as Jr,applyNerModelSelection as Ot,persistConfig as me,configPath as se,bridgeAgentOptions as $t,PERMISSION_MODES as zr,sandboxEnvFor as Gr}from"./configstore.js";import Pt from"node:path";import{resolveDestination as Et,aggregateModelsAsync as Hr,listDestinations as Vr}from"./router.js";import{makeAccessEvent as At}from"./observability.js";import{createPersistentAccessLog as Ur}from"./access-log-store.js";import{planQueries as Fr,multiSearch as Wr}from"./rrf.js";import*as Ue from"./openai.js";import*as Nt from"./responses.js";import*as Fe from"./anthropic.js";import{closeAndExit as Kr}from"./shutdown.js";const ee="0.39.11",N=await Vo(),ae=new Set;function Me({ids:t=[]}={}){const c=N.lossless;if(!c||!ae.size)return;const d=JSON.stringify({newest:c.newest,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of ae)try{m.write(`event: records
2
2
  data: ${d}
3
3
 
4
4
  `)}catch{ae.delete(m)}}setInterval(()=>{for(const t of ae)try{t.write(`: ping
package/src/update.js CHANGED
@@ -1 +1 @@
1
- import J from"node:os";import i from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",ye="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||i.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ae(){m={at:0,error:""}}function T(){const e=i.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(i.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?i.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(i.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=i.dirname(process.execPath);return[i.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),i.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[i.dirname(t),...(n[a]||"").split(i.delimiter).filter(Boolean)].filter((r,o,l)=>l.indexOf(r)===o).join(i.delimiter),n}function ce(){const e=$(),t=le(),[n,a]=e?[process.execPath,[e,"install","-g",`${g}@latest`]]:["npm",["install","-g",`${g}@latest`]];return new Promise(r=>{b(n,a,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(o,l,p)=>{const s=`${l||""}${p||""}`.trim();return o?o.killed&&!s?r({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):r({ok:!1,out:s||(e?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):r({ok:!0,out:s})})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,l=!1,p="",s=0;const c=await oe(),h=c&&c.mode===n,C=()=>{r=h&&c.latest||null,o=h&&c.assetUrl||null,s=h&&c.checkedAt||0,l=!0};if(!t&&h&&Date.now()-c.checkedAt<L)r=c.latest,o=c.assetUrl,s=c.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,F=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),I=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest; chatpanel-gateway --install`:`npm i -g ${g}@latest`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:F,assetUrl:o,stale:l,error:p,npmCommand:I,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let w=null,A=null;function be(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(m.at&&Date.now()-m.at<N):Date.now()-w.seenAt>L))&&!A&&(A=H(e).then(a=>{w={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Ee(){w=null,A=null}async function de(e){const t=process.execPath,n=i.dirname(t),a=i.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let l;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);l=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(l.length<5<<20)throw new Error(`the download was only ${(l.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,l),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(c,h)=>s(c?"":String(h||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,i.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function pe(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await de(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await ce();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function _e(){return{...d}}function Se(e,{restart:t=Q,apply:n=pe}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function Te(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Te as _resetUpdateJob,Ee as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,le as npmInstallEnv,x as npmPackageRoot,Ae as resetUpdateBackoff,pe as selfUpdate,Se as startUpdate,_e as updateJob,be as updateStatus};
1
+ import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",be="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ee(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(l.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[l.dirname(t),...(n[a]||"").split(l.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(l.delimiter),n}function ce(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function de(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function pe(){const e=$(),t=le(),n=de(),[a,r]=e?[process.execPath,[e,...n]]:["npm",n];return new Promise(o=>{b(a,r,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,p,s)=>{const i=`${p||""}${s||""}`.trim();return c?c.killed&&!i?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:i||(e?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ce(),o({ok:!0,out:i}))})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,c=!1,p="",s=0;const i=await oe(),w=i&&i.mode===n,C=()=>{r=w&&i.latest||null,o=w&&i.assetUrl||null,s=w&&i.checkedAt||0,c=!0};if(!t&&w&&Date.now()-i.checkedAt<L)r=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,I=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),F=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:I,assetUrl:o,stale:c,error:p,npmCommand:F,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,A=null;function _e(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>L))&&!A&&(A=H(e).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),h?{...h,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Se(){h=null,A=null}async function ue(e){const t=process.execPath,n=l.dirname(t),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let c;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>s(i?"":String(w||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function me(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ue(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await pe();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Te(){return{...d}}function ve(e,{restart:t=Q,apply:n=me}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function xe(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{xe as _resetUpdateJob,Se as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,de as npmInstallArgs,le as npmInstallEnv,x as npmPackageRoot,Ee as resetUpdateBackoff,me as selfUpdate,ve as startUpdate,Te as updateJob,_e as updateStatus};