@chatpanel/gateway 0.17.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- const e=process.argv[2];try{process.title=e==="--bridge"?"chatpanel-bridge":e==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(e==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(e==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(e==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(e==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(e==="tools"||e==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(e==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const a=await t();process.argv.includes("--json")?console.log(JSON.stringify(a?{...a,label:void 0}:null,null,2)):console.log(o(a))}catch(a){throw a instanceof i&&(console.error(`org policy: ${a.message}`),process.exit(78)),a}}else if(e==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:p}=await import("node:path"),n=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let r=null,c=`no gateway running at ${s}`;try{const d=a(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(n.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${d}`},signal:AbortSignal.timeout(2500)});if(g.ok)r=await g.json();else if(g.status===404){const u=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${u?.version?` (${u.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!r){const{VERSION:d}=await import("../src/server.js");r={...t(l,{ledger:null,version:d}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(r,null,2)):console.log(o(r))}else if(e==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),a=await import("node:os"),n=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(a.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),r=await fetch(`${n}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await r.json().catch(()=>({}));if(r.status===404)throw new Error(`the gateway at ${n} predates pairing (0.9.0) — update and restart it`);if(!r.ok)throw new Error(c.error||`HTTP ${r.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${n}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(e==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(e==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:a,serviceStatus:p,stopService:n}=await import("../src/service.js");switch(e){case"--stop":n(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":a(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(p()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${e}
2
+ const e=process.argv[2];try{process.title=e==="--bridge"?"chatpanel-bridge":e==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(e==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(e==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(e==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(e==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(e==="tools"||e==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(e==="policy"){const{loadPolicy:t,formatPolicy:a,PolicyLoadError:i}=await import("../src/policy.js");try{const o=await t();process.argv.includes("--json")?console.log(JSON.stringify(o?{...o,label:void 0}:null,null,2)):console.log(a(o))}catch(o){throw o instanceof i&&(console.error(`org policy: ${o.message}`),process.exit(78)),o}}else if(e==="--audit"){const{egressAudit:t,formatAudit:a}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:p}=await import("node:path"),n=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let r=null,c=`no gateway running at ${s}`;try{const d=o(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(n.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${d}`},signal:AbortSignal.timeout(2500)});if(g.ok)r=await g.json();else if(g.status===404){const u=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${u?.version?` (${u.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!r){const{VERSION:d}=await import("../src/server.js");r={...t(l,{ledger:null,version:d}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(r,null,2)):console.log(a(r))}else if(e==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:a}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await a(process.argv.slice(3)))}else if(e==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:i}=await import("node:path"),o=await import("node:os"),n=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(o.homedir(),".chatpanel","gateway-token");try{const s=a(l,"utf8").trim(),r=await fetch(`${n}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await r.json().catch(()=>({}));if(r.status===404)throw new Error(`the gateway at ${n} predates pairing (0.9.0) — update and restart it`);if(!r.ok)throw new Error(c.error||`HTTP ${r.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${n}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(e==="local"){const{localStatus:t,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await t()))}else if(e==="connect"){const{connectAgents:t,formatConnect:a}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:a}=await import("../src/server.js"),{installService:i,uninstallService:o,serviceStatus:p,stopService:n}=await import("../src/service.js");switch(e){case"--stop":n(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(a);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":o(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(p()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${e}
4
4
  Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.17.0",
3
+ "version": "0.19.2",
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,9 +22,9 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
- "@chatpanel/bridge": "^0.14.0",
25
+ "@chatpanel/bridge": "^0.17.1",
26
26
  "@chatpanel/events": "^0.117.0",
27
- "@chatpanel/pii": "^0.10.0",
27
+ "@chatpanel/pii": "^0.10.2",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
30
30
  "fflate": "^0.8.3",
@@ -1,3 +1,3 @@
1
- import"node:path";import{existsSync as Y}from"node:fs";import{spawn as q,spawnSync as z}from"node:child_process";import{resolveLaunch as J,standaloneCandidates as I,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as M}from"./bridge.js";const O=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,G=[1e3,2e3,5e3,1e4,3e4],X=6e4,Z=1200;function W(){if(process.env.CHATPANEL_SRT_MODULE)return{};try{return{CHATPANEL_SRT_MODULE:import.meta.resolve("@anthropic-ai/sandbox-runtime")}}catch{return{}}}function H(d,i){const n=String(d||"").split(".").map(t=>parseInt(t,10)),o=String(i||"").split(".").map(t=>parseInt(t,10));if(n.some(Number.isNaN)||o.some(Number.isNaN)||n.length<3||o.length<3)return 0;for(let t=0;t<3;t+=1)if(n[t]!==o[t])return n[t]>o[t]?1:-1;return 0}function U({managed:d=!0,cfgUrl:i="",healthy:n=null,standalone:o=null,embeddedVersion:t=null}={}){if(d===!1||d==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const p=String(i||M);if(!O.test(p))return{action:"off",why:`bridge.url ${p} is not on this machine; nothing to start here`};if(n)return!n.managedBy&&t&&n.version&&H(n.version,t)<0?{action:"replace",why:`a standalone bridge (v${n.version}, run by nobody) answers at ${p} and is older than the embedded one (v${t}) — retiring it`}:{action:"adopt",why:`a bridge already answers at ${p}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const u=o?.version||null;return o?.path&&t&&H(u,t)>0?{action:"spawn-standalone",why:`the installed bridge (v${u}) is newer than the embedded one (v${t})`,path:o.path}:t?{action:"spawn-embedded",why:`starting the embedded bridge (v${t})${o?.path?` — the installed one is v${u||"?"}`:""}`}:o?.path?{action:"spawn-standalone",why:`starting the installed bridge${u?` (v${u})`:""}`,path:o.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function V(d,{timeoutMs:i=Z,fetchImpl:n=fetch}={}){const o=new AbortController,t=setTimeout(()=>o.abort(),i);try{const p=await n(`${String(d).replace(/\/$/,"")}/health`,{signal:o.signal});if(!p.ok)return null;const u=await p.json().catch(()=>null);return u&&u.ok!==!1?{version:u.version||null,managedBy:u.managedBy||null}:null}catch{return null}finally{clearTimeout(t)}}function tt(d,i=[],{timeoutMs:n=8e3}={}){try{const o=z(d,[...i,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),t=String(o.stdout||"").trim().split(`
2
- `).pop();return/^\d+\.\d+\.\d+/.test(t)?t:null}catch{return null}}function et(){const{program:d,args:i}=J();return{program:d,args:[...i,"--bridge"]}}const nt=d=>O.exec(String(d||M))?.[3]||"4319";async function ct(d,{log:i=a=>console.log(a),probe:n=V,spawnImpl:o=q,version:t=tt,candidates:p=I(),exists:u=Y,launch:j=et,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:d?.bridge?.managed,waitForSiblingMs:R=2500,retire:F=Q,retireWaitMs:K=6e3,now:w=Date.now,setTimer:D=setTimeout,setWatch:S=(a,e)=>{const h=setTimeout(a,e);return h.unref?.(),h},watchEveryMs:L=1e4}={}){const a=String(d?.bridge?.url||M).replace(/\/$/,""),e={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(r,c,s={})=>{Object.assign(e,{mode:r,why:c},s),i(` bridge : ${c}`)};let v=await n(a);if(!v&&b!==!1&&b!=="off"&&O.test(a)&&R>0){const r=w()+R;for(;!v&&w()<r;)await new Promise(c=>D(c,500)),v=await n(a)}const E=j(),y=!(b!==!1&&b!=="off")||v&&v.managedBy?null:t(E.program,E.args),N=p.find(r=>u(r))||null,x=N&&!v?{path:N,version:t(N,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:x,embeddedVersion:y});if(f.action==="off")return h("off",f.why),A();const P=r=>r.action==="spawn-embedded"?{...E,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||y}:{program:r.path,args:[],env:{},mode:"standalone",version:x?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:P(f),k=0,$=null,_=0;const C=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const B=await n(a);if(B){_=0,e.version=B.version||e.version,$=S(s,L);return}if(_+=1,_<2){$=S(s,Math.min(L,3e3));return}if(!l){const g=y||t(E.program,E.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:x,embeddedVersion:g});if(m.action==="off"){h("off",`the adopted bridge went away and ${m.why}`);return}l=P({...m,version:g})}i(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),T()};$=S(s,L)},T=()=>{if(e.stopping)return;const r=o(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:nt(a),...W()}});k=w(),e.child=r,e.pid=r.pid||null;const c=(s,B)=>s?.on("data",g=>{for(const m of String(g).split(`
3
- `))m.trim()&&i(`[bridge] ${m}`)});c(r.stdout,"out"),c(r.stderr,"err"),r.on("error",s=>i(`[bridge] could not start ${l.program}: ${s?.message||s}`)),r.on("exit",async(s,B)=>{if(e.child=null,e.pid=null,e.stopping)return;const g=await n(a);if(g){C(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-k>X&&(e.backoff=0);const m=G[Math.min(e.backoff,G.length-1)];e.backoff+=1,e.restarts+=1,i(`[bridge] exited (${B||s}); restarting in ${m/1e3}s`),D(T,m)})};if(f.action==="adopt")return C(f.why,v.version),A();if(f.action==="replace"){i(` bridge : ${f.why}`);try{F({paths:p})}catch(s){i(` bridge : could not retire the standalone bridge: ${s?.message||s}`)}const r=w()+K;let c=await n(a);for(;c&&w()<r;)await new Promise(s=>D(s,500)),c=await n(a);return c?(C(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=P({action:"spawn-embedded",version:y}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${y})`,{version:y}),T(),A())}return h(l.mode,f.why,{version:l.version}),T(),A();function A(){return{status:()=>({mode:e.mode,version:e.version,pid:e.pid,restarts:e.restarts,why:e.why}),stop:()=>{if(e.stopping=!0,$&&(clearTimeout($),$=null),e.child&&!e.child.killed)try{e.child.kill("SIGTERM")}catch{}}}}}export{H as compareVersions,et as embeddedLaunch,ct as ensureBridge,U as planBridge,V as probeBridge,W as srtModuleEnv,I as standaloneCandidates,tt as versionOf};
1
+ import"node:path";import{existsSync as Y}from"node:fs";import{spawn as q,spawnSync as z}from"node:child_process";import{resolveLaunch as J,standaloneCandidates as I,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as C}from"./bridge.js";import{srtModuleUrl as Z}from"./worker-sandbox.js";const O=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,G=[1e3,2e3,5e3,1e4,3e4],W=6e4,V=1200;function tt(){if(process.env.CHATPANEL_SRT_MODULE)return{};const o=Z();return o?{CHATPANEL_SRT_MODULE:o}:{}}function H(o,i){const n=String(o||"").split(".").map(e=>parseInt(e,10)),s=String(i||"").split(".").map(e=>parseInt(e,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let e=0;e<3;e+=1)if(n[e]!==s[e])return n[e]>s[e]?1:-1;return 0}function U({managed:o=!0,cfgUrl:i="",healthy:n=null,standalone:s=null,embeddedVersion:e=null}={}){if(o===!1||o==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const p=String(i||C);if(!O.test(p))return{action:"off",why:`bridge.url ${p} is not on this machine; nothing to start here`};if(n)return!n.managedBy&&e&&n.version&&H(n.version,e)<0?{action:"replace",why:`a standalone bridge (v${n.version}, run by nobody) answers at ${p} and is older than the embedded one (v${e}) — retiring it`}:{action:"adopt",why:`a bridge already answers at ${p}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const u=s?.version||null;return s?.path&&e&&H(u,e)>0?{action:"spawn-standalone",why:`the installed bridge (v${u}) is newer than the embedded one (v${e})`,path:s.path}:e?{action:"spawn-embedded",why:`starting the embedded bridge (v${e})${s?.path?` — the installed one is v${u||"?"}`:""}`}:s?.path?{action:"spawn-standalone",why:`starting the installed bridge${u?` (v${u})`:""}`,path:s.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function et(o,{timeoutMs:i=V,fetchImpl:n=fetch}={}){const s=new AbortController,e=setTimeout(()=>s.abort(),i);try{const p=await n(`${String(o).replace(/\/$/,"")}/health`,{signal:s.signal});if(!p.ok)return null;const u=await p.json().catch(()=>null);return u&&u.ok!==!1?{version:u.version||null,managedBy:u.managedBy||null}:null}catch{return null}finally{clearTimeout(e)}}function nt(o,i=[],{timeoutMs:n=8e3}={}){try{const s=z(o,[...i,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),e=String(s.stdout||"").trim().split(`
2
+ `).pop();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function rt(){const{program:o,args:i}=J();return{program:o,args:[...i,"--bridge"]}}const it=o=>O.exec(String(o||C))?.[3]||"4319";async function ft(o,{log:i=a=>console.log(a),probe:n=et,spawnImpl:s=q,version:e=nt,candidates:p=I(),exists:u=Y,launch:j=rt,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:o?.bridge?.managed,waitForSiblingMs:R=2500,retire:F=Q,retireWaitMs:K=6e3,childEnv:X=()=>({}),now:w=Date.now,setTimer:S=setTimeout,setWatch:D=(a,t)=>{const h=setTimeout(a,t);return h.unref?.(),h},watchEveryMs:N=1e4}={}){const a=String(o?.bridge?.url||C).replace(/\/$/,""),t={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(r,c,d={})=>{Object.assign(t,{mode:r,why:c},d),i(` bridge : ${c}`)};let v=await n(a);if(!v&&b!==!1&&b!=="off"&&O.test(a)&&R>0){const r=w()+R;for(;!v&&w()<r;)await new Promise(c=>S(c,500)),v=await n(a)}const E=j(),$=!(b!==!1&&b!=="off")||v&&v.managedBy?null:e(E.program,E.args),L=p.find(r=>u(r))||null,P=L&&!v?{path:L,version:e(L,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:P,embeddedVersion:$});if(f.action==="off")return h("off",f.why),A();const M=r=>r.action==="spawn-embedded"?{...E,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||$}:{program:r.path,args:[],env:{},mode:"standalone",version:P?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:M(f),k=0,y=null,_=0;const x=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const d=async()=>{if(t.stopping||t.mode!=="adopted")return;const B=await n(a);if(B){_=0,t.version=B.version||t.version,y=D(d,N);return}if(_+=1,_<2){y=D(d,Math.min(N,3e3));return}if(!l){const g=$||e(E.program,E.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:P,embeddedVersion:g});if(m.action==="off"){h("off",`the adopted bridge went away and ${m.why}`);return}l=M({...m,version:g})}i(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),T()};y=D(d,N)},T=()=>{if(t.stopping)return;const r=s(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...X(),...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:it(a),...tt()}});k=w(),t.child=r,t.pid=r.pid||null;const c=(d,B)=>d?.on("data",g=>{for(const m of String(g).split(`
3
+ `))m.trim()&&i(`[bridge] ${m}`)});c(r.stdout,"out"),c(r.stderr,"err"),r.on("error",d=>i(`[bridge] could not start ${l.program}: ${d?.message||d}`)),r.on("exit",async(d,B)=>{if(t.child=null,t.pid=null,t.stopping)return;const g=await n(a);if(g){x(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-k>W&&(t.backoff=0);const m=G[Math.min(t.backoff,G.length-1)];t.backoff+=1,t.restarts+=1,i(`[bridge] exited (${B||d}); restarting in ${m/1e3}s`),S(T,m)})};if(f.action==="adopt")return x(f.why,v.version),A();if(f.action==="replace"){i(` bridge : ${f.why}`);try{F({paths:p})}catch(d){i(` bridge : could not retire the standalone bridge: ${d?.message||d}`)}const r=w()+K;let c=await n(a);for(;c&&w()<r;)await new Promise(d=>S(d,500)),c=await n(a);return c?(x(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=M({action:"spawn-embedded",version:$}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${$})`,{version:$}),T(),A())}return h(l.mode,f.why,{version:l.version}),T(),A();function A(){return{status:()=>({mode:t.mode,version:t.version,pid:t.pid,restarts:t.restarts,why:t.why}),stop:()=>{if(t.stopping=!0,y&&(clearTimeout(y),y=null),t.child&&!t.child.killed)try{t.child.kill("SIGTERM")}catch{}},restart:(r="settings changed")=>{if(!t.child||t.stopping)return t.mode==="adopted"&&i(`[bridge] ${r} — the bridge on ${a} is not ours (${t.why}); set CHATPANEL_SANDBOX* in its own service`),!1;i(`[bridge] restarting: ${r}`),t.backoff=0;try{t.child.kill("SIGTERM")}catch{}return!0}}}}export{H as compareVersions,rt as embeddedLaunch,ft as ensureBridge,U as planBridge,et as probeBridge,tt as srtModuleEnv,I as standaloneCandidates,nt as versionOf};
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as s,existsSync as l}from"node:fs";import{join as p}from"node:path";import d 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}},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:[],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}},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||p(d.homedir(),".chatpanel","gateway.config.json");if(l(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 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:[],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}},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 d,mkdirSync as u,chmodSync as y}from"node:fs";import{join as m,dirname as p}from"node:path";import b from"node:os";import{usage as w}from"./freegate.js";import{assertEndpointUrl as n}from"@chatpanel/pii";function a(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||m(b.homedir(),".chatpanel","gateway.config.json")}function f(e,r=a()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===a({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);u(p(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,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools};d(r,JSON.stringify(o,null,2),{mode:384});try{y(r,384)}catch{}}function E(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:t,...i}=o;return{...i,hasKey:!!t}}),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,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,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}},allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:w(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 N(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function k(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const t=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),i=Number(o.port)||(o.protocol==="https:"?443:80);return t&&i===(Number(r.port)||4320)}const l=["default","acceptEdits","bypassPermissions"];function g(e,r={}){const o=e?.bridge||{};return{...l.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function S(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(t=>[t.id,t]));e.destinations=r.destinations.filter(t=>t&&typeof t.id=="string"&&(t.type==="agent"||t.type==="api")).filter(t=>{const i=k(t,e);return i&&console.log(`[gateway] refusing destination "${t.id}": ${t.baseUrl} is this gateway — a loop`),!i}).map(t=>{const i={id:t.id,type:t.type,models:Array.isArray(t.models)?t.models.filter(s=>typeof s=="string"&&s):[]};if(t.type==="agent"&&(i.agent=t.agent||t.id),t.type==="api"){i.baseUrl=String(t.baseUrl||""),i.protocol=t.protocol==="anthropic"?"anthropic":"openai";const s=typeof t.apiKey=="string"&&t.apiKey?t.apiKey:o.get(t.id)?.apiKey;s&&(i.apiKey=s)}return i})}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),l.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 t=r.upstreams[o];t&&typeof t.baseUrl=="string"&&t.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:t.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.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&&n(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 t=String(o.url||"").trim();t&&n(t),e.search.searxng.url=t}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(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{l as PERMISSION_MODES,S as applyConfigPatch,N as applyNerModelSelection,g as bridgeAgentOptions,a as configPath,k as isSelfDestination,f as persistConfig,E as publicConfig};
1
+ import{writeFileSync as m,mkdirSync as y,chmodSync as b}from"node:fs";import{join as p,dirname as w}from"node:path";import A from"node:os";import{usage as x}from"./freegate.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as k}from"@chatpanel/bridge/src/events/sandbox-policy.js";const D=["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 s(e={}){const r=e&&typeof e=="object"?e:{},o=D.includes(r.mode)?r.mode:"open",{hosts:t}=k({hosts:r.hosts??[]});return{mode:o,hosts:t,write:l(r.write),denyRead:l(r.denyRead)}}function _(e){const r=s(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 d(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json")}function g(e,r=d()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===d({}))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,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox};m(r,JSON.stringify(o,null,2),{mode:384});try{b(r,384)}catch{}}function j(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:t,...i}=o;return{...i,hasKey:!!t}}),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,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:s(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}},allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:x(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 R(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function N(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const t=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),i=Number(o.port)||(o.protocol==="https:"?443:80);return t&&i===(Number(r.port)||4320)}const u=["default","acceptEdits","bypassPermissions"];function L(e,r={}){const o=e?.bridge||{};return{...u.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function P(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(t=>[t.id,t]));e.destinations=r.destinations.filter(t=>t&&typeof t.id=="string"&&(t.type==="agent"||t.type==="api")).filter(t=>{const i=N(t,e);return i&&console.log(`[gateway] refusing destination "${t.id}": ${t.baseUrl} is this gateway — a loop`),!i}).map(t=>{const i={id:t.id,type:t.type,models:Array.isArray(t.models)?t.models.filter(n=>typeof n=="string"&&n):[]};if(t.type==="agent"&&(i.agent=t.agent||t.id),t.type==="api"){i.baseUrl=String(t.baseUrl||""),i.protocol=t.protocol==="anthropic"?"anthropic":"openai";const n=typeof t.apiKey=="string"&&t.apiKey?t.apiKey:o.get(t.id)?.apiKey;n&&(i.apiKey=n)}return i})}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),u.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 t=r.upstreams[o];t&&typeof t.baseUrl=="string"&&t.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:t.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=s({...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 t=String(o.url||"").trim();t&&a(t),e.search.searxng.url=t}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(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{u as PERMISSION_MODES,P as applyConfigPatch,R as applyNerModelSelection,L as bridgeAgentOptions,d as configPath,N as isSelfDestination,s as normalizeSandboxConfig,g as persistConfig,j as publicConfig,_ as sandboxEnvFor};
package/src/runtime.js ADDED
@@ -0,0 +1,3 @@
1
+ import{promisify as T}from"node:util";import{execFile as B}from"node:child_process";import{mkdirSync as C,writeFileSync as L}from"node:fs";import{randomBytes as X}from"node:crypto";import D from"node:os";import A from"node:path";const O=T(B),S=["podman","docker"],u={id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only."};function W(a=[]){return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...(a.length?a:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(f=>[` - name: ${f}`," disabled: false"])," - name: google"," disabled: true",""].join(`
2
+ `)}function x(a=process.platform){return a==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:a==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function v(a,p){const f=p==="podman"?Array.isArray(a.Names)?a.Names[0]:String(a.Names||""):String(a.Names||a.Name||""),g=p==="podman"?Array.isArray(a.Ports)?a.Ports.map(i=>`${i.host_ip||""}:${i.host_port}->${i.container_port}/${i.protocol||"tcp"}`):[]:String(a.Ports||"").split(",").map(i=>i.trim()).filter(Boolean),y=String(a.State||"").toLowerCase()||(/^up/i.test(String(a.Status||""))?"running":"exited");return{name:f,image:String(a.Image||""),state:y,status:String(a.Status||""),ports:g,ours:f.startsWith("chatpanel-"),engine:p}}function U({cfg:a,bridgeHealth:p,workers:f=()=>[],persist:g=()=>{},exec:y=(s,l,h={})=>O(s,l,{timeout:6e4,...h}),platform:i=process.platform,fetchImpl:N=globalThis.fetch,stateDir:b=A.join(D.homedir(),".chatpanel","runtime"),log:E=()=>{}}={}){const s=async(t,e,n)=>{try{const r=await y(t,e,n);return{ok:!0,out:String(r.stdout||"").trim(),err:String(r.stderr||"").trim()}}catch(r){return{ok:!1,out:String(r?.stdout||"").trim(),err:String(r?.stderr||r?.message||r).trim(),code:r?.code}}};async function l(){const t={};for(const n of S){const r=await s(n,["--version"],{timeout:5e3});if(!r.ok){t[n]={installed:!1};continue}const c=(r.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||r.out;let o=!1,d=null;if(n==="podman")if(i==="linux")o=(await s("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const w=await s("podman",["machine","list","--format","json"],{timeout:8e3});try{const m=JSON.parse(w.out||"[]")[0]||null;d=m?{name:m.Name,running:!!m.Running}:null,o=!!m?.Running}catch{d=null}}else o=(await s("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;t[n]={installed:!0,version:c,running:o,...n==="podman"&&i!=="linux"?{machine:d}:{}}}const e=S.find(n=>t[n]?.installed&&t[n].running)||S.find(n=>t[n]?.installed)||null;return{...t,preferred:e,...e?{}:{install:x(i)}}}async function h(t="podman"){if(!S.includes(t))return{ok:!1,error:`unknown engine ${t}`};const e=(await l())[t];if(!e?.installed)return{ok:!1,error:`${t} is not installed`,install:x(i)};if(e.running)return{ok:!0,already:!0};if(t==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(i!=="linux"){if(!e.machine){const r=await s("podman",["machine","init"],{timeout:6e5});if(!r.ok)return{ok:!1,error:`podman machine init: ${r.err||r.out}`}}const n=await s("podman",["machine","start"],{timeout:3e5});if(!n.ok&&!/already running/i.test(n.err))return{ok:!1,error:`podman machine start: ${n.err||n.out}`}}return{ok:!0}}async function R(){const t=await l(),e=t.preferred;if(!e||!t[e].running)return[];if(e==="podman"){const r=await s("podman",["ps","-a","--format","json"],{timeout:1e4});if(!r.ok)return[];try{return JSON.parse(r.out||"[]").map(c=>v(c,"podman"))}catch{return[]}}const n=await s("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return n.ok?n.out.split(`
3
+ `).filter(Boolean).map(r=>{try{return v(JSON.parse(r),"docker")}catch{return null}}).filter(Boolean):[]}async function $(t,e){const n=await s(t,["inspect","--format","{{.State.Status}}",e],{timeout:8e3});return n.ok?/running/i.test(n.out)?"running":"stopped":"absent"}async function _(t){try{return(await N(`${t}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}}async function P(){const t=await l(),e=t.preferred,n=`http://127.0.0.1:${u.port}`;let r="no-engine";e&&t[e].running?r=await $(e,u.container):e&&(r="engine-stopped");const c=String(a.search?.searxng?.url||"");return{searxng:{...u,engine:e,state:r,url:n,configured:c,answering:r==="running"?await _(n):!1}}}async function j(){const t=await l(),e=t.preferred;if(!e)return{ok:!1,error:"no container engine — install Podman first",install:x(i)};if(!t[e].running){const o=await h(e);if(!o.ok)return o}const n=await $(e,u.container);if(n!=="running")if(n==="stopped"){const o=await s(e,["start",u.container],{timeout:6e4});if(!o.ok)return{ok:!1,error:`${e} start: ${o.err||o.out}`}}else{C(b,{recursive:!0,mode:448});const o=A.join(b,"searxng-settings.yml");L(o,W(String(a.search?.searxng?.engines||"").split(",").map(m=>m.trim()).filter(Boolean)),{mode:384});const d=X(32).toString("hex"),w=["run","-d","--name",u.container,"--restart","unless-stopped","-p",`127.0.0.1:${u.port}:8080`,"-v",`${o}:/etc/searxng/settings.yml:ro`,"-e",`SEARXNG_SECRET=${d}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${u.port}/`,"--cap-drop","ALL","--cap-add","CHOWN","--cap-add","SETGID","--cap-add","SETUID",u.image];E(`[runtime] ${e} ${w.filter(m=>!m.startsWith("SEARXNG_SECRET")).join(" ")}`);const k=await s(e,w,{timeout:6e5});if(!k.ok)return{ok:!1,error:`${e} run: ${k.err||k.out}`}}const r=`http://127.0.0.1:${u.port}`;let c=!1;for(let o=0;o<30&&!c;o++)c=await _(r),c||await new Promise(d=>setTimeout(d,1e3));return a.search=a.search||{},a.search.searxng={...a.search.searxng||{},url:r},g(),{ok:!0,url:r,answering:c}}async function G(){const t=await l(),e=t.preferred;if(e&&t[e].running){const n=await s(e,["stop",u.container],{timeout:6e4});if(!n.ok&&!/no such container/i.test(n.err))return{ok:!1,error:`${e} stop: ${n.err||n.out}`}}return a.search?.searxng?.url===`http://127.0.0.1:${u.port}`&&(a.search.searxng.url="",g()),{ok:!0}}return{async status(){const[t,e,n,r]=await Promise.all([p().catch(()=>null),l(),P(),R()]);return{sandbox:t?.sandbox||null,processes:{all:[...Array.isArray(t?.processes)?t.processes:[],...f()],localMcp:Array.isArray(t?.localMcp)?t.localMcp:[],warm:t?.warm||null},containers:r,refused:Array.isArray(t?.sandbox?.refused)?t.sandbox.refused:[],bridge:t?{ok:!0,version:t.version||""}:{ok:!1},engines:e,services:n}},startEngine:h,startService:t=>t==="searxng"?j():Promise.resolve({ok:!1,error:`unknown service ${t}`}),stopService:t=>t==="searxng"?G():Promise.resolve({ok:!1,error:`unknown service ${t}`})}}export{v as containerRow,U as createRuntime,x as installDoor,W as searxngSettings};
package/src/server.js CHANGED
@@ -1,30 +1,30 @@
1
- import{createServer as Et}from"node:http";import{loadConfig as Ve}from"./config.js";import{startEntitlementRefresh as At,maybeRevalidate as Nt}from"./entitlement-refresh.js";import{redactSegments as ge,segment as xe}from"./redact.js";import{pipeRestoredStream as Bt,pipeRestoredOpenAIStream as Dt,makeTokenRestorer as Ue,restoreDeep as Ct}from"./stream.js";import{restoreText as Mt,gatedDictionary as It,narrowSpecs as jt,makeToolHarness as Rt,placeholderToolNote as Lt,placeholderNote as zt,assertEndpointUrl as Gt,capRunOptions as Jt,isPaired as Vt}from"@chatpanel/pii";import{ensureGatewayToken as $e,currentGatewayToken as Ut,isAdminAuthorized as Z,callerTrustOf as be,setPinnedExtensionIds as Ht,issuePairingCode as Ft,claimPairingCode as Wt}from"./gateway-token.js";import{installEgressLedger as Kt,egressAudit as Zt}from"./egress.js";import{initPolicy as Yt,activePolicy as Qt,applyPolicyToConfig as He,managedSummary as pe,PolicyLoadError as Xt}from"./policy.js";import{routeAllowed as Fe,agentAllowed as qt,egressAllowed as eo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ce}from"./bridge.js";import{secureFetch as We}from"./secure-fetch.js";import{streamBridgeChat as Ke,readBridgeToken as ae,openBridgeChat as to}from"./bridge.js";import{createRelaySession as oo,getRelaySession as Ze,endRelaySession as we,pumpBridgeStream as ro,deliverToolResult as no,toolsToSpecs as so,parseToolCallId as Ye,touchRelaySession as Pe}from"./toolrelay.js";import{shaperFor as Ee}from"./shape.js";import{startNer as ao,ensureNer as ke,unionForThisMachine as io,skippedCompanions as lo}from"./ner.js";import{recommendDetector as Qe}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as co}from"./log.js";import{saveBackupSecret as uo,clearBackupSecret as mo,loadBackupSecret as Ae,hasBackupSecret as Xe}from"./history-store.js";import{createMemoryStore as po}from"./memory-store.js";import{createPrefsStore as ho}from"./prefs-store.js";import{createTeamStore as yo,loadOrCreateKey as Ne}from"./team-store.js";import{createScorecardStore as fo}from"./scorecard-store.js";import{createEngineLedgerStore as go}from"./engine-ledger-store.js";import{createProjectStore as bo}from"./project-store.js";import{applicationsFor as wo,recruitPass as ko}from"./recruiting.js";import{ensureBridge as So}from"./bridge-supervisor.js";import{checkForUpdate as vo,updateStatus as To,startUpdate as _o,updateJob as Oo}from"./update.js";import{createHistoryStore as xo}from"./sqlite-store.js";import{ingestBackups as Be}from"./backup-ingest.js";import{toSearchRecord as $o}from"@chatpanel/events/library.js";import{deriveBackupKey as Po,openRecord as Eo,keyCache as Ao,nodeCodec as No}from"@chatpanel/events/backup-envelope.js";import Bo from"node:zlib";import*as P from"./ner-engine.js";import qe from"node:os";import{capabilitiesDocument as Do,handleDetect as Co}from"./capabilities.js";import{createExtractService as Mo}from"./extract/service.js";import{handleExtract as Io}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as jo}from"./extract-capability.js";import{createReader as Ro}from"./retrieval/read.js";import{createSearcher as Lo,toJinaSearch as zo,SEARCH_DEFAULTS as Go}from"./retrieval/search.js";import{createSearxng as Jo}from"./retrieval/search-searxng.js";import{toJinaText as Vo}from"./read-document.js";import*as D from"./stt-engine.js";import*as I from"./diarize-engine.js";import{MODEL_CATALOG as et,isKnownModel as tt,isValidCustomModelId as ot,recommendFor as Uo}from"./models.js";import{STT_MODEL_CATALOG as Ho,isKnownSttModel as Fo,isValidCustomSttId as Wo,DEFAULT_STT_MODEL as De,STT_DTYPES as Ko,isValidDtype as Zo}from"./stt-models.js";import*as O from"./tts-engine.js";import{TTS_MODEL_CATALOG as rt,TTS_VOICES as Yo,isKnownTtsModel as Qo,isValidCustomTtsId as Xo,isKnownVoice as nt,isValidVoiceId as st,DEFAULT_TTS_MODEL as at,DEFAULT_TTS_VOICE as re,TTS_DTYPES as qo,isValidTtsDtype as er,MAX_TTS_CHARS as it,ttsModelHasCustomVoices as tr,resolveDefaultModel as lt,POCKET_VOICES as or,DEFAULT_POCKET_VOICE as Se,isPocketVoice as ve,ttsModelEngine as Te}from"./tts-models.js";import{ttsDestination as rr,synthesizeRemote as nr,isValidRemoteVoice as sr}from"./tts-remote.js";import{rawOrtAvailable as Ce}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as ar}from"./tts-voice-resolve.js";import{resolvePro as ie,checkQuota as ir,consume as lr,usage as cr}from"./freegate.js";import{publicConfig as ct,applyConfigPatch as dr,applyNerModelSelection as dt,persistConfig as le,configPath as ne,bridgeAgentOptions as ut,PERMISSION_MODES as ur}from"./configstore.js";import{resolveDestination as mt,aggregateModelsAsync as mr,listDestinations as pr}from"./router.js";import{makeAccessEvent as pt}from"./observability.js";import{createPersistentAccessLog as hr}from"./access-log-store.js";import{planQueries as yr,multiSearch as fr}from"./rrf.js";import*as Me from"./openai.js";import*as ht from"./responses.js";import*as Ie from"./anthropic.js";const Y="0.17.0",N=await xo(),te=new Set;function _e({ids:t=[]}={}){const l=N.lossless;if(!l||!te.size)return;const d=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of te)try{m.write(`event: records
2
- data: ${d}
1
+ import{createServer as Bt}from"node:http";import{loadConfig as Fe}from"./config.js";import{startEntitlementRefresh as Dt,maybeRevalidate as Ct}from"./entitlement-refresh.js";import{redactSegments as we,segment as $e}from"./redact.js";import{pipeRestoredStream as Mt,pipeRestoredOpenAIStream as jt,makeTokenRestorer as We,restoreDeep as It}from"./stream.js";import{restoreText as Rt,gatedDictionary as Lt,narrowSpecs as zt,makeToolHarness as Gt,placeholderToolNote as Jt,placeholderNote as Vt,assertEndpointUrl as Ut,capRunOptions as Ht,isPaired as Ft}from"@chatpanel/pii";import{ensureGatewayToken as Ae,currentGatewayToken as Wt,isAdminAuthorized as W,callerTrustOf as ke,setPinnedExtensionIds as Kt,issuePairingCode as Zt,claimPairingCode as Yt}from"./gateway-token.js";import{installEgressLedger as Qt,egressAudit as Xt}from"./egress.js";import{initPolicy as qt,activePolicy as eo,applyPolicyToConfig as Ke,managedSummary as he,PolicyLoadError as to}from"./policy.js";import{routeAllowed as Ze,agentAllowed as oo,egressAllowed as ro}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Ye}from"./secure-fetch.js";import{streamBridgeChat as Qe,readBridgeToken as ae,openBridgeChat as no}from"./bridge.js";import{createRelaySession as so,getRelaySession as Xe,endRelaySession as Se,pumpBridgeStream as ao,deliverToolResult as io,toolsToSpecs as lo,parseToolCallId as qe,touchRelaySession as Ee}from"./toolrelay.js";import{shaperFor as Pe}from"./shape.js";import{startNer as co,ensureNer as ve,unionForThisMachine as uo,skippedCompanions as mo}from"./ner.js";import{recommendDetector as et}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as po}from"./log.js";import{saveBackupSecret as ho,clearBackupSecret as yo,loadBackupSecret as Ne,hasBackupSecret as tt}from"./history-store.js";import{createMemoryStore as fo}from"./memory-store.js";import{createPrefsStore as go}from"./prefs-store.js";import{createTeamStore as bo,loadOrCreateKey as Be}from"./team-store.js";import{createScorecardStore as wo}from"./scorecard-store.js";import{createEngineLedgerStore as ko}from"./engine-ledger-store.js";import{createProjectStore as So}from"./project-store.js";import{applicationsFor as vo,recruitPass as To}from"./recruiting.js";import{ensureBridge as xo}from"./bridge-supervisor.js";import{checkForUpdate as Oo,updateStatus as _o,startUpdate as $o,updateJob as Ao}from"./update.js";import{createHistoryStore as Eo}from"./sqlite-store.js";import{ingestBackups as De}from"./backup-ingest.js";import{toSearchRecord as Po}from"@chatpanel/events/library.js";import{deriveBackupKey as No,openRecord as Bo,keyCache as Do,nodeCodec as Co}from"@chatpanel/events/backup-envelope.js";import Mo from"node:zlib";import*as A from"./ner-engine.js";import ot from"node:os";import{capabilitiesDocument as jo,handleDetect as Io}from"./capabilities.js";import{createExtractService as Ro}from"./extract/service.js";import{workerSandbox as Lo,disposeWorkerSandbox as zo}from"./worker-sandbox.js";import{createRuntime as Go}from"./runtime.js";import{handleExtract as Jo}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Vo}from"./extract-capability.js";import{createReader as Uo}from"./retrieval/read.js";import{createSearcher as Ho,toJinaSearch as Fo,SEARCH_DEFAULTS as Wo}from"./retrieval/search.js";import{createSearxng as Ko}from"./retrieval/search-searxng.js";import{toJinaText as Zo}from"./read-document.js";import*as M from"./stt-engine.js";import*as R from"./diarize-engine.js";import{MODEL_CATALOG as rt,isKnownModel as nt,isValidCustomModelId as st,recommendFor as Yo}from"./models.js";import{STT_MODEL_CATALOG as Qo,isKnownSttModel as Xo,isValidCustomSttId as qo,DEFAULT_STT_MODEL as Ce,STT_DTYPES as er,isValidDtype as tr}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as at,TTS_VOICES as or,isKnownTtsModel as rr,isValidCustomTtsId as nr,isKnownVoice as it,isValidVoiceId as lt,DEFAULT_TTS_MODEL as ct,DEFAULT_TTS_VOICE as ie,TTS_DTYPES as sr,isValidTtsDtype as ar,MAX_TTS_CHARS as dt,ttsModelHasCustomVoices as ir,resolveDefaultModel as ut,POCKET_VOICES as lr,DEFAULT_POCKET_VOICE as Te,isPocketVoice as xe,ttsModelEngine as Oe}from"./tts-models.js";import{ttsDestination as cr,synthesizeRemote as dr,isValidRemoteVoice as ur}from"./tts-remote.js";import{rawOrtAvailable as Me}from"./ort.js";import*as J from"./tts-voices.js";import{resolveTtsVoice as mr}from"./tts-voice-resolve.js";import{resolvePro as ue,checkQuota as pr,consume as hr,usage as yr}from"./freegate.js";import{publicConfig as mt,applyConfigPatch as fr,applyNerModelSelection as pt,persistConfig as le,configPath as re,bridgeAgentOptions as ht,PERMISSION_MODES as gr,sandboxEnvFor as br}from"./configstore.js";import{resolveDestination as yt,aggregateModelsAsync as wr,listDestinations as kr}from"./router.js";import{makeAccessEvent as ft}from"./observability.js";import{createPersistentAccessLog as Sr}from"./access-log-store.js";import{planQueries as vr,multiSearch as Tr}from"./rrf.js";import*as je from"./openai.js";import*as gt from"./responses.js";import*as Ie from"./anthropic.js";const K="0.19.2",N=await Eo(),ne=new Set;function _e({ids:t=[]}={}){const l=N.lossless;if(!l||!ne.size)return;const c=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of ne)try{m.write(`event: records
2
+ data: ${c}
3
3
 
4
- `)}catch{te.delete(m)}}setInterval(()=>{for(const t of te)try{t.write(`: ping
4
+ `)}catch{ne.delete(m)}}setInterval(()=>{for(const t of ne)try{t.write(`: ping
5
5
 
6
- `)}catch{te.delete(t)}},25e3).unref?.();const Q=await po(),X=ho(),de=fo({key:Ne()}),ue=go({key:Ne()}),J=bo({key:Ne()}),R=yo({scorecards:de,engines:ue}),je=new Set,yt=(t,l)=>{for(const m of je)try{m({applied:t,by:l,revision:X.revision})}catch{}const d=JSON.stringify({revision:X.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const m of te)try{m.write(`event: prefs
7
- data: ${d}
6
+ `)}catch{ne.delete(t)}},25e3).unref?.();const Z=await fo(),Y=go(),me=wo({key:Be()}),pe=ko({key:Be()}),V=So({key:Be()}),L=bo({scorecards:me,engines:pe}),Re=new Set,bt=(t,l)=>{for(const m of Re)try{m({applied:t,by:l,revision:Y.revision})}catch{}const c=JSON.stringify({revision:Y.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const m of ne)try{m.write(`event: prefs
7
+ data: ${c}
8
8
 
9
- `)}catch{te.delete(m)}},Re=hr(),ft=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),gr=16,br=/^mcp[_-]/i,gt=t=>t&&t.function&&t.function.name||t&&t.name||"",wr=t=>t&&t.function&&t.function.description||t&&t.description||"";function bt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function kr(t,l){if(!t)return"";if(l==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(p=>bt(p&&(p.content??p))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let m=d.length-1;m>=0;m--)if(d[m]&&d[m].role==="user")return bt(d[m].content);return""}const wt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function kt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Sr(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function vr(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const St=Date.now();function Tr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function _r(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Or(t){const l=performance.now(),d={};let m=!1;const p=(b,x)=>{d[b]=Math.round(x*10)/10};return{meta:{},timings:d,mark:p,lap(b,x){p(b,performance.now()-x)},clock(){return performance.now()},commit(){if(m)return;m=!0,p("total",performance.now()-l);const b={...this.meta,timings:d};setImmediate(()=>{t(b),console.log(`[gateway] model=${b.model||"-"} → ${b.dest?`${b.dest}(${b.type})`:"none"} · ${b.redaction==="off"?"redaction OFF (client request)":`redacted ${b.redacted||0}`}${b.sanitized?` · scrubbed ${b.sanitized} hidden`:""}${b.narrowed?` · narrowed -${b.narrowed}`:""} · ${Tr(d)}`)})}}}function vt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const d=[];for(const[m,p]of t.byToken){const b=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),x=b?b[1]:"PII",k=m.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:k,type:x,value:p}:{token:k,type:x})}return d}function xr(t,l,d){return Ie.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Ie,redactable:Ie.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ht.matches(t)?{kind:"responses",adapter:ht,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Me,redactable:Me.matches(t),base:d.upstreams?.openai?.baseUrl}}function Le(t,l){const d=String(t||"");if(ft.has(d))return{agent:d,agentModel:""};const m=d.indexOf("/");if(m>0){const p=d.slice(0,m);if(ft.has(p))return{agent:p,agentModel:d.slice(m+1)}}return{agent:l.bridge.agent,agentModel:""}}function Tt(t,l){return Le(t,l).agent}function $r(t,l){if(l!=="openai"||!t)return!1;const d=Me.extractLatestToolResult(t);if(!d)return!1;const m=Ye(d.tool_call_id);return!!(m&&Ze(m.gwId))}function Pr(t,l){try{const d=new URL(t),m=d.hostname.replace(/^\[|\]$/g,""),p=m==="127.0.0.1"||m==="localhost"||m==="::1",b=d.port||(d.protocol==="https:"?"443":"80");return p&&String(b)===String(l.port)}catch{return!1}}async function _(t,l){const d=[];let m=0;for await(const p of t){if(m+=p.length,l&&m>l){const b=new Error("payload too large");throw b.code=413,b}d.push(p)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function _t(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function ze(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const m=P.health(),p=m.ok&&d==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:P.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:p,tier:d,coverage:p?"names":"patterns"}}async function Ot(t){if(P.state()!=="off"){const d=P.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null,stats:d.stats,companions:d.companions}}const l=_t(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await We(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const m=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:m.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function Er(t,l){const d={};for(const[m,p]of Object.entries(t)){const b=m.toLowerCase();b.startsWith("x-chatpanel-")||wt.has(b)||(d[m]=p)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function xt(t,l,d,m){const p=Ue(l.vault),b=m?m.clock():0;let x=b,k=!0;const T=()=>{m&&k&&(m.lap("upstream",b),x=m.clock(),k=!1)};await ro(l,{onText:n=>{T(),Pe(l.id);const o=p.push(n);o&&t.write(d.sseDelta(o))},onToolRequest:({name:n,restoredArgs:o,toolId:f})=>{T(),Pe(l.id);const c=p.flush();c&&t.write(d.sseDelta(c)),t.write(d.sseToolCalls([{id:f,name:n,arguments:JSON.stringify(o)}])),t.write(d.sseToolFinish()),m&&m.lap("stream",x),t.end(),m?.commit()},onDone:()=>{const n=p.flush();n&&t.write(d.sseDelta(n)),t.write(d.sseTail()),m&&m.lap("stream",x),t.end(),we(l.id),m?.commit()},onError:n=>{t.write(`data: ${JSON.stringify({error:{message:n.message,type:"bridge_error"}})}
9
+ `)}catch{ne.delete(m)}},Le=Sr(),wt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),xr=16,Or=/^mcp[_-]/i,kt=t=>t&&t.function&&t.function.name||t&&t.name||"",_r=t=>t&&t.function&&t.function.description||t&&t.description||"";function St(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function $r(t,l){if(!t)return"";if(l==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(p=>St(p&&(p.content??p))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return St(c[m].content);return""}const vt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Tt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Ar(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function Er(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const xt=Date.now();function Pr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${l[c]||c} ${t[c]}ms`).join(" · ")}function Nr(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Br(t){const l=performance.now(),c={};let m=!1;const p=(y,_)=>{c[y]=Math.round(_*10)/10};return{meta:{},timings:c,mark:p,lap(y,_){p(y,performance.now()-_)},clock(){return performance.now()},commit(){if(m)return;m=!0,p("total",performance.now()-l);const y={...this.meta,timings:c};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${Pr(c)}`)})}}}function Ot(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const c=[];for(const[m,p]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),_=y?y[1]:"PII",k=m.replace(/^\[\[|\]\]$/g,"");c.push(l==="values"?{token:k,type:_,value:p}:{token:k,type:_})}return c}function Dr(t,l,c){return Ie.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Ie,redactable:Ie.matches(t),base:c.upstreams?.anthropic?.baseUrl}:gt.matches(t)?{kind:"responses",adapter:gt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:je,redactable:je.matches(t),base:c.upstreams?.openai?.baseUrl}}function ze(t,l){const c=String(t||"");if(wt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const p=c.slice(0,m);if(wt.has(p))return{agent:p,agentModel:c.slice(m+1)}}return{agent:l.bridge.agent,agentModel:""}}function _t(t,l){return ze(t,l).agent}function Cr(t,l){if(l!=="openai"||!t)return!1;const c=je.extractLatestToolResult(t);if(!c)return!1;const m=qe(c.tool_call_id);return!!(m&&Xe(m.gwId))}function Mr(t,l){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),p=m==="127.0.0.1"||m==="localhost"||m==="::1",y=c.port||(c.protocol==="https:"?"443":"80");return p&&String(y)===String(l.port)}catch{return!1}}async function O(t,l){const c=[];let m=0;for await(const p of t){if(m+=p.length,l&&m>l){const y=new Error("payload too large");throw y.code=413,y}c.push(p)}return Buffer.concat(c)}function s(t,l,c){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function $t(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Ge(t){const l=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),p=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:A.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:p,tier:c,coverage:p?"names":"patterns"}}async function At(t){if(A.state()!=="off"){const c=A.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const l=$t(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Ye(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:l,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:m.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function jr(t,l){const c={};for(const[m,p]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||vt.has(y)||(c[m]=p)}c["accept-encoding"]="identity";try{c.host=new URL(l).host}catch{}return c}async function Et(t,l,c,m){const p=We(l.vault),y=m?m.clock():0;let _=y,k=!0;const T=()=>{m&&k&&(m.lap("upstream",y),_=m.clock(),k=!1)};await ao(l,{onText:j=>{T(),Ee(l.id);const x=p.push(j);x&&t.write(c.sseDelta(x))},onToolRequest:({name:j,restoredArgs:x,toolId:U})=>{T(),Ee(l.id);const n=p.flush();n&&t.write(c.sseDelta(n)),t.write(c.sseToolCalls([{id:U,name:j,arguments:JSON.stringify(x)}])),t.write(c.sseToolFinish()),m&&m.lap("stream",_),t.end(),m?.commit()},onDone:()=>{const j=p.flush();j&&t.write(c.sseDelta(j)),t.write(c.sseTail()),m&&m.lap("stream",_),t.end(),Se(l.id),m?.commit()},onError:j=>{t.write(`data: ${JSON.stringify({error:{message:j.message,type:"bridge_error"}})}
10
10
 
11
- `),t.end(),we(l.id),m?.commit()}})}async function Ar(t,l,{kind:d,adapter:m,agent:p,run:b=null},x,k,T,n,o,f=null,c=null){const{messages:A,system:F}=m.toTurn(x),{agentModel:U}=Le(x?.model,T),v=ut(T,{...U?{model:U}:{},...b||{}}),W=ae(T.bridge.token),B=Ee(d,x?.model||p),z={tier:T.redaction.tier==="full"?"full":"basic",dictionary:It(T.redaction,n),entities:[]},oe=await ce(T),V=oo({vault:k,redactOpts:z,bridgeUrl:oe,token:W,harness:f});let K;try{K=await to({bridgeUrl:oe,agent:p,token:W,messages:A,system:F,specs:so(o),options:v,signal:void 0})}catch(j){return we(V.id),c?.commit(),s(l,502,{error:{message:`bridge: ${j.message}`,type:"bridge_error"}})}return V.reader=K.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(B.sseHead()),xt(l,V,B,c)}async function Nr(t,l,d,m,p=null){Pe(l.id),l.rounds=(l.rounds||0)+1;try{const x=p?p.clock():0;await no(l,d),p&&p.lap("redact",x)}catch(x){return we(l.id),p?.commit(),s(t,502,{error:{message:`tool-result: ${x.message}`,type:"bridge_error"}})}const b=Ee("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(b.sseHead()),xt(t,l,b,p)}async function Br(t,l,{kind:d,adapter:m,redactable:p,pathname:b,agentOverride:x,harness:k,trace:T,run:n=null},o,f,c,A){if(!p)return T?.commit(),s(l,404,{error:`endpoint ${b} not supported by the bridge backend`});if(d==="openai"){const M=m.extractLatestToolResult(o);if(M){const H=Ye(M.tool_call_id),ee=H&&Ze(H.gwId);if(ee)return Nr(l,ee,M.content,o?.model,T)}const $=m.extractTools(o);if($.length&&o?.stream===!0)return Ar(t,l,{kind:d,adapter:m,agent:x||Tt(o?.model,c),run:n},o,f,c,A,$,k,T)}const{messages:F,system:U}=m.toTurn(o),v=x||Tt(o?.model,c),W=o?.stream===!0,B=Ee(d,o?.model||v),z=ae(c.bridge.token),oe=new AbortController;l.on("close",()=>{l.writableFinished||oe.abort()});const{agentModel:V}=Le(o?.model,c),K={bridgeUrl:await ce(c),agent:v,token:z,messages:F,system:U,signal:oe.signal,options:ut(c,{...V?{model:V}:{},...n||{}})};if(!W)try{let M="";const $=T?T.clock():0;await Ke(K,he=>{M+=he}),T&&T.lap("upstream",$);const H=T?T.clock():0,ee=B.full(Mt(M,f));return T&&T.lap("restore",H),l.writeHead(200,{"content-type":B.contentType}),l.end(ee),T?.commit()}catch(M){return T?.commit(),s(l,502,{error:{message:`bridge backend failed: ${M.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(B.sseHead());const j=Ue(f),me=T?T.clock():0;let se=me;try{let M=!0;await Ke(K,H=>{T&&M&&(T.lap("upstream",me),se=T.clock(),M=!1);const ee=j.push(H);ee&&l.write(B.sseDelta(ee))},B.sseActivity?H=>{try{l.write(B.sseActivity(Ct(H,f)))}catch{}}:null);const $=j.flush();$&&l.write(B.sseDelta($)),l.write(B.sseTail())}catch(M){l.write(`data: ${JSON.stringify({error:{message:M.message,type:"bridge_error"}})}
11
+ `),t.end(),Se(l.id),m?.commit()}})}async function Ir(t,l,{kind:c,adapter:m,agent:p,run:y=null},_,k,T,j,x,U=null,n=null){const{messages:o,system:f}=m.toTurn(_),{agentModel:d}=ze(_?.model,T),C=ht(T,{...d?{model:d}:{},...y||{}}),H=ae(T.bridge.token),P=Pe(c,_?.model||p),S={tier:T.redaction.tier==="full"?"full":"basic",dictionary:Lt(T.redaction,j),entities:[]},X=await de(T),te=so({vault:k,redactOpts:S,bridgeUrl:X,token:H,harness:U});let se;try{se=await no({bridgeUrl:X,agent:p,token:H,messages:o,system:f,specs:lo(x),options:C,signal:void 0})}catch(ce){return Se(te.id),n?.commit(),s(l,502,{error:{message:`bridge: ${ce.message}`,type:"bridge_error"}})}return te.reader=se.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(P.sseHead()),Et(l,te,P,n)}async function Rr(t,l,c,m,p=null){Ee(l.id),l.rounds=(l.rounds||0)+1;try{const _=p?p.clock():0;await io(l,c),p&&p.lap("redact",_)}catch(_){return Se(l.id),p?.commit(),s(t,502,{error:{message:`tool-result: ${_.message}`,type:"bridge_error"}})}const y=Pe("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),Et(t,l,y,p)}async function Lr(t,l,{kind:c,adapter:m,redactable:p,pathname:y,agentOverride:_,harness:k,trace:T,run:j=null},x,U,n,o){if(!p)return T?.commit(),s(l,404,{error:`endpoint ${y} not supported by the bridge backend`});if(c==="openai"){const B=m.extractLatestToolResult(x);if(B){const F=qe(B.tool_call_id),G=F&&Xe(F.gwId);if(G)return Rr(l,G,B.content,x?.model,T)}const ee=m.extractTools(x);if(ee.length&&x?.stream===!0)return Ir(t,l,{kind:c,adapter:m,agent:_||_t(x?.model,n),run:j},x,U,n,o,ee,k,T)}const{messages:f,system:d}=m.toTurn(x),C=_||_t(x?.model,n),H=x?.stream===!0,P=Pe(c,x?.model||C),S=ae(n.bridge.token),X=new AbortController;l.on("close",()=>{l.writableFinished||X.abort()});const{agentModel:te}=ze(x?.model,n),se={bridgeUrl:await de(n),agent:C,token:S,messages:f,system:d,signal:X.signal,options:ht(n,{...te?{model:te}:{},...j||{}})};if(!H)try{let B="";const ee=T?T.clock():0;await Qe(se,D=>{B+=D}),T&&T.lap("upstream",ee);const F=T?T.clock():0,G=P.full(Rt(B,U));return T&&T.lap("restore",F),l.writeHead(200,{"content-type":P.contentType}),l.end(G),T?.commit()}catch(B){return T?.commit(),s(l,502,{error:{message:`bridge backend failed: ${B.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(P.sseHead());const ce=We(U),q=T?T.clock():0;let oe=q;try{let B=!0;await Qe(se,F=>{T&&B&&(T.lap("upstream",q),oe=T.clock(),B=!1);const G=ce.push(F);G&&l.write(P.sseDelta(G))},P.sseActivity?F=>{try{l.write(P.sseActivity(It(F,U)))}catch{}}:null);const ee=ce.flush();ee&&l.write(P.sseDelta(ee)),l.write(P.sseTail())}catch(B){l.write(`data: ${JSON.stringify({error:{message:B.message,type:"bridge_error"}})}
12
12
 
13
- `)}T&&T.lap("stream",se),l.end(),T?.commit()}function Dr(t,l,d=""){const m=String(t||"").replace(/\/+$/,""),p=String(l||"").split("/")[1];return p&&m.endsWith(`/${p}`)?m.slice(0,-(p.length+1))+l+d:m+l+d}const Cr=9e4;function Mr(t,l,d){if(l===d)return t;const m=l/d,p=new Float32Array(Math.floor(t.length/m));for(let b=0;b<p.length;b++){const x=b*m,k=Math.floor(x),T=Math.min(t.length-1,k+1),n=x-k;p[b]=t[k]*(1-n)+t[T]*n}return p}const Ir=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ge(t,l){const d=new URLSearchParams;for(const b of t.searchParams.getAll("dir"))b&&d.append("dir",b);const m=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();m&&d.set("workdir",m);const p=d.toString();return p?`?${p}`:""}async function jr(t,l,{adapter:d,kind:m,pathname:p,search:b,base:x,destKey:k,destProtocol:T,harness:n,trace:o},f,c){let A;const F=o?o.clock():0;try{const B=Er(t.headers,x);k&&(T==="anthropic"?(B["x-api-key"]=k,delete B.authorization):B.authorization=`Bearer ${k}`);const z=Gt(Dr(x,p,b)).toString();A=await fetch(z,{method:t.method,headers:B,body:["GET","HEAD"].includes(t.method)?void 0:f})}catch(B){return o?.commit(),s(l,502,{error:`upstream fetch failed: ${B.message}`})}const U=A.headers.get("content-type")||"",v={};if(A.headers.forEach((B,z)=>{wt.has(z.toLowerCase())||(v[z]=B)}),U.includes("text/event-stream")&&A.body){o&&o.lap("upstream",F);const B=o?o.clock():0;l.writeHead(A.status,v);const z=m==="openai"?Dt(A.body,l,c,n):Bt(A.body,l,c);return Promise.resolve(z).finally(()=>{o&&o.lap("stream",B),o?.commit()})}const W=Buffer.from(await A.arrayBuffer());if(o&&o.lap("upstream",F),c&&U.includes("application/json"))try{const B=o?o.clock():0,z=d.restoreResponse(JSON.parse(W.toString("utf8")),c,n);return o&&o.lap("restore",B),l.writeHead(A.status,{...v,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(z),"utf8")),o?.commit()}catch{}l.writeHead(A.status,v),l.end(W),o?.commit()}function Rr(t=Ve()){let l=null;const d=()=>{if(!l){const n=t.read||{};l=Ro({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return l};let m=null;const p=()=>(m||(m=Mo({onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let b=null;const x=()=>{if(!b){const n=t.search||{},o=n.searxng?.url?Jo({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;b=Lo({reader:d(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let c=f;return await ge([xe(()=>c,A=>{c=A})],{...t.redaction,tier:"basic"},{isPro:!0}),c}})}return b};Ht(t.allowedExtensionIds||[]);const k=[],T=n=>{k.push(n),k.length>50&&k.shift()};return Et(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),c=f.pathname;if(!kt(n.headers.host))return s(o,403,{error:"loopback only"});if(!Sr(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&vr(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&n.method==="POST")return Z(n)?s(o,200,{token:$e()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&n.method==="POST"){if(!Z(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ft();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Wt(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${be(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${be(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=ae(t.bridge?.token);return s(o,200,{ok:!0,token:Ut()||$e(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&n.method==="POST"){const e=be(n);return s(o,200,{ok:!0,trust:e,paired:Vt(e),version:Y})}if(c==="/audit"&&n.method==="GET")return Z(n)?s(o,200,Zt(t,{version:Y,startedAt:St,managed:pe()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&n.method!=="GET")&&!Z(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&n.method==="GET"){const e=await vo(Y,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:Y,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Oo()})}if(c==="/update"&&n.method==="POST"){const e=_o(Y);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&n.method==="PUT"&&!Z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!Z(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!Z(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&c==="/health"){const e=D.health(),r=O.health();return s(o,200,{ok:!0,version:Y,backend:t.backend,tier:t.redaction.tier,pairing:!0,...pe()?{managed:pe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Oe?{bridge:Oe.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||at,voice:t.tts?.voice||re,runtime:r.runtime,dtype:r.dtype}})}if(c==="/status"&&n.method==="GET"){Nt(t);const e=await ie(t.pro?.entitlementToken),r=await Ot(t);return s(o,200,{ok:!0,version:Y,backend:t.backend,tier:t.redaction.tier,...pe()?{managed:pe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:ze(t),pro:{unlocked:e},usage:cr(t),uptimeSeconds:Math.floor((Date.now()-St)/1e3),update:To(Y)})}if(c==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:X.revision,stamps:X.stamps()}):s(o,200,{ok:!0,revision:X.revision,sections:X.get(e)})}if(c==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=X.put(e.sections||{},{by:e.by||""});return r.applied.length&&yt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?X.remove(e):!1;return r&&yt([e],""),s(o,200,{ok:!0,removed:r})}if(c==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
13
+ `)}T&&T.lap("stream",oe),l.end(),T?.commit()}function zr(t,l,c=""){const m=String(t||"").replace(/\/+$/,""),p=String(l||"").split("/")[1];return p&&m.endsWith(`/${p}`)?m.slice(0,-(p.length+1))+l+c:m+l+c}const Gr=9e4;function Jr(t,l,c){if(l===c)return t;const m=l/c,p=new Float32Array(Math.floor(t.length/m));for(let y=0;y<p.length;y++){const _=y*m,k=Math.floor(_),T=Math.min(t.length-1,k+1),j=_-k;p[y]=t[k]*(1-j)+t[T]*j}return p}const Vr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Je(t,l){const c=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&c.append("dir",y);const m=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const p=c.toString();return p?`?${p}`:""}async function Ur(t,l,{adapter:c,kind:m,pathname:p,search:y,base:_,destKey:k,destProtocol:T,harness:j,trace:x},U,n){let o;const f=x?x.clock():0;try{const P=jr(t.headers,_);k&&(T==="anthropic"?(P["x-api-key"]=k,delete P.authorization):P.authorization=`Bearer ${k}`);const S=Ut(zr(_,p,y)).toString();o=await fetch(S,{method:t.method,headers:P,body:["GET","HEAD"].includes(t.method)?void 0:U})}catch(P){return x?.commit(),s(l,502,{error:`upstream fetch failed: ${P.message}`})}const d=o.headers.get("content-type")||"",C={};if(o.headers.forEach((P,S)=>{vt.has(S.toLowerCase())||(C[S]=P)}),d.includes("text/event-stream")&&o.body){x&&x.lap("upstream",f);const P=x?x.clock():0;l.writeHead(o.status,C);const S=m==="openai"?jt(o.body,l,n,j):Mt(o.body,l,n);return Promise.resolve(S).finally(()=>{x&&x.lap("stream",P),x?.commit()})}const H=Buffer.from(await o.arrayBuffer());if(x&&x.lap("upstream",f),n&&d.includes("application/json"))try{const P=x?x.clock():0,S=c.restoreResponse(JSON.parse(H.toString("utf8")),n,j);return x&&x.lap("restore",P),l.writeHead(o.status,{...C,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(S),"utf8")),x?.commit()}catch{}l.writeHead(o.status,C),l.end(H),x?.commit()}function Hr(t=Fe()){let l=null;const c=()=>{if(!l){const n=t.read||{};l=Uo({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return l};let m=null;const p=()=>(m||(m=Ro({wrap:(n,o,f,d)=>Lo().wrap(n,o,f,d),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let y=null;const _=()=>(y||(y=Go({cfg:t,bridgeHealth:async()=>{const n=await de(t);if(!n)return null;const o=ae(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{le(t,re())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},workers:()=>{const n=m?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),y);let k=null;const T=()=>{if(!k){const n=t.search||{},o=n.searxng?.url?Ko({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;k=Ho({reader:c(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let d=f;return await we([$e(()=>d,C=>{d=C})],{...t.redaction,tier:"basic"},{isPro:!0}),d}})}return k};Kt(t.allowedExtensionIds||[]);const j=[],x=n=>{j.push(n),j.length>50&&j.shift()},U=Bt(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),d=f.pathname;if(!Tt(n.headers.host))return s(o,403,{error:"loopback only"});if(!Ar(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&Er(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(d==="/admin/token"&&n.method==="POST")return W(n)?s(o,200,{token:Ae()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(d==="/pair/code"&&n.method==="POST"){if(!W(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Zt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(d==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Yt(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${ke(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${ke(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=ae(t.bridge?.token);return s(o,200,{ok:!0,token:Wt()||Ae(),...a?{bridgeToken:a}:{}})}if(d==="/whoami"&&n.method==="POST"){const e=ke(n);return s(o,200,{ok:!0,trust:e,paired:Ft(e),version:K})}if(d==="/audit"&&n.method==="GET")return W(n)?s(o,200,Xt(t,{version:K,startedAt:xt,managed:he()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((d==="/config"||d==="/logs"||d==="/update"&&n.method!=="GET")&&!W(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(d==="/update"&&n.method==="GET"){const e=await Oo(K,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:K,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Ao()})}if(d==="/update"&&n.method==="POST"){const e=$o(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((d==="/v1/history/key"||d==="/v1/history/ingest-backup")&&n.method==="POST"&&!W(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(d==="/v1/history/records"&&n.method==="PUT"&&!W(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/history/ingest"||d==="/v1/history/clear")&&n.method==="POST"&&!W(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/memory/remember"||d==="/v1/memory/forget"||d==="/v1/memory/sync"||d==="/v1/memory/clear")&&n.method==="POST"&&!W(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/prefs"||d.startsWith("/v1/prefs/")||d.startsWith("/v1/teams")||d.startsWith("/v1/agents")||d.startsWith("/v1/projects"))&&!W(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(d.startsWith("/v1/observability")&&!W(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&d==="/health"){const e=M.health(),r=$.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...he()?{managed:he()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...ye?{bridge:ye.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ce,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||ct,voice:t.tts?.voice||ie,runtime:r.runtime,dtype:r.dtype}})}if(d==="/status"&&n.method==="GET"){Ct(t);const e=await ue(t.pro?.entitlementToken),r=await At(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...he()?{managed:he()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:Ge(t),pro:{unlocked:e},usage:yr(t),uptimeSeconds:Math.floor((Date.now()-xt)/1e3),update:_o(K)})}if(d==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(d==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:Y.revision,stamps:Y.stamps()}):s(o,200,{ok:!0,revision:Y.revision,sections:Y.get(e)})}if(d==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Y.put(e.sections||{},{by:e.by||""});return r.applied.length&&bt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(d==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?Y.remove(e):!1;return r&&bt([e],""),s(o,200,{ok:!0,removed:r})}if(d==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
14
14
 
15
- `);e({type:"hello",revision:X.revision,stamps:X.stamps()});const r=i=>e({type:"changed",...i});je.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
15
+ `);e({type:"hello",revision:Y.revision,stamps:Y.stamps()});const r=i=>e({type:"changed",...i});Re.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
16
16
 
17
- `)}catch{}},25e3);o.on("close",()=>{je.delete(r),clearInterval(a)});return}if(c==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:J.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:J.openJobs()});if(c==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:J.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",y=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const h=J.get(r);if(!h)return y();const S=h.jobs.find(w=>w.id===i);if(!S)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const g={cfg:t,prefsStore:X,scorecards:de,engines:ue};if(u==="/applications"&&n.method==="GET"){const w=await wo(S,{...g,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:S,...w})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(S.status))return s(o,400,{error:{message:`job ${i} is ${S.status}; only an open job is recruited`,type:"project_error"}});try{const w=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(w.by||"evaluator").slice(0,80),L=await ko(S,{...g,record:h,reach:w.reach||"any",chatModel:w.chatModel||null,evaluation:w.evaluation||null,text:w.text??null,by:E});let C=null;for(const q of L.events)q.type==="job.updated"?C=J.updateJob(r,i,q.job,{by:q.by||E}):C=J.append(r,[q]);return s(o,200,{ok:!0,project:C,decision:L.decision,applications:L.applications,evaluation:L.evaluation})}catch(w){return s(o,400,{error:{message:`recruit: ${w.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const h=J.get(r,{events:f.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):y()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:J.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},S=String(h.by||"person").slice(0,80),g=a==="/events"?J.append(r,h.events||[]):i?J.updateJob(r,i,h.patch||h,{by:S}):J.postJob(r,h.job||h,{by:S});return s(o,200,{ok:!0,project:g})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!J.get(r))return y();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=E=>o.write(`data: ${JSON.stringify(E)}
17
+ `)}catch{}},25e3);o.on("close",()=>{Re.delete(r),clearInterval(a)});return}if(d==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(d==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(d==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(d);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",w=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const h=V.get(r);if(!h)return w();const v=h.jobs.find(b=>b.id===i);if(!v)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const g={cfg:t,prefsStore:Y,scorecards:me,engines:pe};if(u==="/applications"&&n.method==="GET"){const b=await vo(v,{...g,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:v,...b})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(v.status))return s(o,400,{error:{message:`job ${i} is ${v.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(b.by||"evaluator").slice(0,80),z=await To(v,{...g,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:E});let I=null;for(const Q of z.events)Q.type==="job.updated"?I=V.updateJob(r,i,Q.job,{by:Q.by||E}):I=V.append(r,[Q]);return s(o,200,{ok:!0,project:I,decision:z.decision,applications:z.applications,evaluation:z.evaluation})}catch(b){return s(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const h=V.get(r,{events:f.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):w()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},v=String(h.by||"person").slice(0,80),g=a==="/events"?V.append(r,h.events||[]):i?V.updateJob(r,i,h.patch||h,{by:v}):V.postJob(r,h.job||h,{by:v});return s(o,200,{ok:!0,project:g})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!V.get(r))return w();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=E=>o.write(`data: ${JSON.stringify(E)}
18
18
 
19
- `);let S=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:J.get(r),after:S}});const g=J.watch(r,E=>{E.seq>S&&(S=E.seq,h(E))});for(const E of J.eventsSince(r,S))S=E.seq,h(E);const w=setInterval(()=>{try{o.write(`: keep
19
+ `);let v=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(r),after:v}});const g=V.watch(r,E=>{E.seq>v&&(v=E.seq,h(E))});for(const E of V.eventsSince(r,v))v=E.seq,h(E);const b=setInterval(()=>{try{o.write(`: keep
20
20
 
21
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(w),g()});return}}}if(c==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:de.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await de.get(r)});if(n.method==="POST")try{const a=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},i=await de.append({agentId:r,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ue.fromRating(de.chains.get(r)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/capabilities"&&n.method==="GET")return s(o,200,Do(t,{version:Y,reader:l,searcher:b,extract:p()}));if(c==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Co(e,{ensure:()=>ke(t),model:P.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(c==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,Math.max(t.maxBodyBytes,Math.ceil(jo*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Io(e,{service:p()});return s(o,r.status,r.body)}if(c==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await d().read(e);return s(o,r.status,r.body)}if(c==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await x().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(c)&&n.method==="GET"){let e;try{e=decodeURIComponent(c.slice(11))}catch{e=c.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Go.aliasRead,a=await x().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?zo(a.body):a.body)}if(/^\/v1\/read\/./.test(c)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await d().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Vo(u.body)))}if(c==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ue.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ue.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||_r(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await ue.append({...a,engine:i,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:R.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:R.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=R.get(r,{events:f.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return R.stop(r),s(o,200,{ok:!0,removed:R.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=R.stop(r);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:R.checkpoint(r)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?R.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):R.claim(r,{client:i.client});return s(o,200,{ok:!0,run:u})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:R.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),y=a==="/answer"?R.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?R.decide(r,{postId:i.postId,status:i.status,by:u}):R.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:y})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:R.append(r,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!R.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=g=>o.write(`data: ${JSON.stringify(g)}
21
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),g()});return}}}if(d==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:me.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(d);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await me.get(r)});if(n.method==="POST")try{const a=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},i=await me.append({agentId:r,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return pe.fromRating(me.chains.get(r)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(d==="/v1/capabilities"&&n.method==="GET")return s(o,200,jo(t,{version:K,reader:l,searcher:k,extract:p()}));if(d==="/v1/runtime"&&n.method==="GET")return s(o,200,await _().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(d);if(e&&n.method==="POST"){if(!W(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),i=_(),u=e[1]==="engines"?a==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await i.startService(e[2]):a==="stop"?await i.stopService(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if(d==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Io(e,{ensure:()=>ve(t),model:A.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(d==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,Math.max(t.maxBodyBytes,Math.ceil(Vo*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Jo(e,{service:p()});return s(o,r.status,r.body)}if(d==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await c().read(e);return s(o,r.status,r.body)}if(d==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await T().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(d)&&n.method==="GET"){let e;try{e=decodeURIComponent(d.slice(11))}catch{e=d.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Wo.aliasRead,a=await T().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?Fo(a.body):a.body)}if(/^\/v1\/read\/./.test(d)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await c().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Zo(u.body)))}if(d==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:pe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(d);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await pe.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||Nr(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await pe.append({...a,engine:i,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(d==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:L.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(d==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:L.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(d);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=L.get(r,{events:f.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return L.stop(r),s(o,200,{ok:!0,removed:L.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=L.stop(r);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:L.checkpoint(r)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const i=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?L.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):L.claim(r,{client:i.client});return s(o,200,{ok:!0,run:u})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:L.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const i=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),w=a==="/answer"?L.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?L.decide(r,{postId:i.postId,status:i.status,by:u}):L.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:w})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const i=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:L.append(r,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!L.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=g=>o.write(`data: ${JSON.stringify(g)}
22
22
 
23
- `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let y=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:R.get(r),after:y}});const h=R.watch(r,g=>{g.seq==null?i(g):g.seq>y&&(y=g.seq,i(g))});for(const g of R.eventsSince(r,y))y=g.seq,i(g);const S=setInterval(()=>{try{o.write(`: keep-alive
23
+ `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let w=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:L.get(r),after:w}});const h=L.watch(r,g=>{g.seq==null?i(g):g.seq>w&&(w=g.seq,i(g))});for(const g of L.eventsSince(r,w))w=g.seq,i(g);const v=setInterval(()=>{try{o.write(`: keep-alive
24
24
 
25
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(S)});return}}}if(c==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:Q.size,memories:Q.list()});if(c==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:Q.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:Q.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=Q.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:Q.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:Q.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:Q.clear(),size:Q.size});if(c==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(c==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=yr(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),y=await fr(a,S=>N.search(S,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?y:[...y.filter(S=>S.type==="brief"),...y.filter(S=>S.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:r})})}if(c==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes,lossless:N.lossless?{records:N.lossless.size,newest:N.lossless.newest}:null});if(c==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Re.snapshot(e)})}if(c==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Re.push(pt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&n.method==="PUT"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let y=0;const h={upserts:[],removes:[]},S=g=>{if(!g||g.deletedAt){g?.id&&h.removes.push(g.id);return}try{const w=$o(g);w&&h.upserts.push(w)}catch{}};if(Array.isArray(r.records)){const g=e.upsert(r.records,{host:a,at:i});u.push(...g);for(const w of r.records)g.includes(w?.id)&&S(w)}if(Array.isArray(r.entries)){const g=Ae(),w=g?Ao((C,q)=>Po(g,{salt:C,iterations:q})):null,E=async C=>{if(!w||!C.blob)return null;const q=await w(C.blob),ye=C.blob.compression&&C.blob.compression!=="none"?No(Bo,C.blob.compression):null;return Eo(C.blob,q,{codec:ye})},L=await e.upsertEntries(r.entries,{open:E});u.push(...L.written),y+=L.sealed;for(const C of L.written)S(e.get(C))}return(h.upserts.length||h.removes.length)&&N.bulk(h),u.length&&_e({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:y,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
26
- data: ${JSON.stringify({newest:e.newest,size:e.size,version:Y,prefsRevision:X.revision})}
25
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(v)});return}}}if(d==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:Z.size,memories:Z.list()});if(d==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Z.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:Z.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(d==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Z.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:Z.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(d==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=Z.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:Z.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(d==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Z.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:Z.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(d==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:Z.clear(),size:Z.size});if(d==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(d==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(d==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=vr(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),w=await Tr(a,v=>N.search(v,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?w:[...w.filter(v=>v.type==="brief"),...w.filter(v=>v.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(d==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:r})})}if(d==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes,lossless:N.lossless?{records:N.lossless.size,newest:N.lossless.newest}:null});if(d==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Le.snapshot(e)})}if(d==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Le.push(ft({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(d==="/v1/history/records"&&n.method==="PUT"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let w=0;const h={upserts:[],removes:[]},v=g=>{if(!g||g.deletedAt){g?.id&&h.removes.push(g.id);return}try{const b=Po(g);b&&h.upserts.push(b)}catch{}};if(Array.isArray(r.records)){const g=e.upsert(r.records,{host:a,at:i});u.push(...g);for(const b of r.records)g.includes(b?.id)&&v(b)}if(Array.isArray(r.entries)){const g=Ne(),b=g?Do((I,Q)=>No(g,{salt:I,iterations:Q})):null,E=async I=>{if(!b||!I.blob)return null;const Q=await b(I.blob),ge=I.blob.compression&&I.blob.compression!=="none"?Co(Mo,I.blob.compression):null;return Bo(I.blob,Q,{codec:ge})},z=await e.upsertEntries(r.entries,{open:E});u.push(...z.written),w+=z.sealed;for(const I of z.written)v(e.get(I))}return(h.upserts.length||h.removes.length)&&N.bulk(h),u.length&&_e({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:w,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(d==="/v1/history/stream"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
26
+ data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:Y.revision})}
27
27
 
28
- `),te.add(o),n.on("close",()=>te.delete(o));return}if(c==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=f.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(c==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=N.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:Xe()});if(c==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?uo(String(e.passphrase)):mo();const r=e.passphrase?await Be(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&_e(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Be(N,Ae());return e.ok&&e.whole&&_e(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(n.method==="GET"){const e=await Ot(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await ke(t),P.state()!=="off"){if(!P.isReady()){const r=P.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await _(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await P.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=_t(t);if(!e){const r=P.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:P.state(),model:t.ner?.model||null})}try{const r=await _(n,t.maxBodyBytes),a=await We(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:ze(t)});try{let r=e;const a=await ie(t.pro?.entitlementToken);await ke(t);const i=await ge([xe(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:vt(i.vault,"types")||[],detector:ze(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(n.method==="GET"){const e=P.health().model||t.ner?.model||null,r=Math.round(qe.totalmem()/1048576),a=Uo(et,{totalRamMB:r}).map(i=>({...i,installed:P.modelOnDisk(i.id)}));for(const i of[e,...P.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:P.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:P.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:lo(),recommendation:Qe(a,{totalRamMB:r},[]),state:P.state(),progress:P.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(qe.totalmem()/1048576),i=Qe(et.map(u=>({...u,installed:P.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(tt(u)||ot(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||P.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&dt(t,r);try{le(t,ne())}catch{}return(async()=>{r&&await P.setModel(r,{onLog:y=>console.log(y)});const u=io(t.ner,{log:y=>console.log(y)});for(const y of P.companions())u.includes(y.model)||await P.removeCompanion(y.model);for(const y of u)await P.addCompanion(y,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});P.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:P.companions(),state:P.state()})}if(!r||!(tt(r)||ot(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});dt(t,r);try{le(t,ne())}catch{}return P.setModel(r,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:r,state:P.state(),progress:P.progress()})}}if(c==="/stt/models"){if(n.method==="GET"){const e=D.health().model||t.stt?.model||De,r=Ho.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:Ko})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Fo(r)||Wo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Zo(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{le(t,ne())}catch{}return D.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:D.state(),progress:D.progress()})}}if(c==="/diarize/model"){if(n.method==="GET"){const e=I.health();return s(o,200,{active:I.DIARIZE_MODEL,state:e.state,progress:I.progress(),available:[{id:I.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:I.modelOnDisk()}]})}if(n.method==="POST")return I.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:I.DIARIZE_MODEL,state:I.state(),progress:I.progress()})}if(c==="/tts/models"){if(n.method==="GET"){const e=O.health().model||t.tts?.model||lt(Ce()),r=Ce(),a=rt.find(u=>u.id===e)||null,i=rt.map(u=>({...u,installed:O.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:O.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:O.state(),progress:O.progress(),available:i,voice:t.tts?.voice||(Te(e)==="pocket-tts"?Se:re),arch:O.arch(),supportsVoices:O.arch()?O.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:O.arch()?O.supportsCustomVoices():!!a?.customVoices,sampleRate:O.sampleRate(),voices:O.isPocket()||!O.arch()&&Te(e)==="pocket-tts"?(O.builtinVoices().length?O.builtinVoices():or).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:O.builtinVoices().includes(u)})):O.arch()&&O.arch()!=="style-tts2"?[]:Yo.map(u=>({...u,installed:O.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:O.health().dtype,runtime:O.health().runtime,dtypes:qo})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Qo(r)||Xo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const u=G.parseCustomVoice(a);if(!(u?!!G.getVoice(u):ve(a)||nt(a)&&st(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&er(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:at,voice:re,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=tr(r),y=G.parseCustomVoice(t.tts.voice||""),h=!!(y&&G.getVoice(y));if(u&&!h)if(Te(r)==="pocket-tts")t.tts.voice=Se;else{const g=G.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!u&&h&&(t.tts.voice=re);const S=Te(r)==="pocket-tts";S&&!G.parseCustomVoice(t.tts.voice||"")&&!ve(t.tts.voice)&&(t.tts.voice=Se),!S&&ve(t.tts.voice)&&(t.tts.voice=re)}i&&(t.tts.dtype=i==="auto"?null:i);try{le(t,ne())}catch{}return r&&O.setModel(r,{onLog:u=>console.log(u),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:O.state(),progress:O.progress()})}}if(c==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:G.listVoices(),usable:O.supportsCustomVoices(),embedder:I.DIARIZE_MODEL,embedderReady:I.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!G.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(i,r),usable:O.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!I.isReady()){const w=I.download({onLog:C=>console.log(C)}),E=Symbol("timeout"),L=await Promise.race([w.then(()=>null).catch(C=>C),new Promise(C=>setTimeout(()=>C(E),Cr))]);if(L===E||!I.isReady())return s(o,503,{error:{message:L===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${I.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:I.progress()})}const u=Float32Array.from(a),y=await I.embed(u);let h=null;try{const w=await O.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});w&&(h=await w.encodeVoice(Mr(u,16e3,24e3)))}catch(w){console.log(`[tts] pocket conditioning unavailable for this voice (${w.message})`)}const S=i?G.replaceVoice(i,{vec:y,pocket:h}):G.saveVoice({name:r,vec:y,pocket:h}),g=i&&r&&r!==S.name?G.renameVoice(i,r):S;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${g.name}" (${(S.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...S,...g,usable:O.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=G.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:re;try{le(t,ne())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>it)return s(o,413,{error:{message:`text too long (max ${it} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=rr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,y=u||(i?i.voice:t.tts?.voice||re);if(i&&!sr(y))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:fe,contentType:$t,redacted:Pt}=await nr({dest:i,text:r,voice:y,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ie(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":$t,"Content-Length":String(fe.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Pt)}),o.end(fe)}if(!await O.ready({onLog:fe=>console.log(fe),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||lt(Ce()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:O.health().error||"tts model not ready",type:"tts_unavailable"}});const g=ar({requested:u,configured:y,engine:O,voices:G,isPocketVoice:ve,isKnownVoice:nt,isValidVoiceId:st,defaultVoice:re,defaultPocketVoice:Se});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:w,customId:E,speakerEmbedding:L}=g,C=await O.synth(r,{voice:w,speed:a,speakerEmbedding:L}),q=O.sampleRate(),ye=h==="pcm"?Buffer.from(new Float32Array(C).buffer):O.toWav(C,q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ye.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(q),...E||O.isPocket()||O.supportsVoices()?{"X-Tts-Voice":w}:{}}),o.end(ye)}catch(S){return s(o,500,{error:{message:S.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}D.isReady()||D.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});const r=e?.diarize===!0&&t.stt?.diarize!==!1;r&&!I.isReady()&&I.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});try{const{id:a}=D.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:r,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:D.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await _(n,t.maxBodyBytes);return D.pushAudio(r,D.toFloat32(a)),s(o,200,{ok:!0,state:D.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=D.getSession(r);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=w=>o.write(`data: ${JSON.stringify(w)}
28
+ `),ne.add(o),n.on("close",()=>ne.delete(o));return}if(d==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(d==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=f.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(d==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=N.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(d==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:tt()});if(d==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?ho(String(e.passphrase)):yo();const r=e.passphrase?await De(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&_e(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(d==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await De(N,Ne());return e.ok&&e.whole&&_e(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(d==="/ner"){if(n.method==="GET"){const e=await At(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await ve(t),A.state()!=="off"){if(!A.isReady()){const r=A.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await O(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await A.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=$t(t);if(!e){const r=A.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:A.state(),model:t.ner?.model||null})}try{const r=await O(n,t.maxBodyBytes),a=await Ye(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(d==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ge(t)});try{let r=e;const a=await ue(t.pro?.entitlementToken);await ve(t);const i=await we([$e(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ot(i.vault,"types")||[],detector:Ge(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(d==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(ot.totalmem()/1048576),a=Yo(rt,{totalRamMB:r}).map(i=>({...i,installed:A.modelOnDisk(i.id)}));for(const i of[e,...A.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:A.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:mo(),recommendation:et(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(ot.totalmem()/1048576),i=et(rt.map(u=>({...u,installed:A.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(nt(u)||st(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&pt(t,r);try{le(t,re())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:w=>console.log(w)});const u=uo(t.ner,{log:w=>console.log(w)});for(const w of A.companions())u.includes(w.model)||await A.removeCompanion(w.model);for(const w of u)await A.addCompanion(w,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(nt(r)||st(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});pt(t,r);try{le(t,re())}catch{}return A.setModel(r,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:r,state:A.state(),progress:A.progress()})}}if(d==="/stt/models"){if(n.method==="GET"){const e=M.health().model||t.stt?.model||Ce,r=Qo.map(a=>({...a,installed:M.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:M.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:M.state(),progress:M.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:M.health().dtype,runtime:M.health().runtime,dtypes:er})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Xo(r)||qo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&tr(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{le(t,re())}catch{}return M.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:M.state(),progress:M.progress()})}}if(d==="/diarize/model"){if(n.method==="GET"){const e=R.health();return s(o,200,{active:R.DIARIZE_MODEL,state:e.state,progress:R.progress(),available:[{id:R.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:R.modelOnDisk()}]})}if(n.method==="POST")return R.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:R.DIARIZE_MODEL,state:R.state(),progress:R.progress()})}if(d==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||ut(Me()),r=Me(),a=at.find(u=>u.id===e)||null,i=at.map(u=>({...u,installed:$.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:$.state(),progress:$.progress(),available:i,voice:t.tts?.voice||(Oe(e)==="pocket-tts"?Te:ie),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!a?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&Oe(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():lr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:or.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:sr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(rr(r)||nr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const u=J.parseCustomVoice(a);if(!(u?!!J.getVoice(u):xe(a)||it(a)&&lt(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&ar(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:ct,voice:ie,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=ir(r),w=J.parseCustomVoice(t.tts.voice||""),h=!!(w&&J.getVoice(w));if(u&&!h)if(Oe(r)==="pocket-tts")t.tts.voice=Te;else{const g=J.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!u&&h&&(t.tts.voice=ie);const v=Oe(r)==="pocket-tts";v&&!J.parseCustomVoice(t.tts.voice||"")&&!xe(t.tts.voice)&&(t.tts.voice=Te),!v&&xe(t.tts.voice)&&(t.tts.voice=ie)}i&&(t.tts.dtype=i==="auto"?null:i);try{le(t,re())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:$.state(),progress:$.progress()})}}if(d==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:J.listVoices(),usable:$.supportsCustomVoices(),embedder:R.DIARIZE_MODEL,embedderReady:R.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!J.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...J.renameVoice(i,r),usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!R.isReady()){const b=R.download({onLog:I=>console.log(I)}),E=Symbol("timeout"),z=await Promise.race([b.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(E),Gr))]);if(z===E||!R.isReady())return s(o,503,{error:{message:z===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${R.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:R.progress()})}const u=Float32Array.from(a),w=await R.embed(u);let h=null;try{const b=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});b&&(h=await b.encodeVoice(Jr(u,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const v=i?J.replaceVoice(i,{vec:w,pocket:h}):J.saveVoice({name:r,vec:w,pocket:h}),g=i&&r&&r!==v.name?J.renameVoice(i,r):v;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${g.name}" (${(v.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...v,...g,usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=J.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=J.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ie;try{le(t,re())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((d==="/tts"||d==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>dt)return s(o,413,{error:{message:`text too long (max ${dt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=cr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ie);if(i&&!ur(w))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:be,contentType:Pt,redacted:Nt}=await dr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ue(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Pt,"Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Nt)}),o.end(be)}if(!await $.ready({onLog:be=>console.log(be),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||ut(Me()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const g=mr({requested:u,configured:w,engine:$,voices:J,isPocketVoice:xe,isKnownVoice:it,isValidVoiceId:lt,defaultVoice:ie,defaultPocketVoice:Te});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:b,customId:E,speakerEmbedding:z}=g,I=await $.synth(r,{voice:b,speed:a,speakerEmbedding:z}),Q=$.sampleRate(),ge=h==="pcm"?Buffer.from(new Float32Array(I).buffer):$.toWav(I,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ge.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),...E||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ge)}catch(v){return s(o,500,{error:{message:v.message,type:"tts_failed"}})}}if(d==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}M.isReady()||M.init({model:t.stt?.model||Ce,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});const r=e?.diarize===!0&&t.stt?.diarize!==!1;r&&!R.isReady()&&R.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});try{const{id:a}=M.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:r,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:M.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=d.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await O(n,t.maxBodyBytes);return M.pushAudio(r,M.toFloat32(a)),s(o,200,{ok:!0,state:M.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=M.getSession(r);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=b=>o.write(`data: ${JSON.stringify(b)}
29
29
 
30
- `),u=a.redact?await ie(t.pro?.entitlementToken):!0,y=async w=>{if(w.type!=="final"||!a.redact)return w;try{let E=w.text;return await ge([xe(()=>E,L=>{E=L})],t.redaction,{isPro:u}),{...w,text:E}}catch{return w}};i({type:"state",state:D.state()});const h=setInterval(()=>{const w=D.state();if(w==="downloading"||w==="loading"){i({type:"progress",state:w,...D.progress()||{}});return}if(w==="error"){i({type:"error",code:"model_failed",message:D.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const E=I.state();if(E==="downloading"||E==="loading"){i({type:"diarize-progress",state:E,...I.progress()||{}});return}}i({type:"state",state:w}),clearInterval(h)},500);h.unref?.();let S=Promise.resolve();const g=D.subscribe(r,w=>{S=S.then(async()=>{i(await y(w)),w.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),g?.()});return}if(!e[2]&&n.method==="DELETE")return await D.endSession(r),s(o,200,{ok:!0})}}if(c==="/logs"&&n.method==="GET")return s(o,200,{entries:[...k].reverse()});if(c==="/config"&&n.method==="GET"){const e=await ie(t.pro?.entitlementToken);return s(o,200,ct(t,{proUnlocked:e}))}if(c==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});dr(t,e),He(t);try{le(t,ne())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const r=t.redaction?.detection,a=!r||!r.backend||r.backend==="off",i=P.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&P.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const u=await ie(t.pro?.entitlementToken);return s(o,200,ct(t,{proUnlocked:u}))}if(n.method==="GET"&&c==="/skills"){const e=await ce(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ge(f,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ce(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ae(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Ge(f,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(c==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(c)){if(!Z(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(c==="/channels"&&n.method==="GET"||c!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ce(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=n.method==="POST"?(await _(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${c}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ce(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=ae(t.bridge?.token);try{const y=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Ge(f,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await y.json().catch(()=>({}));return y.ok?s(o,200,h):s(o,y.status,{error:{message:h?.error||`bridge ${y.status}`,type:"bridge_error"}})}catch(y){return s(o,502,{error:{message:`bridge unreachable: ${y.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(c))return s(o,200,await mr(t));if(Ir.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${Y}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const A=xr(c,n.headers,t);let F;try{F=await _(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let U=null,v=null,W=F,B=0,z=0,oe=0,V=!1,K=!0;const j=t.logRequests&&A.redactable&&n.method==="POST"?Or(T):null;if(A.redactable&&n.method==="POST"&&F.length){try{v=JSON.parse(F.toString("utf8"))}catch{v=null}if(v&&$r(v,A.kind))W=F;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):gr,w=e.narrowAll?null:L=>!br.test(gt(L)),E=v.tools.length;v.tools=jt(v.tools,kr(v,A.kind),{cap:g,keep:w,name:gt,description:wr}),oe=E-v.tools.length}K=await ie(t.pro?.entitlementToken);const r=ir(t,K);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});V=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&Z(n),V||await ke(t);const a=V?[]:A.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=j?j.clock():0,{vault:y,count:h,sanitized:S}=V?{vault:null,count:0,sanitized:0}:await ge(a,t.redaction,{signal:i.signal,isPro:K,onEgress:g=>Re.push(pt({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(j&&j.lap("redact",u),U=y,B=h,z=S||0,!K&&h>0){lr(t,K);try{le(t,ne())}catch{}}if(!V&&Array.isArray(v.tools)&&v.tools.length&&typeof A.adapter.injectSystemNote=="function"){const g=mt(v?.model,t,A.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim()}),w=!(g&&g.type==="api");A.adapter.injectSystemNote(v,Lt({toolData:t.tools?.toolData,ownTools:w}))}else!V&&h>0&&typeof A.adapter.injectSystemNote=="function"&&A.adapter.injectSystemNote(v,zt());W=Buffer.from(JSON.stringify(v),"utf8")}}const me=Rt({vault:U,toolData:t.tools?.toolData}),se=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;se&&(delete v.chatpanel,W=Buffer.from(JSON.stringify(v),"utf8"));const M={destination:String(n.headers["x-chatpanel-destination"]||se?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||se?.reach||"").trim(),run:Lr(n.headers["x-chatpanel-run"],se?.run)},$=mt(v?.model,t,A.kind,{destination:M.destination});if(M.destination&&(!$||$.id!==M.destination))return j?.commit(),s(o,404,{error:{message:`no destination "${M.destination}" is configured on this gateway`,type:"unknown_destination",known:pr(t).map(e=>e.id)}});j&&(j.meta={t:Date.now(),model:v?.model||null,dest:$?$.id:null,type:$?$.type:null,redacted:B,sanitized:z,narrowed:oe,detail:vt(U,t.logDetail),redaction:V?"off":t.redaction.tier||"basic"});const H=Qt();if(H&&$){const e=$.type==="api"?Fe(H,{model:v?.model||"",endpoint:$.baseUrl||""}):qt(H,$.agent||$.id)?Fe(H,{model:v?.model||""}):{ok:!1,reason:`agent "${$.agent||$.id}" is not allowed by your organisation’s policy`};if(!e.ok)return j?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if($&&$.type==="api")return $.baseUrl?Pr($.baseUrl,t)?(j?.commit(),s(o,508,{error:{message:`destination "${$.id}" points back at the gateway (${$.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):jr(n,o,{...A,pathname:c,search:f.search,base:$.baseUrl,destKey:$.apiKey,destProtocol:$.protocol,harness:me,trace:j},W,U):(j?.commit(),s(o,502,{error:`destination "${$.id}" has no baseUrl`}));const ee=be(n),he=ee==="local"&&t.bridge?.openAgentLane?"token":ee;if(he==="local")return j?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const Je=Jt({...M.run||{},...M.reach?{reach:M.reach}:{}},he);return Br(n,o,{...A,pathname:c,agentOverride:$?.agent,harness:me,trace:j,run:Object.keys(Je).length?Je:null},v,U,t,K)})}function Lr(t,l){let d=l&&typeof l=="object"?l:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(p=>String(p).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const p=d.workspace;m.workspace={repo:String(p.repo).slice(0,400),projectId:String(p.projectId||"").slice(0,120),jobId:String(p.jobId||"").slice(0,120),...p.base?{base:String(p.base).slice(0,120)}:{}}}return d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),ur.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),Object.keys(m).length?m:null}let Oe=null;async function Jn(t=Ve()){co();let l=null;try{l=await Yt()}catch(k){throw k instanceof Xt&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const d=l?.policy||null;d&&(He(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Kt(globalThis,{allow:d?.egress?(k,{local:T})=>eo(d,k,{local:T}):null}),$e();const m=Rr(t),p=ao(t),b=At(t);m.on("error",k=>{k&&k.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${ne()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${k?.message||k}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${Y} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),So(t).then(k=>{Oe=k}).catch(k=>console.log(` bridge : not supervised (${k?.message||k})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),kt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Xe()&&Be(N,Ae()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&_e())}).catch(()=>{});const x=()=>{p?.stop(),b.stop(),Oe?.stop(),_extract?.stop("shutdown"),m.close(()=>process.exit(0))};return process.on("SIGINT",x),process.on("SIGTERM",x),m.on("close",()=>_extract?.stop("closed")),m}export{Y as VERSION,Rr as createGateway,Dr as joinUpstream,Le as parseAgentModel,Jn as start};
30
+ `),u=a.redact?await ue(t.pro?.entitlementToken):!0,w=async b=>{if(b.type!=="final"||!a.redact)return b;try{let E=b.text;return await we([$e(()=>E,z=>{E=z})],t.redaction,{isPro:u}),{...b,text:E}}catch{return b}};i({type:"state",state:M.state()});const h=setInterval(()=>{const b=M.state();if(b==="downloading"||b==="loading"){i({type:"progress",state:b,...M.progress()||{}});return}if(b==="error"){i({type:"error",code:"model_failed",message:M.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const E=R.state();if(E==="downloading"||E==="loading"){i({type:"diarize-progress",state:E,...R.progress()||{}});return}}i({type:"state",state:b}),clearInterval(h)},500);h.unref?.();let v=Promise.resolve();const g=M.subscribe(r,b=>{v=v.then(async()=>{i(await w(b)),b.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),g?.()});return}if(!e[2]&&n.method==="DELETE")return await M.endSession(r),s(o,200,{ok:!0})}}if(d==="/logs"&&n.method==="GET")return s(o,200,{entries:[...j].reverse()});if(d==="/config"&&n.method==="GET"){const e=await ue(t.pro?.entitlementToken);return s(o,200,mt(t,{proUnlocked:e}))}if(d==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{fr(t,e)}catch(h){if(h?.code==="SHAPE")return s(o,400,{error:h.message});throw h}Ke(t),JSON.stringify(t.sandbox||null)!==r&&ye?.restart("sandbox settings changed");try{le(t,re())}catch(h){return s(o,500,{error:`could not persist config: ${h.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await ue(t.pro?.entitlementToken);return s(o,200,mt(t,{proUnlocked:w}))}if(n.method==="GET"&&d==="/skills"){const e=await de(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=await fetch(`${e}/skills${Je(f,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(d)){const e=decodeURIComponent(d.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await de(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ae(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Je(f,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(d==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(d)){if(!W(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(d==="/channels"&&n.method==="GET"||d!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await de(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=n.method==="POST"?(await O(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${d}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(d)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(d),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await de(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=ae(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Je(f,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await w.json().catch(()=>({}));return w.ok?s(o,200,h):s(o,w.status,{error:{message:h?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(d))return s(o,200,await wr(t));if(Vr.some(e=>d===e||d.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${d} — update it to use this feature`,type:"unknown_endpoint"}});const C=Dr(d,n.headers,t);let H;try{H=await O(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let P=null,S=null,X=H,te=0,se=0,ce=0,q=!1,oe=!0;const B=t.logRequests&&C.redactable&&n.method==="POST"?Br(x):null;if(C.redactable&&n.method==="POST"&&H.length){try{S=JSON.parse(H.toString("utf8"))}catch{S=null}if(S&&Cr(S,C.kind))X=H;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):xr,b=e.narrowAll?null:z=>!Or.test(kt(z)),E=S.tools.length;S.tools=zt(S.tools,$r(S,C.kind),{cap:g,keep:b,name:kt,description:_r}),ce=E-S.tools.length}oe=await ue(t.pro?.entitlementToken);const r=pr(t,oe);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});q=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&W(n),q||await ve(t);const a=q?[]:C.adapter.collectSegments(S,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=B?B.clock():0,{vault:w,count:h,sanitized:v}=q?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:i.signal,isPro:oe,onEgress:g=>Le.push(ft({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(B&&B.lap("redact",u),P=w,te=h,se=v||0,!oe&&h>0){hr(t,oe);try{le(t,re())}catch{}}if(!q&&Array.isArray(S.tools)&&S.tools.length&&typeof C.adapter.injectSystemNote=="function"){const g=yt(S?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim()}),b=!(g&&g.type==="api");C.adapter.injectSystemNote(S,Jt({toolData:t.tools?.toolData,ownTools:b}))}else!q&&h>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(S,Vt());X=Buffer.from(JSON.stringify(S),"utf8")}}const ee=Gt({vault:P,toolData:t.tools?.toolData}),F=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;F&&(delete S.chatpanel,X=Buffer.from(JSON.stringify(S),"utf8"));const G={destination:String(n.headers["x-chatpanel-destination"]||F?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||F?.reach||"").trim(),run:Fr(n.headers["x-chatpanel-run"],F?.run)},D=yt(S?.model,t,C.kind,{destination:G.destination});if(G.destination&&(!D||D.id!==G.destination))return B?.commit(),s(o,404,{error:{message:`no destination "${G.destination}" is configured on this gateway`,type:"unknown_destination",known:kr(t).map(e=>e.id)}});B&&(B.meta={t:Date.now(),model:S?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:te,sanitized:se,narrowed:ce,detail:Ot(P,t.logDetail),redaction:q?"off":t.redaction.tier||"basic"});const fe=eo();if(fe&&D){const e=D.type==="api"?Ze(fe,{model:S?.model||"",endpoint:D.baseUrl||""}):oo(fe,D.agent||D.id)?Ze(fe,{model:S?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return B?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?Mr(D.baseUrl,t)?(B?.commit(),s(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ur(n,o,{...C,pathname:d,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:ee,trace:B},X,P):(B?.commit(),s(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ve=ke(n),Ue=Ve==="local"&&t.bridge?.openAgentLane?"token":Ve;if(Ue==="local")return B?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const He=Ht({...G.run||{},...G.reach?{reach:G.reach}:{}},Ue);return Lr(n,o,{...C,pathname:d,agentOverride:D?.agent,harness:ee,trace:B,run:Object.keys(He).length?He:null},S,P,t,oe)});return U.on("close",()=>{m?.stop("closed"),zo()}),U}function Fr(t,l){let c=l&&typeof l=="object"?l:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(p=>String(p).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const p=c.workspace;m.workspace={repo:String(p.repo).slice(0,400),projectId:String(p.projectId||"").slice(0,120),jobId:String(p.jobId||"").slice(0,120),...p.base?{base:String(p.base).slice(0,120)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),gr.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const p=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(_=>String(_).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),y=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(_=>String(_).slice(0,1024)).filter(Boolean).slice(0,32);(p.length||y.length)&&(m.sandbox={...p.length?{hosts:p}:{},...y.length?{write:y}:{}})}return Object.keys(m).length?m:null}let ye=null;async function Qn(t=Fe()){po();let l=null;try{l=await qt()}catch(k){throw k instanceof to&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const c=l?.policy||null;c&&(Ke(t,c),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Qt(globalThis,{allow:c?.egress?(k,{local:T})=>ro(c,k,{local:T}):null}),Ae();const m=Hr(t),p=co(t),y=Dt(t);m.on("error",k=>{k&&k.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${re()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${k?.message||k}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),xo(t,{childEnv:()=>br(t)}).then(k=>{ye=k}).catch(k=>console.log(` bridge : not supervised (${k?.message||k})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Tt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),tt()&&De(N,Ne()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&_e())}).catch(()=>{});const _=()=>{p?.stop(),y.stop(),ye?.stop(),m.close(()=>process.exit(0))};return process.on("SIGINT",_),process.on("SIGTERM",_),m}export{K as VERSION,Hr as createGateway,zr as joinUpstream,ze as parseAgentModel,Qn as start};
@@ -0,0 +1 @@
1
+ import a from"node:path";import{createSandbox as s}from"@chatpanel/bridge/src/sandbox.js";function n(){if(process.env.CHATPANEL_SRT_MODULE)return process.env.CHATPANEL_SRT_MODULE;try{return import.meta.resolve("@anthropic-ai/sandbox-runtime")}catch{return""}}function i(){const e=a.basename(process.execPath||"").toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}let r=null;function p({log:e=t=>console.warn(`[gateway] ${t}`)}={}){if(!r){const t=/^(off|0|false)$/i.test(String(process.env.CHATPANEL_SANDBOX||"")),o=n();r=s({config:{enabled:!t,mode:"none",extraHosts:[],extraWrite:[],extraDenyRead:[]},loadSrt:()=>o?import(o):Promise.reject(new Error("sandbox-runtime is not installed")),compiled:i(),loopback:[],log:e})}return r}function u(e){r=e}async function d(){r=null;const e=n();if(e)try{await(await import(e)).SandboxManager.reset()}catch{}}export{u as _setWorkerSandboxForTest,d as disposeWorkerSandbox,n as srtModuleUrl,p as workerSandbox};