@chatpanel/gateway 0.53.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,14 +52,23 @@ the CLIs (`claude`, `codex`, …) as you normally would — that is all.
52
52
  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
- # Or via npm (needs Node):
55
+ # Or via npm (needs Node.js 22.13+):
56
56
  npm install -g @chatpanel/gateway --ignore-scripts
57
- chatpanel-gateway
58
- # → ChatPanel Privacy Gateway on http://127.0.0.1:4320
59
- # backend : bridge (agent: codex, via http://127.0.0.1:4319)
60
- # bridge : starting the embedded bridge (v0.11.20)
57
+ chatpanel-gateway --install
58
+ # → ChatPanel Privacy Gateway v0.55.0: running at http://127.0.0.1:4320, starts at login.
59
+ # bridge: embedded v0.29.5 — local agents are available.
61
60
  ```
62
61
 
62
+ `--install` is the step to run after every install **and every upgrade**: it registers the login
63
+ auto-start, stops an older gateway still running from before (npm replaced its files, not the
64
+ running process), and waits until the new version — and its bridge — answer. Plain
65
+ `chatpanel-gateway` runs it in the foreground instead, for a terminal; if another gateway already
66
+ holds 4320 it says which one and exits.
67
+
68
+ **Upgrading from the standalone binary to npm:** `install.sh` put `~/.local/bin` first on your
69
+ PATH, so `chatpanel-gateway` still means the old binary there. Run the npm copy by path once —
70
+ `"$(npm prefix -g)/bin/chatpanel-gateway" --install` — and it takes over the login service.
71
+
63
72
  On Windows, if `chatpanel-gateway` is "not recognized" right after `npm i -g`, npm's global bin
64
73
  folder is not on that shell's PATH yet: open a new PowerShell, or run it by path —
65
74
  `node "$(npm root -g)/@chatpanel/gateway/bin/chatpanel-gateway.js" --install`. **Updating on
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
- const s=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"};try{process.title=u[s]||"chatpanel-gateway"}catch{}try{if(s==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(s==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(s==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(s==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(s==="tools"||s==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(s==="policy"){const{loadPolicy:e,formatPolicy:a,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(a(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(s==="--audit"){const{egressAudit:e,formatAudit:a}=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 p=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${p}`},signal:AbortSignal.timeout(2500)});if(g.ok)o=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(!o){const{VERSION:p}=await import("../src/server.js");o={...e(c,{ledger:null,version:p}),observed:[]},console.log(`(${i}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(o,null,2)):console.log(a(o))}else if(s==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:a}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await a(process.argv.slice(3)))}else if(s==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:a}=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=a(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 → Coding Agents → "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(s==="local"){const{localStatus:e,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await e()))}else if(s==="connect"){const{connectAgents:e,formatConnect:a}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:a}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:h,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(s){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(a);break;case"--install":{const t=await n({version:a}),o=t.health;if(t.ok){const i=t.deferredTo?` — the ${t.deferredTo} app's gateway (v${o.version}) is the one answering right now; this install takes over at the next login`:"",p=t.replaced?`, replacing v${t.replaced}`:"";console.log(`ChatPanel Privacy Gateway v${o.version}: running at ${o.url}${p}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else o.ok?(console.error(`ChatPanel Privacy Gateway: v${a} is registered to start at login, but v${o.version} still answers at ${o.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${o.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
4
- ${t.errLog.split(`
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.shadow&&(console.log(` ⚠ ${t.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${a}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${a} either way.)`));try{const{pruneForeignPrebuilds:i,pruneLine:p}=await import("../src/prune-install.js"),g=p(i({log:d=>console.error(d)}));g&&console.log(g)}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: ${s}
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)}
2
+ const r=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"};try{process.title=u[r]||"chatpanel-gateway"}catch{}if(!process.versions.bun&&r!=="--version"&&r!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(r==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(r==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(r==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(r==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(r==="tools"||r==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(r==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:l}=await import("../src/policy.js");try{const i=await t();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(o(i))}catch(i){throw i instanceof l&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(r==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:l}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:d}=await import("node:path"),c=await import("node:os"),p=l(),e=`http://127.0.0.1:${p.port||4320}`;let a=null,n=`no gateway running at ${e}`;try{const h=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||d(c.homedir(),".chatpanel","gateway-token"),"utf8").trim(),s=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(s.ok)a=await s.json();else if(s.status===404){const g=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);n=`the gateway running at ${e}${g?.version?` (${g.version})`:""} predates --audit (0.7.0) — restart it after updating`}else n=`the gateway at ${e} refused the audit (HTTP ${s.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js");a={...t(p,{ledger:null,version:h}),observed:[]},console.log(`(${n}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(r==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(r==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:l}=await import("node:path"),i=await import("node:os"),c=`http://127.0.0.1:${t().port||4320}`,p=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(i.homedir(),".chatpanel","gateway-token");try{const e=o(p,"utf8").trim(),a=await fetch(`${c}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),n=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${c} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(n.error||`HTTP ${a.status}`);console.log(`Pairing code: ${n.display||n.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${c}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${p} — has the gateway started once?)`:""}`),process.exit(1)}}else if(r==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(r==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),l=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:l}),{dryRun:l}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:l,uninstallService:i,serviceReport:d,stopService:c,pathWithDir:p}=await import("../src/service.js");switch(r){case"--stop":c(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":{const e=await l({version:o,force:process.argv.includes("--force")}),a=e.health;if(e.newer){const n=a.managedBy&&a.managedBy!=="gateway"?` (run by the ${a.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${a.version} is already running at ${a.url}${n} — newer than this copy (v${o}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${o} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const n=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${a.version}) is the one answering right now; this install takes over at the next login`:"",h=e.replaced?`, replacing v${e.replaced}`:"";console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}${h}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${n}.`);let s=null;for(let g=0;g<30;g++){try{s=(await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(w=>setTimeout(w,500))}s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up.")}else a.ok?(console.error(`ChatPanel Privacy Gateway: v${o} is registered to start at login, but v${a.version} still answers at ${a.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
4
+ ${e.errLog.split(`
5
+ `).map(n=>` ${n}`).join(`
6
+ `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:n,pruneLine:h}=await import("../src/prune-install.js"),s=h(n({log:g=>console.error(g)}));s&&console.log(s)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&p(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await d());break;case void 0:await t();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${o}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
7
+ `));break;default:console.error(`unknown option: ${r}
8
+ Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.53.1",
3
+ "version": "0.55.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,12 +18,12 @@
18
18
  "README.md"
19
19
  ],
20
20
  "engines": {
21
- "node": ">=18"
21
+ "node": ">=22.13"
22
22
  },
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
- "@chatpanel/bridge": "^0.29.4",
26
- "@chatpanel/events": "^0.212.0",
25
+ "@chatpanel/bridge": "^0.29.5",
26
+ "@chatpanel/events": "^0.213.0",
27
27
  "@chatpanel/pii": "^0.11.3",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
@@ -1,3 +1,5 @@
1
- import"node:path";import{existsSync as Y}from"node:fs";import{spawn as q,spawnSync as z}from"node:child_process";import{resolveLaunch as J,standaloneCandidates as I,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as C}from"./bridge.js";import{srtModuleUrl as Z}from"./worker-sandbox.js";const O=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,G=[1e3,2e3,5e3,1e4,3e4],W=6e4,V=1200;function tt(){if(process.env.CHATPANEL_SRT_MODULE)return{};const o=Z();return o?{CHATPANEL_SRT_MODULE:o}:{}}function H(o,i){const n=String(o||"").split(".").map(e=>parseInt(e,10)),s=String(i||"").split(".").map(e=>parseInt(e,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let e=0;e<3;e+=1)if(n[e]!==s[e])return n[e]>s[e]?1:-1;return 0}function U({managed:o=!0,cfgUrl:i="",healthy:n=null,standalone:s=null,embeddedVersion:e=null}={}){if(o===!1||o==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const p=String(i||C);if(!O.test(p))return{action:"off",why:`bridge.url ${p} is not on this machine; nothing to start here`};if(n)return!n.managedBy&&e&&n.version&&H(n.version,e)<0?{action:"replace",why:`a standalone bridge (v${n.version}, run by nobody) answers at ${p} and is older than the embedded one (v${e}) — retiring it`}:{action:"adopt",why:`a bridge already answers at ${p}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const u=s?.version||null;return s?.path&&e&&H(u,e)>0?{action:"spawn-standalone",why:`the installed bridge (v${u}) is newer than the embedded one (v${e})`,path:s.path}:e?{action:"spawn-embedded",why:`starting the embedded bridge (v${e})${s?.path?` — the installed one is v${u||"?"}`:""}`}:s?.path?{action:"spawn-standalone",why:`starting the installed bridge${u?` (v${u})`:""}`,path:s.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function et(o,{timeoutMs:i=V,fetchImpl:n=fetch}={}){const s=new AbortController,e=setTimeout(()=>s.abort(),i);try{const p=await n(`${String(o).replace(/\/$/,"")}/health`,{signal:s.signal});if(!p.ok)return null;const u=await p.json().catch(()=>null);return u&&u.ok!==!1?{version:u.version||null,managedBy:u.managedBy||null}:null}catch{return null}finally{clearTimeout(e)}}function nt(o,i=[],{timeoutMs:n=8e3}={}){try{const s=z(o,[...i,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),e=String(s.stdout||"").trim().split(`
2
- `).pop();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function rt(){const{program:o,args:i}=J();return{program:o,args:[...i,"--bridge"]}}const it=o=>O.exec(String(o||C))?.[3]||"4319";async function ft(o,{log:i=a=>console.log(a),probe:n=et,spawnImpl:s=q,version:e=nt,candidates:p=I(),exists:u=Y,launch:j=rt,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:o?.bridge?.managed,waitForSiblingMs:R=2500,retire:F=Q,retireWaitMs:K=6e3,childEnv:X=()=>({}),now:w=Date.now,setTimer:S=setTimeout,setWatch:D=(a,t)=>{const h=setTimeout(a,t);return h.unref?.(),h},watchEveryMs:N=1e4}={}){const a=String(o?.bridge?.url||C).replace(/\/$/,""),t={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(r,c,d={})=>{Object.assign(t,{mode:r,why:c},d),i(` bridge : ${c}`)};let v=await n(a);if(!v&&b!==!1&&b!=="off"&&O.test(a)&&R>0){const r=w()+R;for(;!v&&w()<r;)await new Promise(c=>S(c,500)),v=await n(a)}const E=j(),$=!(b!==!1&&b!=="off")||v&&v.managedBy?null:e(E.program,E.args),L=p.find(r=>u(r))||null,P=L&&!v?{path:L,version:e(L,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:P,embeddedVersion:$});if(f.action==="off")return h("off",f.why),A();const M=r=>r.action==="spawn-embedded"?{...E,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||$}:{program:r.path,args:[],env:{},mode:"standalone",version:P?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:M(f),k=0,y=null,_=0;const x=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const d=async()=>{if(t.stopping||t.mode!=="adopted")return;const B=await n(a);if(B){_=0,t.version=B.version||t.version,y=D(d,N);return}if(_+=1,_<2){y=D(d,Math.min(N,3e3));return}if(!l){const g=$||e(E.program,E.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:P,embeddedVersion:g});if(m.action==="off"){h("off",`the adopted bridge went away and ${m.why}`);return}l=M({...m,version:g})}i(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),T()};y=D(d,N)},T=()=>{if(t.stopping)return;const r=s(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...X(),...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:it(a),...tt()}});k=w(),t.child=r,t.pid=r.pid||null;const c=(d,B)=>d?.on("data",g=>{for(const m of String(g).split(`
3
- `))m.trim()&&i(`[bridge] ${m}`)});c(r.stdout,"out"),c(r.stderr,"err"),r.on("error",d=>i(`[bridge] could not start ${l.program}: ${d?.message||d}`)),r.on("exit",async(d,B)=>{if(t.child=null,t.pid=null,t.stopping)return;const g=await n(a);if(g){x(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-k>W&&(t.backoff=0);const m=G[Math.min(t.backoff,G.length-1)];t.backoff+=1,t.restarts+=1,i(`[bridge] exited (${B||d}); restarting in ${m/1e3}s`),S(T,m)})};if(f.action==="adopt")return x(f.why,v.version),A();if(f.action==="replace"){i(` bridge : ${f.why}`);try{F({paths:p})}catch(d){i(` bridge : could not retire the standalone bridge: ${d?.message||d}`)}const r=w()+K;let c=await n(a);for(;c&&w()<r;)await new Promise(d=>S(d,500)),c=await n(a);return c?(x(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=M({action:"spawn-embedded",version:$}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${$})`,{version:$}),T(),A())}return h(l.mode,f.why,{version:l.version}),T(),A();function A(){return{status:()=>({mode:t.mode,version:t.version,pid:t.pid,restarts:t.restarts,why:t.why}),stop:()=>{if(t.stopping=!0,y&&(clearTimeout(y),y=null),t.child&&!t.child.killed)try{t.child.kill("SIGTERM")}catch{}},restart:(r="settings changed")=>{if(!t.child||t.stopping)return t.mode==="adopted"&&i(`[bridge] ${r} — the bridge on ${a} is not ours (${t.why}); set CHATPANEL_SANDBOX* in its own service`),!1;i(`[bridge] restarting: ${r}`),t.backoff=0;try{t.child.kill("SIGTERM")}catch{}return!0}}}}export{H as compareVersions,rt as embeddedLaunch,ft as ensureBridge,U as planBridge,et as probeBridge,tt as srtModuleEnv,I as standaloneCandidates,nt as versionOf};
1
+ import"node:path";import{existsSync as et}from"node:fs";import{spawn as nt,spawnSync as D}from"node:child_process";import{createServer as rt}from"node:net";import{resolveLaunch as it,standaloneCandidates as K,retireStandaloneBridge as ot,compareVersions as k}from"./service.js";import{DEFAULT_BRIDGE_URL as P}from"./bridge.js";import{srtModuleUrl as st}from"./worker-sandbox.js";const w=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,X=[1e3,2e3,5e3,1e4,3e4],at=6e4,dt=1200;function lt(){if(process.env.CHATPANEL_SRT_MODULE)return{};const a=st();return a?{CHATPANEL_SRT_MODULE:a}:{}}function Y({managed:a=!0,cfgUrl:r="",healthy:t=null,standalone:d=null,embeddedVersion:o=null}={}){if(a===!1||a==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const u=String(r||P);if(!w.test(u))return{action:"off",why:`bridge.url ${u} is not on this machine; nothing to start here`};if(t)return!t.managedBy&&o&&t.version&&k(t.version,o)<0?{action:"replace",why:`a standalone bridge (v${t.version}, run by nobody) answers at ${u} and is older than the embedded one (v${o}) — retiring it`}:t.managedBy==="gateway"&&t.orphaned&&o&&t.version&&k(t.version,o)<0?{action:"replace",why:`a bridge an earlier gateway started (v${t.version}) answers at ${u} and is older than the embedded one (v${o}) — replacing it`}:{action:"adopt",why:`a bridge already answers at ${u}${t.version?` (v${t.version}${t.managedBy?`, run by ${t.managedBy}`:""})`:""}`};const f=d?.version||null;return d?.path&&o&&k(f,o)>0?{action:"spawn-standalone",why:`the installed bridge (v${f}) is newer than the embedded one (v${o})`,path:d.path}:o?{action:"spawn-embedded",why:`starting the embedded bridge (v${o})${d?.path?` — the installed one is v${f||"?"}`:""}`}:d?.path?{action:"spawn-standalone",why:`starting the installed bridge${f?` (v${f})`:""}`,path:d.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function ct(a,{timeoutMs:r=dt,fetchImpl:t=fetch}={}){const d=new AbortController,o=setTimeout(()=>d.abort(),r);try{const u=await t(`${String(a).replace(/\/$/,"")}/health`,{signal:d.signal});if(!u.ok)return null;const f=await u.json().catch(()=>null);return f&&f.ok!==!1?{version:f.version||null,managedBy:f.managedBy||null}:null}catch{return null}finally{clearTimeout(o)}}function ut(a,r=[],{timeoutMs:t=8e3}={}){try{const d=D(a,[...r,"--version"],{encoding:"utf8",timeout:t,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),o=String(d.stdout||"").trim().split(`
2
+ `).pop();return/^\d+\.\d+\.\d+/.test(o)?o:null}catch{return null}}function ft(){const{program:a,args:r}=it();return{program:a,args:[...r,"--bridge"]}}const U=a=>w.exec(String(a||P))?.[3]||"4319";function pt(a){const r=w.exec(String(a||""));if(!r||!r[3])return!1;const t=Number(r[3]);return t===0||t>=32768}function gt(a,r="127.0.0.1"){return new Promise(t=>{const d=rt();d.once("error",()=>t(!1)),d.listen(Number(a),r,()=>d.close(()=>t(!0)))})}function mt(a,{platform:r=process.platform,runImpl:t=D,kill:d=o=>process.kill(o,"SIGTERM")}={}){if(r==="win32")return!1;try{const o=Number(String(t("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
3
+ `)[0]);if(!o||o===process.pid)return!1;const u=String(t("ps",["-o","command=","-p",String(o)],{encoding:"utf8",timeout:2e3}).stdout||"");return/chatpanel-bridge/.test(u)?(d(o),!0):!1}catch{return!1}}function ht(a,{platform:r=process.platform,runImpl:t=D}={}){if(r==="win32")return!1;try{const d=Number(String(t("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-t"],{encoding:"utf8",timeout:2e3}).stdout||"").trim().split(`
4
+ `)[0]);return d?Number(String(t("ps",["-o","ppid=","-p",String(d)],{encoding:"utf8",timeout:2e3}).stdout||"").trim())===1:!1}catch{return!1}}function vt(a,{platform:r=process.platform}={}){if(r==="win32")return"";try{const t=D("lsof",["-nP",`-iTCP:${Number(a)}`,"-sTCP:LISTEN","-Fpc"],{encoding:"utf8",timeout:2e3}),d=/^p(\d+)/m.exec(t.stdout||"")?.[1],o=/^c(.+)$/m.exec(t.stdout||"")?.[1];return d?`${o||"a process"} (pid ${d})`:""}catch{return""}}async function At(a,{log:r=n=>console.log(n),probe:t=ct,spawnImpl:d=nt,version:o=ut,candidates:u=K(),exists:f=et,launch:q=ft,managed:y=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:a?.bridge?.managed,waitForSiblingMs:H=2500,retire:z=ot,retireOnPort:J=mt,orphaned:Q=ht,retireWaitMs:Z=6e3,childEnv:W=()=>({}),now:B=Date.now,setTimer:O=setTimeout,setWatch:_=(n,e)=>{const g=setTimeout(n,e);return g.unref?.(),g},watchEveryMs:E=1e4,isFree:R=gt,holder:V=vt}={}){let n=String(a?.bridge?.url||P).replace(/\/$/,"");const e={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},g=(i,c,s={})=>{Object.assign(e,{mode:i,why:c},s),r(` bridge : ${c}`)};pt(n)&&!await t(n)&&(r(` bridge : bridge.url ${n} is a leftover OS-assigned port and nothing answers there — using ${P}`),n=P,a?.bridge&&(a.bridge.url=P));let p=await t(n);if(!p&&y!==!1&&y!=="off"&&w.test(n)&&H>0){const i=B()+H;for(;!p&&B()<i;)await new Promise(c=>O(c,500)),p=await t(n)}const N=q(),tt=y!==!1&&y!=="off";p?.managedBy==="gateway"&&w.test(n)&&(p.orphaned=Q(U(n)));const S=!tt||p&&p.managedBy&&!p.orphaned?null:o(N.program,N.args),M=u.find(i=>f(i))||null,G=M&&!p?{path:M,version:o(M,[])}:null,m=Y({managed:y,cfgUrl:n,healthy:p,standalone:G,embeddedVersion:S});if(m.action==="off")return g("off",m.why),A();const I=i=>i.action==="spawn-embedded"?{...N,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:i.version||S}:{program:i.path,args:[],env:{},mode:"standalone",version:G?.version||null};let l=m.action==="adopt"||m.action==="replace"?null:I(m),j=0,$=null,L=0;const T=(i,c)=>{g("adopted",i,{version:c||null}),L=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const C=await t(n);if(C){L=0,e.version=C.version||e.version,$=_(s,E);return}if(L+=1,L<2){$=_(s,Math.min(E,3e3));return}if(!l){const h=S||o(N.program,N.args),v=Y({managed:y,cfgUrl:n,healthy:null,standalone:G,embeddedVersion:h});if(v.action==="off"){g("off",`the adopted bridge went away and ${v.why}`);return}l=I({...v,version:h})}r(` bridge : the adopted bridge at ${n} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),g(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),x()};$=_(s,E)},b=U(n),F=()=>{const i=V(b);g("blocked",`port ${b} is held by ${i||"another program"}, which is not a ChatPanel bridge — no bridge started; free the port or set bridge.url to a free one (checking again every ${Math.round(E/1e3)} s)`,{version:null,pid:null});const c=async()=>{if(e.stopping||e.mode!=="blocked")return;const s=await t(n);if(s){T(`a bridge now answers at ${n} (v${s.version||"?"}${s.managedBy?`, run by ${s.managedBy}`:""})`,s.version);return}if(await R(b)){g(l.mode,`port ${b} is free again — starting the ${l.mode} bridge (v${l.version||"?"})`,{version:l.version}),x();return}$=_(c,E)};$=_(c,E)},x=async()=>{if(e.stopping)return;if(w.test(n)&&!await R(b)){const s=await t(n);if(s){T(`a bridge already answers at ${n} (v${s.version||"?"}${s.managedBy?`, run by ${s.managedBy}`:""})`,s.version);return}F();return}if(e.stopping)return;const i=d(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...W(),...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:U(n),...lt()}});j=B(),e.child=i,e.pid=i.pid||null;const c=(s,C)=>s?.on("data",h=>{for(const v of String(h).split(`
5
+ `))v.trim()&&r(`[bridge] ${v}`)});c(i.stdout,"out"),c(i.stderr,"err"),i.on("error",s=>r(`[bridge] could not start ${l.program}: ${s?.message||s}`)),i.on("exit",async(s,C)=>{if(e.child=null,e.pid=null,e.stopping)return;const h=await t(n);if(h){T(`a bridge already answers at ${n} (v${h.version||"?"}${h.managedBy?`, run by ${h.managedBy}`:""}) — ours stepped aside`,h.version);return}B()-j>at&&(e.backoff=0);const v=X[Math.min(e.backoff,X.length-1)];e.backoff+=1,e.restarts+=1,r(`[bridge] exited (${C||s}); restarting in ${v/1e3}s`),O(x,v)})};if(m.action==="adopt")return T(m.why,p.version),A();if(m.action==="replace"){r(` bridge : ${m.why}`);try{p.managedBy!=="gateway"&&z({paths:u})}catch(s){r(` bridge : could not retire the standalone bridge: ${s?.message||s}`)}await t(n)&&J(b);const i=B()+Z;let c=await t(n);for(;c&&B()<i;)await new Promise(s=>O(s,500)),c=await t(n);return c?(T(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=I({action:"spawn-embedded",version:S}),g("embedded",`the standalone bridge was retired; starting the embedded bridge (v${S})`,{version:S}),x(),A())}if(w.test(n)&&!await R(b)){const i=await t(n);return i?T(`a bridge already answers at ${n} (v${i.version||"?"}${i.managedBy?`, run by ${i.managedBy}`:""})`,i.version):F(),A()}return g(l.mode,m.why,{version:l.version}),x(),A();function A(){return{status:()=>({mode:e.mode,version:e.version,pid:e.pid,restarts:e.restarts,why:e.why}),stop:()=>{if(e.stopping=!0,$&&(clearTimeout($),$=null),e.child&&!e.child.killed)try{e.child.kill("SIGTERM")}catch{}},restart:(i="settings changed")=>{if(!e.child||e.stopping)return e.mode==="adopted"&&r(`[bridge] ${i} — the bridge on ${n} is not ours (${e.why}); set CHATPANEL_SANDBOX* in its own service`),!1;r(`[bridge] restarting: ${i}`),e.backoff=0;try{e.child.kill("SIGTERM")}catch{}return!0}}}}export{k as compareVersions,ft as embeddedLaunch,At as ensureBridge,vt as holderOf,pt as isEphemeralBridgeUrl,ht as listenerOrphaned,Y as planBridge,gt as portFree,ct as probeBridge,mt as retireBridgeOnPort,lt as srtModuleEnv,K as standaloneCandidates,ut as versionOf};
package/src/bridge.js CHANGED
@@ -1,5 +1,5 @@
1
- import{readFileSync as j,existsSync as C}from"node:fs";import{join as L}from"node:path";import N from"node:os";const S=L(N.homedir(),".chatpanel","bridge-token"),F="http://127.0.0.1:4319",v=1e4;let c={at:0,cfgUrl:"",url:"",fell:!1};async function A(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function z(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":F);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(c.url&&c.cfgUrl===s&&o-c.at<v)return c.url;let i=s||e,l=!1;return e&&i!==e&&!await A(i,r)&&await A(e,r)&&(i=e,l=!0,(!c.fell||c.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),c={at:o,cfgUrl:s,url:i,fell:l},i}function M(){c={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function R(t){try{if(C(t))return j(t,"utf8").trim()}catch{}return""}function J(t,e=S){const r=R(e);return!t||y&&r&&r!==t?r:t}function P(t,e=S){const r=R(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function W(){y=!1}const G=t=>t===401||t===403;async function _(t,e,r,o,s){const i=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),l=J(e,s);let f=await i(l);if(G(f.status)){const a=P(l,s);a&&(await f.text().catch(()=>{}),f=await i(a))}return f}function H(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
2
- `):""}function $(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:H(e.content)}))}async function q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:i,options:l,signal:f,tokenPath:a,approvals:g=!1}){const u=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:l||{},...Array.isArray(i)&&i.length?{pageTools:{specs:i}}:{},...g?{approvals:!0}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await O(u));return u}async function O(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function Q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:i,signal:l,tokenPath:f},a,g=null,u=null){const h=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:i||{}}),l,f);if(!h.ok||!h.body)throw new Error(await O(h));const D=h.body.getReader(),U=new TextDecoder;let d="",w="",b=!1,x=null;const E=m=>{for(const B of m.split(`
3
- `)){const p=B.trim();if(!p.startsWith("data:"))continue;const T=p.slice(5).trim();if(!T||T==="[DONE]")continue;let n;try{n=JSON.parse(T)}catch{continue}n.type==="delta"&&typeof n.text=="string"?(b=!0,w+=n.text,a(n.text)):n.type==="done"?!b&&typeof n.text=="string"&&n.text&&(w+=n.text,a(n.text)):n.type==="error"?x=new Error(n.error||"bridge error"):(n.type==="usage"&&u&&u(n),g&&g(n))}};for(;;){const{done:m,value:B}=await D.read();if(m)break;d+=U.decode(B,{stream:!0});let p;for(;(p=d.indexOf(`
1
+ import{readFileSync as U,existsSync as v}from"node:fs";import{join as C}from"node:path";import L from"node:os";const T=C(L.homedir(),".chatpanel","bridge-token"),N="http://127.0.0.1:4319",F=1e4;let d={at:0,cfgUrl:"",url:"",fell:!1};async function $(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function J(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":N);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(d.url&&d.cfgUrl===s&&o-d.at<F)return d.url;let n=s||e,c=!1;return e&&n!==e&&!await $(n,r)&&await $(e,r)&&(n=e,c=!0,(!d.fell||d.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),d={at:o,cfgUrl:s,url:n,fell:c},n}function M(){d={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function S(t){try{if(v(t))return U(t,"utf8").trim()}catch{}return""}function j(t,e=T){const r=S(e);return!t||y&&r&&r!==t?r:t}function P(t,e=T){const r=S(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function W(){y=!1}async function q(t,{tokenPath:e=T,timeoutMs:r=1500}={}){const o=j(t?.bridge?.token,e),s=[...new Set([o,S(e),t?.bridge?.token].filter(Boolean))];if(!s.length)return{token:"",refused:null};const n=await J(t),c=async a=>{try{const l=await fetch(`${n}/whoami`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":a},body:"{}",signal:AbortSignal.timeout(r)});if(!l.ok)return null;const u=await l.json().catch(()=>null);return typeof u?.trust=="string"?u:null}catch{return null}};let f=null;for(const a of s){const l=await c(a);if(l&&(f=l,l.trust==="token"))return{token:a,refused:null}}return f?{token:"",refused:{url:n,version:f.version||null}}:{token:o,refused:null}}const G=t=>t===401||t===403;async function k(t,e,r,o,s){const n=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),c=j(e,s);let f=await n(c);if(G(f.status)){const a=P(c,s);a&&(await f.text().catch(()=>{}),f=await n(a))}return f}function H(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
2
+ `):""}function O(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:H(e.content)}))}async function Q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:c,signal:f,tokenPath:a,approvals:l=!1}){const u=await k(t,r,JSON.stringify({agent:e,messages:O(o),system:s||"",options:c||{},...Array.isArray(n)&&n.length?{pageTools:{specs:n}}:{},...l?{approvals:!0}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await R(u));return u}async function R(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function V({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:n,signal:c,tokenPath:f},a,l=null,u=null){const h=await k(t,r,JSON.stringify({agent:e,messages:O(o),system:s||"",options:n||{}}),c,f);if(!h.ok||!h.body)throw new Error(await R(h));const _=h.body.getReader(),D=new TextDecoder;let g="",w="",E=!1,x=null;const A=m=>{for(const b of m.split(`
3
+ `)){const p=b.trim();if(!p.startsWith("data:"))continue;const B=p.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(E=!0,w+=i.text,a(i.text)):i.type==="done"?!E&&typeof i.text=="string"&&i.text&&(w+=i.text,a(i.text)):i.type==="error"?x=new Error(i.error||"bridge error"):(i.type==="usage"&&u&&u(i),l&&l(i))}};for(;;){const{done:m,value:b}=await _.read();if(m)break;g+=D.decode(b,{stream:!0});let p;for(;(p=g.indexOf(`
4
4
 
5
- `))!==-1;)E(d.slice(0,p)),d=d.slice(p+2)}if(d.trim()&&E(d),x)throw x;return w}export{F as DEFAULT_BRIDGE_URL,O as bridgeRefusal,P as bridgeTokenRejected,q as openBridgeChat,J as readBridgeToken,M as resetBridgeResolution,W as resetBridgeTokenPreference,z as resolveBridgeUrl,Q as streamBridgeChat,$ as toBridgeMessages};
5
+ `))!==-1;)A(g.slice(0,p)),g=g.slice(p+2)}if(g.trim()&&A(g),x)throw x;return w}export{N as DEFAULT_BRIDGE_URL,q as acceptedBridgeToken,R as bridgeRefusal,P as bridgeTokenRejected,Q as openBridgeChat,j as readBridgeToken,M as resetBridgeResolution,W as resetBridgeTokenPreference,J as resolveBridgeUrl,V as streamBridgeChat,O as toBridgeMessages};
@@ -1 +1 @@
1
- import{secureFetch as k}from"./secure-fetch.js";import{createReadStats as O}from"./retrieval/read.js";import{CAPABILITY_ROUTES as A,overBudget as M,validateRerankRequest as T,validateRerankResponse as L,validateDecideRequest as j,validateDecideResponse as D}from"./capability-endpoints.js";import{adaptRequest as I,adaptResponse as P}from"./capability-adapters.js";const g=Object.freeze(["rerank","decide"]),w={rerank:{request:T,response:L,chars:c=>c.query.length+c.documents.reduce((u,l)=>u+l.length,0)},decide:{request:j,response:D,chars:c=>c.state.length}},x=18e4,C=6e4,d=(c,u,l,p={})=>({status:c,body:{error:{type:u,message:l,...p}}});function J({cfg:c,fetchImpl:u=k,now:l=()=>Date.now()}={}){const p=Object.fromEntries(g.map(e=>[e,{stats:O(),last:null,error:null}])),v=e=>{const r=c.capabilities?.[e];return r&&typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"?r:null};async function _(e,r){if(!g.includes(e))return d(404,"unknown_capability",`no such capability ${e}`);const t=v(e);if(!t)return d(404,"no_provider",`no ${e} provider — run one under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`);const i=w[e];let a;try{a=i.request(r)}catch(s){return d(400,"invalid_request",s.message)}if(a.model&&t.model&&a.model!==t.model)return d(404,"model_not_found",`${e}: model ${a.model} is not served here (${t.model} is)`);const o=p[e],y=i.chars(a),b=M(o.stats.stats(),y,a.budgetMs);if(b)return{status:503,body:b};let h;try{h=I(t.adapter,{...a,model:a.model||t.model||void 0})}catch(s){return d(500,"bad_adapter",s.message)}const S=`${t.url.replace(/\/+$/,"")}${h.route}`,q=l();let m;try{m=await u(S,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify(h.body),signal:AbortSignal.timeout(a.budgetMs?Math.max(a.budgetMs*2,5e3):o.stats.stats().calls?C:x)})}catch(s){return o.error=s.message,o.last=l(),d(503,"provider_unavailable",`${e}: ${t.service?`the ${t.service} container`:t.url} did not answer — ${s.message}`)}let n;try{n=await m.json()}catch{n=null}if(!m.ok)return o.error=`HTTP ${m.status}`,o.last=l(),d(502,"provider_error",`${e}: the provider answered ${m.status}${n?.detail?` — ${typeof n.detail=="string"?n.detail:JSON.stringify(n.detail)}`:n?.error?` — ${typeof n.error=="string"?n.error:n.error.message||""}`:""}`);const $=l()-q;let f;try{const s=P(t.adapter,n,a);f={...s,model:t.model||s.model||t.adapter,...s.model&&t.model&&s.model!==t.model?{providerModel:s.model}:{},ms:$,...e==="decide"?{calibrated:t.calibrated===!0}:{}},i.response(f,a)}catch(s){return o.error=s.message,o.last=l(),d(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${s.message}`)}return o.stats.record($,y),o.error=null,o.last=l(),{status:200,body:f}}function R(e){const r=v(e);if(!r)return null;const t=p[e],i=t.stats.stats();return{id:e,route:A[e],models:r.model?[r.model]:[],...r.model?{default:r.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(r.url)?"none":"trusted"},...e==="decide"?{calibrated:r.calibrated===!0}:{},stats:i,runtime:{state:t.error?"down":i.calls?"ready":"idle",name:r.service?"container":"external",adapter:r.adapter,...r.service?{service:r.service}:{},url:r.url,...t.error?{error:t.error}:{}}}}return{call:_,entry:R,stats:e=>p[e]?.stats.stats()||{calls:0},capabilities:g}}export{J as createCapabilityProxy};
1
+ import{secureFetch as T}from"./secure-fetch.js";import{createReadStats as L}from"./retrieval/read.js";import{CAPABILITY_ROUTES as j,overBudget as D,validateRerankRequest as I,validateRerankResponse as P,validateDecideRequest as x,validateDecideResponse as C}from"./capability-endpoints.js";import{adaptRequest as E,adaptResponse as B}from"./capability-adapters.js";const g=Object.freeze(["rerank","decide"]),z={rerank:{request:I,response:P,chars:i=>i.query.length+i.documents.reduce((p,n)=>p+n.length,0)},decide:{request:x,response:C,chars:i=>i.state.length}},F=18e4,J=6e4,l=(i,p,n,m={})=>({status:i,body:{error:{type:p,message:n,...m}}});function X({cfg:i,fetchImpl:p=T,now:n=()=>Date.now(),wake:m=null}={}){const f=Object.fromEntries(g.map(t=>[t,{stats:L(),last:null,error:null}])),y=t=>{const r=i.capabilities?.[t];return r&&typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"?r:null};async function w(t,r){if(!g.includes(t))return l(404,"unknown_capability",`no such capability ${t}`);const e=y(t);if(!e)return l(404,"no_provider",`no ${t} provider — run one under Settings › Runtime, or point capabilities.${t}.url at a server that provides it`);const d=z[t];let o;try{o=d.request(r)}catch(s){return l(400,"invalid_request",s.message)}if(o.model&&e.model&&o.model!==e.model)return l(404,"model_not_found",`${t}: model ${o.model} is not served here (${e.model} is)`);const a=f[t],$=d.chars(o),_=D(a.stats.stats(),$,o.budgetMs);if(_)return{status:503,body:_};let h;try{h=E(e.adapter,{...o,model:o.model||e.model||void 0})}catch(s){return l(500,"bad_adapter",s.message)}const A=`${e.url.replace(/\/+$/,"")}${h.route}`,R=()=>p(A,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify(h.body),signal:AbortSignal.timeout(o.budgetMs?Math.max(o.budgetMs*2,5e3):a.stats.stats().calls?J:F)}),k=!!(e.service&&typeof m=="function");if(k){const s=await m(e.service).catch(b=>({ok:!1,error:b.message}));if(!s?.ok)return a.error=s?.error||"could not start",a.last=n(),l(503,"provider_unavailable",`${t}: the ${e.service} container could not be started — ${a.error}`)}const M=n();let u;try{u=await R()}catch(s){const b=k?await m(e.service,{force:!0}).catch(()=>null):null;try{if(!b?.ok)throw s;u=await R()}catch(q){return a.error=q.message,a.last=n(),l(503,"provider_unavailable",`${t}: ${e.service?`the ${e.service} container`:e.url} did not answer — ${q.message}`)}}let c;try{c=await u.json()}catch{c=null}if(!u.ok)return a.error=`HTTP ${u.status}`,a.last=n(),l(502,"provider_error",`${t}: the provider answered ${u.status}${c?.detail?` — ${typeof c.detail=="string"?c.detail:JSON.stringify(c.detail)}`:c?.error?` — ${typeof c.error=="string"?c.error:c.error.message||""}`:""}`);const S=n()-M;let v;try{const s=B(e.adapter,c,o);v={...s,model:e.model||s.model||e.adapter,...s.model&&e.model&&s.model!==e.model?{providerModel:s.model}:{},ms:S,...t==="decide"?{calibrated:e.calibrated===!0}:{}},d.response(v,o)}catch(s){return a.error=s.message,a.last=n(),l(502,"bad_shape",`${t}: the provider's answer did not fit the contract — ${s.message}`)}return a.stats.record(S,$),a.error=null,a.last=n(),{status:200,body:v}}function O(t){const r=y(t);if(!r)return null;const e=f[t],d=e.stats.stats();return{id:t,route:j[t],models:r.model?[r.model]:[],...r.model?{default:r.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(r.url)?"none":"trusted"},...t==="decide"?{calibrated:r.calibrated===!0}:{},stats:d,runtime:{state:e.error?"down":d.calls?"ready":"idle",name:r.service?"container":"external",adapter:r.adapter,...r.service?{service:r.service}:{},url:r.url,...e.error?{error:e.error}:{}}}}return{call:w,entry:O,stats:t=>f[t]?.stats.stats()||{calls:0},capabilities:g}}export{X as createCapabilityProxy};
@@ -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-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};
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,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function x({exec:e,platform:t=process.platform,arch:n=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 t==="darwin"&&n==="arm64"?"apple":await l("nvidia-smi",["-L"])?"cuda":t==="linux"&&await l("rocm-smi",["--showid"])?"rocm":t==="linux"&&await l("sycl-ls",[])?"xpu":null}function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:l=null,vllmOnPath:a=!1,containerOnly:i=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&i?{backend:"cpu",kind:"container",image:o.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install: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?n==="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."}:{}}:n==="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."}:n==="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(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function y({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:l=!1}={}){const a=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="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 P({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:l=()=>[]}={}){const a=Math.round(n()/1073741824),i=l().length||0;let r=Math.max(1,Math.floor(i/2))||1,c=r;if(t==="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:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,o as VLLM_IMAGES,L as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,m as deviceArgs,P as hostShape,M as pickInferenceEngine,y as pickLlamaEngine,U as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
@@ -1 +1 @@
1
- const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; the ship default."},{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",note:"Half the size, most of the quality. The pick when the engine has 2 GB."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"What OpenDecision ships with; 8k context. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",note:"A third of the size, close on most typed decisions. The pick when the engine has 2 GB."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for trying vLLM-Metal here."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(i=>i.id===t)||A(t):s(n).some(i=>i.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function T(n,{active:e=null,engineRamMB:t=0,engine:i=null,platform:m=process.platform,installed:c=()=>!1}={}){const r=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>i==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${r(a.ramMB)} of memory while loaded — the container engine has ${r(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${r(a.ramMB)} while loaded — the engine has ${r(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,T as modelsFor,w as vllmTaskOf};
1
+ const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for trying vLLM-Metal here."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(r=>r.id===t)||A(t):s(n).some(r=>r.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:r=null,platform:m=process.platform,installed:c=()=>!1}={}){const i=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>r==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:r==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${i(a.ramMB)} of memory while loaded — the container engine has ${i(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${i(a.ramMB)} while loaded — the engine has ${i(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,R as modelsFor,w as vllmTaskOf};