@chatpanel/gateway 0.87.0 → 0.88.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/bin/chatpanel-gateway.js +6 -6
- package/package.json +3 -3
- package/src/apple-helper-fetch.js +1 -0
- package/src/apple-model.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/inference-engines.js +1 -1
- package/src/runtime.js +6 -6
- package/src/sandbox-cli.js +7 -0
- package/src/server.js +17 -17
- package/src/service.js +11 -11
- package/src/version.js +1 -1
package/src/service.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import x from"node:os";import{SERVICE_ENV as xe}from"@chatpanel/events/service-standby.js";import f from"node:path";import{mkdirSync as _,writeFileSync as L,readFileSync as W,rmSync as $,existsSync as g,statSync as $e,realpathSync as J}from"node:fs";import{spawnSync as Se,spawn as
|
|
2
|
-
`),
|
|
1
|
+
import x from"node:os";import{SERVICE_ENV as xe}from"@chatpanel/events/service-standby.js";import f from"node:path";import{mkdirSync as _,writeFileSync as L,readFileSync as W,rmSync as $,existsSync as g,statSync as $e,realpathSync as J}from"node:fs";import{spawnSync as Se,spawn as O}from"node:child_process";import{loadConfig as ve}from"./config.js";import{VERSION as G}from"./version.js";const A="net.chatpanel.gateway",be="ChatPanel Privacy Gateway";function Q(e,t){const n=String(e||"").split(".").map(r=>parseInt(r,10)),s=String(t||"").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 E(e,{real:t=J.native||J}={}){if(!e)return e;try{return t(e)}catch{return e}}function Pe(e,{exists:t=g}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(e||""));if(!n)return e;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return t(s)?s:e}function k({execPath:e=Pe(E(process.execPath)),argv1:t=E(process.argv[1]||"")}={}){const n=f.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[f.resolve(t)]}:{program:e,args:[]}}function P(){const e=f.join(x.homedir(),".chatpanel");return _(e,{recursive:!0}),{out:f.join(e,"gateway.log"),err:f.join(e,"gateway.err.log")}}function p(e,t,n={}){return Se(e,t,{encoding:"utf8",...n})}const j=()=>f.join(x.homedir(),"Library","LaunchAgents",`${A}.plist`),Ae={MallocLargeCache:"0"};function ee({program:e,args:t,out:n,err:s,env:r={...Ae,...xe},label:i=A}={}){const o=c=>String(c).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),a=[e,...t].map(c=>` <string>${o(c)}</string>`).join(`
|
|
2
|
+
`),l=Object.entries(r).map(([c,d])=>` <key>${o(c)}</key><string>${o(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">
|
|
@@ -11,7 +11,7 @@ ${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/>
|
|
@@ -19,12 +19,12 @@ ${c}
|
|
|
19
19
|
<key>StandardErrorPath</key><string>${o(s)}</string>
|
|
20
20
|
</dict>
|
|
21
21
|
</plist>
|
|
22
|
-
`}function Ee(){const{program:e,args:t}=k(),{out:n,err:s}=
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=
|
|
22
|
+
`}function Ee(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=ee({program:e,args:t,out:n,err:s}),i=j();_(f.dirname(i),{recursive:!0}),L(i,r),p("launchctl",["unload",i]);const o=p("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function ke(){const e=j();p("launchctl",["unload","-w",e]),g(e)&&$(e)}function je(){return(p("launchctl",["list"]).stdout||"").includes(A)}function D({execPath:e=E(process.execPath),argv1:t=E(process.argv[1]||""),platform:n=process.platform,isFile:s=V}={}){const r=n==="win32"?f.win32:f.posix,i=r.basename(e).toLowerCase();if(!(i.startsWith("node")||i.startsWith("bun")))return r.dirname(e);const o=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const c=r.dirname(a);if(c===a)break;if(a=c,s(r.join(a,o)))return a;if(s(r.join(a,"bin",o)))return r.join(a,"bin")}return""}const V=e=>{try{return $e(e).isFile()}catch{return!1}};function U(e,t,{delimiter:n=f.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=l=>s==="win32"?l.replace(/%([^%]+)%/g,(c,d)=>r[d]??r[d.toUpperCase()]??c):l,o=l=>{const c=i(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(e||"").split(n).filter(l=>l.trim());return a.some(l=>o(l)===o(t))?null:[...a,t].join(n)}function B({dir:e=D(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=V}={}){if(!e)return"";const r=n==="win32"?f.win32:f.posix,i=n==="win32"?";":":",o=l=>{const c=String(l).trim().replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const l of String(t).split(i)){const c=l.trim();if(c){if(o(c)===o(e))return"";if(a.some(d=>s(r.join(c,d))))return c}}return""}function Ie({embedded:e="",pathEnv:t=process.env.PATH||"",platform:n=process.platform,real:s=E,read:r=o=>W(o,"utf8"),isFile:i=V}={}){if(!e)return[];const o=n==="win32"?f.win32:f.posix,a=n==="win32"?["chatpanel-bridge.cmd"]:["chatpanel-bridge"],l=[],c=new Set;for(const d of String(t).split(n==="win32"?";":":")){const u=d.trim().replace(/[\\/]+$/,"");if(!u)continue;const h=a.map(y=>o.join(u,y)).find(y=>i(y));if(!h||c.has(h))continue;c.add(h);const T=n==="win32"?[o.join(u,"node_modules","@chatpanel","bridge")]:[o.dirname(o.dirname(s(h))),o.join(o.dirname(u),"lib","node_modules","@chatpanel","bridge")];let w="";for(const y of T)try{const b=JSON.parse(r(o.join(y,"package.json")));if(b?.name==="@chatpanel/bridge"&&b.version){w=String(b.version);break}}catch{}if(!w||Q(w,e)>=0)continue;const R=o.join(u,n==="win32"?"npm.cmd":"npm");l.push({path:h,version:w,remove:`${i(R)?R:"npm"} rm -g @chatpanel/bridge`})}return l}function Ne(e,{embedded:t=""}={}){if(!e?.length)return[];const n=[` ⚠ An older ChatPanel bridge is still installed: ${e.map(s=>`${s.path} (v${s.version})`).join(", ")}.`,` The gateway carries its own bridge${t?` (v${t})`:""} and does not use ${e.length===1?"it":"them"}, but typing \`chatpanel-bridge\` runs the old copy — which starts a second bridge instead of doing what was asked.`];for(const s of e)n.push(` Remove it: ${s.remove}`);return n.push(" To pair a browser: chatpanel-gateway pair"),n}const S="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",M="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",F=()=>f.join(x.homedir(),".chatpanel","gateway-launch.vbs"),te=e=>Buffer.from(e,"utf16le").toString("base64");function q({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=g}={}){return t(f.join(e,"System32","vbscript.dll"))}function ne({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=u=>`"${u}"`;if(i){const u=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${u.replace(/"/g,'""')}", 0, False\r
|
|
23
|
+
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=u=>`'${String(u).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(u=>a(o(u))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${l} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",te(c)];return{kind:"powershell",file:"",text:c,runValue:d.join(" "),argv:d}}function Z(e=p){const t=e("reg",["query",S,"/v",m]);if(t.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function Te(e=p){const t=e("reg",["query",M,"/v",m]);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 re(e=p){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 Re=`$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 d=Number(
|
|
26
|
+
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function Ce(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=re(t),r=U(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const i=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return i.status!==0?{added:!1,dir:e,error:(i.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",te(Re)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function _e(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return U(re(t).value,e,{delimiter:";",platform:"win32",env:n})===null||U(s,e,{delimiter:";",platform:"win32",env:n})===null}function Le({pid:e=process.pid}={}){return`${`$keep = @(${e}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}'; $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 We({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Le({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function K(e=p){for(const[t,n]of We())e(t,n,{timeout:15e3})}function Oe(){return process.platform==="win32"?K():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),ie())}function De(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=ne({program:e,args:t,out:n,err:s,vbs:F(),vbscript:q()});r.file?L(r.file,r.text):$(F(),{force:!0});const i=p("reg",["add",S,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");p("reg",["delete",M,"/v",m,"/f"]);const o=Ce(D());return K(),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:o}}function Ue(){p("reg",["delete",S,"/v",m,"/f"]),$(F(),{force:!0}),K()}function se(){return p("reg",["query",S,"/v",m]).status===0}function v({env:e=process.env,release:t=x.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function I(e=p){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const c of t){if(n=e(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 i=c=>(e("wslpath",["-u",c]).stdout||"").trim(),o=i(r),a=i(s);if(!o||!a)return null;const l=f.posix.join(o,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:o,exe:{reg:f.posix.join(l,"reg.exe"),wscript:f.posix.join(l,"wscript.exe"),powershell:f.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}const Be=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function oe(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function He({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=oe,depth:s=8}={}){const r=new Set([e]);let i=t;for(let o=0;o<s&&i>1&&!r.has(i);o+=1)r.add(i),i=n(i);return r}function ie({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Be}={}){const r=t||He({parentOf:a=>oe(a,e)}),i=[],o=new Set;for(const a of s){const l=e("pgrep",["-f",a]);for(const c of(l.stdout||"").split(`
|
|
27
|
+
`)){const d=Number(c.trim());if(!(!d||r.has(d)||o.has(d))){o.add(d);try{n(d),i.push(d)}catch{}}}}return i}const ae=()=>ie(),ce=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:f.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ge(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Ve(e){const{program:t,args:n}=k(),{out:s,err:r}=P(),i=h=>`'${String(h).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=ce(e),c=ne({program:"wsl.exe",args:[...a,"-u",x.userInfo().username,"--","bash","-lc",o],vbs:l.win,vbscript:q({systemRoot:e.sysUnix})});_(f.dirname(l.unix),{recursive:!0}),c.file?L(l.unix,c.text):$(l.unix,{force:!0});const d=p(e.exe.reg,["add",S,"/v",m,"/t","REG_SZ","/d",c.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");p(e.exe.reg,["delete",M,"/v",m,"/f"]),ae(),Fe(800);const u=Ge(e,c);return p(u[0],u.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:D()}}}function Me(e){p(e.exe.reg,["delete",S,"/v",m,"/f"]),$(ce(e).unix,{force:!0}),ae()}function le(e){return p(e.exe.reg,["query",S,"/v",m]).status===0}function Fe(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const H=()=>f.join(x.homedir(),".config","systemd","user","chatpanel-gateway.service");function ue({exec:e,display:t=be}={}){return`[Unit]
|
|
28
28
|
Description=${t}
|
|
29
29
|
After=network.target
|
|
30
30
|
|
|
@@ -36,8 +36,8 @@ RestartSec=2
|
|
|
36
36
|
|
|
37
37
|
[Install]
|
|
38
38
|
WantedBy=default.target
|
|
39
|
-
`}function qe(){const e=v()?
|
|
39
|
+
`}function qe(){const e=v()?I():null;if(e)return Ve(e);if(v()&&!g("/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}=k(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=ue({exec:s}),i=H();_(f.dirname(i),{recursive:!0}),L(i,r),p("systemctl",["--user","daemon-reload"]);const o=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function Ze(){const e=v()?I():null;e&&Me(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();g(t)&&$(t)}function pe(){const e=v()?I():null;return e&&le(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Ke({home:e=x.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?f.win32:f.posix;return t==="win32"?[s.join(n.LOCALAPPDATA||s.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(e,".local","bin","chatpanel-bridge")]}const de="net.chatpanel.bridge",Y="ChatPanelBridge";function Ye({platform:e=process.platform,runImpl:t=p,paths:n=Ke(),home:s=x.homedir()}={}){if(e==="win32"){t("reg",["delete",S,"/v",Y,"/f"]),t("schtasks",["/End","/TN",Y]),t("schtasks",["/Delete","/TN",Y,"/F"]);for(const r of n){const i=`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",i],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${de}`]);const r=f.join(s,"Library","LaunchAgents",`${de}.plist`);g(r)&&$(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=f.join(s,".config","systemd","user","chatpanel-bridge.service");g(r)&&$(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function N(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 Xe({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function ct({winInstall:e=""}={}){try{if(process.platform==="darwin")return g(j())?(O("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${A}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=v()?I():null;if(t&&le(t)){const n=Z((r,i,o)=>p(r==="reg"?t.exe.reg:r,i,o));return n?(O("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 g(H())?(O("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=Z();if(!t)return!1;const n=f.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${f.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,a,l)=>l.indexOf(o)===a).join(";"),O("cmd",["/c",s],Xe({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function lt(){try{return N(()=>g(j()),se,pe)}catch{return!1}}function fe(){try{return`http://127.0.0.1:${ve().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function he(e=fe(),{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):"",install:s.install?String(s.install):"",...typeof s.appleHelper=="boolean"?{appleHelper:s.appleHelper}:{}}}catch{return{ok:!1,url:e}}}function ge(e=8){try{const t=W(P().err,"utf8").trimEnd();return t?t.split(`
|
|
40
40
|
`).slice(-e).join(`
|
|
41
|
-
`):""}catch{return""}}function
|
|
42
|
-
`).map(
|
|
43
|
-
`)}export{Ae as DARWIN_LAUNCH_ENV,Be as GATEWAY_ARGV_PATTERNS,D as commandDir,Q as compareVersions,ge as errLogTail,ut as installService,v as isWsl,
|
|
41
|
+
`):""}catch{return""}}function ze({platform:e=process.platform,text:t=we(),loaded:n=null}={}){if(e!=="darwin"&&e!=="linux")return!1;try{if(e==="linux"&&v())return!1;const{program:s,args:r}=k(),i=e==="darwin"?ee({program:s,args:r,...P()}):ue({exec:[s,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" ")});return!t||t!==i?!1:n===null?me():!!n}catch{return!1}}function Je({sandbox:e=null,appleHelper:t}={}){const n=[];if(e){e.enabled?e.runtime?e.narrowed?n.push(`agents: sandboxed through the \`srt\` command — a fixed list of hosts, not "${e.mode}": each agent reaches its own service, the developer hosts and the ones you allow. The npm package (npm i -g @chatpanel/gateway) runs "open".`):n.push(`agents: sandboxed, network "${e.mode}"`):n.push(`agents: NOT sandboxed — ${e.reason||"no sandbox runtime was found"}`):n.push("agents: NOT sandboxed — the sandbox is switched off (sandbox.mode, or CHATPANEL_SANDBOX in the service's environment)");for(const[s,r]of Object.entries(e.agents||{})){const i=[r.signIn?.length?`may sign in with ${r.signIn.join(", ")}`:"",r.outside?"runs OUTSIDE the sandbox":"",r.hosts?.length?`may also reach ${r.hosts.join(", ")}`:"",r.write?.length?`may also write ${r.write.join(", ")}`:""].filter(Boolean);i.length&&n.push(` ${s}: ${i.join("; ")}`)}for(const s of e.warnings||[])n.push(` ⚠ ${s}`)}return t===!1&&n.push(" ✕ Apple on-device: its helper is not in the running install — `chatpanel-gateway --fetch-apple-helper` fetches it (then Start on its row)"),n}async function ut({waitMs:e=4e4,version:t="",probe:n=he,stop:s=Oe,install:r=()=>N(Ee,De,qe),retire:i=Ye,wait:o=d=>new Promise(u=>setTimeout(u,d)),now:a=()=>Date.now(),force:l=!1,current:c=ze}={}){const d=fe(),u=await n(d);if(!l&&u.ok&&t&&u.version&&Q(u.version,t)>0)return{ok:!1,newer:!0,health:u,shadow:B()};i();const h=u.ok&&u.managedBy&&u.managedBy!=="gateway"?u.managedBy:"";if(!l&&u.ok&&t&&u.version===t&&!h&&c())return{ok:!0,unchanged:!0,health:u,replaced:"",deferredTo:"",shadow:B(),errLog:""};const T=!!(u.ok&&t&&u.version&&u.version!==t),w=T&&!h;w&&(s(),await o(1200));const R=r()||{},y=w?t:"",b=z=>z.ok&&(!y||z.version===y),ye=a()+e;let C=await n(d);for(;!b(C)&&a()<ye;)await o(500),C=await n(d);const X=b(C);return{...R,health:C,ok:X,replaced:w?u.version:"",deferredTo:T?h:"",shadow:B(),errLog:X?"":ge()}}function pt(){return N(ke,Ue,Ze)}function me(){return N(je,se,pe)}function Qe(e,t=process.platform){const n=String(e||"");if(t==="darwin"){const r=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(n);if(!r)return[];const i=o=>o.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");return[...r[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map(o=>i(o[1]))}const s=/^ExecStart=(.*)$/m.exec(n);return s?[...s[1].matchAll(/"([^"]*)"|(\S+)/g)].map(r=>r[1]??r[2]):[]}function et({text:e,loaded:t,exists:n=g,platform:s=process.platform}){if(!e)return{state:"none",missing:[]};const o=Qe(e,s).slice(0,2).filter((a,l)=>l===0||/[\\/]/.test(a)&&!a.startsWith("-")).filter(a=>a.startsWith("/")&&!n(a));return o.length?{state:"gone",missing:o}:{state:t?"ok":"unloaded",missing:[]}}function we(){try{return N(()=>W(j(),"utf8"),()=>"",()=>W(H(),"utf8"))}catch{return""}}async function dt({platform:e=process.platform}={}){const t=[];let n=!1;try{n=me()}catch(l){t.push(`auto-start: ${l.message}`)}const s=e==="win32"?{state:"none",missing:[]}:et({text:we(),loaded:n,platform:e});s.state==="gone"?t.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"?t.push("auto-start: installed but switched off (the service manager is not running it) — `chatpanel-gateway --install` turns it back on"):t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const r=e==="linux"&&v()?I():null;if(e==="win32"||r){const l=r?(d,u,h)=>p(d==="reg"?r.exe.reg:d,u,h):p,c=n?Z(l):"";c&&t.push(` launcher: ${c.length>120?`${c.slice(0,117)}…`:c}`),c.startsWith("wscript")&&!q(r?{systemRoot:r.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&&Te(l)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),r&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const i=D();i&&(e==="win32"?t.push(_e(i)?`command: ${i} (on PATH)`:`command: ${i} — NOT on your PATH; \`--install\` adds it`):t.push(U(process.env.PATH||"",i,{platform:e})===null?`command: ${i} (on PATH)`:`command: ${i} — not on your PATH: export PATH="${i}:$PATH"`));const o=B({platform:e});o&&t.push(` ✕ ${o}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${G}`);const a=await he();try{const l=a.ok?String((await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.bridge?.version||""):"";t.push(...Ne(Ie({embedded:l,platform:e}),{embedded:l}).map(c=>c.replace(/^ {2}/,"")))}catch{}if(a.ok){const l=a.version===G?"":` — this command is v${G}; \`--install\` makes it the one that runs`;t.push(`running: v${a.version}${a.install==="binary"?" (the standalone binary)":a.install==="npm"?" (the npm package)":""} at ${a.url}${a.managedBy?` (run by ${a.managedBy})`:""}${a.managedBy?"":l}`);let c=null;try{c=(await(await fetch(`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||4319}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.sandbox||null}catch{}t.push(...Je({sandbox:c,appleHelper:a.appleHelper}))}else{t.push(`running: nothing answers at ${a.url}`);const l=ge();l&&t.push(` last of ${P().err}:`,...l.split(`
|
|
42
|
+
`).map(c=>` ${c}`))}return t.join(`
|
|
43
|
+
`)}export{Ae as DARWIN_LAUNCH_ENV,Be as GATEWAY_ARGV_PATTERNS,D as commandDir,Q as compareVersions,ge as errLogTail,ut as installService,v as isWsl,ue as linUnitText,ee as macPlistText,B as pathShadow,U as pathWithDir,he as probeHealth,te as psEncode,E as realPath,k as resolveLaunch,ct as restartService,Ye as retireStandaloneBridge,Je as runningInstallLines,He as selfAndAncestors,lt as serviceRegistered,dt as serviceReport,me as serviceStatus,Pe as stableNodePath,Ie as staleBridgeCommands,Ne as staleBridgeLines,Ke as standaloneCandidates,ie as stopOtherGateways,Oe as stopService,pt as uninstallService,ze as unitCurrent,et as unitHealth,Qe as unitLaunch,q as vbscriptAvailable,_e as winCommandOnPath,Ce as winEnsureOnPath,ne as winLauncher,Xe as winRelaunchOpts,Te as winStartupDisabled,We as winStopArgs,Le as winStopScript};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.88.0";export{o as VERSION};
|