@chatpanel/gateway 0.11.5 → 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.5",
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,4 +1,4 @@
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.5",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
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
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};