@chatpanel/gateway 0.23.2 → 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.23.2",
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": {
@@ -22,15 +22,14 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
- "@chatpanel/bridge": "^0.17.1",
26
- "@chatpanel/events": "^0.117.0",
27
- "@chatpanel/pii": "^0.10.2",
25
+ "@chatpanel/bridge": "^0.20.1",
26
+ "@chatpanel/events": "^0.189.0",
27
+ "@chatpanel/pii": "^0.11.0",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
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
  },
@@ -0,0 +1,4 @@
1
+ import{spawn as u}from"node:child_process";const g=16e3;function A(t,r){const i=/boundary=(?:"([^"]+)"|([^;]+))/i.exec(String(r||""));if(!i)throw Object.assign(new Error("multipart/form-data with a boundary expected"),{code:415});const e=Buffer.from(`--${i[1]||i[2]}`),d=[];let n=t.indexOf(e);for(;n!==-1&&(n+=e.length,!(t[n]===45&&t[n+1]===45));){t[n]===13?n+=2:t[n]===10&&(n+=1);const o=t.indexOf(`\r
2
+ \r
3
+ `,n);if(o===-1)break;const c=t.subarray(n,o).toString("utf8"),l=t.indexOf(e,o+4);if(l===-1)break;let a=l;t[a-1]===10&&a--,t[a-1]===13&&a--;const s=/name="([^"]*)"(?:;\s*filename="([^"]*)")?/i.exec(c)||[],f=(/content-type:\s*([^\r\n]+)/i.exec(c)||[])[1]||null;d.push({name:s[1]||"",filename:s[2]||null,type:f,data:t.subarray(o+4,a)}),n=l}return d}function E(t,r){const i=t[0].length,e=new Float32Array(i);for(let c=0;c<i;c++){let l=0;for(const a of t)l+=a[c];e[c]=l/t.length}if(r===g)return e;const d=Math.max(1,Math.round(i*g/r)),n=new Float32Array(d),o=r/g;for(let c=0;c<d;c++){const l=c*o,a=Math.floor(l),s=l-a;n[c]=(1-s)*(e[a]??0)+s*(e[a+1]??e[a]??0)}return n}function w(t){if(t.length<44||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")return null;let r=12,i=null,e=null;for(;r+8<=t.length;){const f=t.toString("ascii",r,r+4),m=t.readUInt32LE(r+4);if(f==="fmt "&&(i={format:t.readUInt16LE(r+8),channels:t.readUInt16LE(r+10),rate:t.readUInt32LE(r+12),bits:t.readUInt16LE(r+22)}),f==="data"){e=t.subarray(r+8,Math.min(t.length,r+8+m));break}r+=8+m+m%2}if(!i||!e)throw Object.assign(new Error("WAV without fmt or data chunk"),{code:415});const{channels:d,rate:n,bits:o}=i,c=i.format===3||i.format===65534&&o===32,l=o/8,a=Math.floor(e.length/(l*d)),s=Array.from({length:d},()=>new Float32Array(a));for(let f=0;f<a;f++)for(let m=0;m<d;m++){const p=(f*d+m)*l;s[m][f]=c?e.readFloatLE(p):o===16?e.readInt16LE(p)/32768:o===8?(e[p]-128)/128:o===24?((e[p]|e[p+1]<<8|e[p+2]<<16)<<8>>8)/8388608:e.readInt32LE(p)/2147483648}return{pcm:E(s,n),rate:g,seconds:a/n}}function x(t,{spawn:r=u,bin:i="ffmpeg",timeoutMs:e=12e4}={}){return new Promise((d,n)=>{let o;try{o=r(i,["-nostdin","-loglevel","error","-i","pipe:0","-f","f32le","-ac","1","-ar",String(g),"pipe:1"],{stdio:["pipe","pipe","pipe"]})}catch(s){return n(Object.assign(new Error(`ffmpeg: ${s.message}`),{code:415}))}const c=[];let l="";const a=setTimeout(()=>{try{o.kill("SIGKILL")}catch{}n(Object.assign(new Error("ffmpeg: timed out"),{code:500}))},e);o.stdout.on("data",s=>c.push(s)),o.stderr.on("data",s=>{l+=s}),o.on("error",s=>{clearTimeout(a),n(Object.assign(new Error(s.code==="ENOENT"?"ffmpeg is not on PATH — send a WAV, or install ffmpeg for mp3/m4a/webm/ogg":`ffmpeg: ${s.message}`),{code:415}))}),o.on("close",s=>{if(clearTimeout(a),s!==0)return n(Object.assign(new Error(`ffmpeg could not read this file${l?`: ${l.trim().split(`
4
+ `).pop()}`:""}`),{code:415}));const f=Buffer.concat(c),m=f.length-f.length%4,p=new Float32Array(m/4);for(let h=0;h<p.length;h++)p[h]=f.readFloatLE(h*4);d({pcm:p,rate:g,seconds:p.length/g})}),o.stdin.on("error",()=>{}),o.stdin.end(t)})}async function L(t,r={}){const i=w(t);return i||x(t,r)}export{g as TARGET_RATE,L as decodeAudioFile,w as decodeWav,x as decodeWithFfmpeg,A as parseMultipart,E as toMono16k};
package/src/bridge.js CHANGED
@@ -1,5 +1,5 @@
1
- import{readFileSync as D,existsSync as j}from"node:fs";import{join as C}from"node:path";import L from"node:os";const A=C(L.homedir(),".chatpanel","bridge-token"),N="http://127.0.0.1:4319",v=1e4;let c={at:0,cfgUrl:"",url:"",fell:!1};async function E(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function k(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(c.url&&c.cfgUrl===s&&o-c.at<v)return c.url;let n=s||e,l=!1;return e&&n!==e&&!await E(n,r)&&await E(e,r)&&(n=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:n,fell:l},n}function z(){c={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function S(t){try{if(j(t))return D(t,"utf8").trim()}catch{}return""}function F(t,e=A){const r=S(e);return!t||y&&r&&r!==t?r:t}function J(t,e=A){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 M(){y=!1}const P=t=>t===401||t===403;async function R(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}),l=F(e,s);let f=await n(l);if(P(f.status)){const a=J(l,s);a&&(await f.text().catch(()=>{}),f=await n(a))}return f}function G(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:G(e.content)}))}async function W({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:l,signal:f,tokenPath:a}){const u=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:l||{},...Array.isArray(n)&&n.length?{pageTools:{specs:n}}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await $(u));return u}async function $(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:n,signal:l,tokenPath:f},a,u=null){const p=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:n||{}}),l,f);if(!p.ok||!p.body)throw new Error(await $(p));const O=p.body.getReader(),U=new TextDecoder;let d="",h="",T=!1,w=null;const b=x=>{for(const m of x.split(`
3
- `)){const g=m.trim();if(!g.startsWith("data:"))continue;const B=g.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(T=!0,h+=i.text,a(i.text)):i.type==="done"?!T&&typeof i.text=="string"&&i.text&&(h+=i.text,a(i.text)):i.type==="error"?w=new Error(i.error||"bridge error"):u&&u(i)}};for(;;){const{done:x,value:m}=await O.read();if(x)break;d+=U.decode(m,{stream:!0});let g;for(;(g=d.indexOf(`
1
+ import{readFileSync as D,existsSync as j}from"node:fs";import{join as v}from"node:path";import C from"node:os";const A=v(C.homedir(),".chatpanel","bridge-token"),L="http://127.0.0.1:4319",N=1e4;let u={at:0,cfgUrl:"",url:"",fell:!1};async function E(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function k(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":L);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(u.url&&u.cfgUrl===s&&o-u.at<N)return u.url;let n=s||e,l=!1;return e&&n!==e&&!await E(n,r)&&await E(e,r)&&(n=e,l=!0,(!u.fell||u.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)`)),u={at:o,cfgUrl:s,url:n,fell:l},n}function z(){u={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function S(t){try{if(j(t))return D(t,"utf8").trim()}catch{}return""}function F(t,e=A){const r=S(e);return!t||y&&r&&r!==t?r:t}function J(t,e=A){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 M(){y=!1}const P=t=>t===401||t===403;async function R(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}),l=F(e,s);let c=await n(l);if(P(c.status)){const a=J(l,s);a&&(await c.text().catch(()=>{}),c=await n(a))}return c}function G(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:G(e.content)}))}async function W({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:l,signal:c,tokenPath:a,approvals:p=!1}){const f=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:l||{},...Array.isArray(n)&&n.length?{pageTools:{specs:n}}:{},...p?{approvals:!0}:{}}),c,a);if(!f.ok||!f.body)throw new Error(await $(f));return f}async function $(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:n,signal:l,tokenPath:c},a,p=null){const f=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:n||{}}),l,c);if(!f.ok||!f.body)throw new Error(await $(f));const O=f.body.getReader(),U=new TextDecoder;let d="",h="",T=!1,w=null;const b=x=>{for(const m of x.split(`
3
+ `)){const g=m.trim();if(!g.startsWith("data:"))continue;const B=g.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(T=!0,h+=i.text,a(i.text)):i.type==="done"?!T&&typeof i.text=="string"&&i.text&&(h+=i.text,a(i.text)):i.type==="error"?w=new Error(i.error||"bridge error"):p&&p(i)}};for(;;){const{done:x,value:m}=await O.read();if(x)break;d+=U.decode(m,{stream:!0});let g;for(;(g=d.indexOf(`
4
4
 
5
- `))!==-1;)b(d.slice(0,g)),d=d.slice(g+2)}if(d.trim()&&b(d),w)throw w;return h}export{N as DEFAULT_BRIDGE_URL,$ as bridgeRefusal,J as bridgeTokenRejected,W as openBridgeChat,F as readBridgeToken,z as resetBridgeResolution,M as resetBridgeTokenPreference,k as resolveBridgeUrl,q as streamBridgeChat,_ as toBridgeMessages};
5
+ `))!==-1;)b(d.slice(0,g)),d=d.slice(g+2)}if(d.trim()&&b(d),w)throw w;return h}export{L as DEFAULT_BRIDGE_URL,$ as bridgeRefusal,J as bridgeTokenRejected,W as openBridgeChat,F as readBridgeToken,z as resetBridgeResolution,M as resetBridgeTokenPreference,k as resolveBridgeUrl,q as streamBridgeChat,_ as toBridgeMessages};
@@ -1 +1 @@
1
- import*as s from"./ner-engine.js";import*as E from"./stt-engine.js";import*as A from"./tts-engine.js";import{MODEL_CATALOG as L,DEFAULT_MODEL as q}from"./models.js";import{STT_MODEL_CATALOG as M,DEFAULT_STT_MODEL as w}from"./stt-models.js";import{TTS_MODEL_CATALOG as S,resolveDefaultModel as k}from"./tts-models.js";import{rawOrtAvailable as C}from"./ort.js";import{CAPABILITY_ROUTES as y,overBudget as R,validateDetectRequest as U}from"./capability-endpoints.js";import{extractCapabilityEntry as $}from"./extract/handler.js";const h=e=>[...new Set(e.filter(Boolean))];function b(e,i={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...i}}function Y(e,{version:i="",reader:o=null,searcher:t=null,extract:d=null,proxy:u=null}={}){const l=s.health(),a=e?.redaction?.detection,r=!!(a&&a.backend&&a.backend!=="off"),m=l.model||e?.ner?.model||q,g=E.health(),x=A.health(),v=x.model||e?.tts?.model||k(C()),c=[{id:"detect",route:y.detect,models:h([m,...L.map(n=>n.id)]),default:m,union:l.companions?.filter(n=>n.state==="ready").map(n=>n.model)||[],labels:s.isReady()?s.labels():[],maxTokens:s.isReady()?s.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:r?{state:"external",name:a.backend,url:a.url||null}:b(l,{installed:s.modelOnDisk(m)})},{id:"stt",route:y.stt,streaming:"/stt/sessions",models:h([g.model||e?.stt?.model||w,...M.map(n=>n.id)]),default:g.model||e?.stt?.model||w,requirements:{egress:"none"},runtime:b(g)},{id:"tts",route:y.tts,voices:"/tts/voices",models:h([v,...S.map(n=>n.id)]),default:v,requirements:{egress:"none"},runtime:b(x)}],T=e?.read||{},O=!!T.remote?.url;c.push({id:"read",route:y.read,providers:o?o.providers():["defuddle","text",...O?["remote"]:[]],default:T.provider||"defuddle",requirements:{egress:"web"},stats:o?o.stats():{calls:0},runtime:{state:"ready",cache:o?o.cache.size():0,remote:O?"configured":"off"}});const p=e?.search||{},f=!!p.searxng?.url,D=t?.searxng?t.searxng.state():f?"unknown":"off";if(c.push({id:"search",route:y.search,providers:t?t.providers():["serp",...f?["searxng"]:[]],default:p.provider==="searxng"||p.provider==="serp"?p.provider:f?"searxng":"serp",requirements:{egress:"web"},stats:t?t.stats()[f?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:D,...f?{searxngUrl:p.searxng.url}:{}}}),d)try{c.push($(d))}catch{}if(u)for(const n of u.capabilities){const _=u.entry(n);_&&c.push(_)}return{capabilities:c,server:{name:"chatpanel-gateway",version:String(i),audit:"/audit"}}}async function j(e,{ensure:i=async()=>s.state(),model:o=null}={}){let t;try{t=U(e)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}if(t.model&&o&&t.model!==o)return{status:404,body:{error:{message:`model ${t.model} is not loaded here (serving ${o})`,type:"model_not_found"}}};if(await i(),!s.isReady()){const r=s.health();return{status:503,body:{error:{message:r.state==="error"?`detector failed to load: ${r.error||"unknown error"}`:`detector is ${r.state} — not ready yet`,type:r.state==="error"?"detector_error":"detector_unready"},state:r.state,model:r.model}}}const d=R(s.stats(),t.text.length,t.budgetMs);if(d)return{status:503,body:{...d,model:s.health().model}};const u=performance.now();let l=await s.detectSpans(t.text);if(t.labels){const r=new Set(t.labels);l=l.filter(m=>r.has(m.type))}const a=s.health();return{status:200,body:{entities:l,model:a.model,ms:Math.round(performance.now()-u),runtime:{name:a.runtime||null,dtype:a.dtype||null}}}}export{Y as capabilitiesDocument,j as handleDetect};
1
+ import*as r from"./ner-engine.js";import*as A from"./stt-engine.js";import*as L from"./tts-engine.js";import{MODEL_CATALOG as M,DEFAULT_MODEL as S}from"./models.js";import{STT_MODEL_CATALOG as C,DEFAULT_STT_MODEL as E}from"./stt-models.js";import{TTS_MODEL_CATALOG as R,resolveDefaultModel as U}from"./tts-models.js";import{rawOrtAvailable as $}from"./ort.js";import{providerOf as B,providerTable as G}from"./providers.js";import{CAPABILITY_ROUTES as u,overBudget as j,validateDetectRequest as F}from"./capability-endpoints.js";import{extractCapabilityEntry as I}from"./extract/handler.js";const b=e=>[...new Set(e.filter(Boolean))];function x(e,c={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...c}}function Q(e,{version:c="",reader:n=null,searcher:s=null,extract:p=null,proxy:f=null}={}){const l=r.health(),a=e?.redaction?.detection,o=!!(a&&a.backend&&a.backend!=="off"),m=l.model||e?.ner?.model||S,g=A.health(),v=L.health(),O=v.model||e?.tts?.model||U($()),i=[{id:"detect",route:u.detect,models:b([m,...M.map(t=>t.id)]),default:m,union:l.companions?.filter(t=>t.state==="ready").map(t=>t.model)||[],labels:r.isReady()?r.labels():[],maxTokens:r.isReady()?r.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:o?{state:"external",name:a.backend,url:a.url||null}:x(l,{installed:r.modelOnDisk(m)})},{id:"stt",route:u.stt,streaming:"/stt/sessions",models:b([g.model||e?.stt?.model||E,...C.map(t=>t.id)]),default:g.model||e?.stt?.model||E,requirements:{egress:"none"},runtime:x(g)},{id:"tts",route:u.tts,voices:"/tts/voices",models:b([O,...R.map(t=>t.id)]),default:O,requirements:{egress:"none"},runtime:x(v)}],T=e?.read||{},w=!!T.remote?.url;i.push({id:"read",route:u.read,providers:n?n.providers():["defuddle","text",...w?["remote"]:[]],default:T.provider||"defuddle",requirements:{egress:"web"},stats:n?n.stats():{calls:0},runtime:{state:"ready",cache:n?n.cache.size():0,remote:w?"configured":"off"}});const h=e?.search||{},y=!!h.searxng?.url,k=s?.searxng?s.searxng.state():y?"unknown":"off";if(i.push({id:"search",route:u.search,providers:s?s.providers():["serp",...y?["searxng"]:[]],default:h.provider==="searxng"||h.provider==="serp"?h.provider:y?"searxng":"serp",requirements:{egress:"web"},stats:s?s.stats()[y?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:k,...y?{searxngUrl:h.searxng.url}:{}}}),p)try{i.push(I(p))}catch{}if(f)for(const t of f.capabilities){const d=f.entry(t);d&&i.push(d)}i.push({id:"chat",route:u.chat,models:[],dialects:["/v1/chat/completions","/v1/messages","/v1/responses"],listing:"/v1/models"});const _={sttModel:g.model,ttsModel:v.model,nerModel:m};for(const t of i){const d=B(e,t.id,_),{token:D,...q}=d;t.provider=q,d.kind==="remote"&&(t.requirements={...t.requirements||{},egress:d.egress})}return{capabilities:i,server:{name:"chatpanel-gateway",version:String(c),audit:"/audit"},providers:Object.fromEntries(Object.entries(G(e,_)).map(([t,{token:d,...D}])=>[t,D]))}}async function V(e,{ensure:c=async()=>r.state(),model:n=null}={}){let s;try{s=F(e)}catch(o){return{status:400,body:{error:{message:o.message,type:"invalid_request"}}}}if(s.model&&n&&s.model!==n)return{status:404,body:{error:{message:`model ${s.model} is not loaded here (serving ${n})`,type:"model_not_found"}}};if(await c(),!r.isReady()){const o=r.health();return{status:503,body:{error:{message:o.state==="error"?`detector failed to load: ${o.error||"unknown error"}`:`detector is ${o.state} — not ready yet`,type:o.state==="error"?"detector_error":"detector_unready"},state:o.state,model:o.model}}}const p=j(r.stats(),s.text.length,s.budgetMs);if(p)return{status:503,body:{...p,model:r.health().model}};const f=performance.now();let l=await r.detectSpans(s.text);if(s.labels){const o=new Set(s.labels);l=l.filter(m=>o.has(m.type))}const a=r.health();return{status:200,body:{entities:l,model:a.model,ms:Math.round(performance.now()-f),runtime:{name:a.runtime||null,dtype:a.dtype||null}}}}export{Q as capabilitiesDocument,V as handleDetect};
@@ -1 +1 @@
1
- import{EventError as v}from"@chatpanel/events/event.js";const q=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract"]),p=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract"}),f=Object.freeze(new Set(["search","read","extract"])),g=Object.freeze(["day","week","month","year"]),b=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),S="/v1/capabilities",$="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,d=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new v("SHAPE",s)};function x(e,s){if(!a(e)||!(e.calls>0))return null;const r=d(e.p50Ms)?e.p50Ms:0,n=d(e.charsPerSec)&&e.charsPerSec>0&&d(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,n))}function R(e,s,r){if(!d(r)||r<=0)return null;const n=x(e,s);return n===null||n<=r?null:{error:{type:$,message:`predicted ${n} ms is over the ${r} ms budget`,predictedMs:n,budgetMs:r}}}function j(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function w(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(i(e.model),"detect: model required"),t(d(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&i(r.value)&&i(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(d(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function I(e){t(a(e),"search: body must be an object"),t(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(i(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(g.includes(e.freshness),`search: freshness must be one of ${g.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function _(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(i(e.provider),"search: provider required"),t(d(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(i(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&A(s.read)}),e}function O(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function A(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(i(e.provider),"read: provider required"),t(d(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&i(r.id)&&i(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&b.includes(e.restricted.reason),`read: restricted.reason must be one of ${b.join(", ")}`),e}const h=Object.freeze(["choice","score","noul"]),k=/^[A-Za-z_][A-Za-z0-9_]*$/;function E(e){t(a(e),"decide: body must be an object"),t(i(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[n,u]of Object.entries(e.questions)){t(k.test(n),`decide: question key ${JSON.stringify(n)} must be an identifier`),t(a(u)&&h.includes(u.type),`decide: question ${n}.type must be one of ${h.join(", ")}`),t(i(u.instructions),`decide: question ${n} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${n}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${n}.options needs 2–255 entries`),l.options=u.options.map(o=>i(o)?{value:o}:(t(a(o)&&i(o.value),`decide: question ${n}: an option is a string or { value, describe? }`),o.describe!=null?{value:o.value,describe:String(o.describe)}:{value:o.value})),t(new Set(l.options.map(o=>o.value)).size===l.options.length,`decide: question ${n}.options must be distinct`)),s[n]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(i(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function N(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(i(e.model),"decide: model required"),t(d(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=n=>d(n)&&n>=0&&n<=1;for(const n of Object.keys(s?s.questions:e.answers)){const u=e.answers[n];t(a(u),`decide: answer ${n} missing`),t(r(u.p),`decide: answer ${n}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(o=>a(o)&&o.value!==void 0&&r(o.p)),`decide: answer ${n}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${n}.confidence must be in [0,1]`);const l=s?.questions?.[n];l?.type==="choice"&&t(l.options.some(o=>o.value===u.value),`decide: answer ${n}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${n}.value must be a boolean`),l?.type==="score"&&t(d(u.value),`decide: answer ${n}.value must be a number`)}return e}function C(e){t(a(e),"rerank: body must be an object"),t(i(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(i(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function z(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(i(e.model),"rerank: model required"),t(d(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,n=new Set;let u=1/0;return e.results.forEach((l,o)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${o} needs an index into the documents`),t(!n.has(l.index),`rerank: index ${l.index} listed twice`),n.add(l.index),t(d(l.relevance_score),`rerank: result ${o} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function D(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&q.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===p[r.id],`capabilities: ${r.id} must be served at ${p[r.id]}`),f.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(i),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(i),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(i),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(f.has(r.id)||d(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&i(r.runtime.state),`capabilities: ${r.id}.runtime needs state`);return e}function T(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{q as CAPABILITIES,p as CAPABILITY_ROUTES,h as DECIDE_QUESTION_TYPES,S as DISCOVERY_ROUTE,$ as OVER_BUDGET,f as PROVIDER_CAPABILITIES,c as READ_FORMATS,b as READ_RESTRICTIONS,g as SEARCH_FRESHNESS,T as offeredCapabilities,R as overBudget,x as predictMs,D as validateCapabilitiesResponse,E as validateDecideRequest,N as validateDecideResponse,j as validateDetectRequest,w as validateDetectResponse,O as validateReadRequest,A as validateReadResponse,C as validateRerankRequest,z as validateRerankResponse,I as validateSearchRequest,_ as validateSearchResponse};
1
+ import{EventError as q}from"./event.js";const x=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),b=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),g=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),I="/v1/capabilities",A="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n=e=>typeof e=="string"&&e.length>0,d=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new q("SHAPE",s)};function k(e,s){if(!a(e)||!(e.calls>0))return null;const r=d(e.p50Ms)?e.p50Ms:0,i=d(e.charsPerSec)&&e.charsPerSec>0&&d(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,i))}function _(e,s,r){if(!d(r)||r<=0)return null;const i=k(e,s);return i===null||i<=r?null:{error:{type:A,message:`predicted ${i} ms is over the ${r} ms budget`,predictedMs:i,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(n(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(n),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function w(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(n(e.model),"detect: model required"),t(d(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&n(r.value)&&n(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(d(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!n(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function E(e){t(a(e),"search: body must be an object"),t(n(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(n(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(n(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(n(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function N(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(n(e.provider),"search: provider required"),t(d(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(n(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&S(s.read)}),e}function C(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(n(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function S(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(n(e.provider),"read: provider required"),t(d(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&n(r.id)&&n(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const $=Object.freeze(["choice","score","noul"]),M=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(n(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[i,u]of Object.entries(e.questions)){t(M.test(i),`decide: question key ${JSON.stringify(i)} must be an identifier`),t(a(u)&&$.includes(u.type),`decide: question ${i}.type must be one of ${$.join(", ")}`),t(n(u.instructions),`decide: question ${i} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${i}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${i}.options needs 2–255 entries`),l.options=u.options.map(o=>n(o)?{value:o}:(t(a(o)&&n(o.value),`decide: question ${i}: an option is a string or { value, describe? }`),o.describe!=null?{value:o.value,describe:String(o.describe)}:{value:o.value})),t(new Set(l.options.map(o=>o.value)).size===l.options.length,`decide: question ${i}.options must be distinct`)),s[i]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(n(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function z(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(n(e.model),"decide: model required"),t(d(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=i=>d(i)&&i>=0&&i<=1;for(const i of Object.keys(s?s.questions:e.answers)){const u=e.answers[i];t(a(u),`decide: answer ${i} missing`),t(r(u.p),`decide: answer ${i}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(o=>a(o)&&o.value!==void 0&&r(o.p)),`decide: answer ${i}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${i}.confidence must be in [0,1]`);const l=s?.questions?.[i];l?.type==="choice"&&t(l.options.some(o=>o.value===u.value),`decide: answer ${i}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${i}.value must be a boolean`),l?.type==="score"&&t(d(u.value),`decide: answer ${i}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(n(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(n(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function T(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(n(e.model),"rerank: model required"),t(d(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,i=new Set;let u=1/0;return e.results.forEach((l,o)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${o} needs an index into the documents`),t(!i.has(l.index),`rerank: index ${l.index} listed twice`),i.add(l.index),t(d(l.relevance_score),`rerank: result ${o} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function y(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&n(e.server.name)&&n(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&x.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===b[r.id],`capabilities: ${r.id} must be served at ${b[r.id]}`),g.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(n),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(n),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(n),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(g.has(r.id)||d(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&n(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&j(r.provider,r.id);return e}function j(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(n(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(n(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(n(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(n(e.label),`capabilities: ${s}.provider.label must be a string`),e}function B(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{x as CAPABILITIES,b as CAPABILITY_ROUTES,$ as DECIDE_QUESTION_TYPES,I as DISCOVERY_ROUTE,f as EGRESS_KINDS,A as OVER_BUDGET,g as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,c as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,B as offeredCapabilities,_ as overBudget,k as predictMs,y as validateCapabilitiesResponse,D as validateDecideRequest,z as validateDecideResponse,O as validateDetectRequest,w as validateDetectResponse,j as validateProvider,C as validateReadRequest,S as validateReadResponse,P as validateRerankRequest,T as validateRerankResponse,E as validateSearchRequest,N as validateSearchResponse};
@@ -0,0 +1,4 @@
1
+ import{validateEvent as E,EventError as o}from"./event.js";const u="1.0",i="net.chatpanel",p="urn:chatpanel:host:",a=t=>typeof t=="string"&&t.length>0;function f(t){const e=Number(t);if(!Number.isFinite(e))throw new o("SHAPE","time: a finite epoch-ms number is required");return new Date(e).toISOString()}function d(t){return`${p}${encodeURIComponent(String(t))}`}function C(t){const e=String(t||"");return e.startsWith(p)?decodeURIComponent(e.slice(p.length)):null}function l(t,{source:e=null}={}){const n=E(t);return{specversion:u,id:n.id,source:e||d(n.host),type:`${i}.${n.type}`,time:f(n.at),datacontenttype:"application/json",seq:n.seq,host:n.host,causes:n.causes.join(","),chatpanelv:n.v,data:n.payload}}function w(t){if(!t||typeof t!="object")throw new o("CLOUDEVENT","a CloudEvent must be an object");if(t.specversion!==u)throw new o("CLOUDEVENT",`specversion ${t.specversion} is not ${u}`,t.specversion);if(!a(t.id))throw new o("CLOUDEVENT","id required");if(!a(t.type)||!t.type.startsWith(`${i}.`))throw new o("CLOUDEVENT",`type must start with ${i}.`,t.type);if(!a(t.time))throw new o("CLOUDEVENT","time required (RFC 3339)");const e=Date.parse(t.time);if(!Number.isFinite(e))throw new o("CLOUDEVENT",`time is not RFC 3339: ${t.time}`,t.time);const n=a(t.host)?t.host:C(t.source);if(!n)throw new o("CLOUDEVENT","host required (the `host` extension or a urn:chatpanel:host: source)");const r=Number(t.seq);if(!Number.isInteger(r)||r<0)throw new o("CLOUDEVENT","seq extension required: a non-negative integer");const h=Number(t.chatpanelv);if(!Number.isInteger(h))throw new o("CLOUDEVENT","chatpanelv extension required: the log schema version");const c=t.causes==null||t.causes===""?[]:Array.isArray(t.causes)?t.causes.map(String):String(t.causes).split(",").map(m=>m.trim()).filter(Boolean);let s=t.data;if(typeof s=="string")try{s=JSON.parse(s)}catch{throw new o("CLOUDEVENT","data is a string that is not JSON")}return E({v:h,id:t.id,host:n,seq:r,causes:c,at:e,type:t.type.slice(i.length+1),payload:s})}function v(t,e){const n=(t||[]).map(r=>JSON.stringify(l(r,e)));return n.length?`${n.join(`
2
+ `)}
3
+ `:""}function g(t){return String(t||"").split(`
4
+ `).map(e=>e.trim()).filter(Boolean).map(e=>w(JSON.parse(e)))}function O(t,e){return(t||[]).map(n=>l(n,e))}export{p as CE_SOURCE_PREFIX,u as CE_SPECVERSION,i as CE_TYPE_PREFIX,C as ceHostOf,d as ceSourceOf,w as fromCloudEvent,g as fromCloudEventLines,f as rfc3339,l as toCloudEvent,O as toCloudEventBatch,v as toCloudEventLines};
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as s,existsSync as d}from"node:fs";import{join as l}from"node:path";import p from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as A}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:A,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function _(t=process.env){let e=a;const i=t.CHATPANEL_GATEWAY_CONFIG||l(p.homedir(),".chatpanel","gateway.config.json");if(d(i))try{e=r(e,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${a.port}`),e=r(e,{port:a.port})),e}export{a as DEFAULTS,_ as loadConfig};
1
+ import{readFileSync as s,existsSync as d}from"node:fs";import{join as l}from"node:path";import p from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as u}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:u,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function _(t=process.env){let e=a;const i=t.CHATPANEL_GATEWAY_CONFIG||l(p.homedir(),".chatpanel","gateway.config.json");if(d(i))try{e=r(e,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${a.port}`),e=r(e,{port:a.port})),e}export{a as DEFAULTS,_ as loadConfig};
@@ -1 +1 @@
1
- import{writeFileSync as y,mkdirSync as b,chmodSync as p}from"node:fs";import{join as w,dirname as A}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const f=["open","allowlist","off"],d=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},o=f.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:d(r.write),denyRead:d(r.denyRead)}}function _(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||w(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);b(A(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox};y(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function P(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function C(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function M(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(t=>typeof t=="string"&&t):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const t=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;t&&(n.apiKey=t)}return n})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),m.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o];continue}if(!i||typeof i!="object")continue;const t={...e.capabilities[o]||{}};if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),!t.url){delete e.capabilities[o];continue}delete t.service,e.capabilities[o]=t}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{m as PERMISSION_MODES,M as applyConfigPatch,P as applyNerModelSelection,C as bridgeAgentOptions,u as configPath,E as isSelfDestination,l as normalizeSandboxConfig,R as persistConfig,L as publicConfig,_ as sandboxEnvFor};
1
+ import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const v=["open","allowlist","off"],l=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=v.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function P(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function C(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function M(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function I(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return t&&(n.service=t),n})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),m.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=f(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t={...e.capabilities[o]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[o];continue}t.provider="remote",delete t.service,e.capabilities[o]=t,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{m as PERMISSION_MODES,I as applyConfigPatch,C as applyNerModelSelection,M as bridgeAgentOptions,u as configPath,E as isSelfDestination,d as normalizeSandboxConfig,R as persistConfig,L as publicConfig,P as sandboxEnvFor};
@@ -1 +1 @@
1
- import{ensureLib as H,modelRoot as P}from"./ner-engine.js";import{join as R}from"node:path";import{existsSync as T,readdirSync as E}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";const m="Xenova/wavlm-base-plus-sv";let i="off",c=null,p=null,h=null,u=null,f=null,a=null,_=0,x=0;function v(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return i}function A(){return i==="ready"&&!!c&&!!p}function Z(){return f}function B(){return{configured:i!=="off",ok:A(),state:i,model:c,error:h,warmMs:a?.warmMs??null}}function G(){return!!a?.pending()}function J(){_++,a?.disarm()}function K(){_=Math.max(0,_-1),_===0&&x===0&&A()&&a?.arm()}function w(){return _>0||x>0||i==="loading"||i==="downloading"}async function k({log:e=()=>{}}={}){if(w())return!1;a?.disarm();const t=c;if(c=null,p=null,u=null,f=null,h=null,i="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function O(e=m,t=v()){const n=R(P(),...e.split("/"),"onnx");if(!T(n))return!1;const r=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return E(n).some(l=>l===`model${r}.onnx`)}catch{return!1}}async function S({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await H()}catch(o){return i="error",h=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const r=O();if(n.env.allowRemoteModels=r?!1:!!t,!r&&!t)return i="error",h="model not on disk and downloads disabled",!1;const l=n.env.remoteHost;if(!r)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=r?"loading":"downloading",r||(f={model:m,file:null,pct:0},e(`[diarize] downloading ${m} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,g=d=>{if(!d)return;const F=typeof d.progress=="number"?Math.round(d.progress):f?.pct??0;(d.status==="progress"||d.status==="download"||d.status==="initiate")&&(f={model:m,file:d.file||f?.file||null,pct:F})},y=await s.from_pretrained(m,{progress_callback:g}),q=await o.from_pretrained(m,{dtype:v(),progress_callback:g});return p=y,c=q,i="ready",h=null,f=null,e(`[diarize] ready — ${m} @ ${v()}`),!0}catch(o){return h=o.message,f=null,i="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{n.env.remoteHost=l}catch{}}}function Q(e={}){if(u&&i!=="error")return u;i="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=M({warmMs:e.warmMs,busy:w,log:t,unload:()=>k({log:t})}),u=$(S({log:t,allowDownload:e.allowDownload!==!1})),u}function $(e){return e.then(t=>(t&&!w()&&a?.arm(),t))}function U({onLog:e}={}){return u=null,i="loading",a??=M({warmMs:void 0,busy:w,log:e||(()=>{}),unload:()=>k({log:e||(()=>{})})}),u=$(S({log:e,allowDownload:!0})),u}const D=16e3;function b(e){let t=0;for(const r of e)t+=r*r;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}async function z(e){try{const t=await p(e),n=await c(t),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function V(e){if(!A()||!(e instanceof Float32Array)||!e.length)return null;x++;try{return await I(e)}finally{x--,w()||a?.arm()}}async function I(e){const t=2*D,n=Math.round(1.3*D);if(e.length<=Math.round(t*1.4)){const o=await z(e);return o?b(o):null}const r=[];for(let o=0;o+t<=e.length;o+=n){const s=await z(e.subarray(o,o+t));s&&r.push(b(s))}if(!r.length){const o=await z(e);return o?b(o):null}const l=new Float32Array(r[0].length);for(const o of r)for(let s=0;s<l.length;s++)l[s]+=o[s];return b(l)}function Y(){a?.disarm(),a=null,_=0,x=0,i="off",c=null,p=null,h=null,u=null,f=null}function tt(e,t,{warmMs:n=null}={}){c=e,p=t,i=e?"ready":"off",n!==null&&(a=M({warmMs:n,busy:w,unload:()=>k()}),e&&a.arm())}function L(e,t){let n=0,r=0,l=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],l+=t[s]*t[s];const o=Math.sqrt(r)*Math.sqrt(l);return o?n/o:0}class et{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null,weak:r=!1}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let l=null,o=-1;const s={};for(const g of this.centroids){const y=L(t,g.vec);s[g.label]=Math.round(y*1e3)/1e3,y>o&&(o=y,l=g)}return r&&l?{...this._merge(l,t,{update:!1}),scores:s,weak:!0}:l&&o>=this.threshold?{...this._merge(l,t),scores:s}:this.centroids.length>=this.maxSpeakers&&l?{...this._merge(l,t),scores:s}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:s,...r?{weak:!0}:{}}}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n,{update:r=!0}={}){if(!t.vec)t.vec=Float32Array.from(n),t.n=1;else if(r){for(let l=0;l<t.vec.length;l++)t.vec[l]=(t.vec[l]*t.n+n[l])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{m as DIARIZE_MODEL,et as Diarizer,Y as _reset,tt as _setForTest,U as download,V as embed,B as health,Q as init,A as isReady,O as modelOnDisk,Z as progress,K as release,J as retain,X as state,k as unload,G as warmPending};
1
+ import{ensureLib as H,modelRoot as P}from"./ner-engine.js";import{join as R}from"node:path";import{existsSync as T,readdirSync as E}from"node:fs";import{makeWarmTimer as A}from"./warm-timer.js";const h="Xenova/wavlm-base-plus-sv";let i="off",c=null,p=null,g=null,f=null,d=null,a=null,_=0,b=0;function v(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return i}function k(){return i==="ready"&&!!c&&!!p}function Z(){return d}function B(){return{configured:i!=="off",ok:k(),state:i,model:c,error:g,warmMs:a?.warmMs??null}}function G(){return!!a?.pending()}function J(){_++,a?.disarm()}function K(){_=Math.max(0,_-1),_===0&&b===0&&k()&&a?.arm()}function w(){return _>0||b>0||i==="loading"||i==="downloading"}async function z({log:e=()=>{}}={}){if(w())return!1;a?.disarm();const t=c;if(c=null,p=null,f=null,d=null,g=null,i="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function O(e=h,t=v()){const n=R(P(),...e.split("/"),"onnx");if(!T(n))return!1;const o=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return E(n).some(s=>s===`model${o}.onnx`)}catch{return!1}}async function $({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await H()}catch(r){return i="error",g=r.message,e(`[diarize] engine unavailable (${r.message})`),!1}const o=O();if(n.env.allowRemoteModels=o?!1:!!t,!o&&!t)return i="error",g="model not on disk and downloads disabled",!1;const s=n.env.remoteHost;if(!o)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=o?"loading":"downloading",o||(d={model:h,file:null,pct:0},e(`[diarize] downloading ${h} (one-time)…`));try{const{AutoModel:r,AutoProcessor:l}=n,u=m=>{if(!m)return;const F=typeof m.progress=="number"?Math.round(m.progress):d?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(d={model:h,file:m.file||d?.file||null,pct:F})},y=await l.from_pretrained(h,{progress_callback:u}),x=await r.from_pretrained(h,{dtype:v(),progress_callback:u});return p=y,c=x,i="ready",g=null,d=null,e(`[diarize] ready — ${h} @ ${v()}`),!0}catch(r){return g=r.message,d=null,i="error",e(`[diarize] load failed (${r.message}) — diarization off`),!1}finally{try{n.env.remoteHost=s}catch{}}}function Q(e={}){if(f&&i!=="error")return f;i="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=A({warmMs:e.warmMs,busy:w,log:t,unload:()=>z({log:t})}),f=D($({log:t,allowDownload:e.allowDownload!==!1})),f}function D(e){return e.then(t=>(t&&!w()&&a?.arm(),t))}function U({onLog:e}={}){return f=null,i="loading",a??=A({warmMs:void 0,busy:w,log:e||(()=>{}),unload:()=>z({log:e||(()=>{})})}),f=D($({log:e,allowDownload:!0})),f}const q=16e3;function M(e){let t=0;for(const o of e)t+=o*o;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let o=0;o<e.length;o++)n[o]=e[o]/t;return n}async function S(e){try{const t=await p(e),n=await c(t),o=n.embeddings??n.logits??n.last_hidden_state;return o?.data?Float32Array.from(o.data):null}catch{return null}}async function V(e){if(!k()||!(e instanceof Float32Array)||!e.length)return null;b++;try{return await I(e)}finally{b--,w()||a?.arm()}}async function I(e){const t=2*q,n=Math.round(1.3*q);if(e.length<=Math.round(t*1.4)){const r=await S(e);return r?M(r):null}const o=[];for(let r=0;r+t<=e.length;r+=n){const l=await S(e.subarray(r,r+t));l&&o.push(M(l))}if(!o.length){const r=await S(e);return r?M(r):null}const s=new Float32Array(o[0].length);for(const r of o)for(let l=0;l<s.length;l++)s[l]+=r[l];return M(s)}function Y(){a?.disarm(),a=null,_=0,b=0,i="off",c=null,p=null,g=null,f=null,d=null}function tt(e,t,{warmMs:n=null}={}){c=e,p=t,i=e?"ready":"off",n!==null&&(a=A({warmMs:n,busy:w,unload:()=>z()}),e&&a.arm())}function L(e,t){let n=0,o=0,s=0;for(let l=0;l<e.length;l++)n+=e[l]*t[l],o+=e[l]*e[l],s+=t[l]*t[l];const r=Math.sqrt(o)*Math.sqrt(s);return r?n/r:0}class et{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null,weak:o=!1,thin:s=!1}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let r=null,l=-1;const u={};for(const y of this.centroids){const x=L(t,y.vec);u[y.label]=Math.round(x*1e3)/1e3,x>l&&(l=x,r=y)}return o&&r?{...this._merge(r,t,{update:!1}),scores:u,weak:!0}:r&&l>=this.threshold?{...this._merge(r,t),scores:u}:this.centroids.length>=this.maxSpeakers&&r?{...this._merge(r,t),scores:u}:s&&r?{...this._merge(r,t,{update:!1}),scores:u,thin:!0}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:u,...o?{weak:!0}:{}}}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n,{update:o=!0}={}){if(!t.vec)t.vec=Float32Array.from(n),t.n=1;else if(o){for(let s=0;s<t.vec.length;s++)t.vec[s]=(t.vec[s]*t.n+n[s])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{h as DIARIZE_MODEL,et as Diarizer,Y as _reset,tt as _setForTest,U as download,V as embed,B as health,Q as init,k as isReady,O as modelOnDisk,Z as progress,K as release,J as retain,X as state,z as unload,G as warmPending};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const o=g(r);if(!o||!o.host)return;const i=`${o.scheme}://${o.host}:${o.port}`,c=e(),a=t.get(i);if(a){a.count+=1,a.lastAt=c;return}t.set(i,{host:o.host,port:o.port,scheme:o.scheme,local:u(o.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,o)=>r.local===o.local?o.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function L(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let o=t;r.setGate=c=>{o=c},r.blocked=[];const i=e.fetch;return typeof i=="function"&&(e.fetch=function(a,p){let s=null;try{s=g(a),r.record(a)}catch{}if(o&&s?.host){let l=!0;try{l=o(`${s.scheme}://${s.host}:${s.port}`,{local:u(s.host)})}catch{l=!0}if(!l){const n=`${s.host}:${s.port}`;r.blocked.includes(n)||r.blocked.push(n);const h=new Error(`egress to ${s.host} is blocked by your organisation’s policy`);return h.code="EGRESS_POLICY",Promise.reject(h)}}return i.call(this,a,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],o=(s,l,{when:n="always",off:h=null,local:m=!1,data:y=""}={})=>{s&&r.push({host:s,purpose:l,when:n,off:h,local:m,data:y})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const i=e.search?.searxng?.url||"";if(i){let s=i;try{s=new URL(i).host}catch{}o(s,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(s)})}if(e.search?.provider!=="searxng"&&(o("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}o(s,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(s)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"}};for(const[s,l]of Object.entries(c)){const n=e.capabilities?.[s];if(!n?.url)continue;let h=n.url;try{h=new URL(n.url).host}catch{}o(h,`${l.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${l.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(h)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[s,l]of Object.entries(e.upstreams||{}))l?.baseUrl&&o(d(l.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:u(d(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&o(d(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:u(d(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const a=e.tts||{};if(a.provider==="openai"||a.provider==="elevenlabs"){const s=a.remote?.baseUrl?d(a.remote.baseUrl):a.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(s,`remote read-aloud voice (${a.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:a.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return o(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function S(e,{ledger:t=$(),version:r="",startedAt:o=null,env:i=process.env,managed:c=null}={}){return{ok:!0,version:r,since:o?new Date(o).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,i)}}function x(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,o])=>o===!0?r:`${r}=${o}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{v as createEgressLedger,k as declaredEgress,S as egressAudit,$ as egressLedger,x as formatAudit,L as installEgressLedger};
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const y=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=y}={}){const t=new Map;return{record(r){const s=g(r);if(!s||!s.host)return;const h=`${s.scheme}://${s.host}:${s.port}`,c=e(),o=t.get(h);if(o){o.count+=1,o.lastAt=c;return}t.set(h,{host:s.host,port:s.port,scheme:s.scheme,local:u(s.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,s)=>r.local===s.local?s.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function x(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let s=t;r.setGate=c=>{s=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(o,p){let a=null;try{a=g(o),r.record(o)}catch{}if(s&&a?.host){let i=!0;try{i=s(`${a.scheme}://${a.host}:${a.port}`,{local:u(a.host)})}catch{i=!0}if(!i){const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,o,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],s=(a,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{a&&r.push({host:a,purpose:i,when:n,off:l,local:m,data:b})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"&&(s("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,i]of Object.entries(c)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}s(l,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&s(d(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(d(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:u(d(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const o=e.tts||{};if(o.provider==="openai"||o.provider==="elevenlabs"){const a=o.remote?.baseUrl?d(o.remote.baseUrl):o.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${o.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:o.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return s(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function L(e,{ledger:t=$(),version:r="",startedAt:s=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:s?new Date(s).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,s])=>s===!0?r:`${r}=${s}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{v as createEgressLedger,k as declaredEgress,L as egressAudit,$ as egressLedger,S as formatAudit,x as installEgressLedger};
@@ -0,0 +1 @@
1
+ function p(e){const a=String(e||"").trim();if(!a)return[];const t=[];let l="",n=null;for(const o of a)n?o===n?n=null:l+=o:o==='"'||o==="'"?n=o:/\s/.test(o)?l&&(t.push(l),l=""):l+=o;return l&&t.push(l),t}const f=Object.freeze([{id:"maxModelLen",label:"Context ceiling",kind:"number",what:"The longest prompt + answer the engine holds. Bounds the KV cache — without it the cache grows until the machine is full.",engines:["vllm","vllm-metal","llama"],default:({task:e})=>e==="chat"?8192:2048,min:512,max:262144,args:e=>["--max-model-len",String(e)],by:{llama:{default:({ramGB:e})=>e>0&&e<24?8192:16384,args:e=>["-c",String(e)]}}},{id:"prefixCache",label:"Prefix caching",kind:"bool",what:"Reuse the computed cache of a shared prompt prefix — the system prompt and tool list an agent resends every turn cost once.",engines:["vllm","vllm-metal","llama"],default:!0,args:e=>e?["--enable-prefix-caching"]:["--no-enable-prefix-caching"],by:{llama:{args:(e,{values:a})=>e?["--cache-reuse",String(a.maxModelLen>=32768?512:256)]:["--cache-reuse","0"]}}},{id:"kvCacheDtype",label:"KV cache precision",kind:"choice",options:["auto","fp8"],what:"fp8 halves the cache, so twice the context fits — on CUDA and ROCm; elsewhere leave auto.",engines:["vllm","llama"],default:"auto",backends:["cuda","rocm","metal","vulkan","cpu"],args:e=>e&&e!=="auto"?["--kv-cache-dtype",e]:[],by:{llama:{options:["auto","f16","q8_0"],what:"q8_0 halves the cache with little quality lost; auto takes q8_0 once the context is 32k or more.",args:(e,{values:a})=>e==="q8_0"||e==="auto"&&a.maxModelLen>=32768?["-ctk","q8_0","-ctv","q8_0"]:[]}}},{id:"gpuMemory",label:"GPU memory share",kind:"number",what:"The fraction of the accelerator’s memory the engine may take for weights and cache. Lower it when something else needs the GPU.",engines:["vllm"],default:.9,min:.1,max:.99,backends:["cuda","rocm","xpu"],args:e=>["--gpu-memory-utilization",String(e)]},{id:"gpuOffload",label:"GPU offload",kind:"bool",what:"Put every layer on the GPU (Metal, CUDA, Vulkan). Off runs the model on the CPU — only for a build without a GPU.",engines:["llama"],default:({backend:e})=>e!=="cpu",args:e=>["-ngl",e?"all":"0"]},{id:"flashAttention",label:"Flash attention",kind:"bool",what:"The fused attention kernel — less memory and faster on Metal and CUDA. Leave it on.",engines:["llama"],default:!0,args:e=>["-fa",e?"on":"off"]},{id:"threads",label:"Generation threads",kind:"number",what:"CPU threads for decoding. The performance cores — more only contends.",engines:["llama"],default:({perfCores:e})=>e||8,min:1,max:128,args:e=>["-t",String(e)]},{id:"batchThreads",label:"Prompt threads",kind:"number",what:"CPU threads for reading the prompt. All the physical cores.",engines:["llama"],default:({cores:e})=>e||8,min:1,max:128,args:e=>["-tb",String(e)]},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","ngram"],what:"Draft tokens by n-gram lookup in the prompt and verify them in one pass — faster on code and edits, where the answer repeats the input.",engines:["vllm","vllm-metal","llama"],default:"off",tasks:["chat"],args:e=>e==="ngram"?["--speculative-config",JSON.stringify({method:"ngram",num_speculative_tokens:5,prompt_lookup_max:4})]:[],by:{llama:{options:["off","ngram","draft-mtp","draft"],default:({values:e})=>e?.draftModel?"draft-mtp":"off",what:"Draft tokens and verify them in one pass. ngram needs nothing; draft-mtp is the model’s own MTP head (name the draft file below — the `lm` recipe, ~0.75 accepted); draft is a small sibling model.",args:(e,{values:a,backend:t})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:a.draftModel?["--model-draft",a.draftModel,"--spec-type",e,"--spec-draft-n-max","3","--spec-draft-ngl",t==="cpu"?"0":"all",...a.maxModelLen>=32768?["--spec-draft-type-k","q8_0","--spec-draft-type-v","q8_0"]:[]]:[]}}},{id:"draftModel",label:"Draft model",kind:"text",what:"The GGUF the draft-mtp / draft modes draft with — the model’s MTP file (…-MTP.gguf) or a small sibling. A path, or a Hugging Face id.",engines:["llama"],default:"",tasks:["chat"],args:()=>[]},{id:"toolCalls",label:"Tool calling",kind:"choice",options:["off","hermes","llama3_json","mistral","pythonic","qwen3_coder"],what:"Parse the model’s tool calls into OpenAI tool_calls, so a harness sees tools and not text. Qwen3 and SmolLM3 speak hermes; Llama 3 llama3_json.",engines:["vllm","vllm-metal"],default:({model:e})=>/^(Qwen\/Qwen3|mlx-community\/Qwen3|HuggingFaceTB\/SmolLM3)/i.test(e||"")?"hermes":/Llama-3/i.test(e||"")?"llama3_json":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--enable-auto-tool-choice","--tool-call-parser",e]:[]},{id:"reasoning",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek_r1"],what:"Split a thinking model’s reasoning from its answer, so the answer arrives clean and the thinking is a separate field.",engines:["vllm","vllm-metal","llama"],default:({model:e})=>/Qwen3/i.test(e||"")?"qwen3":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--reasoning-parser",e]:[],by:{llama:{options:["auto","on","off"],default:"auto",label:"Thinking",what:"Whether the model thinks before answering (a template that supports it): on with a 1024-token budget returned as a separate field, off for direct answers, auto as the model decides.",args:e=>e==="on"?["--reasoning","on","--reasoning-budget","1024","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"chatTemplate",label:"Chat template",kind:"text",what:"A Jinja template file that overrides the model’s own — the fix when a fresh release ships a broken prompt template.",engines:["vllm","vllm-metal","llama","mlx"],default:"",tasks:["chat"],args:e=>e?["--chat-template",e]:[],by:{llama:{args:e=>e?["--chat-template-file",e]:[]}}},{id:"vision",label:"Vision projector",kind:"text",what:"The model’s multimodal projector (mmproj-*.gguf) — with it the server takes images; without it, more memory for text. A path.",engines:["llama"],default:"",tasks:["chat"],args:e=>e?["--mmproj",e,"--mmproj-offload"]:[]},{id:"maxSeqs",label:"Concurrent requests",kind:"number",what:"How many requests the engine batches at once. One user needs few; a team behind the gateway more — each costs cache.",engines:["vllm","vllm-metal","llama"],default:8,min:1,max:256,args:e=>["--max-num-seqs",String(e)],by:{llama:{default:1,what:"Server slots. One for a big model and a long context; more only when several people share this machine — each slot holds its own context.",args:e=>["-np",String(e)]}}},{id:"extraArgs",label:"Extra flags",kind:"args",what:"Anything else the engine takes, as you would type it after the command — the engine’s own documentation is the list. Appended last, so it wins over the rows above.",engines:["vllm","vllm-metal","llama","mlx"],default:"",args:e=>p(e)}]),x=e=>f.find(a=>a.id===e)||null;function b(e,a){const t=e.by?.[a];return t?{...e,...t,by:void 0}:e}function d(e,{task:a="chat",backend:t=null}={}){return f.filter(l=>l.engines.includes(e)&&(!l.tasks||l.tasks.includes(a))&&(!l.backends||!t||l.backends.includes(t))).map(l=>b(l,e))}function u(e,a){return typeof e.default=="function"?e.default(a):e.default}function w(e,a){if(!e)return null;if(e.kind==="bool")return typeof a=="boolean"?a:a==="true"?!0:a==="false"?!1:null;if(e.kind==="number"){const t=Number(a);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}if(e.kind==="choice")return e.options.includes(a)?a:null;if(e.kind==="text"){const t=String(a??"").trim();return t.length<=512&&!t.startsWith("-")&&!/[\s"'`$;|&<>]/.test(t)?t:null}if(e.kind==="args"){const t=String(a??"").trim();return t.length<=2e3&&!/[`$;|&<>\n]/.test(t)?t:null}return null}function y(e,a,t,l={}){const n={...a||{}},o=d(e,l);for(const[s,i]of Object.entries(t||{})){const r=o.find(h=>h.id===s);if(!r)return{error:`no tuning ${JSON.stringify(s)} for ${e}`};if(i==null){delete n[s];continue}const m=w(r,i);if(m===null)return{error:`${r.label}: ${r.kind==="choice"?`one of ${r.options.join(", ")}`:r.kind==="number"?`a number between ${r.min} and ${r.max}`:r.kind==="bool"?"on or off":r.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};n[s]=m}return n}function c(e,a,t={}){const l={};for(const n of d(e,t))l[n.id]=a&&a[n.id]!==void 0?a[n.id]:u(n,{...t,values:{...a||{},...l}});return l}function v(e,a,t={}){const l=c(e,a,t),n=[];for(const o of d(e,t))n.push(...o.args(l[o.id],{...t,values:l}));return n}function S(e,a,t={}){const l=c(e,a,t);return d(e,t).map(n=>({id:n.id,label:n.label,what:n.what,kind:n.kind,...n.options?{options:n.options}:{},...n.kind==="number"?{min:n.min,max:n.max}:{},default:a&&a[n.id]!==void 0?u(n,{...t,values:l}):l[n.id],...a&&a[n.id]!==void 0?{value:a[n.id]}:{}}))}const M=Object.freeze({vllm:{label:"vLLM engine arguments",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},"vllm-metal":{label:"vLLM engine arguments (vLLM-Metal takes the same)",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},llama:{label:"llama-server flags",url:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"},mlx:{label:"mlx_lm.server flags",url:"https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/SERVER.md"}}),k=Object.freeze([{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest context, the least memory.",ctx:({ramGB:e})=>e>0&&e<24?4096:8192,needGB:0},{id:"coding",label:"Coding",what:"A coding assistant’s room for a file and a conversation. The default.",ctx:({ramGB:e})=>e>0&&e<24?8192:16384,needGB:0},{id:"long",label:"Long context",what:"Several files or a long page at once — slower, the cache quantised to fit.",ctx:({ramGB:e})=>e>=36?32768:e>=24?16384:8192,needGB:24},{id:"xl",label:"Extra long",what:"A whole repository’s worth. An experiment under 64 GB: close other apps and watch memory.",ctx:({ramGB:e})=>e>=48?65536:32768,needGB:48}]);function _(e,a,t={}){const l=d(e,t);if((t.task||"chat")!=="chat"||!l.some(s=>s.id==="maxModelLen"))return[];const n=c(e,a,t);let o=!1;return k.map(s=>{const i=s.ctx(t),r={maxModelLen:i,...l.some(g=>g.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":t.backend==="cuda"||t.backend==="rocm"?"fp8":"auto":"auto"}:{}},m=!t.ramGB||t.ramGB>=s.needGB,h=!o&&n.maxModelLen===i;return h&&(o=!0),{id:s.id,label:s.label,what:s.what,patch:r,fits:m,...m?{}:{why:`needs ${s.needGB} GB of memory; this machine has ${t.ramGB}`},active:h}})}export{M as ENGINE_DOCS,k as PROFILES,f as TUNINGS,w as coerceTuning,b as forEngine,y as patchTunings,_ as profilesFor,c as resolveTunings,p as splitArgs,v as tuningArgs,u as tuningDefault,S as tuningRows,d as tuningsFor};
@@ -0,0 +1 @@
1
+ const j=864e5,m=n=>{try{return JSON.stringify(n).length}catch{return 0}},D=n=>{const s=[],a=(e,l)=>{if(!(!e||typeof e!="object"||l>3)){if(typeof e.hash=="string"&&typeof e.kind=="string"){s.push(e.hash);return}for(const y of Array.isArray(e)?e:Object.values(e))a(y,l+1)}};return a(n,0),s},k=n=>Math.round(n*1e3)/10;function I(n=[]){const s=Array.isArray(n)?n.filter(t=>t&&typeof t=="object"):[];let a=0,e=1/0,l=-1/0;const y={},g={},b=new Map,c=[];let v=0,M=0;for(const t of s){const r=m(t);a+=r,Number.isFinite(t.at)&&(t.at<e&&(e=t.at),t.at>l&&(l=t.at));const u=y[t.host]||(y[t.host]={events:0,bytes:0});u.events+=1,u.bytes+=r,g[t.type]=(g[t.type]||0)+1;const d=t.payload?.turnId;if(typeof d=="string"&&d){const p=b.get(d)||{events:0,bytes:0,surface:null};p.events+=1,p.bytes+=r,t.type==="turn.started"&&typeof t.payload.surface=="string"&&(p.surface=t.payload.surface),b.set(d,p)}c.push(...D(t.payload)),t.type==="capability.invoked"&&(v+=1),t.type==="capability.resulted"&&t.payload?.ok===!1&&(M+=1)}const i=s.length&&l>e?Math.max(1,(l-e)/864e5):s.length?1:0,o=[...b.values()],h=o.map(t=>t.events).sort((t,r)=>t-r),f={};for(const t of o){const r=t.surface||"unknown",u=f[r]||(f[r]={turns:0,events:0,bytes:0});u.turns+=1,u.events+=t.events,u.bytes+=t.bytes}for(const t of Object.values(f))t.avgEvents=Math.round(t.events/t.turns),t.avgBytes=Math.round(t.bytes/t.turns),delete t.events,delete t.bytes;const A=new Set(c).size;return{events:s.length,bytes:a,avgBytes:s.length?Math.round(a/s.length):0,span:{fromAt:Number.isFinite(e)?e:null,toAt:Number.isFinite(l)?l:null,days:Math.round(i*10)/10},perDay:{events:i?Math.round(s.length/i):0,bytes:i?Math.round(a/i):0},hosts:y,types:g,turns:{count:o.length,avgEvents:o.length?Math.round(o.reduce((t,r)=>t+r.events,0)/o.length):0,avgBytes:o.length?Math.round(o.reduce((t,r)=>t+r.bytes,0)/o.length):0,p95Events:h.length?h[Math.min(h.length-1,Math.floor(h.length*.95))]:0,bySurface:f},refs:{total:c.length,distinct:A,dedupHitRate:c.length?k(1-A/c.length):0},toolCalls:{total:v,perTurn:o.length?Math.round(v/o.length*10)/10:0,failed:M}}}function Y(n,{capEvents:s=2e4}={}){if(!n||!n.span?.days)return null;const a=Math.round(n.perDay.events*365),e=Math.round(n.perDay.bytes*365);return{eventsPerYear:a,bytesPerYear:e,daysToCap:n.perDay.events?Math.round(s/n.perDay.events):null}}export{I as eventStats,Y as projectYear};
@@ -0,0 +1,15 @@
1
+ import{join as T}from"node:path";import{mkdirSync as O,chmodSync as A,existsSync as L}from"node:fs";import f from"node:os";import{openDb as S}from"./sqlite-store.js";import{validateEvent as C,EventError as M}from"./event.js";const p=T(f.homedir(),".chatpanel"),m=process.env.CHATPANEL_EVENTS_DB||T(p,"events.db"),I=25e3,d=2e4,y=250,b=16e3,a=1e3,D=`
2
+ CREATE TABLE IF NOT EXISTS events (
3
+ id TEXT PRIMARY KEY,
4
+ host TEXT NOT NULL,
5
+ seq INTEGER NOT NULL,
6
+ at INTEGER NOT NULL,
7
+ type TEXT NOT NULL,
8
+ causes TEXT NOT NULL DEFAULT '[]',
9
+ payload TEXT NOT NULL,
10
+ v INTEGER NOT NULL DEFAULT 1,
11
+ UNIQUE (host, seq)
12
+ );
13
+ CREATE INDEX IF NOT EXISTS events_at ON events (at, host, seq);
14
+ CREATE INDEX IF NOT EXISTS events_type ON events (type, at);
15
+ `;class _{constructor({path:t=m,now:s=()=>Date.now()}={}){this.path=t,this.now=s,this.db=null,this._sinceCheck=0,this._watchers=new Set}async init(){if(this.path!==":memory:"){O(p,{recursive:!0,mode:448});const t=!L(this.path);if(this.db=await S(this.path),t)try{A(this.path,384)}catch{}}else this.db=await S(this.path);return this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec(D),this}append(t){if(C(t),this.db.get("SELECT 1 AS x FROM events WHERE id = ?",[t.id]))return{appended:!1,event:t};const s=this.db.get("SELECT MAX(seq) AS seq FROM events WHERE host = ?",[t.host])?.seq;if(Number.isFinite(s)&&s!==null&&t.seq<=s)throw new M("SEQ",`seq ${t.seq} <= ${s} already seen for host ${t.host}`,t.host);let e=JSON.stringify(t.payload);e.length>b&&(e=JSON.stringify({_clipped:!0,_chars:e.length,...q(t.payload)})),this.db.run("INSERT INTO events (id, host, seq, at, type, causes, payload, v) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.host,t.seq,t.at,t.type,JSON.stringify(t.causes),e,t.v]),this._sinceCheck+=1,this._sinceCheck>=y&&(this._sinceCheck=0,this.prune());for(const h of this._watchers)try{h(t)}catch{}return{appended:!0,event:t}}cursor(){const t={};for(const s of this.db.all("SELECT host, MAX(seq) AS seq FROM events GROUP BY host ORDER BY host"))t[s.host]=s.seq;return t}since(t={},{limit:s=a,host:e=null}={}){const h=Math.max(1,Math.min(a,Number(s)||a)),u=e?[e]:this.db.all("SELECT DISTINCT host FROM events ORDER BY host").map(n=>n.host),r=[];let i=!1;for(const n of u){if(r.length>=h){i=!0;break}const R=Number.isInteger(t?.[n])?t[n]:-1,c=this.db.all("SELECT * FROM events WHERE host = ? AND seq > ? ORDER BY seq ASC LIMIT ?",[n,R,h-r.length+1]);c.length>h-r.length&&(i=!0,c.length=h-r.length);for(const N of c)r.push(l(N))}const E={...t};for(const n of r)E[n.host]=Math.max(E[n.host]??-1,n.seq);return{events:r,cursor:E,more:i}}recent({limit:t=200,type:s=null}={}){const e=Math.max(1,Math.min(a,Number(t)||200));return(s?this.db.all("SELECT * FROM events WHERE type = ? ORDER BY at DESC, seq DESC LIMIT ?",[s,e]):this.db.all("SELECT * FROM events ORDER BY at DESC, host DESC, seq DESC LIMIT ?",[e])).map(l)}all(){return this.db.all("SELECT * FROM events ORDER BY at ASC, host ASC, seq ASC").map(l)}count(){return this.db.get("SELECT COUNT(*) AS n FROM events")?.n||0}hosts(){return this.db.all("SELECT host, COUNT(*) AS n, MAX(seq) AS seq, MAX(at) AS at FROM events GROUP BY host ORDER BY host")}prune(){const t=this.count();return t<=I?0:(this.db.run("DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY at ASC, host ASC, seq ASC LIMIT ?)",[t-d]),t-d)}watch(t){return this._watchers.add(t),()=>this._watchers.delete(t)}clear(){this.db.exec("DELETE FROM events")}}function l(o){return{v:o.v??1,id:o.id,host:o.host,seq:o.seq,at:o.at,type:o.type,causes:JSON.parse(o.causes||"[]"),payload:JSON.parse(o.payload)}}function q(o){const t={};for(const[s,e]of Object.entries(o||{}))t[s]=typeof e=="string"&&e.length>2e3?`${e.slice(0,2e3)}…`:e;return t}async function X(o={}){try{return await new _(o).init()}catch(t){return console.log(`[events] SQLite unavailable (${t.message}); the event log is off`),null}}export{_ as EventStore,I as MAX_EVENTS,a as PAGE_LIMIT,d as PRUNE_TO,X as createEventStore};
@@ -0,0 +1 @@
1
+ import{toCloudEvent as g,fromCloudEvent as m}from"./cloudevents.js";const d=Object.freeze({maxEvents:500,maxBytes:512*1024});function h({events:o=[],cursor:t={},host:e,maxEvents:r=d.maxEvents,maxBytes:n=d.maxBytes}={}){const c=Number.isInteger(t?.[e])?t[e]:-1,u=o.filter(s=>s&&s.host===e&&s.seq>c).sort((s,p)=>s.seq-p.seq),i=[];let f=0,a=null;for(const s of u){const p=g(s),l=JSON.stringify(p).length;if(i.length&&(i.length>=r||f+l>n))break;i.push(p),f+=l,a=s.seq}return{batch:i,seq:a,remaining:u.length-i.length}}function v(o,t){const e={appended:0,duplicates:0,rejected:[],events:[]};for(const r of Array.isArray(t)?t:[]){let n;try{n=m(r),o.append(n).appended?(e.appended+=1,e.events.push(n)):e.duplicates+=1}catch(c){e.rejected.push({id:typeof r?.id=="string"?r.id:null,code:c?.code||"INGEST",message:String(c?.message||c)})}}return e}function x(o){const t=o?.cursor??o;if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[r,n]of Object.entries(t))typeof r=="string"&&Number.isInteger(n)&&n>=0&&(e[r]=n);return e}export{d as PUSH_LIMITS,x as cursorOf,v as ingestCloudEvents,h as planEventPush};
package/src/event.js ADDED
@@ -0,0 +1 @@
1
+ import{isRef as n}from"./ref.js";const i=1,v=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded","retrieved"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"]}),m=Object.freeze(Object.entries(v).flatMap(([e,r])=>r.map(s=>`${e}.${s}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),x=Object.freeze(["global","site","tab","session","agent"]),u=Object.freeze(["R","M","L","C","A","X","H"]),S=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),k=Object.freeze(["none","redacted","delegated"]);class a extends Error{constructor(r,s,c=null){super(s),this.name="EventError",this.code=r,this.detail=c}}const t=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),l=e=>Array.isArray(e);function d(e){return!!e&&w.includes(e.kind)&&t(e.id)}function A(e){return!!e&&x.includes(e.kind)&&t(e.id)}const O={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&n(e.ref),"assistant.message":e=>t(e.turnId)&&n(e.ref),"assistant.reasoning":e=>t(e.turnId)&&n(e.ref),"context.assembled":e=>o(e.budget)&&o(e.used)&&!!e.parts&&typeof e.parts=="object"&&l(e.resident)&&e.resident.every(n)&&o(e.reachableCount),"context.attached":e=>n(e.ref),"context.expanded":e=>n(e.ref)&&o(e.tokens),"context.retrieved":e=>t(e.tool)&&o(e.count)&&l(e.sources)&&e.sources.every(r=>r&&typeof r=="object"&&o(r.rank)),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&d(e.actor),"capability.denied":e=>t(e.capability)&&d(e.actor),"capability.activated":e=>t(e.capability)&&u.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&d(e.actor)&&A(e.scope)&&S.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&u.includes(e.classUsed)&&!!e.cost&&o(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(o),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&d(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>n(e.ref),"data.updated":e=>n(e.ref),"data.deleted":e=>n(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&u.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason)};function y(e){if(!e||typeof e!="object")throw new a("SHAPE","event must be an object");if(e.v!==i)throw new a("VERSION",`expected v=${i}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new a("SHAPE","id required");if(!t(e.host))throw new a("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new a("SHAPE","seq must be a non-negative integer");if(!l(e.causes)||!e.causes.every(t))throw new a("SHAPE","causes must be string[]");if(!o(e.at))throw new a("SHAPE","at required (advisory wall clock)");if(!m.includes(e.type))throw new a("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new a("SHAPE","payload required");const r=O[e.type];if(r&&!r(e.payload))throw new a("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function I(e){try{return y(e),!0}catch{return!1}}function P({host:e,seq:r=0,now:s=()=>Date.now(),newId:c}){if(!t(e))throw new a("SHAPE","host required");const p=c||(()=>globalThis.crypto.randomUUID());let f=r;return{get host(){return e},get seq(){return f},append(b,h,E=[]){const g=Object.freeze({v:i,id:p(),host:e,seq:f++,causes:Object.freeze([...E]),at:s(),type:b,payload:h});return y(g)}}}export{w as ACTOR_KINDS,m as ALL_TYPES,u as CLASSES,i as CURRENT_VERSION,S as EFFECTS,k as EGRESS,v as EVENT_TYPES,a as EventError,x as SCOPE_KINDS,P as createAppender,I as isValidEvent,y as validateEvent};
package/src/fusions.js ADDED
@@ -0,0 +1 @@
1
+ import{FUSION_KINDS as l,validateFusion as c,pickMember as p,describeFusion as m,fusionIdOf as b,normalizeMember as y}from"@chatpanel/events/model-fusion.js";function k(r){const e=r?.active||r?.model||null,t=(r?.companions||[]).filter(i=>i.state==="ready"||i.state==="loaded").map(i=>i.model);return!e||!t.length?null:{id:"ner-union",kind:"union",capability:"detect",members:[e,...t],source:"ner",derived:!0}}function v(r){const e=[];for(const[t,i]of Object.entries(r?.services||{})){if(!i||typeof i!="object"||!Array.isArray(i.tunings)||!i.model)continue;const n=a=>{const u=i.tunings.find(f=>f.id===a);return u?u.value!==void 0?u.value:u.default:void 0},o=n("speculative"),s=n("draftModel");(o==="draft-mtp"||o==="draft")&&s&&e.push({id:`${t}-draft`,kind:"draft",capability:"chat",members:[{id:i.model,role:"target"},{id:s,role:"draft"}],source:t,derived:!0,running:i.state==="running"})}return e}function d(r){return(Array.isArray(r.fusions)?r.fusions:[]).filter(e=>e&&typeof e=="object")}function g(r,e){if(e===null)return r.fusions=[],null;if(!Array.isArray(e))return"fusions: a list";const t=[];for(const i of e){const n=c(i);if(n)return`fusions ${JSON.stringify(i?.id??"?")}: ${n}`;if(t.some(o=>o.id===i.id))return`fusions: id ${JSON.stringify(i.id)} twice`;if(i.id==="ner-union"||/-draft$/.test(i.id))return`fusions: ${JSON.stringify(i.id)} is a derived id`;t.push({id:i.id,kind:i.kind,capability:i.capability,members:i.members.map(y),...i.label?{label:String(i.label).slice(0,80)}:{}})}return r.fusions=t,null}function x({cfg:r,ner:e=null,runtimeDoc:t=null,nameOf:i=n=>n}){const n=[k(e),...v(t),...d(r)].filter(Boolean);return{kinds:l,fusions:n.map(o=>({...o,describe:m(o,i)}))}}function F(r,e,t=()=>"unknown"){const i=b(r);if(!i)return null;const n=d(e).find(s=>s.id===i);if(!n)return{error:`no fusion "${i}" on this gateway`};if(n.kind!=="fallback"||n.capability!=="chat")return{error:`fusion "${i}" is a ${n.kind} for ${n.capability} — only a chat fallback can be sent a turn`};const o=p(n,t);return o.member?{model:o.member.id,fusion:n,next:o.next.map(s=>s.id),skipped:o.skipped.map(s=>s.id)}:{error:`fusion "${i}": every member is down (${o.skipped.map(s=>s.id).join(", ")})`}}export{g as applyFusionsPatch,d as composedFusions,v as draftFusions,x as fusionsDocument,k as nerUnionFusion,F as resolveFusionModel};