@chatpanel/gateway 0.23.1 → 0.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
- const e=process.argv[2];try{process.title=e==="--bridge"?"chatpanel-bridge":e==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(e==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(e==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(e==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(e==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(e==="tools"||e==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(e==="policy"){const{loadPolicy:t,formatPolicy:a,PolicyLoadError:i}=await import("../src/policy.js");try{const o=await t();process.argv.includes("--json")?console.log(JSON.stringify(o?{...o,label:void 0}:null,null,2)):console.log(a(o))}catch(o){throw o instanceof i&&(console.error(`org policy: ${o.message}`),process.exit(78)),o}}else if(e==="--audit"){const{egressAudit:t,formatAudit:a}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:p}=await import("node:path"),n=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let r=null,c=`no gateway running at ${s}`;try{const d=o(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(n.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${d}`},signal:AbortSignal.timeout(2500)});if(g.ok)r=await g.json();else if(g.status===404){const u=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${u?.version?` (${u.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!r){const{VERSION:d}=await import("../src/server.js");r={...t(l,{ledger:null,version:d}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(r,null,2)):console.log(a(r))}else if(e==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:a}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await a(process.argv.slice(3)))}else if(e==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:i}=await import("node:path"),o=await import("node:os"),n=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(o.homedir(),".chatpanel","gateway-token");try{const s=a(l,"utf8").trim(),r=await fetch(`${n}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await r.json().catch(()=>({}));if(r.status===404)throw new Error(`the gateway at ${n} predates pairing (0.9.0) — update and restart it`);if(!r.ok)throw new Error(c.error||`HTTP ${r.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${n}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(e==="local"){const{localStatus:t,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await t()))}else if(e==="connect"){const{connectAgents:t,formatConnect:a}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:a}=await import("../src/server.js"),{installService:i,uninstallService:o,serviceStatus:p,stopService:n}=await import("../src/service.js");switch(e){case"--stop":n(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(a);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":o(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(p()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${e}
4
- Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
2
+ const o=process.argv[2];try{process.title=o==="--bridge"?"chatpanel-bridge":o==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(o==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(o==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(o==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(o==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(o==="tools"||o==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(o==="policy"){const{loadPolicy:e,formatPolicy:s,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(s(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(o==="--audit"){const{egressAudit:e,formatAudit:s}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:p}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let a=null,i=`no gateway running at ${t}`;try{const h=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(g.ok)a=await g.json();else if(g.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js");a={...e(c,{ledger:null,version:h}),observed:[]},console.log(`(${i}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(s(a))}else if(o==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await s(process.argv.slice(3)))}else if(o==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=s(c,"utf8").trim(),a=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(i.error||`HTTP ${a.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(o==="local"){const{localStatus:e,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await e()))}else if(o==="connect"){const{connectAgents:e,formatConnect:s}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:s}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:p,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(o){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--install":{const t=await n(),a=t.health;if(a.ok){const i=a.managedBy&&a.managedBy!=="gateway"?` — the ${a.managedBy} app's gateway is the one answering right now; this install takes over at the next login`:"";console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
4
+ ${t.errLog.split(`
5
+ `).map(i=>` ${i}`).join(`
6
+ `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await p());break;case void 0:await e();break;default:console.error(`unknown option: ${o}
7
+ Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(e){console.error(`error: ${e.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.23.1",
3
+ "version": "0.23.2",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createServer as Dt}from"node:http";import{loadConfig as We}from"./config.js";import{startEntitlementRefresh as Ct,maybeRevalidate as Mt}from"./entitlement-refresh.js";import{redactSegments as ke,segment as Ae}from"./redact.js";import{pipeRestoredStream as jt,pipeRestoredOpenAIStream as It,makeTokenRestorer as Ke,restoreDeep as Rt}from"./stream.js";import{restoreText as Lt,gatedDictionary as zt,narrowSpecs as Jt,makeToolHarness as Gt,placeholderToolNote as Vt,placeholderNote as Ut,assertEndpointUrl as Ht,capRunOptions as Ft,isPaired as Wt}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Kt,isAdminAuthorized as F,callerTrustOf as Se,setPinnedExtensionIds as Zt,issuePairingCode as Yt,claimPairingCode as Qt}from"./gateway-token.js";import{installEgressLedger as Xt,egressAudit as qt}from"./egress.js";import{initPolicy as eo,activePolicy as to,applyPolicyToConfig as Ze,managedSummary as ye,PolicyLoadError as oo}from"./policy.js";import{routeAllowed as Ye,agentAllowed as ro,egressAllowed as no}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Qe}from"./secure-fetch.js";import{streamBridgeChat as Xe,readBridgeToken as ae,openBridgeChat as so}from"./bridge.js";import{createRelaySession as ao,getRelaySession as qe,endRelaySession as ve,pumpBridgeStream as io,deliverToolResult as lo,toolsToSpecs as co,parseToolCallId as et,touchRelaySession as Ee}from"./toolrelay.js";import{shaperFor as Ne}from"./shape.js";import{startNer as uo,ensureNer as Te,unionForThisMachine as mo,skippedCompanions as po}from"./ner.js";import{recommendDetector as tt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as ho}from"./log.js";import{saveBackupSecret as yo,clearBackupSecret as fo,loadBackupSecret as Be,hasBackupSecret as ot}from"./history-store.js";import{createMemoryStore as go}from"./memory-store.js";import{createPrefsStore as bo}from"./prefs-store.js";import{createTeamStore as wo,loadOrCreateKey as De}from"./team-store.js";import{createScorecardStore as ko}from"./scorecard-store.js";import{createEngineLedgerStore as So}from"./engine-ledger-store.js";import{createProjectStore as vo}from"./project-store.js";import{applicationsFor as To,recruitPass as xo}from"./recruiting.js";import{ensureBridge as Oo}from"./bridge-supervisor.js";import{checkForUpdate as _o,updateStatus as $o,startUpdate as Ao,updateJob as Po}from"./update.js";import{createHistoryStore as Eo}from"./sqlite-store.js";import{ingestBackups as Ce}from"./backup-ingest.js";import{toSearchRecord as No}from"@chatpanel/events/library.js";import{deriveBackupKey as Bo,openRecord as Do,keyCache as Co,nodeCodec as Mo}from"@chatpanel/events/backup-envelope.js";import jo from"node:zlib";import*as A from"./ner-engine.js";import rt from"node:os";import{capabilitiesDocument as Io,handleDetect as Ro}from"./capabilities.js";import{createExtractService as Lo}from"./extract/service.js";import{workerSandbox as zo,disposeWorkerSandbox as Jo}from"./worker-sandbox.js";import{createRuntime as Go}from"./runtime.js";import{createCapabilityProxy as Vo}from"./capability-proxy.js";import{handleExtract as Uo}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Ho}from"./extract-capability.js";import{createReader as Fo}from"./retrieval/read.js";import{createSearcher as Wo,toJinaSearch as Ko,SEARCH_DEFAULTS as Zo}from"./retrieval/search.js";import{createSearxng as Yo}from"./retrieval/search-searxng.js";import{toJinaText as Qo}from"./read-document.js";import*as B from"./stt-engine.js";import*as L from"./diarize-engine.js";import{MODEL_CATALOG as nt,isKnownModel as st,isValidCustomModelId as at,recommendFor as Xo}from"./models.js";import{STT_MODEL_CATALOG as qo,isKnownSttModel as er,isValidCustomSttId as tr,DEFAULT_STT_MODEL as Me,STT_DTYPES as or,isValidDtype as rr}from"./stt-models.js";import*as _ from"./tts-engine.js";import{TTS_MODEL_CATALOG as it,TTS_VOICES as nr,isKnownTtsModel as sr,isValidCustomTtsId as ar,isKnownVoice as lt,isValidVoiceId as ct,DEFAULT_TTS_MODEL as dt,DEFAULT_TTS_VOICE as ie,TTS_DTYPES as ir,isValidTtsDtype as lr,MAX_TTS_CHARS as ut,ttsModelHasCustomVoices as cr,resolveDefaultModel as mt,POCKET_VOICES as dr,DEFAULT_POCKET_VOICE as xe,isPocketVoice as Oe,ttsModelEngine as _e}from"./tts-models.js";import{ttsDestination as ur,synthesizeRemote as mr,isValidRemoteVoice as pr}from"./tts-remote.js";import{rawOrtAvailable as je}from"./ort.js";import*as U from"./tts-voices.js";import{resolveTtsVoice as hr}from"./tts-voice-resolve.js";import{resolvePro as ue,checkQuota as yr,consume as fr,usage as gr}from"./freegate.js";import{publicConfig as pt,applyConfigPatch as br,applyNerModelSelection as ht,persistConfig as le,configPath as re,bridgeAgentOptions as yt,PERMISSION_MODES as wr,sandboxEnvFor as kr}from"./configstore.js";import{resolveDestination as ft,aggregateModelsAsync as Sr,listDestinations as vr}from"./router.js";import{makeAccessEvent as gt}from"./observability.js";import{createPersistentAccessLog as Tr}from"./access-log-store.js";import{planQueries as xr,multiSearch as Or}from"./rrf.js";import*as Ie from"./openai.js";import*as bt from"./responses.js";import*as Re from"./anthropic.js";import{closeAndExit as _r}from"./shutdown.js";const Z="0.23.1",N=await Eo(),ne=new Set;function $e({ids:t=[]}={}){const l=N.lossless;if(!l||!ne.size)return;const c=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of ne)try{m.write(`event: records
1
+ import{createServer as Dt}from"node:http";import{loadConfig as We}from"./config.js";import{startEntitlementRefresh as Ct,maybeRevalidate as Mt}from"./entitlement-refresh.js";import{redactSegments as ke,segment as Ae}from"./redact.js";import{pipeRestoredStream as jt,pipeRestoredOpenAIStream as It,makeTokenRestorer as Ke,restoreDeep as Rt}from"./stream.js";import{restoreText as Lt,gatedDictionary as zt,narrowSpecs as Jt,makeToolHarness as Gt,placeholderToolNote as Vt,placeholderNote as Ut,assertEndpointUrl as Ht,capRunOptions as Ft,isPaired as Wt}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Kt,isAdminAuthorized as F,callerTrustOf as Se,setPinnedExtensionIds as Zt,issuePairingCode as Yt,claimPairingCode as Qt}from"./gateway-token.js";import{installEgressLedger as Xt,egressAudit as qt}from"./egress.js";import{initPolicy as eo,activePolicy as to,applyPolicyToConfig as Ze,managedSummary as ye,PolicyLoadError as oo}from"./policy.js";import{routeAllowed as Ye,agentAllowed as ro,egressAllowed as no}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Qe}from"./secure-fetch.js";import{streamBridgeChat as Xe,readBridgeToken as ae,openBridgeChat as so}from"./bridge.js";import{createRelaySession as ao,getRelaySession as qe,endRelaySession as ve,pumpBridgeStream as io,deliverToolResult as lo,toolsToSpecs as co,parseToolCallId as et,touchRelaySession as Ee}from"./toolrelay.js";import{shaperFor as Ne}from"./shape.js";import{startNer as uo,ensureNer as Te,unionForThisMachine as mo,skippedCompanions as po}from"./ner.js";import{recommendDetector as tt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as ho}from"./log.js";import{saveBackupSecret as yo,clearBackupSecret as fo,loadBackupSecret as Be,hasBackupSecret as ot}from"./history-store.js";import{createMemoryStore as go}from"./memory-store.js";import{createPrefsStore as bo}from"./prefs-store.js";import{createTeamStore as wo,loadOrCreateKey as De}from"./team-store.js";import{createScorecardStore as ko}from"./scorecard-store.js";import{createEngineLedgerStore as So}from"./engine-ledger-store.js";import{createProjectStore as vo}from"./project-store.js";import{applicationsFor as To,recruitPass as xo}from"./recruiting.js";import{ensureBridge as Oo}from"./bridge-supervisor.js";import{checkForUpdate as _o,updateStatus as $o,startUpdate as Ao,updateJob as Po}from"./update.js";import{createHistoryStore as Eo}from"./sqlite-store.js";import{ingestBackups as Ce}from"./backup-ingest.js";import{toSearchRecord as No}from"@chatpanel/events/library.js";import{deriveBackupKey as Bo,openRecord as Do,keyCache as Co,nodeCodec as Mo}from"@chatpanel/events/backup-envelope.js";import jo from"node:zlib";import*as A from"./ner-engine.js";import rt from"node:os";import{capabilitiesDocument as Io,handleDetect as Ro}from"./capabilities.js";import{createExtractService as Lo}from"./extract/service.js";import{workerSandbox as zo,disposeWorkerSandbox as Jo}from"./worker-sandbox.js";import{createRuntime as Go}from"./runtime.js";import{createCapabilityProxy as Vo}from"./capability-proxy.js";import{handleExtract as Uo}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Ho}from"./extract-capability.js";import{createReader as Fo}from"./retrieval/read.js";import{createSearcher as Wo,toJinaSearch as Ko,SEARCH_DEFAULTS as Zo}from"./retrieval/search.js";import{createSearxng as Yo}from"./retrieval/search-searxng.js";import{toJinaText as Qo}from"./read-document.js";import*as B from"./stt-engine.js";import*as L from"./diarize-engine.js";import{MODEL_CATALOG as nt,isKnownModel as st,isValidCustomModelId as at,recommendFor as Xo}from"./models.js";import{STT_MODEL_CATALOG as qo,isKnownSttModel as er,isValidCustomSttId as tr,DEFAULT_STT_MODEL as Me,STT_DTYPES as or,isValidDtype as rr}from"./stt-models.js";import*as _ from"./tts-engine.js";import{TTS_MODEL_CATALOG as it,TTS_VOICES as nr,isKnownTtsModel as sr,isValidCustomTtsId as ar,isKnownVoice as lt,isValidVoiceId as ct,DEFAULT_TTS_MODEL as dt,DEFAULT_TTS_VOICE as ie,TTS_DTYPES as ir,isValidTtsDtype as lr,MAX_TTS_CHARS as ut,ttsModelHasCustomVoices as cr,resolveDefaultModel as mt,POCKET_VOICES as dr,DEFAULT_POCKET_VOICE as xe,isPocketVoice as Oe,ttsModelEngine as _e}from"./tts-models.js";import{ttsDestination as ur,synthesizeRemote as mr,isValidRemoteVoice as pr}from"./tts-remote.js";import{rawOrtAvailable as je}from"./ort.js";import*as U from"./tts-voices.js";import{resolveTtsVoice as hr}from"./tts-voice-resolve.js";import{resolvePro as ue,checkQuota as yr,consume as fr,usage as gr}from"./freegate.js";import{publicConfig as pt,applyConfigPatch as br,applyNerModelSelection as ht,persistConfig as le,configPath as re,bridgeAgentOptions as yt,PERMISSION_MODES as wr,sandboxEnvFor as kr}from"./configstore.js";import{resolveDestination as ft,aggregateModelsAsync as Sr,listDestinations as vr}from"./router.js";import{makeAccessEvent as gt}from"./observability.js";import{createPersistentAccessLog as Tr}from"./access-log-store.js";import{planQueries as xr,multiSearch as Or}from"./rrf.js";import*as Ie from"./openai.js";import*as bt from"./responses.js";import*as Re from"./anthropic.js";import{closeAndExit as _r}from"./shutdown.js";const Z="0.23.2",N=await Eo(),ne=new Set;function $e({ids:t=[]}={}){const l=N.lossless;if(!l||!ne.size)return;const c=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of ne)try{m.write(`event: records
2
2
  data: ${c}
3
3
 
4
4
  `)}catch{ne.delete(m)}}setInterval(()=>{for(const t of ne)try{t.write(`: ping
package/src/service.js CHANGED
@@ -1,33 +1,41 @@
1
- import u from"node:os";import o from"node:path";import{mkdirSync as f,writeFileSync as b,rmSync as g,existsSync as l}from"node:fs";import{spawnSync as C,spawn as x}from"node:child_process";const d="net.chatpanel.gateway",I="ChatPanel Privacy Gateway";function P(){const e=process.execPath,t=o.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[o.resolve(process.argv[1])]}:{program:e,args:[]}}function N(){const e=o.join(u.homedir(),".chatpanel");return f(e,{recursive:!0}),{out:o.join(e,"gateway.log"),err:o.join(e,"gateway.err.log")}}function s(e,t,n={}){return C(e,t,{encoding:"utf8",...n})}const m=()=>o.join(u.homedir(),"Library","LaunchAgents",`${d}.plist`),_={MallocLargeCache:"0"};function R({program:e,args:t,out:n,err:c,env:r=_,label:a=d}={}){const i=p=>String(p).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),v=[e,...t].map(p=>` <string>${i(p)}</string>`).join(`
2
- `),$=Object.entries(r).map(([p,L])=>` <key>${i(p)}</key><string>${i(L)}</string>`).join(`
1
+ import g from"node:os";import p from"node:path";import{mkdirSync as P,writeFileSync as b,readFileSync as X,rmSync as w,existsSync as h,statSync as J}from"node:fs";import{spawnSync as Q,spawn as E}from"node:child_process";import{loadConfig as ee}from"./config.js";const v="net.chatpanel.gateway",te="ChatPanel Privacy Gateway";function A(){const e=process.execPath,t=p.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[p.resolve(process.argv[1])]}:{program:e,args:[]}}function S(){const e=p.join(g.homedir(),".chatpanel");return P(e,{recursive:!0}),{out:p.join(e,"gateway.log"),err:p.join(e,"gateway.err.log")}}function c(e,t,n={}){return Q(e,t,{encoding:"utf8",...n})}const k=()=>p.join(g.homedir(),"Library","LaunchAgents",`${v}.plist`),ne={MallocLargeCache:"0"};function re({program:e,args:t,out:n,err:s,env:r=ne,label:o=v}={}){const i=u=>String(u).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[e,...t].map(u=>` <string>${i(u)}</string>`).join(`
2
+ `),l=Object.entries(r).map(([u,d])=>` <key>${i(u)}</key><string>${i(d)}</string>`).join(`
3
3
  `);return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5
5
  <plist version="1.0">
6
6
  <dict>
7
- <key>Label</key><string>${a}</string>
7
+ <key>Label</key><string>${o}</string>
8
8
  <key>ProgramArguments</key>
9
9
  <array>
10
- ${v}
10
+ ${a}
11
11
  </array>
12
12
  <key>EnvironmentVariables</key>
13
13
  <dict>
14
- ${$}
14
+ ${l}
15
15
  </dict>
16
16
  <key>RunAtLoad</key><true/>
17
17
  <key>KeepAlive</key><true/>
18
18
  <key>StandardOutPath</key><string>${i(n)}</string>
19
- <key>StandardErrorPath</key><string>${i(c)}</string>
19
+ <key>StandardErrorPath</key><string>${i(s)}</string>
20
20
  </dict>
21
21
  </plist>
22
- `}function D(){const{program:e,args:t}=P(),{out:n,err:c}=N(),r=R({program:e,args:t,out:n,err:c}),a=m();f(o.dirname(a),{recursive:!0}),b(a,r),s("launchctl",["unload",a]);const i=s("launchctl",["load","-w",a]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function W(){const e=m();s("launchctl",["unload","-w",e]),l(e)&&g(e)}function U(){return(s("launchctl",["list"]).stdout||"").includes(d)}const h="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",S="ChatPanelGateway",k=()=>o.join(u.homedir(),".chatpanel","gateway-launch.vbs");function j(){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 }`;s("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),s("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function z(){if(process.platform==="win32")return j();process.platform==="darwin"?s("launchctl",["bootout",`gui/${process.getuid?.()??""}/${d}`]):s("systemctl",["--user","stop","chatpanel-gateway.service"]),s("pkill",["-f","chatpanel-gateway"])}function O(){const{program:e,args:t}=P(),n=[e,...t].map(a=>`""${a}""`).join(" "),c=k();f(o.dirname(c),{recursive:!0}),b(c,`CreateObject("WScript.Shell").Run "${n}", 0, False\r
23
- `);const r=s("reg",["add",h,"/v",S,"/t","REG_SZ","/d",`wscript.exe "${c}"`,"/f"]);if(r.status!==0)throw new Error((r.stderr||"").trim()||"reg add failed");j(),s("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),s("wscript.exe",[c])}function T(){s("reg",["delete",h,"/v",S,"/f"]),j()}function B(){return s("reg",["query",h,"/v",S]).status===0}const y=()=>o.join(u.homedir(),".config","systemd","user","chatpanel-gateway.service");function F(){const{program:e,args:t}=P(),n=[e,...t].map(i=>/\s/.test(i)?`"${i}"`:i).join(" "),c=`[Unit]
24
- Description=${I}
22
+ `}function se(){const{program:e,args:t}=A(),{out:n,err:s}=S(),r=re({program:e,args:t,out:n,err:s}),o=k();P(p.dirname(o),{recursive:!0}),b(o,r),c("launchctl",["unload",o]);const i=c("launchctl",["load","-w",o]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function oe(){const e=k();c("launchctl",["unload","-w",e]),h(e)&&w(e)}function ie(){return(c("launchctl",["list"]).stdout||"").includes(v)}function j({execPath:e=process.execPath,argv1:t=process.argv[1]||"",platform:n=process.platform,isFile:s=ae}={}){const r=n==="win32"?p.win32:p.posix,o=r.basename(e).toLowerCase();if(!(o.startsWith("node")||o.startsWith("bun")))return r.dirname(e);const i=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const u=r.dirname(a);if(u===a)break;if(a=u,s(r.join(a,i)))return a;if(s(r.join(a,"bin",i)))return r.join(a,"bin")}return""}const ae=e=>{try{return J(e).isFile()}catch{return!1}};function R(e,t,{delimiter:n=p.delimiter,platform:s=process.platform,env:r=process.env}={}){const o=l=>s==="win32"?l.replace(/%([^%]+)%/g,(u,d)=>r[d]??r[d.toUpperCase()]??u):l,i=l=>{const u=o(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?u.toLowerCase():u},a=String(e||"").split(n).filter(l=>l.trim());return a.some(l=>i(l)===i(t))?null:[...a,t].join(n)}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",_="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",f="ChatPanelGateway",C=()=>p.join(g.homedir(),".chatpanel","gateway-launch.vbs"),O=e=>Buffer.from(e,"utf16le").toString("base64");function L({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=h}={}){return t(p.join(e,"System32","vbscript.dll"))}function B({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:o=!0}){const i=m=>`"${m}"`;if(o){const m=`cmd.exe /c "${[e,...t].map(i).join(" ")} >> ${i(n)} 2>> ${i(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${m.replace(/"/g,'""')}", 0, False\r
23
+ `,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=m=>`'${String(m).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(m=>a(i(m))).join(", ")})`:"",u=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${l} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",O(u)];return{kind:"powershell",file:"",text:u,runValue:d.join(" "),argv:d}}function N(e=c){const t=e("reg",["query",y,"/v",f]);if(t.status!==0)return"";const n=new RegExp(`${f}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function ce(e=c){const t=e("reg",["query",_,"/v",f]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function H(e=c){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const le=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
24
+ $t = Add-Type -MemberDefinition $sig -Name 'Env' -Namespace 'ChatPanelWin32' -PassThru
25
+ $r = [UIntPtr]::Zero
26
+ [void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function ue(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=H(t),r=R(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const o=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return o.status!==0?{added:!1,dir:e,error:(o.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",O(le)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function pe(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return R(H(t).value,e,{delimiter:";",platform:"win32",env:n})===null||R(s,e,{delimiter:";",platform:"win32",env:n})===null}function W(){const e=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} -and $_.ProcessId -ne $PID } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;c("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),c("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function Re(){if(process.platform==="win32")return W();process.platform==="darwin"?c("launchctl",["bootout",`gui/${process.getuid?.()??""}/${v}`]):c("systemctl",["--user","stop","chatpanel-gateway.service"]),c("pkill",["-f","chatpanel-gateway"])}function de(){const{program:e,args:t}=A(),{out:n,err:s}=S(),r=B({program:e,args:t,out:n,err:s,vbs:C(),vbscript:L()});r.file?b(r.file,r.text):w(C(),{force:!0});const o=c("reg",["add",y,"/v",f,"/t","REG_SZ","/d",r.runValue,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");c("reg",["delete",_,"/v",f,"/f"]);const i=ue(j());return W(),c("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),c(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:i}}function fe(){c("reg",["delete",y,"/v",f,"/f"]),w(C(),{force:!0}),W()}function M(){return c("reg",["query",y,"/v",f]).status===0}function x({env:e=process.env,release:t=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function $(e=c){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const u of t){if(n=e(u,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const o=u=>(e("wslpath",["-u",u]).stdout||"").trim(),i=o(r),a=o(s);if(!i||!a)return null;const l=p.posix.join(i,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:i,exe:{reg:p.posix.join(l,"reg.exe"),wscript:p.posix.join(l,"wscript.exe"),powershell:p.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}function F(){const e=c("pgrep",["-f","chatpanel-gateway"]);for(const t of(e.stdout||"").split(`
27
+ `)){const n=Number(t.trim());if(!(!n||n===process.pid||n===process.ppid))try{process.kill(n,"SIGTERM")}catch{}}}const G=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:p.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function me(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function he(e){const{program:t,args:n}=A(),{out:s,err:r}=S(),o=z=>`'${String(z).replace(/'/g,"'\\''")}'`,i=`exec ${[t,...n].map(o).join(" ")} >> ${o(s)} 2>> ${o(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=G(e),u=B({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",i],vbs:l.win,vbscript:L({systemRoot:e.sysUnix})});P(p.dirname(l.unix),{recursive:!0}),u.file?b(l.unix,u.text):w(l.unix,{force:!0});const d=c(e.exe.reg,["add",y,"/v",f,"/t","REG_SZ","/d",u.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");c(e.exe.reg,["delete",_,"/v",f,"/f"]),F(),we(800);const m=me(e,u);return c(m[0],m.slice(1),{timeout:2e4}),{launcher:u.kind,wsl:!0,path:{added:!1,dir:j()}}}function ge(e){c(e.exe.reg,["delete",y,"/v",f,"/f"]),w(G(e).unix,{force:!0}),F()}function V(e){return c(e.exe.reg,["query",y,"/v",f]).status===0}function we(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const T=()=>p.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function ye(){const e=x()?$():null;if(e)return he(e);if(x()&&!h("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=A(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=`[Unit]
28
+ Description=${te}
25
29
  After=network.target
26
30
 
27
31
  [Service]
28
- ExecStart=${n}
32
+ ExecStart=${s}
29
33
  Restart=on-failure
30
34
 
31
35
  [Install]
32
36
  WantedBy=default.target
33
- `,r=y();f(o.dirname(r),{recursive:!0}),b(r,c),s("systemctl",["--user","daemon-reload"]);const a=s("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"systemctl enable failed")}function G(){s("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=y();l(e)&&g(e)}function M(){return(s("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function K({home:e=u.homedir(),platform:t=process.platform,env:n=process.env}={}){return t==="win32"?[o.join(n.LOCALAPPDATA||o.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[o.join(e,".local","bin","chatpanel-bridge")]}const A="net.chatpanel.bridge",E="ChatPanelBridge";function V({platform:e=process.platform,runImpl:t=s,paths:n=K(),home:c=u.homedir()}={}){if(e==="win32"){t("reg",["delete",h,"/v",E,"/f"]),t("schtasks",["/End","/TN",E]),t("schtasks",["/Delete","/TN",E,"/F"]);for(const r of n){const a=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",a],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]);const r=o.join(c,"Library","LaunchAgents",`${A}.plist`);l(r)&&g(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=o.join(c,".config","systemd","user","chatpanel-bridge.service");l(r)&&g(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function w(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function J({winInstall:e=""}={}){try{if(process.platform==="darwin")return l(m())?(x("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${d}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return l(y())?(x("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const t=k();if(!l(t))return!1;const n=o.dirname(process.execPath),c=`timeout /t 3 >nul & ${e?`${e} & `:""}wscript.exe "${t}" & del /q "${o.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},a=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[a]=[n,...(r[a]||"").split(";").filter(Boolean)].filter((i,v,$)=>$.indexOf(i)===v).join(";"),x("cmd",["/c",c],{detached:!0,stdio:"ignore",windowsHide:!0,env:r}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function Q(){try{return w(()=>l(m()),()=>l(k()),()=>l(y()))}catch{return!1}}function X(){return V(),w(D,O,F)}function ee(){return w(W,T,G)}function te(){return w(U,B,M)}export{_ as DARWIN_LAUNCH_ENV,X as installService,R as macPlistText,P as resolveLaunch,J as restartService,V as retireStandaloneBridge,Q as serviceRegistered,te as serviceStatus,K as standaloneCandidates,z as stopService,ee as uninstallService};
37
+ `,o=T();P(p.dirname(o),{recursive:!0}),b(o,r),c("systemctl",["--user","daemon-reload"]);const i=c("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"systemctl enable failed")}function xe(){const e=x()?$():null;e&&ge(e),c("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=T();h(t)&&w(t)}function q(){const e=x()?$():null;return e&&V(e)?!0:(c("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function ve({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){return t==="win32"?[p.join(n.LOCALAPPDATA||p.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[p.join(e,".local","bin","chatpanel-bridge")]}const Z="net.chatpanel.bridge",U="ChatPanelBridge";function Se({platform:e=process.platform,runImpl:t=c,paths:n=ve(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",U,"/f"]),t("schtasks",["/End","/TN",U]),t("schtasks",["/Delete","/TN",U,"/F"]);for(const r of n){const o=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${Z}`]);const r=p.join(s,"Library","LaunchAgents",`${Z}.plist`);h(r)&&w(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=p.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function I(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Ie({winInstall:e=""}={}){try{if(process.platform==="darwin")return h(k())?(E("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${v}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?$():null;if(t&&V(t)){const n=N((r,o,i)=>c(r==="reg"?t.exe.reg:r,o,i));return n?(E("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return h(T())?(E("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=N();if(!t)return!1;const n=p.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${p.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},o=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[o]=[n,...(r[o]||"").split(";").filter(Boolean)].filter((i,a,l)=>l.indexOf(i)===a).join(";"),E("cmd",["/c",s],{detached:!0,stdio:"ignore",windowsHide:!0,env:r}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function je(){try{return I(()=>h(k()),M,q)}catch{return!1}}function K(){try{return`http://127.0.0.1:${ee().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function D(e=K(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:e}}}function Y(e=8){try{const t=X(S().err,"utf8").trimEnd();return t?t.split(`
38
+ `).slice(-e).join(`
39
+ `):""}catch{return""}}async function _e({waitMs:e=4e4}={}){Se();const t=I(se,de,ye)||{},n=K(),s=Date.now()+e;let r=await D(n);for(;!r.ok&&Date.now()<s;)await new Promise(o=>setTimeout(o,500)),r=await D(n);return{...t,health:r,errLog:r.ok?"":Y()}}function Ce(){return I(oe,fe,xe)}function $e(){return I(ie,M,q)}async function Le({platform:e=process.platform}={}){const t=[];let n=!1;try{n=$e()}catch(i){t.push(`auto-start: ${i.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?$():null;if(e==="win32"||s){const i=s?(l,u,d)=>c(l==="reg"?s.exe.reg:l,u,d):c,a=n?N(i):"";a&&t.push(` launcher: ${a.length>120?`${a.slice(0,117)}…`:a}`),a.startsWith("wscript")&&!L(s?{systemRoot:s.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&ce(i)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),s&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const r=j();r&&(e==="win32"?t.push(pe(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(R(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const o=await D();if(o.ok)t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}`);else{t.push(`running: nothing answers at ${o.url}`);const i=Y();i&&t.push(` last of ${S().err}:`,...i.split(`
40
+ `).map(a=>` ${a}`))}return t.join(`
41
+ `)}export{ne as DARWIN_LAUNCH_ENV,j as commandDir,Y as errLogTail,_e as installService,x as isWsl,re as macPlistText,R as pathWithDir,D as probeHealth,O as psEncode,A as resolveLaunch,Ie as restartService,Se as retireStandaloneBridge,je as serviceRegistered,Le as serviceReport,$e as serviceStatus,ve as standaloneCandidates,Re as stopService,Ce as uninstallService,L as vbscriptAvailable,pe as winCommandOnPath,ue as winEnsureOnPath,B as winLauncher,ce as winStartupDisabled};