@chatpanel/gateway 0.61.2 → 0.75.0
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/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +5 -4
- package/src/apple-model.js +1 -0
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-tunings.js +1 -1
- package/src/host-memory.js +1 -0
- package/src/inference-engines.js +1 -1
- package/src/link-host.js +1 -1
- package/src/lossless-store.js +4 -4
- package/src/runtime-models.js +1 -1
- package/src/runtime.js +5 -5
- package/src/server.js +28 -24
- package/src/service.js +17 -16
- package/src/version.js +1 -1
- package/src/ws-accept.js +7 -0
package/src/service.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import g from"node:os";import d from"node:path";import{mkdirSync as
|
|
2
|
-
`),u=Object.entries(r).map(([c,l])=>` <key>${
|
|
1
|
+
import g from"node:os";import{SERVICE_ENV as ft}from"@chatpanel/events/service-standby.js";import d from"node:path";import{mkdirSync as k,writeFileSync as I,readFileSync as L,rmSync as w,existsSync as h,statSync as ht,realpathSync as Y}from"node:fs";import{spawnSync as mt,spawn as N}from"node:child_process";import{loadConfig as gt}from"./config.js";import{VERSION as U}from"./version.js";const S="net.chatpanel.gateway",wt="ChatPanel Privacy Gateway";function yt(t,e){const n=String(t||"").split(".").map(r=>parseInt(r,10)),s=String(e||"").split(".").map(r=>parseInt(r,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let r=0;r<3;r+=1)if(n[r]!==s[r])return n[r]>s[r]?1:-1;return 0}function R(t,{real:e=Y.native||Y}={}){if(!t)return t;try{return e(t)}catch{return t}}function xt(t,{exists:e=h}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(t||""));if(!n)return t;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return e(s)?s:t}function C({execPath:t=xt(R(process.execPath)),argv1:e=R(process.argv[1]||"")}={}){const n=d.basename(t).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&e?{program:t,args:[d.resolve(e)]}:{program:t,args:[]}}function v(){const t=d.join(g.homedir(),".chatpanel");return k(t,{recursive:!0}),{out:d.join(t,"gateway.log"),err:d.join(t,"gateway.err.log")}}function p(t,e,n={}){return mt(t,e,{encoding:"utf8",...n})}const P=()=>d.join(g.homedir(),"Library","LaunchAgents",`${S}.plist`),$t={MallocLargeCache:"0"};function St({program:t,args:e,out:n,err:s,env:r={...$t,...ft},label:o=S}={}){const i=c=>String(c).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),a=[t,...e].map(c=>` <string>${i(c)}</string>`).join(`
|
|
2
|
+
`),u=Object.entries(r).map(([c,l])=>` <key>${i(c)}</key><string>${i(l)}</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>${
|
|
7
|
+
<key>Label</key><string>${o}</string>
|
|
8
8
|
<key>ProgramArguments</key>
|
|
9
9
|
<array>
|
|
10
10
|
${a}
|
|
@@ -15,28 +15,29 @@ ${u}
|
|
|
15
15
|
</dict>
|
|
16
16
|
<key>RunAtLoad</key><true/>
|
|
17
17
|
<key>KeepAlive</key><true/>
|
|
18
|
-
<key>StandardOutPath</key><string>${
|
|
19
|
-
<key>StandardErrorPath</key><string>${
|
|
18
|
+
<key>StandardOutPath</key><string>${i(n)}</string>
|
|
19
|
+
<key>StandardErrorPath</key><string>${i(s)}</string>
|
|
20
20
|
</dict>
|
|
21
21
|
</plist>
|
|
22
|
-
`}function
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=f=>`'${String(f).replace(/'/g,"''")}'`,u=
|
|
22
|
+
`}function vt(){const{program:t,args:e}=C(),{out:n,err:s}=v(),r=St({program:t,args:e,out:n,err:s}),o=P();k(d.dirname(o),{recursive:!0}),I(o,r),p("launchctl",["unload",o]);const i=p("launchctl",["load","-w",o]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function Pt(){const t=P();p("launchctl",["unload","-w",t]),h(t)&&w(t)}function bt(){return(p("launchctl",["list"]).stdout||"").includes(S)}function _({execPath:t=R(process.execPath),argv1:e=R(process.argv[1]||""),platform:n=process.platform,isFile:s=z}={}){const r=n==="win32"?d.win32:d.posix,o=r.basename(t).toLowerCase();if(!(o.startsWith("node")||o.startsWith("bun")))return r.dirname(t);const i=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(e));for(let u=0;u<6;u++){const c=r.dirname(a);if(c===a)break;if(a=c,s(r.join(a,i)))return a;if(s(r.join(a,"bin",i)))return r.join(a,"bin")}return""}const z=t=>{try{return ht(t).isFile()}catch{return!1}};function j(t,e,{delimiter:n=d.delimiter,platform:s=process.platform,env:r=process.env}={}){const o=u=>s==="win32"?u.replace(/%([^%]+)%/g,(c,l)=>r[l]??r[l.toUpperCase()]??c):u,i=u=>{const c=o(u.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(t||"").split(n).filter(u=>u.trim());return a.some(u=>i(u)===i(e))?null:[...a,e].join(n)}function D({dir:t=_(),pathEnv:e=process.env.PATH||"",platform:n=process.platform,isFile:s=z}={}){if(!t)return"";const r=n==="win32"?d.win32:d.posix,o=n==="win32"?";":":",i=u=>{const c=String(u).trim().replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const u of String(e).split(o)){const c=u.trim();if(c){if(i(c)===i(t))return"";if(a.some(l=>s(r.join(c,l))))return c}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",O="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",B=()=>d.join(g.homedir(),".chatpanel","gateway-launch.vbs"),X=t=>Buffer.from(t,"utf16le").toString("base64");function G({systemRoot:t=process.env.SystemRoot||"C:\\Windows",exists:e=h}={}){return e(d.join(t,"System32","vbscript.dll"))}function J({program:t,args:e=[],out:n,err:s,vbs:r,vbscript:o=!0}){const i=f=>`"${f}"`;if(o){const f=`cmd.exe /c "${[t,...e].map(i).join(" ")} >> ${i(n)} 2>> ${i(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${f.replace(/"/g,'""')}", 0, False\r
|
|
23
|
+
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=f=>`'${String(f).replace(/'/g,"''")}'`,u=e.length?` -ArgumentList @(${e.map(f=>a(i(f))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(t)}${u} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,l=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",X(c)];return{kind:"powershell",file:"",text:c,runValue:l.join(" "),argv:l}}function H(t=p){const e=t("reg",["query",y,"/v",m]);if(e.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(e.stdout||"");return n?n[1].trim():""}function At(t=p){const e=t("reg",["query",O,"/v",m]);if(e.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(e.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function Q(t=p){const e=t("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(e.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const Et=`$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
24
|
$t = Add-Type -MemberDefinition $sig -Name 'Env' -Namespace 'ChatPanelWin32' -PassThru
|
|
25
25
|
$r = [UIntPtr]::Zero
|
|
26
|
-
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function
|
|
27
|
-
`)){const l=Number(c.trim());if(!(!l||r.has(l)||
|
|
28
|
-
Description=${
|
|
26
|
+
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function kt(t,{runImpl:e=p,env:n=process.env}={}){if(!t)return{added:!1,dir:t};const s=Q(e),r=j(s.value,t,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:t,onPath:!0};const o=e("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return o.status!==0?{added:!1,dir:t,error:(o.stderr||"").trim()||"reg add failed"}:(e("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",X(Et)],{timeout:15e3}),{added:!0,dir:t,onPath:!0})}function It(t,{runImpl:e=p,env:n=process.env}={}){if(!t)return!0;const s=n.Path??n.PATH??"";return j(Q(e).value,t,{delimiter:";",platform:"win32",env:n})===null||j(s,t,{delimiter:";",platform:"win32",env:n})===null}function Nt({pid:t=process.pid}={}){return`${`$keep = @(${t}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${t}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function Rt({pid:t=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Nt({pid:t})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${t}`]]]}function V(t=p){for(const[e,n]of Rt())t(e,n,{timeout:15e3})}function Ct(){return process.platform==="win32"?V():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${S}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),nt())}function _t(){const{program:t,args:e}=C(),{out:n,err:s}=v(),r=J({program:t,args:e,out:n,err:s,vbs:B(),vbscript:G()});r.file?I(r.file,r.text):w(B(),{force:!0});const o=p("reg",["add",y,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");p("reg",["delete",O,"/v",m,"/f"]);const i=kt(_());return V(),p("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),p(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:i}}function jt(){p("reg",["delete",y,"/v",m,"/f"]),w(B(),{force:!0}),V()}function tt(){return p("reg",["query",y,"/v",m]).status===0}function $({env:t=process.env,release:e=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!t.WSL_DISTRO_NAME||/microsoft/i.test(e))}function b(t=p){const e=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const c of e){if(n=t(c,["/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=c=>(t("wslpath",["-u",c]).stdout||"").trim(),i=o(r),a=o(s);if(!i||!a)return null;const u=d.posix.join(i,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:i,exe:{reg:d.posix.join(u,"reg.exe"),wscript:d.posix.join(u,"wscript.exe"),powershell:d.posix.join(u,"WindowsPowerShell","v1.0","powershell.exe")}}}const Tt=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function et(t,e=p){const n=e("ps",["-o","ppid=","-p",String(t)]);return Number((n.stdout||"").trim())||0}function Wt({pid:t=process.pid,ppid:e=process.ppid,parentOf:n=et,depth:s=8}={}){const r=new Set([t]);let o=e;for(let i=0;i<s&&o>1&&!r.has(o);i+=1)r.add(o),o=n(o);return r}function nt({runImpl:t=p,keep:e=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Tt}={}){const r=e||Wt({parentOf:a=>et(a,t)}),o=[],i=new Set;for(const a of s){const u=t("pgrep",["-f",a]);for(const c of(u.stdout||"").split(`
|
|
27
|
+
`)){const l=Number(c.trim());if(!(!l||r.has(l)||i.has(l))){i.add(l);try{n(l),o.push(l)}catch{}}}}return o}const rt=()=>nt(),st=t=>({win:`${t.home}\\.chatpanel\\gateway-launch.vbs`,unix:d.posix.join(t.homeUnix,".chatpanel","gateway-launch.vbs")});function Lt(t,e){const[n,...s]=e.argv;return[n==="wscript.exe"?t.exe.wscript:t.exe.powershell,...s]}function Ut(t){const{program:e,args:n}=C(),{out:s,err:r}=v(),o=x=>`'${String(x).replace(/'/g,"'\\''")}'`,i=`exec ${[e,...n].map(o).join(" ")} >> ${o(s)} 2>> ${o(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],u=st(t),c=J({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",i],vbs:u.win,vbscript:G({systemRoot:t.sysUnix})});k(d.dirname(u.unix),{recursive:!0}),c.file?I(u.unix,c.text):w(u.unix,{force:!0});const l=p(t.exe.reg,["add",y,"/v",m,"/t","REG_SZ","/d",c.runValue,"/f"]);if(l.status!==0)throw new Error((l.stderr||"").trim()||"reg.exe add failed");p(t.exe.reg,["delete",O,"/v",m,"/f"]),rt(),Ot(800);const f=Lt(t,c);return p(f[0],f.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:_()}}}function Dt(t){p(t.exe.reg,["delete",y,"/v",m,"/f"]),w(st(t).unix,{force:!0}),rt()}function ot(t){return p(t.exe.reg,["query",y,"/v",m]).status===0}function Ot(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{}}const T=()=>d.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Bt({exec:t,display:e=wt}={}){return`[Unit]
|
|
28
|
+
Description=${e}
|
|
29
29
|
After=network.target
|
|
30
30
|
|
|
31
31
|
[Service]
|
|
32
|
-
ExecStart=${
|
|
32
|
+
ExecStart=${t}
|
|
33
|
+
Environment=CHATPANEL_SERVICE=1
|
|
33
34
|
Restart=always
|
|
34
35
|
RestartSec=2
|
|
35
36
|
|
|
36
37
|
[Install]
|
|
37
38
|
WantedBy=default.target
|
|
38
|
-
`}function
|
|
39
|
-
`).slice(-
|
|
40
|
-
`):""}catch{return""}}async function
|
|
41
|
-
`).map(
|
|
42
|
-
`)}export{
|
|
39
|
+
`}function Gt(){const t=$()?b():null;if(t)return Ut(t);if($()&&!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:e,args:n}=C(),s=[e,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=Bt({exec:s}),o=T();k(d.dirname(o),{recursive:!0}),I(o,r),p("systemctl",["--user","daemon-reload"]);const i=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"systemctl enable failed")}function Ht(){const t=$()?b():null;t&&Dt(t),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=T();h(e)&&w(e)}function it(){const t=$()?b():null;return t&&ot(t)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Vt({home:t=g.homedir(),platform:e=process.platform,env:n=process.env}={}){const s=e==="win32"?d.win32:d.posix;return e==="win32"?[s.join(n.LOCALAPPDATA||s.join(t,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(t,".local","bin","chatpanel-bridge")]}const at="net.chatpanel.bridge",F="ChatPanelBridge";function Ft({platform:t=process.platform,runImpl:e=p,paths:n=Vt(),home:s=g.homedir()}={}){if(t==="win32"){e("reg",["delete",y,"/v",F,"/f"]),e("schtasks",["/End","/TN",F]),e("schtasks",["/Delete","/TN",F,"/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 }`;e("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{timeout:15e3})}return}if(t==="darwin"){e("launchctl",["bootout",`gui/${process.getuid?.()??""}/${at}`]);const r=d.join(s,"Library","LaunchAgents",`${at}.plist`);h(r)&&w(r,{force:!0})}else{e("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=d.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)e("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function A(t,e,n){if(process.platform==="darwin")return t();if(process.platform==="win32")return e();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Mt({env:t=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:t}}function re({winInstall:t=""}={}){try{if(process.platform==="darwin")return h(P())?(N("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${S}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const e=$()?b():null;if(e&&ot(e)){const n=H((r,o,i)=>p(r==="reg"?e.exe.reg:r,o,i));return n?(N("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())?(N("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const e=H();if(!e)return!1;const n=d.dirname(process.execPath),s=`timeout /t 3 >nul & ${t?`${t} & `:""}${e} & del /q "${d.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,u)=>u.indexOf(i)===a).join(";"),N("cmd",["/c",s],Mt({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function se(){try{return A(()=>h(P()),tt,it)}catch{return!1}}function ct(){try{return`http://127.0.0.1:${gt().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ut(t=ct(),{timeoutMs:e=2e3}={}){try{const n=await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)});if(!n.ok)return{ok:!1,url:t};const s=await n.json();return{ok:!0,url:t,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:t}}}function lt(t=8){try{const e=L(v().err,"utf8").trimEnd();return e?e.split(`
|
|
40
|
+
`).slice(-t).join(`
|
|
41
|
+
`):""}catch{return""}}async function oe({waitMs:t=4e4,version:e="",probe:n=ut,stop:s=Ct,install:r=()=>A(vt,_t,Gt),retire:o=Ft,wait:i=c=>new Promise(l=>setTimeout(l,c)),now:a=()=>Date.now(),force:u=!1}={}){const c=ct(),l=await n(c);if(!u&&l.ok&&e&&l.version&&yt(l.version,e)>0)return{ok:!1,newer:!0,health:l,shadow:D()};o();const f=l.ok&&l.managedBy&&l.managedBy!=="gateway"?l.managedBy:"",x=!!(l.ok&&e&&l.version&&l.version!==e),W=x&&!f;W&&(s(),await i(1200));const pt=r()||{},M=W?e:"",q=K=>K.ok&&(!M||K.version===M),dt=a()+t;let E=await n(c);for(;!q(E)&&a()<dt;)await i(500),E=await n(c);const Z=q(E);return{...pt,health:E,ok:Z,replaced:W?l.version:"",deferredTo:x?f:"",shadow:D(),errLog:Z?"":lt()}}function ie(){return A(Pt,jt,Ht)}function qt(){return A(bt,tt,it)}function Zt(t,e=process.platform){const n=String(t||"");if(e==="darwin"){const r=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(n);if(!r)return[];const o=i=>i.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");return[...r[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map(i=>o(i[1]))}const s=/^ExecStart=(.*)$/m.exec(n);return s?[...s[1].matchAll(/"([^"]*)"|(\S+)/g)].map(r=>r[1]??r[2]):[]}function Kt({text:t,loaded:e,exists:n=h,platform:s=process.platform}){if(!t)return{state:"none",missing:[]};const i=Zt(t,s).slice(0,2).filter((a,u)=>u===0||/[\\/]/.test(a)&&!a.startsWith("-")).filter(a=>a.startsWith("/")&&!n(a));return i.length?{state:"gone",missing:i}:{state:e?"ok":"unloaded",missing:[]}}function Yt(){try{return A(()=>L(P(),"utf8"),()=>"",()=>L(T(),"utf8"))}catch{return""}}async function ae({platform:t=process.platform}={}){const e=[];let n=!1;try{n=qt()}catch(u){e.push(`auto-start: ${u.message}`)}const s=t==="win32"?{state:"none",missing:[]}:Kt({text:Yt(),loaded:n,platform:t});s.state==="gone"?e.push(`auto-start: ✕ registered, but it starts ${s.missing.join(" and ")}, which is gone (a Node upgrade or a version manager removed it) — \`chatpanel-gateway --install\` registers it again with this copy`):s.state==="unloaded"?e.push("auto-start: installed but switched off (the service manager is not running it) — `chatpanel-gateway --install` turns it back on"):e.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const r=t==="linux"&&$()?b():null;if(t==="win32"||r){const u=r?(l,f,x)=>p(l==="reg"?r.exe.reg:l,f,x):p,c=n?H(u):"";c&&e.push(` launcher: ${c.length>120?`${c.slice(0,117)}…`:c}`),c.startsWith("wscript")&&!G(r?{systemRoot:r.sysUnix}:{})&&e.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&At(u)&&e.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),r&&e.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const o=_();o&&(t==="win32"?e.push(It(o)?`command: ${o} (on PATH)`:`command: ${o} — NOT on your PATH; \`--install\` adds it`):e.push(j(process.env.PATH||"",o,{platform:t})===null?`command: ${o} (on PATH)`:`command: ${o} — not on your PATH: export PATH="${o}:$PATH"`));const i=D({platform:t});i&&e.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${U}`);const a=await ut();if(a.ok){const u=a.version===U?"":` — this command is v${U}; \`--install\` makes it the one that runs`;e.push(`running: v${a.version} at ${a.url}${a.managedBy?` (run by ${a.managedBy})`:""}${a.managedBy?"":u}`)}else{e.push(`running: nothing answers at ${a.url}`);const u=lt();u&&e.push(` last of ${v().err}:`,...u.split(`
|
|
42
|
+
`).map(c=>` ${c}`))}return e.join(`
|
|
43
|
+
`)}export{$t as DARWIN_LAUNCH_ENV,Tt as GATEWAY_ARGV_PATTERNS,_ as commandDir,yt as compareVersions,lt as errLogTail,oe as installService,$ as isWsl,Bt as linUnitText,St as macPlistText,D as pathShadow,j as pathWithDir,ut as probeHealth,X as psEncode,R as realPath,C as resolveLaunch,re as restartService,Ft as retireStandaloneBridge,Wt as selfAndAncestors,se as serviceRegistered,ae as serviceReport,qt as serviceStatus,xt as stableNodePath,Vt as standaloneCandidates,nt as stopOtherGateways,Ct as stopService,ie as uninstallService,Kt as unitHealth,Zt as unitLaunch,G as vbscriptAvailable,It as winCommandOnPath,kt as winEnsureOnPath,J as winLauncher,Mt as winRelaunchOpts,At as winStartupDisabled,Rt as winStopArgs,Nt as winStopScript};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.75.0";export{o as VERSION};
|
package/src/ws-accept.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{createHash as C}from"node:crypto";const O="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",n={cont:0,text:1,binary:2,close:8,ping:9,pong:10},P=o=>C("sha1").update(String(o)+O).digest("base64");function k(o,e,f=""){const g={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",426:"Upgrade Required",429:"Too Many Requests"}[e]||"Error",i=f?JSON.stringify({error:f}):"";try{o.end(`HTTP/1.1 ${e} ${g}\r
|
|
2
|
+
connection: close\r
|
|
3
|
+
content-type: application/json\r
|
|
4
|
+
content-length: ${Buffer.byteLength(i)}\r
|
|
5
|
+
\r
|
|
6
|
+
${i}`)}catch{}}function m(o,e=Buffer.alloc(0)){const f=e.length,g=f<126?Buffer.from([128|o,f]):f<65536?Buffer.from([128|o,126,f>>8,f&255]):null;if(g)return Buffer.concat([g,e]);const i=Buffer.alloc(10);return i[0]=128|o,i[1]=127,i.writeBigUInt64BE(BigInt(f),2),Buffer.concat([i,e])}function N(o,e,f,{protocol:g=null,maxMessage:i=65535}={}){const A=o.headers["sec-websocket-key"];if(String(o.headers.upgrade||"").toLowerCase()!=="websocket"||!A||o.headers["sec-websocket-version"]!=="13")return k(e,426,"websocket upgrade required"),null;const I=String(o.headers["sec-websocket-protocol"]||"").split(",").map(t=>t.trim());e.setNoDelay?.(!0),e.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${P(A)}`,...g&&I.includes(g)?[`Sec-WebSocket-Protocol: ${g}`]:[],"",""].join(`\r
|
|
7
|
+
`));const d={readyState:1,onmessage:null,onclose:null,binaryType:"arraybuffer"};let r=f?.length?Buffer.from(f):Buffer.alloc(0),x=[],U=0,b=0,B=!1;const S=t=>{if(!B){B=!0,d.readyState=3;try{e.destroy()}catch{}queueMicrotask(()=>d.onclose?.({code:t}))}},c=(t,s="")=>{if(B)return;const h=Buffer.from(String(s).slice(0,120)),u=Buffer.alloc(2+h.length);u.writeUInt16BE(t,0),h.copy(u,2);try{e.write(m(n.close,u)),e.end()}catch{}d.readyState=2,setTimeout(()=>S(t),1e3).unref?.()};function E(){for(;;){if(r.length<2)return;const t=r[0],s=r[1],h=(t&128)!==0,u=t&15;if(t&112)return c(1002,"reserved bits");if(!(s&128))return c(1002,"client frames are masked");let l=s&127,y=2;if(l===126){if(r.length<4)return;l=r.readUInt16BE(2),y=4}else if(l===127){if(r.length<10)return;const a=r.readBigUInt64BE(2);if(a>BigInt(i))return c(1009,"too large");l=Number(a),y=10}if(l>i)return c(1009,"too large");if(r.length<y+4+l)return;const T=r.subarray(y,y+4),p=Buffer.from(r.subarray(y+4,y+4+l));for(let a=0;a<p.length;a++)p[a]^=T[a&3];if(r=r.subarray(y+4+l),u>=8){if(!h||l>125)return c(1002,"bad control frame");if(u===n.ping){try{e.write(m(n.pong,p))}catch{}continue}if(u===n.pong)continue;if(u===n.close){const a=p.length>=2?p.readUInt16BE(0):1005;try{e.write(m(n.close,p.subarray(0,2))),e.end()}catch{}S(a);return}return c(1002,"unknown opcode")}if(u===n.cont?!b:b)return c(1002,"bad continuation");if(u!==n.cont&&(b=u),b!==n.text&&b!==n.binary)return c(1002,"unknown opcode");if(U+=p.length,U>i)return c(1009,"too large");if(x.push(p),!h)continue;const w=x.length===1?x[0]:Buffer.concat(x),$=b;if(x=[],U=0,b=0,$===n.text){if(w.toString("utf8")==="ping"){try{e.write(m(n.text,Buffer.from("pong")))}catch{}continue}return c(1003,"binary frames only")}else d.onmessage?.({data:w.buffer.slice(w.byteOffset,w.byteOffset+w.length)});if(B)return}}return e.on("data",t=>{B||(r=r.length?Buffer.concat([r,t]):t,E())}),e.on("close",()=>S(1006)),e.on("error",()=>S(1006)),queueMicrotask(E),d.send=t=>{if(B||d.readyState!==1)return;const s=typeof t=="string",h=s?Buffer.from(t):Buffer.from(t instanceof ArrayBuffer?new Uint8Array(t):t);e.write(m(s?n.text:n.binary,h))},d.close=(t=1e3,s="")=>c(t,s),d}export{P as acceptKey,N as acceptWebSocket,k as refuseUpgrade};
|