@chatpanel/gateway 0.11.4 → 0.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
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": {
@@ -21,7 +21,7 @@
21
21
  "node": ">=18"
22
22
  },
23
23
  "dependencies": {
24
- "@chatpanel/bridge": "^0.13.3",
24
+ "@chatpanel/bridge": "^0.13.5",
25
25
  "@chatpanel/events": "^0.117.0",
26
26
  "@chatpanel/pii": "^0.8.0",
27
27
  "@huggingface/transformers": "^4.2.0",
@@ -1,3 +1,3 @@
1
- import U from"node:os";import P from"node:path";import{existsSync as F}from"node:fs";import{spawn as K,spawnSync as Y}from"node:child_process";import{resolveLaunch as q}from"./service.js";import{DEFAULT_BRIDGE_URL as x}from"./bridge.js";const C=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,M=[1e3,2e3,5e3,1e4,3e4],z=6e4,J=1200;function Q({home:r=U.homedir(),platform:o=process.platform,env:n=process.env}={}){return o==="win32"?[P.join(n.LOCALAPPDATA||P.join(r,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[P.join(r,".local","bin","chatpanel-bridge")]}function X(r,o){const n=String(r||"").split(".").map(e=>parseInt(e,10)),i=String(o||"").split(".").map(e=>parseInt(e,10));if(n.some(Number.isNaN)||i.some(Number.isNaN)||n.length<3||i.length<3)return 0;for(let e=0;e<3;e+=1)if(n[e]!==i[e])return n[e]>i[e]?1:-1;return 0}function j({managed:r=!0,cfgUrl:o="",healthy:n=null,standalone:i=null,embeddedVersion:e=null}={}){if(r===!1||r==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const g=String(o||x);if(!C.test(g))return{action:"off",why:`bridge.url ${g} is not on this machine; nothing to start here`};if(n)return{action:"adopt",why:`a bridge already answers at ${g}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const d=i?.version||null;return i?.path&&e&&X(d,e)>0?{action:"spawn-standalone",why:`the installed bridge (v${d}) is newer than the embedded one (v${e})`,path:i.path}:e?{action:"spawn-embedded",why:`starting the embedded bridge (v${e})${i?.path?` — the installed one is v${d||"?"}`:""}`}:i?.path?{action:"spawn-standalone",why:`starting the installed bridge${d?` (v${d})`:""}`,path:i.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function Z(r,{timeoutMs:o=J,fetchImpl:n=fetch}={}){const i=new AbortController,e=setTimeout(()=>i.abort(),o);try{const g=await n(`${String(r).replace(/\/$/,"")}/health`,{signal:i.signal});if(!g.ok)return null;const d=await g.json().catch(()=>null);return d&&d.ok!==!1?{version:d.version||null,managedBy:d.managedBy||null}:null}catch{return null}finally{clearTimeout(e)}}function V(r,o=[],{timeoutMs:n=8e3}={}){try{const i=Y(r,[...o,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),e=String(i.stdout||"").trim().split(`
2
- `).pop();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function W(){const{program:r,args:o}=q();return{program:r,args:[...o,"--bridge"]}}const tt=r=>C.exec(String(r||x))?.[3]||"4319";async function at(r,{log:o=a=>console.log(a),probe:n=Z,spawnImpl:i=K,version:e=V,candidates:g=Q(),exists:d=F,launch:H=W,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:r?.bridge?.managed,waitForSiblingMs:O=2500,now:A=Date.now,setTimer:k=setTimeout,setWatch:E=(a,t)=>{const h=setTimeout(a,t);return h.unref?.(),h},watchEveryMs:_=1e4}={}){const a=String(r?.bridge?.url||x).replace(/\/$/,""),t={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(s,u,c={})=>{Object.assign(t,{mode:s,why:u},c),o(` bridge : ${u}`)};let m=await n(a);if(!m&&b!==!1&&b!=="off"&&C.test(a)&&O>0){const s=A()+O;for(;!m&&A()<s;)await new Promise(u=>k(u,500)),m=await n(a)}const y=H(),D=b===!1||b==="off"||m?null:e(y.program,y.args),T=g.find(s=>d(s))||null,L=T&&!m?{path:T,version:e(T,[])}:null,v=j({managed:b,cfgUrl:a,healthy:m,standalone:L,embeddedVersion:D});if(v.action==="off")return h("off",v.why),N();const I=s=>s.action==="spawn-embedded"?{...y,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:s.version||D}:{program:s.path,args:[],env:{},mode:"standalone",version:L?.version||null};let l=v.action==="adopt"?null:I(v),R=0,w=null,B=0;const G=(s,u)=>{h("adopted",s,{version:u||null}),B=0;const c=async()=>{if(t.stopping||t.mode!=="adopted")return;const $=await n(a);if($){B=0,t.version=$.version||t.version,w=E(c,_);return}if(B+=1,B<2){w=E(c,Math.min(_,3e3));return}if(!l){const p=D||e(y.program,y.args),f=j({managed:b,cfgUrl:a,healthy:null,standalone:L,embeddedVersion:p});if(f.action==="off"){h("off",`the adopted bridge went away and ${f.why}`);return}l=I({...f,version:p})}o(` 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}),S()};w=E(c,_)},S=()=>{if(t.stopping)return;const s=i(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:tt(a)}});R=A(),t.child=s,t.pid=s.pid||null;const u=(c,$)=>c?.on("data",p=>{for(const f of String(p).split(`
3
- `))f.trim()&&o(`[bridge] ${f}`)});u(s.stdout,"out"),u(s.stderr,"err"),s.on("error",c=>o(`[bridge] could not start ${l.program}: ${c?.message||c}`)),s.on("exit",async(c,$)=>{if(t.child=null,t.pid=null,t.stopping)return;const p=await n(a);if(p){G(`a bridge already answers at ${a} (v${p.version||"?"}${p.managedBy?`, run by ${p.managedBy}`:""}) — ours stepped aside`,p.version);return}A()-R>z&&(t.backoff=0);const f=M[Math.min(t.backoff,M.length-1)];t.backoff+=1,t.restarts+=1,o(`[bridge] exited (${$||c}); restarting in ${f/1e3}s`),k(S,f)})};if(v.action==="adopt")return G(v.why,m.version),N();return h(l.mode,v.why,{version:l.version}),S(),N();function N(){return{status:()=>({mode:t.mode,version:t.version,pid:t.pid,restarts:t.restarts,why:t.why}),stop:()=>{if(t.stopping=!0,w&&(clearTimeout(w),w=null),t.child&&!t.child.killed)try{t.child.kill("SIGTERM")}catch{}}}}}export{X as compareVersions,W as embeddedLaunch,at as ensureBridge,j as planBridge,Z as probeBridge,Q as standaloneCandidates,V 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 G,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as C}from"./bridge.js";const I=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,M=[1e3,2e3,5e3,1e4,3e4],X=6e4,Z=1200;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||C);if(!I.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 W(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 V(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 tt(){const{program:d,args:i}=J();return{program:d,args:[...i,"--bridge"]}}const et=d=>I.exec(String(d||C))?.[3]||"4319";async function lt(d,{log:i=a=>console.log(a),probe:n=W,spawnImpl:o=q,version:t=V,candidates:p=G(),exists:u=Y,launch:j=tt,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:d?.bridge?.managed,waitForSiblingMs:O=2500,retire:F=Q,retireWaitMs:K=6e3,now:w=Date.now,setTimer:S=setTimeout,setWatch:T=(a,e)=>{const h=setTimeout(a,e);return h.unref?.(),h},watchEveryMs:N=1e4}={}){const a=String(d?.bridge?.url||C).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"&&I.test(a)&&O>0){const r=w()+O;for(;!v&&w()<r;)await new Promise(c=>S(c,500)),v=await n(a)}const B=j(),y=!(b!==!1&&b!=="off")||v&&v.managedBy?null:t(B.program,B.args),x=p.find(r=>u(r))||null,L=x&&!v?{path:x,version:t(x,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:L,embeddedVersion:y});if(f.action==="off")return h("off",f.why),E();const P=r=>r.action==="spawn-embedded"?{...B,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||y}:{program:r.path,args:[],env:{},mode:"standalone",version:L?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:P(f),R=0,$=null,_=0;const k=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const A=await n(a);if(A){_=0,e.version=A.version||e.version,$=T(s,N);return}if(_+=1,_<2){$=T(s,Math.min(N,3e3));return}if(!l){const g=y||t(B.program,B.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:L,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}),D()};$=T(s,N)},D=()=>{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:et(a)}});R=w(),e.child=r,e.pid=r.pid||null;const c=(s,A)=>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,A)=>{if(e.child=null,e.pid=null,e.stopping)return;const g=await n(a);if(g){k(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-R>X&&(e.backoff=0);const m=M[Math.min(e.backoff,M.length-1)];e.backoff+=1,e.restarts+=1,i(`[bridge] exited (${A||s}); restarting in ${m/1e3}s`),S(D,m)})};if(f.action==="adopt")return k(f.why,v.version),E();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=>S(s,500)),c=await n(a);return c?(k(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),E()):(l=P({action:"spawn-embedded",version:y}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${y})`,{version:y}),D(),E())}return h(l.mode,f.why,{version:l.version}),D(),E();function E(){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,tt as embeddedLaunch,lt as ensureBridge,U as planBridge,W as probeBridge,G as standaloneCandidates,V as versionOf};
package/src/server.js CHANGED
@@ -1,30 +1,30 @@
1
- import{createServer as gt}from"node:http";import{loadConfig as je}from"./config.js";import{startEntitlementRefresh as bt,maybeRevalidate as wt}from"./entitlement-refresh.js";import{redactSegments as we,segment as Me}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Re,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as _t,narrowSpecs as Ot,makeToolHarness as $t,placeholderToolNote as Et,placeholderNote as At,assertEndpointUrl as Pt,capRunOptions as xt,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as W,callerTrustOf as me,setPinnedExtensionIds as Dt,issuePairingCode as Ct,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as zt,applyPolicyToConfig as ze,managedSummary as le,PolicyLoadError as Lt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ce}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{streamBridgeChat as Ve,readBridgeToken as oe,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Je,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as He,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as _e,hasBackupSecret as Ue}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as Oe}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as $e}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as yo,openRecord as ho,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import bo from"node:zlib";import*as D from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as wo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as _o,DEFAULT_STT_MODEL as Ee,STT_DTYPES as Oo,isValidDtype as $o}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fe,TTS_VOICES as Eo,isKnownTtsModel as Ao,isValidCustomTtsId as Po,isKnownVoice as We,isValidVoiceId as Ke,DEFAULT_TTS_MODEL as Ze,DEFAULT_TTS_VOICE as X,TTS_DTYPES as xo,isValidTtsDtype as No,MAX_TTS_CHARS as Ye,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Qe,POCKET_VOICES as Do,DEFAULT_POCKET_VOICE as ye,isPocketVoice as he,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Co,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as Ae}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as ee,checkQuota as Ro,consume as zo,usage as Lo}from"./freegate.js";import{publicConfig as Xe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as re,configPath as te,bridgeAgentOptions as qe,PERMISSION_MODES as Jo}from"./configstore.js";import{resolveDestination as et,aggregateModelsAsync as Ho,listDestinations as Uo}from"./router.js";import{makeAccessEvent as tt}from"./observability.js";import{createPersistentAccessLog as Fo}from"./access-log-store.js";import{planQueries as Wo,multiSearch as Ko}from"./rrf.js";import*as Pe from"./openai.js";import*as ot from"./responses.js";import*as xe from"./anthropic.js";const K="0.11.4",O=await mo(),Q=new Set;function ge({ids:t=[]}={}){const i=O.lossless;if(!i||!Q.size)return;const d=JSON.stringify({newest:i.newest,size:i.size,ids:t.slice(0,50),at:Date.now()});for(const r of Q)try{r.write(`event: records
1
+ import{createServer as gt}from"node:http";import{loadConfig as je}from"./config.js";import{startEntitlementRefresh as bt,maybeRevalidate as wt}from"./entitlement-refresh.js";import{redactSegments as we,segment as Me}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Re,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as _t,narrowSpecs as Ot,makeToolHarness as $t,placeholderToolNote as Pt,placeholderNote as At,assertEndpointUrl as Et,capRunOptions as xt,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as H,callerTrustOf as me,setPinnedExtensionIds as Dt,issuePairingCode as Ct,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as zt,applyPolicyToConfig as ze,managedSummary as ce,PolicyLoadError as Lt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as re}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{streamBridgeChat as Ve,readBridgeToken as ee,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Je,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as He,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as _e,hasBackupSecret as Ue}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as Oe}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as $e}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as ho,openRecord as yo,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import bo from"node:zlib";import*as D from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as wo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as _o,DEFAULT_STT_MODEL as Pe,STT_DTYPES as Oo,isValidDtype as $o}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fe,TTS_VOICES as Po,isKnownTtsModel as Ao,isValidCustomTtsId as Eo,isKnownVoice as We,isValidVoiceId as Ke,DEFAULT_TTS_MODEL as Ze,DEFAULT_TTS_VOICE as X,TTS_DTYPES as xo,isValidTtsDtype as No,MAX_TTS_CHARS as Ye,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Qe,POCKET_VOICES as Do,DEFAULT_POCKET_VOICE as he,isPocketVoice as ye,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Co,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as Ae}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as te,checkQuota as Ro,consume as zo,usage as Lo}from"./freegate.js";import{publicConfig as Xe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as ne,configPath as oe,bridgeAgentOptions as qe,PERMISSION_MODES as Jo}from"./configstore.js";import{resolveDestination as et,aggregateModelsAsync as Ho,listDestinations as Uo}from"./router.js";import{makeAccessEvent as tt}from"./observability.js";import{createPersistentAccessLog as Fo}from"./access-log-store.js";import{planQueries as Wo,multiSearch as Ko}from"./rrf.js";import*as Ee from"./openai.js";import*as ot from"./responses.js";import*as xe from"./anthropic.js";const K="0.11.6",O=await mo(),Q=new Set;function ge({ids:t=[]}={}){const l=O.lossless;if(!l||!Q.size)return;const d=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const r of Q)try{r.write(`event: records
2
2
  data: ${d}
3
3
 
4
4
  `)}catch{Q.delete(r)}}setInterval(()=>{for(const t of Q)try{t.write(`: ping
5
5
 
6
- `)}catch{Q.delete(t)}},25e3).unref?.();const H=await Xt(),U=qt(),ne=to({key:Oe()}),se=oo({key:Oe()}),V=ro({key:Oe()}),C=eo({scorecards:ne,engines:se}),Ne=new Set,rt=(t,i)=>{for(const r of Ne)try{r({applied:t,by:i,revision:U.revision})}catch{}const d=JSON.stringify({revision:U.revision,applied:(t||[]).slice(0,50),by:i||"",at:Date.now()});for(const r of Q)try{r.write(`event: prefs
6
+ `)}catch{Q.delete(t)}},25e3).unref?.();const U=await Xt(),F=qt(),se=to({key:Oe()}),ae=oo({key:Oe()}),V=ro({key:Oe()}),C=eo({scorecards:se,engines:ae}),Ne=new Set,rt=(t,l)=>{for(const r of Ne)try{r({applied:t,by:l,revision:F.revision})}catch{}const d=JSON.stringify({revision:F.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const r of Q)try{r.write(`event: prefs
7
7
  data: ${d}
8
8
 
9
- `)}catch{Q.delete(r)}},Be=Fo(),nt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zo=16,Yo=/^mcp[_-]/i,st=t=>t&&t.function&&t.function.name||t&&t.name||"",Qo=t=>t&&t.function&&t.function.description||t&&t.description||"";function at(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Xo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>at(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return at(d[r].content);return""}const it=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function lt(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function qo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function er(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),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 ct=Date.now();function tr(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function or(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function rr(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${tr(d)}`)})}}}function dt(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",g=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function nr(t,i,d){return xe.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:xe,redactable:xe.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ot.matches(t)?{kind:"responses",adapter:ot,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Pe,redactable:Pe.matches(t),base:d.upstreams?.openai?.baseUrl}}function De(t,i){const d=String(t||"");if(nt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(nt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function ut(t,i){return De(t,i).agent}function sr(t,i){if(i!=="openai"||!t)return!1;const d=Pe.extractLatestToolResult(t);if(!d)return!1;const r=He(d.tool_call_id);return!!(r&&Je(r.gwId))}function ar(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function mt(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function Ce(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=D.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:D.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function pt(t){if(D.state()!=="off"){const d=D.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}}const i=mt(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ge(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function ir(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||it.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function yt(t,i,d,r){const o=Re(i.vault),u=r?r.clock():0;let c=u,g=!0;const w=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(i,{onText:E=>{w(),Se(i.id);const p=o.push(E);p&&t.write(d.sseDelta(p))},onToolRequest:({name:E,restoredArgs:p,toolId:z})=>{w(),Se(i.id);const x=o.flush();x&&t.write(d.sseDelta(x)),t.write(d.sseToolCalls([{id:z,name:E,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
9
+ `)}catch{Q.delete(r)}},Be=Fo(),nt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zo=16,Yo=/^mcp[_-]/i,st=t=>t&&t.function&&t.function.name||t&&t.name||"",Qo=t=>t&&t.function&&t.function.description||t&&t.description||"";function at(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Xo(t,l){if(!t)return"";if(l==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>at(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return at(d[r].content);return""}const it=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function lt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function qo(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 ct=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 or(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function rr(t){const l=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-l);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${tr(d)}`)})}}}function dt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",g=r.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function nr(t,l,d){return xe.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:xe,redactable:xe.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ot.matches(t)?{kind:"responses",adapter:ot,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.openai?.baseUrl}}function De(t,l){const d=String(t||"");if(nt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(nt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:l.bridge.agent,agentModel:""}}function ut(t,l){return De(t,l).agent}function sr(t,l){if(l!=="openai"||!t)return!1;const d=Ee.extractLatestToolResult(t);if(!d)return!1;const r=He(d.tool_call_id);return!!(r&&Je(r.gwId))}function ar(t,l){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(l.port)}catch{return!1}}async function v(t,l){const d=[];let r=0;for await(const o of t){if(r+=o.length,l&&r>l){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function mt(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Ce(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 r=D.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:D.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function pt(t){if(D.state()!=="off"){const d=D.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}}const l=mt(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ge(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:r.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function ir(t,l){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||it.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function ht(t,l,d,r){const o=Re(l.vault),u=r?r.clock():0;let c=u,g=!0;const w=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(l,{onText:P=>{w(),Se(l.id);const p=o.push(P);p&&t.write(d.sseDelta(p))},onToolRequest:({name:P,restoredArgs:p,toolId:z})=>{w(),Se(l.id);const x=o.flush();x&&t.write(d.sseDelta(x)),t.write(d.sseToolCalls([{id:z,name:P,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const P=o.flush();P&&t.write(d.sseDelta(P)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(l.id),r?.commit()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
10
10
 
