@chatpanel/gateway 0.11.7 → 0.11.8

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.7",
3
+ "version": "0.11.8",
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 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.7",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.8",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/update.js CHANGED
@@ -1 +1 @@
1
- import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as V,readFile as Y,writeFile as D,rm as K}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",ge="chatpanel/chatpanel-gateway",N="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,j=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",R={"User-Agent":"chatpanel-gateway-updater"},ae=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ne(e){try{const t=new URL(e);return t.protocol==="https:"&&ae.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function ye(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function O(e,t){const r=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let n=0;n<Math.max(r.length,a.length);n+=1){const o=(r[n]||0)-(a[n]||0);if(o)return o>0?1:-1}return 0}async function se(){try{return JSON.parse(await Y(_,"utf8"))}catch{return null}}async function oe(e){try{await V(l.dirname(_),{recursive:!0}),await D(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const r=new AbortController,a=setTimeout(()=>r.abort(),t);try{const n=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...R},signal:r.signal});if(!n.ok)throw new Error(n.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${n.status}`);return await n.json()}catch(n){const o=n?.cause?.code||n?.cause?.message||n?.message||String(n);throw new Error(r.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function $(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const r=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return r?r[1]:""}function ie(){const e=$();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function x(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(r=>W(r))||""}function le(){const e=x(),t={...process.env,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete t.ELECTRON_RUN_AS_NODE;const[r,a]=e?[process.execPath,[e,"install","-g",`${g}@latest`]]:["npm",["install","-g",`${g}@latest`]];return new Promise(n=>{b(r,a,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(o,d,p)=>{const s=`${d||""}${p||""}`.trim();return o?o.killed&&!s?n({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):n({ok:!1,out:s||(e?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):n({ok:!0,out:s})})})}async function H(e,{force:t=!1}={}){const r=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:r,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:r==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let n=null,o=null,d=!1,p="",s=0;const i=await se(),h=i&&i.mode===r,U=()=>{n=h&&i.latest||null,o=h&&i.assetUrl||null,s=h&&i.checkedAt||0,d=!0};if(!t&&h&&Date.now()-i.checkedAt<L)n=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<j)p=m.error,U();else try{if(r==="npm"){let u;try{u=await v(X),n=f(u.version)}catch(B){const C=await v(N);if(n=f(C?.npm?.version)||f(C?.version),!n)throw B}}else{const u=await v(N);n=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await oe({checkedAt:s,mode:r,latest:n,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},U()}const M=!!n&&O(n,e)>0,F=r==="binary"?!!o&&(process.platform!=="win32"||y()):!!$()&&(process.platform!=="win32"||y()&&!!x()),I=r==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest; chatpanel-gateway --install`:`npm i -g ${g}@latest`:null;return{current:e,latest:n,updateAvailable:M,mode:r,canSelfUpdate:F,assetUrl:o,stale:d,error:p,npmCommand:I,channel:r==="npm"?"npm":"release",service:y(),checkedAt:s}}let w=null,A=null;function Ae(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(m.at&&Date.now()-m.at<j):Date.now()-w.seenAt>L))&&!A&&(A=H(e).then(a=>{w={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function be(){w=null,A=null}async function ce(e){const t=process.execPath,r=l.dirname(t),a=l.join(r,`.chatpanel-gateway.new-${Date.now()}`),n=new AbortController,o=setTimeout(()=>n.abort(),te);let d;try{const s=await fetch(e.assetUrl,{headers:R,redirect:"follow",signal:n.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ne(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);d=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(d.length<5<<20)throw new Error(`the download was only ${(d.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await D(a,d),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,h)=>s(i?"":String(h||"").trim())));if(!f(p))throw await K(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(r,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function de(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ce(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${x()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const r=await le();if(!r.ok)throw new Error(`npm install failed: ${r.out.slice(0,800)}`);const a=ie();if(!a||O(a,e)<=0)throw new Error(`npm ran, but the install at ${$()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const c={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Ee(){return{...c}}function _e(e,{restart:t=Q,apply:r=de}={}){return c.state==="installing"||c.state==="restarting"?{...c,already:!0}:(Object.assign(c,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),r(e).then(a=>{Object.assign(c,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(c,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(c,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...c})}function Se(){Object.assign(c,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Se as _resetUpdateJob,be as _resetUpdateStatus,H as checkForUpdate,O as cmpVersions,ne as downloadHostAllowed,T as isCompiledBinary,$ as npmPackageRoot,ye as resetUpdateBackoff,de as selfUpdate,_e as startUpdate,Ee as updateJob,Ae as updateStatus};
1
+ import J from"node:os";import i from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",ye="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||i.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ae(){m={at:0,error:""}}function T(){const e=i.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(i.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?i.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(i.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=i.dirname(process.execPath);return[i.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),i.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[i.dirname(t),...(n[a]||"").split(i.delimiter).filter(Boolean)].filter((r,o,l)=>l.indexOf(r)===o).join(i.delimiter),n}function ce(){const e=$(),t=le(),[n,a]=e?[process.execPath,[e,"install","-g",`${g}@latest`]]:["npm",["install","-g",`${g}@latest`]];return new Promise(r=>{b(n,a,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(o,l,p)=>{const s=`${l||""}${p||""}`.trim();return o?o.killed&&!s?r({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):r({ok:!1,out:s||(e?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):r({ok:!0,out:s})})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,l=!1,p="",s=0;const c=await oe(),h=c&&c.mode===n,C=()=>{r=h&&c.latest||null,o=h&&c.assetUrl||null,s=h&&c.checkedAt||0,l=!0};if(!t&&h&&Date.now()-c.checkedAt<L)r=c.latest,o=c.assetUrl,s=c.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,F=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),I=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest; chatpanel-gateway --install`:`npm i -g ${g}@latest`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:F,assetUrl:o,stale:l,error:p,npmCommand:I,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let w=null,A=null;function be(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(m.at&&Date.now()-m.at<N):Date.now()-w.seenAt>L))&&!A&&(A=H(e).then(a=>{w={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Ee(){w=null,A=null}async function de(e){const t=process.execPath,n=i.dirname(t),a=i.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let l;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);l=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(l.length<5<<20)throw new Error(`the download was only ${(l.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,l),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(c,h)=>s(c?"":String(h||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,i.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function pe(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await de(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await ce();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function _e(){return{...d}}function Se(e,{restart:t=Q,apply:n=pe}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function Te(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Te as _resetUpdateJob,Ee as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,le as npmInstallEnv,x as npmPackageRoot,Ae as resetUpdateBackoff,pe as selfUpdate,Se as startUpdate,_e as updateJob,be as updateStatus};