11
- `),t.end(),pe(i.id),r?.commit()}})}async function lr(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,g,w,E,p,z=null,x=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:L}=De(c?.model,w),R=qe(w,{...L?{model:L}:{},...u||{}}),N=oe(w.bridge.token),$=ve(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:_t(w.redaction,E),entities:[]},J=await ce(w),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:z});let Z;try{Z=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(q){return pe(T.id),x?.commit(),s(i,502,{error:{message:`bridge: ${q.message}`,type:"bridge_error"}})}return T.reader=Z.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write($.sseHead()),yt(i,T,$,x)}async function cr(t,i,d,r,o=null){Se(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Ft(i,d),o&&o.lap("redact",c)}catch(c){return pe(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),yt(t,i,u,o)}async function dr(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:w,run:E=null},p,z,x,I){if(!o)return w?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=He(e.tool_call_id),l=a&&Je(a.gwId);if(l)return cr(i,l,e.content,p?.model,w)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return lr(t,i,{kind:d,adapter:r,agent:c||ut(p?.model,x),run:E},p,z,x,I,n,g,w)}const{messages:Y,system:L}=r.toTurn(p),R=c||ut(p?.model,x),N=p?.stream===!0,$=ve(d,p?.model||R),j=oe(x.bridge.token),J=new AbortController;i.on("close",()=>{i.writableFinished||J.abort()});const{agentModel:T}=De(p?.model,x),Z={bridgeUrl:await ce(x),agent:R,token:j,messages:Y,system:L,signal:J.signal,options:qe(x,{...T?{model:T}:{},...E||{}})};if(!N)try{let e="";const n=w?w.clock():0;await Ve(Z,m=>{e+=m}),w&&w.lap("upstream",n);const a=w?w.clock():0,l=$.full(Tt(e,z));return w&&w.lap("restore",a),i.writeHead(200,{"content-type":$.contentType}),i.end(l),w?.commit()}catch(e){return w?.commit(),s(i,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write($.sseHead());const q=Re(z),ae=w?w.clock():0;let ie=ae;try{let e=!0;await Ve(Z,a=>{w&&e&&(w.lap("upstream",ae),ie=w.clock(),e=!1);const l=q.push(a);l&&i.write($.sseDelta(l))},$.sseActivity?a=>{try{i.write($.sseActivity(vt(a,z)))}catch{}}:null);const n=q.flush();n&&i.write($.sseDelta(n)),i.write($.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
11
+ `),t.end(),pe(l.id),r?.commit()}})}async function lr(t,l,{kind:d,adapter:r,agent:o,run:u=null},c,g,w,P,p,z=null,x=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:L}=De(c?.model,w),R=qe(w,{...L?{model:L}:{},...u||{}}),N=ee(w.bridge.token),$=ve(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:_t(w.redaction,P),entities:[]},J=await re(w),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:z});let Z;try{Z=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(q){return pe(T.id),x?.commit(),s(l,502,{error:{message:`bridge: ${q.message}`,type:"bridge_error"}})}return T.reader=Z.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead()),ht(l,T,$,x)}async function cr(t,l,d,r,o=null){Se(l.id),l.rounds=(l.rounds||0)+1;try{const c=o?o.clock():0;await Ft(l,d),o&&o.lap("redact",c)}catch(c){return pe(l.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ht(t,l,u,o)}async function dr(t,l,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:w,run:P=null},p,z,x,I){if(!o)return w?.commit(),s(l,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=He(e.tool_call_id),i=a&&Je(a.gwId);if(i)return cr(l,i,e.content,p?.model,w)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return lr(t,l,{kind:d,adapter:r,agent:c||ut(p?.model,x),run:P},p,z,x,I,n,g,w)}const{messages:Y,system:L}=r.toTurn(p),R=c||ut(p?.model,x),N=p?.stream===!0,$=ve(d,p?.model||R),j=ee(x.bridge.token),J=new AbortController;l.on("close",()=>{l.writableFinished||J.abort()});const{agentModel:T}=De(p?.model,x),Z={bridgeUrl:await re(x),agent:R,token:j,messages:Y,system:L,signal:J.signal,options:qe(x,{...T?{model:T}:{},...P||{}})};if(!N)try{let e="";const n=w?w.clock():0;await Ve(Z,m=>{e+=m}),w&&w.lap("upstream",n);const a=w?w.clock():0,i=$.full(Tt(e,z));return w&&w.lap("restore",a),l.writeHead(200,{"content-type":$.contentType}),l.end(i),w?.commit()}catch(e){return w?.commit(),s(l,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead());const q=Re(z),ie=w?w.clock():0;let le=ie;try{let e=!0;await Ve(Z,a=>{w&&e&&(w.lap("upstream",ie),le=w.clock(),e=!1);const i=q.push(a);i&&l.write($.sseDelta(i))},$.sseActivity?a=>{try{l.write($.sseActivity(vt(a,z)))}catch{}}:null);const n=q.flush();n&&l.write($.sseDelta(n)),l.write($.sseTail())}catch(e){l.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
12
12
 
13
- `)}w&&w.lap("stream",ie),i.end(),w?.commit()}function ur(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const mr=9e4;function pr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),w=Math.min(t.length-1,g+1),E=c-g;o[u]=t[g]*(1-E)+t[w]*E}return o}const yr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ie(t,i){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(i?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function hr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:w,harness:E,trace:p},z,x){let I;const Y=p?p.clock():0;try{const $=ir(t.headers,c);g&&(w==="anthropic"?($["x-api-key"]=g,delete $.authorization):$.authorization=`Bearer ${g}`);const j=Pt(ur(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:$,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch($){return p?.commit(),s(i,502,{error:`upstream fetch failed: ${$.message}`})}const L=I.headers.get("content-type")||"",R={};if(I.headers.forEach(($,j)=>{it.has(j.toLowerCase())||(R[j]=$)}),L.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const $=p?p.clock():0;i.writeHead(I.status,R);const j=r==="openai"?St(I.body,i,x,E):kt(I.body,i,x);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",$),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),x&&L.includes("application/json"))try{const $=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),x,E);return p&&p.lap("restore",$),i.writeHead(I.status,{...R,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}i.writeHead(I.status,R),i.end(N),p?.commit()}function fr(t=je()){Dt(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!lt(r.headers.host))return s(o,403,{error:"loopback only"});if(!qo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&er(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return W(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!W(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ct();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${me(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${me(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=oe(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=me(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:K})}if(c==="/audit"&&r.method==="GET")return W(r)?s(o,200,Mt(t,{version:K,startedAt:ct,managed:le()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!W(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!W(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!W(r))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")&&r.method==="POST"&&!W(r))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")&&r.method==="POST"&&!W(r))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"))&&!W(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!W(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...le()?{managed:le()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...be?{bridge:be.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ee,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ze,voice:t.tts?.voice||X,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){wt(t);const e=await ee(t.pro?.entitlementToken),n=await pt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...le()?{managed:le()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Ce(t),pro:{unlocked:e},usage:Lo(t),uptimeSeconds:Math.floor((Date.now()-ct)/1e3),update:lo(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:U.revision,stamps:U.stamps()}):s(o,200,{ok:!0,revision:U.revision,sections:U.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.put(e.sections||{},{by:e.by||""});return n.applied.length&&rt(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?U.remove(e):!1;return n&&rt([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
13
+ `)}w&&w.lap("stream",le),l.end(),w?.commit()}function ur(t,l,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(l||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+l+d:r+l+d}const mr=9e4;function pr(t,l,d){if(l===d)return t;const r=l/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),w=Math.min(t.length-1,g+1),P=c-g;o[u]=t[g]*(1-P)+t[w]*P}return o}const hr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ie(t,l){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function yr(t,l,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:w,harness:P,trace:p},z,x){let I;const Y=p?p.clock():0;try{const $=ir(t.headers,c);g&&(w==="anthropic"?($["x-api-key"]=g,delete $.authorization):$.authorization=`Bearer ${g}`);const j=Et(ur(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:$,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch($){return p?.commit(),s(l,502,{error:`upstream fetch failed: ${$.message}`})}const L=I.headers.get("content-type")||"",R={};if(I.headers.forEach(($,j)=>{it.has(j.toLowerCase())||(R[j]=$)}),L.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const $=p?p.clock():0;l.writeHead(I.status,R);const j=r==="openai"?St(I.body,l,x,P):kt(I.body,l,x);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",$),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),x&&L.includes("application/json"))try{const $=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),x,P);return p&&p.lap("restore",$),l.writeHead(I.status,{...R,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}l.writeHead(I.status,R),l.end(N),p?.commit()}function fr(t=je()){Dt(t.allowedExtensionIds||[]);const l=[],d=r=>{l.push(r),l.length>50&&l.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!lt(r.headers.host))return s(o,403,{error:"loopback only"});if(!qo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&er(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return H(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!H(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ct();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${me(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${me(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ee(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=me(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:K})}if(c==="/audit"&&r.method==="GET")return H(r)?s(o,200,Mt(t,{version:K,startedAt:ct,managed:ce()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!H(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!H(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!H(r))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")&&r.method==="POST"&&!H(r))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")&&r.method==="POST"&&!H(r))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"))&&!H(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!H(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ce()?{managed:ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...be?{bridge:be.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Pe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ze,voice:t.tts?.voice||X,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){wt(t);const e=await te(t.pro?.entitlementToken),n=await pt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...ce()?{managed:ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Ce(t),pro:{unlocked:e},usage:Lo(t),uptimeSeconds:Math.floor((Date.now()-ct)/1e3),update:lo(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:F.revision,stamps:F.stamps()}):s(o,200,{ok:!0,revision:F.revision,sections:F.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=F.put(e.sections||{},{by:e.by||""});return n.applied.length&&rt(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?F.remove(e):!1;return n&&rt([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.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:U.revision,stamps:U.stamps()});const n=l=>e({type:"changed",...l});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
15
+ `);e({type:"hello",revision:F.revision,stamps:F.stamps()});const n=i=>e({type:"changed",...i});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
16
16
 
17
- `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,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(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",m=e[4]||"",b=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const y=V.get(n);if(!y)return b();const k=y.jobs.find(f=>f.id===l);if(!k)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const h={cfg:t,prefsStore:U,scorecards:ne,engines:se};if(m==="/applications"&&r.method==="GET"){const f=await no(k,{...h,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${l} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await so(k,{...h,record:y,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let P=null;for(const F of M.events)F.type==="job.updated"?P=V.updateJob(n,l,F.job,{by:F.by||_}):P=V.append(n,[F]);return s(o,200,{ok:!0,project:P,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const y=V.get(n,{events:u.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):b()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(y.by||"person").slice(0,80),h=a==="/events"?V.append(n,y.events||[]):l?V.updateJob(n,l,y.patch||y,{by:k}):V.postJob(n,y.job||y,{by:k});return s(o,200,{ok:!0,project:h})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return b();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
17
+ `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,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(c);if(e){const n=e[1],a=e[2]||"",i=e[3]||"",m=e[4]||"",b=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return b();const k=h.jobs.find(f=>f.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const y={cfg:t,prefsStore:F,scorecards:se,engines:ae};if(m==="/applications"&&r.method==="GET"){const f=await no(k,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await so(k,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let E=null;for(const W of M.events)W.type==="job.updated"?E=V.updateJob(n,i,W.job,{by:W.by||_}):E=V.append(n,[W]);return s(o,200,{ok:!0,project:E,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):b()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):i?V.updateJob(n,i,h.patch||h,{by:k}):V.postJob(n,h.job||h,{by:k});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return b();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
18
18
 
19
- `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:k}});const h=V.watch(n,_=>{_.seq>k&&(k=_.seq,y(_))});for(const _ of V.eventsSince(n,k))k=_.seq,y(_);const f=setInterval(()=>{try{o.write(`: keep
19
+ `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:k}});const y=V.watch(n,_=>{_.seq>k&&(k=_.seq,h(_))});for(const _ of V.eventsSince(n,k))k=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
20
20
 
21
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),h()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:ne.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await ne.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await ne.append({agentId:n,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 se.fromRating(ne.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:se.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await se.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||or(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await se.append({...a,engine:l,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.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 n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=C.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=C.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):C.claim(n,{client:l.client});return s(o,200,{ok:!0,run:m})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(l.by||"person").slice(0,40),b=a==="/answer"?C.answer(n,{threadId:l.threadId,text:l.text,by:m}):a==="/decide"?C.decide(n,{postId:l.postId,status:l.status,by:m}):C.post(n,{threadId:l.threadId,text:l.text,by:m,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:b})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=h=>o.write(`data: ${JSON.stringify(h)}
21
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await se.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=await se.append({agentId:n,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 ae.fromRating(se.chains.get(n)||[],{...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/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ae.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ae.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||or(n);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await ae.append({...a,engine:i,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.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 n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const i=C.get(n,{events:u.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const i=C.stop(n);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):C.claim(n,{client:i.client});return s(o,200,{ok:!0,run:m})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{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")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(i.by||"person").slice(0,40),b=a==="/answer"?C.answer(n,{threadId:i.threadId,text:i.text,by:m}):a==="/decide"?C.decide(n,{postId:i.postId,status:i.status,by:m}):C.post(n,{threadId:i.threadId,text:i.text,by:m,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:b})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,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"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=y=>o.write(`data: ${JSON.stringify(y)}
22
22
 
23
- `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let b=Number.isFinite(m)?m:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:b}});const y=C.watch(n,h=>{h.seq==null?l(h):h.seq>b&&(b=h.seq,l(h))});for(const h of C.eventsSince(n,b))b=h.seq,l(h);const k=setInterval(()=>{try{o.write(`: keep-alive
23
+ `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let b=Number.isFinite(m)?m:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:b}});const h=C.watch(n,y=>{y.seq==null?i(y):y.seq>b&&(b=y.seq,i(y))});for(const y of C.eventsSince(n,b))b=y.seq,i(y);const k=setInterval(()=>{try{o.write(`: keep-alive
24
24
 
25
- `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:H.size,memories:H.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.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:H.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.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:n.action,record:n.record,replaced:n.replaces||null,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=H.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:H.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:H.clear(),size:H.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=O.clear();return s(o,200,{ok:!0,dropped:e,size:O.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.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:O.size,newest:O.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Wo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),b=await Ko(a,k=>O.search(k,{limit:m,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=l.type?b:[...b.filter(k=>k.type==="brief"),...b.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:O.size,newest:O.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:O.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:O.size,newest:O.newest,bytes:O.bytes,lossless:O.lossless?{records:O.lossless.size,newest:O.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:O.size,bytes:O.bytes,newest:O.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(tt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),m=[];let b=0;const y={upserts:[],removes:[]},k=h=>{if(!h||h.deletedAt){h?.id&&y.removes.push(h.id);return}try{const f=po(h);f&&y.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const h=e.upsert(n.records,{host:a,at:l});m.push(...h);for(const f of n.records)h.includes(f?.id)&&k(f)}if(Array.isArray(n.entries)){const h=_e(),f=h?fo((P,F)=>yo(h,{salt:P,iterations:F})):null,_=async P=>{if(!f||!P.blob)return null;const F=await f(P.blob),de=P.blob.compression&&P.blob.compression!=="none"?go(bo,P.blob.compression):null;return ho(P.blob,F,{codec:de})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),b+=M.sealed;for(const P of M.written)k(e.get(P))}return(y.upserts.length||y.removes.length)&&O.bulk(y),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:b,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=O.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:U.revision})}
25
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:U.size,memories:U.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.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:U.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.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:n.action,record:n.record,replaced:n.replaces||null,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=U.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:U.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:U.clear(),size:U.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=O.clear();return s(o,200,{ok:!0,dropped:e,size:O.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.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:O.size,newest:O.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Wo(n,{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},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),b=await Ko(a,k=>O.search(k,{limit:m,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?b:[...b.filter(k=>k.type==="brief"),...b.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:O.size,newest:O.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"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:O.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:O.size,newest:O.newest,bytes:O.bytes,lossless:O.lossless?{records:O.lossless.size,newest:O.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:O.size,bytes:O.bytes,newest:O.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(tt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),i=Number(n.at)||Date.now(),m=[];let b=0;const h={upserts:[],removes:[]},k=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=po(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:i});m.push(...y);for(const f of n.records)y.includes(f?.id)&&k(f)}if(Array.isArray(n.entries)){const y=_e(),f=y?fo((E,W)=>ho(y,{salt:E,iterations:W})):null,_=async E=>{if(!f||!E.blob)return null;const W=await f(E.blob),de=E.blob.compression&&E.blob.compression!=="none"?go(bo,E.blob.compression):null;return yo(E.blob,W,{codec:de})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),b+=M.sealed;for(const E of M.written)k(e.get(E))}return(h.upserts.length||h.removes.length)&&O.bulk(h),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:b,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=O.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:F.revision})}
27
27
 
28
- `),Q.add(o),r.on("close",()=>Q.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...O.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=O.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});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"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ue()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await $e(O,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await $e(O,_e());return e.ok&&e.whole&&ge(),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(r.method==="GET"){const e=await pt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),D.state()!=="off"){if(!D.isReady()){const n=D.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await D.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=mt(t);if(!e){const n=D.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:D.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ce(t)});try{let n=e;const a=await ee(t.pro?.entitlementToken);await Te(t);const l=await we([Me(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dt(l.vault,"types")||[],detector:Ce(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=D.health().model||t.ner?.model||null,n=wo.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{re(t,te())}catch{}return D.setModel(n,{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:n,state:D.state(),progress:D.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Ee,n=vo.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Oo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||_o(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&$o(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{re(t,te())}catch{}return A.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Qe(Ae()),n=Ae(),a=Fe.find(m=>m.id===e)||null,l=Fe.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(m=>m.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:l,voice:t.tts?.voice||(fe(e)==="pocket-tts"?ye:X),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Do).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Eo.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:xo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Ao(n)||Po(n)))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 m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):he(a)||We(a)&&Ke(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ze,voice:X,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),b=G.parseCustomVoice(t.tts.voice||""),y=!!(b&&G.getVoice(b));if(m&&!y)if(fe(n)==="pocket-tts")t.tts.voice=ye;else{const h=G.listVoices();t.tts.voice=h.length?`custom:${h[0].id}`:""}else!m&&y&&(t.tts.voice=X);const k=fe(n)==="pocket-tts";k&&!G.parseCustomVoice(t.tts.voice||"")&&!he(t.tts.voice)&&(t.tts.voice=ye),!k&&he(t.tts.voice)&&(t.tts.voice=X)}l&&(t.tts.dtype=l==="auto"?null:l);try{re(t,te())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!G.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(l,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.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(!n)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(!B.isReady()){const f=B.download({onLog:P=>console.log(P)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(P=>P),new Promise(P=>setTimeout(()=>P(_),mr))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),b=await B.embed(m);let y=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(y=await f.encodeVoice(pr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const k=l?G.replaceVoice(l,{vec:b,pocket:y}):G.saveVoice({name:n,vec:b,pocket:y}),h=l&&n&&n!==k.name?G.renameVoice(l,n):k;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${h.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...k,...h,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:X;try{re(t,te())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.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 v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ye)return s(o,413,{error:{message:`text too long (max ${Ye} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Co(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,b=m||(l?l.voice:t.tts?.voice||X);if(l&&!jo(b))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ue,contentType:ht,redacted:ft}=await Io({dest:l,text:n,voice:b,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ee(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":ht,"Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(ft)}),o.end(ue)}if(!await S.ready({onLog:ue=>console.log(ue),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Qe(Ae()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const h=Mo({requested:m,configured:b,engine:S,voices:G,isPocketVoice:he,isKnownVoice:We,isValidVoiceId:Ke,defaultVoice:X,defaultPocketVoice:ye});if(!h.ok)return s(o,h.status,{error:{message:h.message,type:h.type}});const{voice:f,customId:_,speakerEmbedding:M}=h,P=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),F=S.sampleRate(),de=y==="pcm"?Buffer.from(new Float32Array(P).buffer):S.toWav(P,F);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(F),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(de)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.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 v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Ee,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.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 n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.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"&&r.method==="GET"){const a=A.getSession(n);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 l=f=>o.write(`data: ${JSON.stringify(f)}
28
+ `),Q.add(o),r.on("close",()=>Q.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...O.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=O.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});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"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ue()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await $e(O,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await $e(O,_e());return e.ok&&e.whole&&ge(),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(r.method==="GET"){const e=await pt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),D.state()!=="off"){if(!D.isReady()){const n=D.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const i=await D.detect(a);return s(o,200,{entities:i})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=mt(t);if(!e){const n=D.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:D.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ce(t)});try{let n=e;const a=await te(t.pro?.entitlementToken);await Te(t);const i=await we([Me(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dt(i.vault,"types")||[],detector:Ce(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=D.health().model||t.ner?.model||null,n=wo.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{ne(t,oe())}catch{}return D.setModel(n,{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:n,state:D.state(),progress:D.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Pe,n=vo.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Oo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||_o(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&$o(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{ne(t,oe())}catch{}return A.setModel(n,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Qe(Ae()),n=Ae(),a=Fe.find(m=>m.id===e)||null,i=Fe.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(m=>m.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:i,voice:t.tts?.voice||(fe(e)==="pocket-tts"?he:X),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Do).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Po.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:xo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Ao(n)||Eo(n)))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 m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):ye(a)||We(a)&&Ke(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ze,voice:X,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),b=G.parseCustomVoice(t.tts.voice||""),h=!!(b&&G.getVoice(b));if(m&&!h)if(fe(n)==="pocket-tts")t.tts.voice=he;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=X);const k=fe(n)==="pocket-tts";k&&!G.parseCustomVoice(t.tts.voice||"")&&!ye(t.tts.voice)&&(t.tts.voice=he),!k&&ye(t.tts.voice)&&(t.tts.voice=X)}i&&(t.tts.dtype=i==="auto"?null:i);try{ne(t,oe())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),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:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=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(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(i,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.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(!n)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(!B.isReady()){const f=B.download({onLog:E=>console.log(E)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(E=>E),new Promise(E=>setTimeout(()=>E(_),mr))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),b=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(pr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const k=i?G.replaceVoice(i,{vec:b,pocket:h}):G.saveVoice({name:n,vec:b,pocket:h}),y=i&&n&&n!==k.name?G.renameVoice(i,n):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${y.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:X;try{ne(t,oe())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.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 v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ye)return s(o,413,{error:{message:`text too long (max ${Ye} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Co(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,b=m||(i?i.voice:t.tts?.voice||X);if(i&&!jo(b))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:ue,contentType:yt,redacted:ft}=await Io({dest:i,text:n,voice:b,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":yt,"Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(ft)}),o.end(ue)}if(!await S.ready({onLog:ue=>console.log(ue),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Qe(Ae()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=Mo({requested:m,configured:b,engine:S,voices:G,isPocketVoice:ye,isKnownVoice:We,isValidVoiceId:Ke,defaultVoice:X,defaultPocketVoice:he});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:_,speakerEmbedding:M}=y,E=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),W=S.sampleRate(),de=h==="pcm"?Buffer.from(new Float32Array(E).buffer):S.toWav(E,W);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(de)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.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 v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Pe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.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 n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.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"&&r.method==="GET"){const a=A.getSession(n);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=f=>o.write(`data: ${JSON.stringify(f)}
29
29
 
30
- `),m=a.redact?await ee(t.pro?.entitlementToken):!0,b=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await we([Me(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};l({type:"state",state:A.state()});const y=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){l({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){l({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...B.progress()||{}});return}}l({type:"state",state:f}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const h=A.subscribe(n,f=>{k=k.then(async()=>{l(await b(f)),f.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(y),h?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await ee(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),ze(t);try{re(t,te())}catch(b){return s(o,500,{error:`could not persist config: ${b.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=D.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&D.setModel(t.ner.model,{onLog:b=>console.log(b)}).then(b=>{b&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await ee(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:m}))}if(r.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 n=oe(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ie(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.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 n=await ce(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=oe(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}${Ie(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:m?.skill||null}):s(o,l.status,{error:{message:m?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),n=decodeURIComponent(e[1]),a=e[2];if(!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const l=await ce(t);if(!l)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const m=oe(t.bridge?.token);try{const b=await fetch(`${l}/skills/${encodeURIComponent(n)}/file/${a}${Ie(u,t)}`,{headers:{Accept:"application/json",...m?{Authorization:`Bearer ${m}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await b.json().catch(()=>({}));return b.ok?s(o,200,y):s(o,b.status,{error:{message:y?.error||`bridge ${b.status}`,type:"bridge_error"}})}catch(b){return s(o,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Ho(t));if(yr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=nr(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let E=null,p=null,z=w,x=0,I=0,Y=0,L=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?rr(d):null;if(g.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&sr(p,g.kind))z=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const h=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zo,f=e.narrowAll?null:M=>!Yo.test(st(M)),_=p.tools.length;p.tools=Ot(p.tools,Xo(p,g.kind),{cap:h,keep:f,name:st,description:Qo}),Y=_-p.tools.length}R=await ee(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});L=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&W(r),L||await Te(t);const a=L?[]:g.adapter.collectSegments(p,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const m=N?N.clock():0,{vault:b,count:y,sanitized:k}=L?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:l.signal,isPro:R,onEgress:h=>Be.push(tt({ts:Date.now(),client:"redaction",tool:`detect:${h.backend}@${h.host||"local"}`,ok:h.ok,ms:h.ms,error:h.error}))});if(N&&N.lap("redact",m),E=b,x=y,I=k||0,!R&&y>0){zo(t,R);try{re(t,te())}catch{}}if(!L&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const h=et(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(h&&h.type==="api");g.adapter.injectSystemNote(p,Et({toolData:t.tools?.toolData,ownTools:f}))}else!L&&y>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,At());z=Buffer.from(JSON.stringify(p),"utf8")}}const $=$t({vault:E,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,z=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:gr(r.headers["x-chatpanel-run"],j?.run)},T=et(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Uo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:x,sanitized:I,narrowed:Y,detail:dt(E,t.logDetail),redaction:L?"off":t.redaction.tier||"basic"});const Z=zt();if(Z&&T){const e=T.type==="api"?Le(Z,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(Z,T.agent||T.id)?Le(Z,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?ar(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):hr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:$,trace:N},z,E):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const q=me(r),ae=q==="local"&&t.bridge?.openAgentLane?"token":q;if(ae==="local")return N?.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 ie=xt({...J.run||{},...J.reach?{reach:J.reach}:{}},ae);return dr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:$,trace:N,run:Object.keys(ie).length?ie:null},p,E,t,R)})}function gr(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(r.workingDir=d.workingDir.trim().slice(0,1024)),Jo.includes(d.permissionMode)&&d.permissionMode!=="default"&&(r.permissionMode=d.permissionMode),Object.keys(r).length?r:null}let be=null;async function dn(t=je()){Zt();let i=null;try{i=await Rt()}catch(g){throw g instanceof Lt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=i?.policy||null;d&&(ze(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:w})=>Vt(d,g,{local:w}):null}),ke();const r=fr(t),o=Kt(t),u=bt(t);r.on("error",g=>{g&&g.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 ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.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"),ao(t).then(g=>{be=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),lt(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.`)}),Ue()&&$e(O,_e()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),be?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,fr as createGateway,ur as joinUpstream,De as parseAgentModel,dn as start};
30
+ `),m=a.redact?await te(t.pro?.entitlementToken):!0,b=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await we([Me(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};i({type:"state",state:A.state()});const h=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){i({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...B.progress()||{}});return}}i({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let k=Promise.resolve();const y=A.subscribe(n,f=>{k=k.then(async()=>{i(await b(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...l].reverse()});if(c==="/config"&&r.method==="GET"){const e=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),ze(t);try{ne(t,oe())}catch(b){return s(o,500,{error:`could not persist config: ${b.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",i=D.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&D.setModel(t.ner.model,{onLog:b=>console.log(b)}).then(b=>{b&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ie(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},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(r.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 n=await re(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ee(t.bridge?.token);try{const i=await fetch(`${n}/skills/${encodeURIComponent(e)}${Ie(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:m?.skill||null}):s(o,i.status,{error:{message:m?.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(!H(r))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(c==="/channels"&&r.method==="GET"||c!=="/channels"&&r.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${c}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),m=await i.json().catch(()=>({}));return s(o,i.status,m)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),n=decodeURIComponent(e[1]),a=e[2];if(!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await re(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const m=ee(t.bridge?.token);try{const b=await fetch(`${i}/skills/${encodeURIComponent(n)}/file/${a}${Ie(u,t)}`,{headers:{Accept:"application/json",...m?{Authorization:`Bearer ${m}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await b.json().catch(()=>({}));return b.ok?s(o,200,h):s(o,b.status,{error:{message:h?.error||`bridge ${b.status}`,type:"bridge_error"}})}catch(b){return s(o,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Ho(t));if(hr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=nr(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let P=null,p=null,z=w,x=0,I=0,Y=0,L=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?rr(d):null;if(g.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&sr(p,g.kind))z=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zo,f=e.narrowAll?null:M=>!Yo.test(st(M)),_=p.tools.length;p.tools=Ot(p.tools,Xo(p,g.kind),{cap:y,keep:f,name:st,description:Qo}),Y=_-p.tools.length}R=await te(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});L=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(r),L||await Te(t);const a=L?[]:g.adapter.collectSegments(p,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const m=N?N.clock():0,{vault:b,count:h,sanitized:k}=L?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:i.signal,isPro:R,onEgress:y=>Be.push(tt({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),P=b,x=h,I=k||0,!R&&h>0){zo(t,R);try{ne(t,oe())}catch{}}if(!L&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=et(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Pt({toolData:t.tools?.toolData,ownTools:f}))}else!L&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,At());z=Buffer.from(JSON.stringify(p),"utf8")}}const $=$t({vault:P,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,z=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:gr(r.headers["x-chatpanel-run"],j?.run)},T=et(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Uo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:x,sanitized:I,narrowed:Y,detail:dt(P,t.logDetail),redaction:L?"off":t.redaction.tier||"basic"});const Z=zt();if(Z&&T){const e=T.type==="api"?Le(Z,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(Z,T.agent||T.id)?Le(Z,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?ar(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):yr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:$,trace:N},z,P):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const q=me(r),ie=q==="local"&&t.bridge?.openAgentLane?"token":q;if(ie==="local")return N?.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 le=xt({...J.run||{},...J.reach?{reach:J.reach}:{}},ie);return dr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:$,trace:N,run:Object.keys(le).length?le:null},p,P,t,R)})}function gr(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 r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(r.workingDir=d.workingDir.trim().slice(0,1024)),Jo.includes(d.permissionMode)&&d.permissionMode!=="default"&&(r.permissionMode=d.permissionMode),Object.keys(r).length?r:null}let be=null;async function dn(t=je()){Zt();let l=null;try{l=await Rt()}catch(g){throw g instanceof Lt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=l?.policy||null;d&&(ze(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:w})=>Vt(d,g,{local:w}):null}),ke();const r=fr(t),o=Kt(t),u=bt(t);r.on("error",g=>{g&&g.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 ${oe()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.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"),ao(t).then(g=>{be=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),lt(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.`)}),Ue()&&$e(O,_e()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),be?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,fr as createGateway,ur as joinUpstream,De as parseAgentModel,dn as start};
package/src/service.js CHANGED
@@ -1,12 +1,12 @@
1
- import p from"node:os";import n from"node:path";import{mkdirSync as d,writeFileSync as w,rmSync as k,existsSync as i}from"node:fs";import{spawnSync as I,spawn as y}from"node:child_process";const u="net.chatpanel.gateway",E="ChatPanel Privacy Gateway";function h(){const t=process.execPath,r=n.basename(t).toLowerCase();return(r.startsWith("node")||r.startsWith("bun"))&&process.argv[1]?{program:t,args:[n.resolve(process.argv[1])]}:{program:t,args:[]}}function j(){const t=n.join(p.homedir(),".chatpanel");return d(t,{recursive:!0}),{out:n.join(t,"gateway.log"),err:n.join(t,"gateway.err.log")}}function e(t,r,s={}){return I(t,r,{encoding:"utf8",...s})}const f=()=>n.join(p.homedir(),"Library","LaunchAgents",`${u}.plist`);function L(){const{program:t,args:r}=h(),{out:s,err:a}=j(),c=[t,...r].map(b=>` <string>${b}</string>`).join(`
2
- `),l=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import u from"node:os";import n from"node:path";import{mkdirSync as d,writeFileSync as y,rmSync as f,existsSync as i}from"node:fs";import{spawnSync as E,spawn as $}from"node:child_process";const p="net.chatpanel.gateway",I="ChatPanel Privacy Gateway";function v(){const e=process.execPath,t=n.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[n.resolve(process.argv[1])]}:{program:e,args:[]}}function j(){const e=n.join(u.homedir(),".chatpanel");return d(e,{recursive:!0}),{out:n.join(e,"gateway.log"),err:n.join(e,"gateway.err.log")}}function r(e,t,s={}){return E(e,t,{encoding:"utf8",...s})}const g=()=>n.join(u.homedir(),"Library","LaunchAgents",`${p}.plist`);function L(){const{program:e,args:t}=v(),{out:s,err:a}=j(),o=[e,...t].map(A=>` <string>${A}</string>`).join(`
2
+ `),c=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4
4
  <plist version="1.0">
5
5
  <dict>
6
- <key>Label</key><string>${u}</string>
6
+ <key>Label</key><string>${p}</string>
7
7
  <key>ProgramArguments</key>
8
8
  <array>
9
- ${c}
9
+ ${o}
10
10
  </array>
11
11
  <key>RunAtLoad</key><true/>
12
12
  <key>KeepAlive</key><true/>
@@ -14,9 +14,9 @@ ${c}
14
14
  <key>StandardErrorPath</key><string>${a}</string>
15
15
  </dict>
16
16
  </plist>
17
- `,o=f();d(n.dirname(o),{recursive:!0}),w(o,l),e("launchctl",["unload",o]);const P=e("launchctl",["load","-w",o]);if(P.status!==0)throw new Error((P.stderr||"").trim()||"launchctl load failed")}function A(){const t=f();e("launchctl",["unload","-w",t]),i(t)&&k(t)}function C(){return(e("launchctl",["list"]).stdout||"").includes(u)}const v="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",S="ChatPanelGateway",$=()=>n.join(p.homedir(),".chatpanel","gateway-launch.vbs");function x(){const t=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;e("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3}),e("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function M(){if(process.platform==="win32")return x();process.platform==="darwin"?e("launchctl",["bootout",`gui/${process.getuid?.()??""}/${u}`]):e("systemctl",["--user","stop","chatpanel-gateway.service"]),e("pkill",["-f","chatpanel-gateway"])}function N(){const{program:t,args:r}=h(),s=[t,...r].map(l=>`""${l}""`).join(" "),a=$();d(n.dirname(a),{recursive:!0}),w(a,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
18
- `);const c=e("reg",["add",v,"/v",S,"/t","REG_SZ","/d",`wscript.exe "${a}"`,"/f"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"reg add failed");x(),e("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),e("wscript.exe",[a])}function U(){e("reg",["delete",v,"/v",S,"/f"]),x()}function R(){return e("reg",["query",v,"/v",S]).status===0}const m=()=>n.join(p.homedir(),".config","systemd","user","chatpanel-gateway.service");function W(){const{program:t,args:r}=h(),s=[t,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" "),a=`[Unit]
19
- Description=${E}
17
+ `,l=g();d(n.dirname(l),{recursive:!0}),y(l,c),r("launchctl",["unload",l]);const x=r("launchctl",["load","-w",l]);if(x.status!==0)throw new Error((x.stderr||"").trim()||"launchctl load failed")}function C(){const e=g();r("launchctl",["unload","-w",e]),i(e)&&f(e)}function _(){return(r("launchctl",["list"]).stdout||"").includes(p)}const m="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",b="ChatPanelGateway",P=()=>n.join(u.homedir(),".chatpanel","gateway-launch.vbs");function S(){const e=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;r("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),r("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function Y(){if(process.platform==="win32")return S();process.platform==="darwin"?r("launchctl",["bootout",`gui/${process.getuid?.()??""}/${p}`]):r("systemctl",["--user","stop","chatpanel-gateway.service"]),r("pkill",["-f","chatpanel-gateway"])}function N(){const{program:e,args:t}=v(),s=[e,...t].map(c=>`""${c}""`).join(" "),a=P();d(n.dirname(a),{recursive:!0}),y(a,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
18
+ `);const o=r("reg",["add",m,"/v",b,"/t","REG_SZ","/d",`wscript.exe "${a}"`,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");S(),r("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),r("wscript.exe",[a])}function R(){r("reg",["delete",m,"/v",b,"/f"]),S()}function W(){return r("reg",["query",m,"/v",b]).status===0}const h=()=>n.join(u.homedir(),".config","systemd","user","chatpanel-gateway.service");function D(){const{program:e,args:t}=v(),s=[e,...t].map(l=>/\s/.test(l)?`"${l}"`:l).join(" "),a=`[Unit]
19
+ Description=${I}
20
20
  After=network.target
21
21
 
22
22
  [Service]
@@ -25,4 +25,4 @@ Restart=on-failure
25
25
 
26
26
  [Install]
27
27
  WantedBy=default.target
28
- `,c=m();d(n.dirname(c),{recursive:!0}),w(c,a),e("systemctl",["--user","daemon-reload"]);const l=e("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(l.status!==0)throw new Error((l.stderr||"").trim()||"systemctl enable failed")}function _(){e("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=m();i(t)&&k(t)}function D(){return(e("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function g(t,r,s){if(process.platform==="darwin")return t();if(process.platform==="win32")return r();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function B({winInstall:t=""}={}){try{if(process.platform==="darwin")return i(f())?(y("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${u}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return i(m())?(y("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const r=$();if(!i(r))return!1;const s=n.dirname(process.execPath),a=`timeout /t 3 >nul & ${t?`${t} & `:""}wscript.exe "${r}" & del /q "${n.join(s,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`;return y("cmd",["/c",a],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function K(){try{return g(()=>i(f()),()=>i($()),()=>i(m()))}catch{return!1}}function Y(){return g(L,N,W)}function q(){return g(A,U,_)}function H(){return g(C,R,D)}export{Y as installService,h as resolveLaunch,B as restartService,K as serviceRegistered,H as serviceStatus,M as stopService,q as uninstallService};
28
+ `,o=h();d(n.dirname(o),{recursive:!0}),y(o,a),r("systemctl",["--user","daemon-reload"]);const c=r("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"systemctl enable failed")}function U(){r("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=h();i(e)&&f(e)}function B(){return(r("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function F({home:e=u.homedir(),platform:t=process.platform,env:s=process.env}={}){return t==="win32"?[n.join(s.LOCALAPPDATA||n.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[n.join(e,".local","bin","chatpanel-bridge")]}const k="net.chatpanel.bridge",O="ChatPanelBridge";function G({platform:e=process.platform,runImpl:t=r,paths:s=F(),home:a=u.homedir()}={}){if(e==="win32"){t("reg",["delete",m,"/v",O,"/f"]);for(const o of s){const c=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${o.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",c],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${k}`]);const o=n.join(a,"Library","LaunchAgents",`${k}.plist`);i(o)&&f(o,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const o=n.join(a,".config","systemd","user","chatpanel-bridge.service");i(o)&&f(o,{force:!0})}for(const o of s)t("pkill",["-f",`^${o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function w(e,t,s){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function H({winInstall:e=""}={}){try{if(process.platform==="darwin")return i(g())?($("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${p}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return i(h())?($("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const t=P();if(!i(t))return!1;const s=n.dirname(process.execPath),a=`timeout /t 3 >nul & ${e?`${e} & `:""}wscript.exe "${t}" & del /q "${n.join(s,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`;return $("cmd",["/c",a],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function V(){try{return w(()=>i(g()),()=>i(P()),()=>i(h()))}catch{return!1}}function Z(){return G(),w(L,N,D)}function z(){return w(C,R,U)}function J(){return w(_,W,B)}export{Z as installService,v as resolveLaunch,H as restartService,G as retireStandaloneBridge,V as serviceRegistered,J as serviceStatus,F as standaloneCandidates,Y as stopService,z as uninstallService};