@chatpanel/gateway 0.53.2 → 0.55.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/src/service.js CHANGED
@@ -1,5 +1,5 @@
1
- import g from"node:os";import p from"node:path";import{mkdirSync as b,writeFileSync as E,readFileSync as pe,rmSync as w,existsSync as m,statSync as de,realpathSync as q}from"node:fs";import{spawnSync as fe,spawn as k}from"node:child_process";import{loadConfig as he}from"./config.js";import{VERSION as C}from"./version.js";const S="net.chatpanel.gateway",me="ChatPanel Privacy Gateway";function I(e,{real:t=q.native||q}={}){if(!e)return e;try{return t(e)}catch{return e}}function R({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||"")}={}){const n=p.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[p.resolve(t)]}:{program:e,args:[]}}function v(){const e=p.join(g.homedir(),".chatpanel");return b(e,{recursive:!0}),{out:p.join(e,"gateway.log"),err:p.join(e,"gateway.err.log")}}function u(e,t,n={}){return fe(e,t,{encoding:"utf8",...n})}const j=()=>p.join(g.homedir(),"Library","LaunchAgents",`${S}.plist`),ge={MallocLargeCache:"0"};function we({program:e,args:t,out:n,err:s,env:r=ge,label:i=S}={}){const o=a=>String(a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),c=[e,...t].map(a=>` <string>${o(a)}</string>`).join(`
2
- `),l=Object.entries(r).map(([a,d])=>` <key>${o(a)}</key><string>${o(d)}</string>`).join(`
1
+ import g from"node:os";import d from"node:path";import{mkdirSync as A,writeFileSync as E,readFileSync as de,rmSync as w,existsSync as h,statSync as fe,realpathSync as K}from"node:fs";import{spawnSync as me,spawn as k}from"node:child_process";import{loadConfig as he}from"./config.js";import{VERSION as W}from"./version.js";const $="net.chatpanel.gateway",ge="ChatPanel Privacy Gateway";function we(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 I(e,{real:t=K.native||K}={}){if(!e)return e;try{return t(e)}catch{return e}}function ye(e,{exists:t=h}={}){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 N({execPath:e=ye(I(process.execPath)),argv1:t=I(process.argv[1]||"")}={}){const n=d.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[d.resolve(t)]}:{program:e,args:[]}}function S(){const e=d.join(g.homedir(),".chatpanel");return A(e,{recursive:!0}),{out:d.join(e,"gateway.log"),err:d.join(e,"gateway.err.log")}}function p(e,t,n={}){return me(e,t,{encoding:"utf8",...n})}const R=()=>d.join(g.homedir(),"Library","LaunchAgents",`${$}.plist`),xe={MallocLargeCache:"0"};function $e({program:e,args:t,out:n,err:s,env:r=xe,label:i=$}={}){const o=c=>String(c).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[e,...t].map(c=>` <string>${o(c)}</string>`).join(`
2
+ `),u=Object.entries(r).map(([c,l])=>` <key>${o(c)}</key><string>${o(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">
@@ -7,11 +7,11 @@ import g from"node:os";import p from"node:path";import{mkdirSync as b,writeFileS
7
7
  <key>Label</key><string>${i}</string>
8
8
  <key>ProgramArguments</key>
9
9
  <array>
10
- ${c}
10
+ ${a}
11
11
  </array>
12
12
  <key>EnvironmentVariables</key>
13
13
  <dict>
14
- ${l}
14
+ ${u}
15
15
  </dict>
16
16
  <key>RunAtLoad</key><true/>
17
17
  <key>KeepAlive</key><true/>
@@ -19,12 +19,12 @@ ${l}
19
19
  <key>StandardErrorPath</key><string>${o(s)}</string>
20
20
  </dict>
21
21
  </plist>
22
- `}function ye(){const{program:e,args:t}=R(),{out:n,err:s}=v(),r=we({program:e,args:t,out:n,err:s}),i=j();b(p.dirname(i),{recursive:!0}),E(i,r),u("launchctl",["unload",i]);const o=u("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function xe(){const e=j();u("launchctl",["unload","-w",e]),m(e)&&w(e)}function $e(){return(u("launchctl",["list"]).stdout||"").includes(S)}function _({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||""),platform:n=process.platform,isFile:s=Z}={}){const r=n==="win32"?p.win32:p.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 c=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const a=r.dirname(c);if(a===c)break;if(c=a,s(r.join(c,o)))return c;if(s(r.join(c,"bin",o)))return r.join(c,"bin")}return""}const Z=e=>{try{return de(e).isFile()}catch{return!1}};function N(e,t,{delimiter:n=p.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=l=>s==="win32"?l.replace(/%([^%]+)%/g,(a,d)=>r[d]??r[d.toUpperCase()]??a):l,o=l=>{const a=i(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?a.toLowerCase():a},c=String(e||"").split(n).filter(l=>l.trim());return c.some(l=>o(l)===o(t))?null:[...c,t].join(n)}function K({dir:e=_(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=Z}={}){if(!e)return"";const r=n==="win32"?p.win32:p.posix,i=n==="win32"?";":":",o=l=>{const a=String(l).trim().replace(/[\\/]+$/,"");return n==="win32"?a.toLowerCase():a},c=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const l of String(t).split(i)){const a=l.trim();if(a){if(o(a)===o(e))return"";if(c.some(d=>s(r.join(a,d))))return a}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",W="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",h="ChatPanelGateway",L=()=>p.join(g.homedir(),".chatpanel","gateway-launch.vbs"),Y=e=>Buffer.from(e,"utf16le").toString("base64");function U({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=m}={}){return t(p.join(e,"System32","vbscript.dll"))}function z({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=f=>`"${f}"`;if(i){const f=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(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 c=f=>`'${String(f).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(f=>c(o(f))).join(", ")})`:"",a=`Start-Process -WindowStyle Hidden -FilePath ${c(e)}${l} -RedirectStandardOutput ${c(n)} -RedirectStandardError ${c(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Y(a)];return{kind:"powershell",file:"",text:a,runValue:d.join(" "),argv:d}}function D(e=u){const t=e("reg",["query",y,"/v",h]);if(t.status!==0)return"";const n=new RegExp(`${h}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function Se(e=u){const t=e("reg",["query",W,"/v",h]);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 X(e=u){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 ve=`$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);'
22
+ `}function Se(){const{program:e,args:t}=N(),{out:n,err:s}=S(),r=$e({program:e,args:t,out:n,err:s}),i=R();A(d.dirname(i),{recursive:!0}),E(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 ve(){const e=R();p("launchctl",["unload","-w",e]),h(e)&&w(e)}function Pe(){return(p("launchctl",["list"]).stdout||"").includes($)}function j({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||""),platform:n=process.platform,isFile:s=Y}={}){const r=n==="win32"?d.win32:d.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 u=0;u<6;u++){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 Y=e=>{try{return fe(e).isFile()}catch{return!1}};function _(e,t,{delimiter:n=d.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=u=>s==="win32"?u.replace(/%([^%]+)%/g,(c,l)=>r[l]??r[l.toUpperCase()]??c):u,o=u=>{const c=i(u.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(e||"").split(n).filter(u=>u.trim());return a.some(u=>o(u)===o(t))?null:[...a,t].join(n)}function L({dir:e=j(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=Y}={}){if(!e)return"";const r=n==="win32"?d.win32:d.posix,i=n==="win32"?";":":",o=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(t).split(i)){const c=u.trim();if(c){if(o(c)===o(e))return"";if(a.some(l=>s(r.join(c,l))))return c}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",U="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",D=()=>d.join(g.homedir(),".chatpanel","gateway-launch.vbs"),z=e=>Buffer.from(e,"utf16le").toString("base64");function O({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=h}={}){return t(d.join(e,"System32","vbscript.dll"))}function X({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=f=>`"${f}"`;if(i){const f=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(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=t.length?` -ArgumentList @(${t.map(f=>a(o(f))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${u} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,l=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",z(c)];return{kind:"powershell",file:"",text:c,runValue:l.join(" "),argv:l}}function B(e=p){const t=e("reg",["query",y,"/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 be(e=p){const t=e("reg",["query",U,"/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 J(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 Ae=`$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 Pe(e,{runImpl:t=u,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=X(t),r=N(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",Y(ve)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function Ae(e,{runImpl:t=u,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return N(X(t).value,e,{delimiter:";",platform:"win32",env:n})===null||N(s,e,{delimiter:";",platform:"win32",env:n})===null}function be({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 Ee({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",be({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function O(e=u){for(const[t,n]of Ee())e(t,n,{timeout:15e3})}function ke(){return process.platform==="win32"?O():(process.platform==="darwin"?u("launchctl",["bootout",`gui/${process.getuid?.()??""}/${S}`]):u("systemctl",["--user","stop","chatpanel-gateway.service"]),ee())}function Ie(){const{program:e,args:t}=R(),{out:n,err:s}=v(),r=z({program:e,args:t,out:n,err:s,vbs:L(),vbscript:U()});r.file?E(r.file,r.text):w(L(),{force:!0});const i=u("reg",["add",y,"/v",h,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");u("reg",["delete",W,"/v",h,"/f"]);const o=Pe(_());return O(),u("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),u(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:o}}function Re(){u("reg",["delete",y,"/v",h,"/f"]),w(L(),{force:!0}),O()}function J(){return u("reg",["query",y,"/v",h]).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 P(e=u){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const a of t){if(n=e(a,["/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=a=>(e("wslpath",["-u",a]).stdout||"").trim(),o=i(r),c=i(s);if(!o||!c)return null;const l=p.posix.join(o,"System32");return{home:s,homeUnix:c,sysRoot:r,sysUnix:o,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")}}}const je=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function Q(e,t=u){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function _e({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=Q,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 ee({runImpl:e=u,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=je}={}){const r=t||_e({parentOf:c=>Q(c,e)}),i=[],o=new Set;for(const c of s){const l=e("pgrep",["-f",c]);for(const a of(l.stdout||"").split(`
27
- `)){const d=Number(a.trim());if(!(!d||r.has(d)||o.has(d))){o.add(d);try{n(d),i.push(d)}catch{}}}}return i}const te=()=>ee(),ne=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:p.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ne(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Te(e){const{program:t,args:n}=R(),{out:s,err:r}=v(),i=$=>`'${String($).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,c=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=ne(e),a=z({program:"wsl.exe",args:[...c,"-u",g.userInfo().username,"--","bash","-lc",o],vbs:l.win,vbscript:U({systemRoot:e.sysUnix})});b(p.dirname(l.unix),{recursive:!0}),a.file?E(l.unix,a.text):w(l.unix,{force:!0});const d=u(e.exe.reg,["add",y,"/v",h,"/t","REG_SZ","/d",a.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");u(e.exe.reg,["delete",W,"/v",h,"/f"]),te(),We(800);const f=Ne(e,a);return u(f[0],f.slice(1),{timeout:2e4}),{launcher:a.kind,wsl:!0,path:{added:!1,dir:_()}}}function Ce(e){u(e.exe.reg,["delete",y,"/v",h,"/f"]),w(ne(e).unix,{force:!0}),te()}function re(e){return u(e.exe.reg,["query",y,"/v",h]).status===0}function We(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const B=()=>p.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Le({exec:e,display:t=me}={}){return`[Unit]
26
+ [void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function Ee(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=J(t),r=_(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",z(Ae)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function ke(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return _(J(t).value,e,{delimiter:";",platform:"win32",env:n})===null||_(s,e,{delimiter:";",platform:"win32",env:n})===null}function Ie({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 Ne({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Ie({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function G(e=p){for(const[t,n]of Ne())e(t,n,{timeout:15e3})}function Re(){return process.platform==="win32"?G():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${$}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),te())}function je(){const{program:e,args:t}=N(),{out:n,err:s}=S(),r=X({program:e,args:t,out:n,err:s,vbs:D(),vbscript:O()});r.file?E(r.file,r.text):w(D(),{force:!0});const i=p("reg",["add",y,"/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",U,"/v",m,"/f"]);const o=Ee(j());return G(),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 _e(){p("reg",["delete",y,"/v",m,"/f"]),w(D(),{force:!0}),G()}function Q(){return p("reg",["query",y,"/v",m]).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 v(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 u=d.posix.join(o,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:o,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 Ce=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function ee(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function Te({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=ee,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 te({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Ce}={}){const r=t||Te({parentOf:a=>ee(a,e)}),i=[],o=new Set;for(const a of s){const u=e("pgrep",["-f",a]);for(const c of(u.stdout||"").split(`
27
+ `)){const l=Number(c.trim());if(!(!l||r.has(l)||o.has(l))){o.add(l);try{n(l),i.push(l)}catch{}}}}return i}const ne=()=>te(),re=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:d.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function We(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Le(e){const{program:t,args:n}=N(),{out:s,err:r}=S(),i=P=>`'${String(P).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]:[],u=re(e),c=X({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",o],vbs:u.win,vbscript:O({systemRoot:e.sysUnix})});A(d.dirname(u.unix),{recursive:!0}),c.file?E(u.unix,c.text):w(u.unix,{force:!0});const l=p(e.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(e.exe.reg,["delete",U,"/v",m,"/f"]),ne(),De(800);const f=We(e,c);return p(f[0],f.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:j()}}}function Ue(e){p(e.exe.reg,["delete",y,"/v",m,"/f"]),w(re(e).unix,{force:!0}),ne()}function se(e){return p(e.exe.reg,["query",y,"/v",m]).status===0}function De(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const H=()=>d.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Oe({exec:e,display:t=ge}={}){return`[Unit]
28
28
  Description=${t}
29
29
  After=network.target
30
30
 
@@ -35,8 +35,8 @@ RestartSec=2
35
35
 
36
36
  [Install]
37
37
  WantedBy=default.target
38
- `}function Ue(){const e=x()?P():null;if(e)return Te(e);if(x()&&!m("/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}=R(),s=[t,...n].map(c=>/\s/.test(c)?`"${c}"`:c).join(" "),r=Le({exec:s}),i=B();b(p.dirname(i),{recursive:!0}),E(i,r),u("systemctl",["--user","daemon-reload"]);const o=u("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function De(){const e=x()?P():null;e&&Ce(e),u("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=B();m(t)&&w(t)}function se(){const e=x()?P():null;return e&&re(e)?!0:(u("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Oe({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?p.win32:p.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 oe="net.chatpanel.bridge",G="ChatPanelBridge";function Be({platform:e=process.platform,runImpl:t=u,paths:n=Oe(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",G,"/f"]),t("schtasks",["/End","/TN",G]),t("schtasks",["/Delete","/TN",G,"/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?.()??""}/${oe}`]);const r=p.join(s,"Library","LaunchAgents",`${oe}.plist`);m(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");m(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function T(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 Ge({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function Ye({winInstall:e=""}={}){try{if(process.platform==="darwin")return m(j())?(k("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${S}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?P():null;if(t&&re(t)){const n=D((r,i,o)=>u(r==="reg"?t.exe.reg:r,i,o));return n?(k("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 m(B())?(k("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=D();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},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,c,l)=>l.indexOf(o)===c).join(";"),k("cmd",["/c",s],Ge({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function ze(){try{return T(()=>m(j()),J,se)}catch{return!1}}function ie(){try{return`http://127.0.0.1:${he().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ae(e=ie(),{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 ce(e=8){try{const t=pe(v().err,"utf8").trimEnd();return t?t.split(`
38
+ `}function Be(){const e=x()?v():null;if(e)return Le(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}=N(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=Oe({exec:s}),i=H();A(d.dirname(i),{recursive:!0}),E(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 Ge(){const e=x()?v():null;e&&Ue(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();h(t)&&w(t)}function oe(){const e=x()?v():null;return e&&se(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function He({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?d.win32:d.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 ie="net.chatpanel.bridge",F="ChatPanelBridge";function Fe({platform:e=process.platform,runImpl:t=p,paths:n=He(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",F,"/f"]),t("schtasks",["/End","/TN",F]),t("schtasks",["/Delete","/TN",F,"/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?.()??""}/${ie}`]);const r=d.join(s,"Library","LaunchAgents",`${ie}.plist`);h(r)&&w(r,{force:!0})}else{t("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)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function C(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 Me({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function Je({winInstall:e=""}={}){try{if(process.platform==="darwin")return h(R())?(k("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${$}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?v():null;if(t&&se(t)){const n=B((r,i,o)=>p(r==="reg"?t.exe.reg:r,i,o));return n?(k("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(H())?(k("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=B();if(!t)return!1;const n=d.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${d.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,u)=>u.indexOf(o)===a).join(";"),k("cmd",["/c",s],Me({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function Qe(){try{return C(()=>h(R()),Q,oe)}catch{return!1}}function ae(){try{return`http://127.0.0.1:${he().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ce(e=ae(),{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 ue(e=8){try{const t=de(S().err,"utf8").trimEnd();return t?t.split(`
39
39
  `).slice(-e).join(`
40
- `):""}catch{return""}}async function Xe({waitMs:e=4e4,version:t="",probe:n=ae,stop:s=ke,install:r=()=>T(ye,Ie,Ue),retire:i=Be,wait:o=l=>new Promise(a=>setTimeout(a,l)),now:c=()=>Date.now()}={}){i();const l=ie(),a=await n(l),d=a.ok&&a.managedBy&&a.managedBy!=="gateway"?a.managedBy:"",f=!!(a.ok&&t&&a.version&&a.version!==t),$=f&&!d;$&&(s(),await o(1200));const le=r()||{},H=$?t:"",F=V=>V.ok&&(!H||V.version===H),ue=c()+e;let A=await n(l);for(;!F(A)&&c()<ue;)await o(500),A=await n(l);const M=F(A);return{...le,health:A,ok:M,replaced:$?a.version:"",deferredTo:f?d:"",shadow:K(),errLog:M?"":ce()}}function Je(){return T(xe,Re,De)}function He(){return T($e,J,se)}async function Qe({platform:e=process.platform}={}){const t=[];let n=!1;try{n=He()}catch(c){t.push(`auto-start: ${c.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?P():null;if(e==="win32"||s){const c=s?(a,d,f)=>u(a==="reg"?s.exe.reg:a,d,f):u,l=n?D(c):"";l&&t.push(` launcher: ${l.length>120?`${l.slice(0,117)}…`:l}`),l.startsWith("wscript")&&!U(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&&Se(c)&&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=_();r&&(e==="win32"?t.push(Ae(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(N(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const i=K({platform:e});i&&t.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${C}`);const o=await ae();if(o.ok){const c=o.version===C?"":` — this command is v${C}; \`--install\` makes it the one that runs`;t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}${o.managedBy?"":c}`)}else{t.push(`running: nothing answers at ${o.url}`);const c=ce();c&&t.push(` last of ${v().err}:`,...c.split(`
41
- `).map(l=>` ${l}`))}return t.join(`
42
- `)}export{ge as DARWIN_LAUNCH_ENV,je as GATEWAY_ARGV_PATTERNS,_ as commandDir,ce as errLogTail,Xe as installService,x as isWsl,Le as linUnitText,we as macPlistText,K as pathShadow,N as pathWithDir,ae as probeHealth,Y as psEncode,I as realPath,R as resolveLaunch,Ye as restartService,Be as retireStandaloneBridge,_e as selfAndAncestors,ze as serviceRegistered,Qe as serviceReport,He as serviceStatus,Oe as standaloneCandidates,ee as stopOtherGateways,ke as stopService,Je as uninstallService,U as vbscriptAvailable,Ae as winCommandOnPath,Pe as winEnsureOnPath,z as winLauncher,Ge as winRelaunchOpts,Se as winStartupDisabled,Ee as winStopArgs,be as winStopScript};
40
+ `):""}catch{return""}}async function et({waitMs:e=4e4,version:t="",probe:n=ce,stop:s=Re,install:r=()=>C(Se,je,Be),retire:i=Fe,wait:o=c=>new Promise(l=>setTimeout(l,c)),now:a=()=>Date.now(),force:u=!1}={}){const c=ae(),l=await n(c);if(!u&&l.ok&&t&&l.version&&we(l.version,t)>0)return{ok:!1,newer:!0,health:l,shadow:L()};i();const f=l.ok&&l.managedBy&&l.managedBy!=="gateway"?l.managedBy:"",P=!!(l.ok&&t&&l.version&&l.version!==t),T=P&&!f;T&&(s(),await o(1200));const le=r()||{},M=T?t:"",V=Z=>Z.ok&&(!M||Z.version===M),pe=a()+e;let b=await n(c);for(;!V(b)&&a()<pe;)await o(500),b=await n(c);const q=V(b);return{...le,health:b,ok:q,replaced:T?l.version:"",deferredTo:P?f:"",shadow:L(),errLog:q?"":ue()}}function tt(){return C(ve,_e,Ge)}function Ve(){return C(Pe,Q,oe)}async function nt({platform:e=process.platform}={}){const t=[];let n=!1;try{n=Ve()}catch(a){t.push(`auto-start: ${a.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?v():null;if(e==="win32"||s){const a=s?(c,l,f)=>p(c==="reg"?s.exe.reg:c,l,f):p,u=n?B(a):"";u&&t.push(` launcher: ${u.length>120?`${u.slice(0,117)}…`:u}`),u.startsWith("wscript")&&!O(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&&be(a)&&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(ke(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(_(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const i=L({platform:e});i&&t.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${W}`);const o=await ce();if(o.ok){const a=o.version===W?"":` — this command is v${W}; \`--install\` makes it the one that runs`;t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}${o.managedBy?"":a}`)}else{t.push(`running: nothing answers at ${o.url}`);const a=ue();a&&t.push(` last of ${S().err}:`,...a.split(`
41
+ `).map(u=>` ${u}`))}return t.join(`
42
+ `)}export{xe as DARWIN_LAUNCH_ENV,Ce as GATEWAY_ARGV_PATTERNS,j as commandDir,we as compareVersions,ue as errLogTail,et as installService,x as isWsl,Oe as linUnitText,$e as macPlistText,L as pathShadow,_ as pathWithDir,ce as probeHealth,z as psEncode,I as realPath,N as resolveLaunch,Je as restartService,Fe as retireStandaloneBridge,Te as selfAndAncestors,Qe as serviceRegistered,nt as serviceReport,Ve as serviceStatus,ye as stableNodePath,He as standaloneCandidates,te as stopOtherGateways,Re as stopService,tt as uninstallService,O as vbscriptAvailable,ke as winCommandOnPath,Ee as winEnsureOnPath,X as winLauncher,Me as winRelaunchOpts,be as winStartupDisabled,Ne as winStopArgs,Ie as winStopScript};
package/src/team-store.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as m,writeFileSync as y,existsSync as v,mkdirSync as E,renameSync as $}from"node:fs";import{join as w,dirname as _}from"node:path";import x from"node:os";import{randomBytes as f,createCipheriv as N,createDecipheriv as R}from"node:crypto";import"./team-board.js";import{foldRun as M,emptyRun as q,checkpointFrom as B,isResumable as O,LIVE_RUN_STATUSES as J}from"./team-record.js";const A=w(x.homedir(),".chatpanel"),z=process.env.CHATPANEL_TEAMS_STORE||w(A,"team-runs.enc"),d=process.env.CHATPANEL_HISTORY_KEY||w(A,"history-key"),b=200,L=2e3,H=64*1024,P=5*6e4,U=/^[a-zA-Z0-9_-]{4,64}$/,g=new Set(J);function j(){try{if(v(d))return Buffer.from(m(d,"utf8").trim(),"base64")}catch{}const o=f(32);return E(_(d),{recursive:!0,mode:448}),y(d,o.toString("base64"),{mode:384}),o}function C(o,t){const e=f(12),r=N("aes-256-gcm",o,e),n=Buffer.concat([r.update(t),r.final()]);return{v:1,iv:e.toString("base64"),tag:r.getAuthTag().toString("base64"),ct:n.toString("base64")}}function D(o,t){const e=R("aes-256-gcm",o,Buffer.from(t.iv,"base64"));return e.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([e.update(Buffer.from(t.ct,"base64")),e.final()])}const S=o=>o===void 0?void 0:JSON.parse(JSON.stringify(o));function F(o,t){return M(o,t)}class V{constructor({storePath:t=z,now:e=()=>Date.now(),staleAfterMs:r=P,scorecards:n=null,engines:s=null}={}){this.scorecards=n,this.engines=s,this.path=t,this.now=e,this.staleAfterMs=r,this._key=null,this.runs=new Map,this.watchers=new Map}load(){this._key=j();try{if(v(this.path)){const t=JSON.parse(m(this.path,"utf8")),e=JSON.parse(D(this._key,t).toString("utf8"));for(const r of Array.isArray(e?.runs)?e.runs:[])r?.id&&this.runs.set(r.id,r)}}catch{this.runs=new Map}return this}save(){E(_(this.path),{recursive:!0,mode:448});const t=C(this._key,Buffer.from(JSON.stringify({v:1,runs:[...this.runs.values()]}),"utf8")),e=`${this.path}.${process.pid}.tmp`;y(e,JSON.stringify(t),{mode:384}),$(e,this.path)}_fresh(t,{client:e=""}={}){return{...q({id:t,client:e,now:this.now()}),events:[]}}_evict(){if(this.runs.size<=b)return;const t=[...this.runs.values()].sort((e,r)=>e.createdAt-r.createdAt);for(const e of t.slice(0,this.runs.size-b))this.runs.delete(e.id)}_view(t,{events:e=!1}={}){const r=S({...t,events:void 0});return delete r.events,r.stale=g.has(t.status)&&this.now()-t.lastEventAt>this.staleAfterMs,r.quietMs=g.has(t.status)?Math.max(0,this.now()-t.lastEventAt):0,r.resumable=O(r),e&&(r.events=S(t.events)),r}create({id:t,client:e,team:r,request:n}={}){if(!U.test(String(t||"")))throw new Error("run id: 4–64 of [a-zA-Z0-9_-]");if(this.runs.has(t))throw new Error(`run ${t} already exists`);const s=this._fresh(t,{client:e});return s.team=String(r||"").slice(0,64),s.request=String(n||"").slice(0,4e3),this.runs.set(t,s),this._evict(),this.save(),this._view(s)}append(t,e){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);const n=Array.isArray(e)?e:[e];let s=r.events.length,a=0;for(const i of n){if(!i||typeof i!="object"||!i.type)continue;let u;try{u=Buffer.byteLength(JSON.stringify(i),"utf8")}catch{continue}if(u>H)continue;const{type:c,at:p,runId:Y,...k}=i,l=String(c)==="task.delta",h={seq:l?null:s++,type:String(c),at:Number(p)||this.now(),payload:k};l||(r.events.length<L?r.events.push(h):(h.seq=null,r.eventsTruncated=!0,s-=1)),l||(a+=1),F(r,h),this.scorecards&&h.type==="task.scored"&&this.scorecards.fromRunEvent(h,r),this.engines&&(h.type==="task.routed"||h.type==="task.reappointed"||h.type==="task.handoff"||h.type==="task.scored")&&this.engines.fromRunEvent(h,r);for(const T of this.watchers.get(r.id)||[])try{T(h)}catch{}}return a&&this.save(),this._view(r)}get(t,e){const r=this.runs.get(String(t||""));return r?this._view(r,e):null}list({limit:t=50,team:e=""}={}){return[...this.runs.values()].filter(r=>!e||r.team===e).sort((r,n)=>n.createdAt-r.createdAt).slice(0,Math.max(1,Math.min(200,Number(t)||50))).map(r=>{const n=this._view(r);return{...n,board:void 0,threads:void 0,checkpoint:void 0,tasks:n.tasks.map(s=>({...s,text:void 0,transcript:void 0})),findings:r.board.length,waiting:(r.threads?.threads||[]).filter(s=>s.kind==="ask"&&s.status==="waiting").length}})}answer(t,{threadId:e,text:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);const a=(s.threads?.threads||[]).find(p=>p.id===e);if(!a)throw new Error(`no thread ${e}`);if(a.kind!=="ask")throw new Error(`thread ${e} is not an ask`);const i=this.now(),c={id:`ans_${f(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:"answer",text:String(r||"").slice(0,4e3),refs:[],replyTo:null,status:"open",at:i};return this.append(t,[{type:"board.post",at:i,post:c},{type:"board.thread-status",at:i,threadId:e,status:"resolved",answeredAt:i}])}decide(t,{postId:e,status:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);if(!["approved","rejected","proposed","open"].includes(r))throw new Error("status must be approved, rejected, proposed or open");if(!(s.threads?.posts||[]).some(i=>i.id===e))throw new Error(`no post ${e}`);const a=this.now();return this.append(t,[{type:"board.decision",at:a,postId:e,status:r,by:String(n||"person").slice(0,40)}])}post(t,{threadId:e,text:r,by:n="person",kind:s="note",replyTo:a=null}={}){const i=this.runs.get(String(t||""));if(!i)throw new Error(`no run ${t}`);if(!(i.threads?.threads||[]).some(p=>p.id===e))throw new Error(`no thread ${e}`);const u=this.now(),c={id:`pp_${f(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:["note","question","decision"].includes(s)?s:"note",text:String(r||"").slice(0,4e3),refs:[],replyTo:a||null,status:"open",at:u};return this.append(t,[{type:"board.post",at:u,post:c}])}removeThread(t,{threadId:e,by:r="person"}={}){const n=this.runs.get(String(t||""));if(!n)throw new Error(`no run ${t}`);const s=(n.threads?.threads||[]).find(a=>a.id===e);if(!s)throw new Error(`no thread ${e}`);if(s.kind==="ask"&&s.status==="waiting")throw new Error("an ask that is waiting cannot be removed — answer it, or stop the run");return this.append(t,[{type:"board.thread-removed",at:this.now(),threadId:e,by:String(r||"person").slice(0,40)}])}checkpoint(t){const e=this.runs.get(String(t||""));if(!e)throw new Error(`no run ${t}`);return B(this._view(e))}handoff(t,{taskId:e,model:r,by:n="person",reason:s=""}={}){const a=this.runs.get(String(t||""));if(!a)throw new Error(`no run ${t}`);if(!a.tasks.some(i=>i.id===e))throw new Error(`no task ${e}`);if(!r)throw new Error("a model is required");return this.append(t,[{type:"task.handoff-requested",at:this.now(),taskId:e,model:String(r).slice(0,120),by:String(n||"person").slice(0,40),reason:String(s||"").slice(0,400)}])}claim(t,{client:e=""}={}){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);return r.client=String(e||r.client||"").slice(0,40),r.stopRequested=null,this.save(),this._view(r)}stop(t){const e=this.runs.get(String(t||""));return e?g.has(e.status)?this.append(t,[{type:"run.stop-requested",at:this.now()}]):this._view(e):null}eventsSince(t,e=-1){const r=this.runs.get(String(t||""));return r?r.events.filter(n=>n.seq>e).map(S):[]}watch(t,e){return this.watchers.has(t)||this.watchers.set(t,new Set),this.watchers.get(t).add(e),()=>this.watchers.get(t)?.delete(e)}remove(t){const e=this.runs.delete(String(t||""));return e&&(this.watchers.delete(String(t||"")),this.save()),e}get size(){return this.runs.size}}function tt(o){return new V(o).load()}export{L as MAX_EVENTS_PER_RUN,H as MAX_EVENT_BYTES,b as MAX_RUNS,P as STALE_AFTER_MS,V as TeamStore,F as applyEvent,tt as createTeamStore,j as loadOrCreateKey};
1
+ import{readFileSync as m,writeFileSync as y,existsSync as v,mkdirSync as _,renameSync as $}from"node:fs";import{join as w,dirname as E}from"node:path";import x from"node:os";import{randomBytes as p,createCipheriv as N,createDecipheriv as R}from"node:crypto";import"./team-board.js";import{foldRun as M,emptyRun as q,checkpointFrom as B,isResumable as O,LIVE_RUN_STATUSES as J}from"./team-record.js";const A=w(x.homedir(),".chatpanel"),z=process.env.CHATPANEL_TEAMS_STORE||w(A,"team-runs.enc"),d=process.env.CHATPANEL_HISTORY_KEY||w(A,"history-key"),b=200,L=2e3,H=64*1024,P=5*6e4,U=/^[a-zA-Z0-9_-]{4,64}$/,g=new Set(J);function j(){try{if(v(d))return Buffer.from(m(d,"utf8").trim(),"base64")}catch{}const o=p(32);return _(E(d),{recursive:!0,mode:448}),y(d,o.toString("base64"),{mode:384}),o}function C(o,t){const e=p(12),r=N("aes-256-gcm",o,e),n=Buffer.concat([r.update(t),r.final()]);return{v:1,iv:e.toString("base64"),tag:r.getAuthTag().toString("base64"),ct:n.toString("base64")}}function D(o,t){const e=R("aes-256-gcm",o,Buffer.from(t.iv,"base64"));return e.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([e.update(Buffer.from(t.ct,"base64")),e.final()])}const S=o=>o===void 0?void 0:JSON.parse(JSON.stringify(o));function F(o,t){return M(o,t)}class V{constructor({storePath:t=z,now:e=()=>Date.now(),staleAfterMs:r=P,scorecards:n=null,engines:s=null}={}){this.scorecards=n,this.engines=s,this.path=t,this.now=e,this.staleAfterMs=r,this._key=null,this.runs=new Map,this.watchers=new Map,this.listWatchers=new Set}_changed(t,e=!1){for(const r of this.listWatchers)try{r({id:t,removed:e})}catch{}}load(){this._key=j();try{if(v(this.path)){const t=JSON.parse(m(this.path,"utf8")),e=JSON.parse(D(this._key,t).toString("utf8"));for(const r of Array.isArray(e?.runs)?e.runs:[])r?.id&&this.runs.set(r.id,r)}}catch{this.runs=new Map}return this}save(){_(E(this.path),{recursive:!0,mode:448});const t=C(this._key,Buffer.from(JSON.stringify({v:1,runs:[...this.runs.values()]}),"utf8")),e=`${this.path}.${process.pid}.tmp`;y(e,JSON.stringify(t),{mode:384}),$(e,this.path)}_fresh(t,{client:e=""}={}){return{...q({id:t,client:e,now:this.now()}),events:[]}}_evict(){if(this.runs.size<=b)return;const t=[...this.runs.values()].sort((e,r)=>e.createdAt-r.createdAt);for(const e of t.slice(0,this.runs.size-b))this.runs.delete(e.id)}_view(t,{events:e=!1}={}){const r=S({...t,events:void 0});return delete r.events,r.stale=g.has(t.status)&&this.now()-t.lastEventAt>this.staleAfterMs,r.quietMs=g.has(t.status)?Math.max(0,this.now()-t.lastEventAt):0,r.resumable=O(r),e&&(r.events=S(t.events)),r}create({id:t,client:e,team:r,request:n}={}){if(!U.test(String(t||"")))throw new Error("run id: 4–64 of [a-zA-Z0-9_-]");if(this.runs.has(t))throw new Error(`run ${t} already exists`);const s=this._fresh(t,{client:e});return s.team=String(r||"").slice(0,64),s.request=String(n||"").slice(0,4e3),this.runs.set(t,s),this._evict(),this.save(),this._changed(t),this._view(s)}append(t,e){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);const n=Array.isArray(e)?e:[e];let s=r.events.length,a=0;for(const i of n){if(!i||typeof i!="object"||!i.type)continue;let c;try{c=Buffer.byteLength(JSON.stringify(i),"utf8")}catch{continue}if(c>H)continue;const{type:u,at:f,runId:W,...k}=i,l=String(u)==="task.delta",h={seq:l?null:s++,type:String(u),at:Number(f)||this.now(),payload:k};l||(r.events.length<L?r.events.push(h):(h.seq=null,r.eventsTruncated=!0,s-=1)),l||(a+=1),F(r,h),this.scorecards&&h.type==="task.scored"&&this.scorecards.fromRunEvent(h,r),this.engines&&(h.type==="task.routed"||h.type==="task.reappointed"||h.type==="task.handoff"||h.type==="task.scored")&&this.engines.fromRunEvent(h,r);for(const T of this.watchers.get(r.id)||[])try{T(h)}catch{}}return a&&(this.save(),this._changed(r.id)),this._view(r)}get(t,e){const r=this.runs.get(String(t||""));return r?this._view(r,e):null}list({limit:t=50,team:e=""}={}){return[...this.runs.values()].filter(r=>!e||r.team===e).sort((r,n)=>n.createdAt-r.createdAt).slice(0,Math.max(1,Math.min(200,Number(t)||50))).map(r=>{const n=this._view(r);return{...n,board:void 0,threads:void 0,checkpoint:void 0,tasks:n.tasks.map(s=>({...s,text:void 0,transcript:void 0})),findings:r.board.length,waiting:(r.threads?.threads||[]).filter(s=>s.kind==="ask"&&s.status==="waiting").length}})}answer(t,{threadId:e,text:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);const a=(s.threads?.threads||[]).find(f=>f.id===e);if(!a)throw new Error(`no thread ${e}`);if(a.kind!=="ask")throw new Error(`thread ${e} is not an ask`);const i=this.now(),u={id:`ans_${p(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:"answer",text:String(r||"").slice(0,4e3),refs:[],replyTo:null,status:"open",at:i};return this.append(t,[{type:"board.post",at:i,post:u},{type:"board.thread-status",at:i,threadId:e,status:"resolved",answeredAt:i}])}decide(t,{postId:e,status:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);if(!["approved","rejected","proposed","open"].includes(r))throw new Error("status must be approved, rejected, proposed or open");if(!(s.threads?.posts||[]).some(i=>i.id===e))throw new Error(`no post ${e}`);const a=this.now();return this.append(t,[{type:"board.decision",at:a,postId:e,status:r,by:String(n||"person").slice(0,40)}])}post(t,{threadId:e,text:r,by:n="person",kind:s="note",replyTo:a=null}={}){const i=this.runs.get(String(t||""));if(!i)throw new Error(`no run ${t}`);if(!(i.threads?.threads||[]).some(f=>f.id===e))throw new Error(`no thread ${e}`);const c=this.now(),u={id:`pp_${p(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:["note","question","decision"].includes(s)?s:"note",text:String(r||"").slice(0,4e3),refs:[],replyTo:a||null,status:"open",at:c};return this.append(t,[{type:"board.post",at:c,post:u}])}removeThread(t,{threadId:e,by:r="person"}={}){const n=this.runs.get(String(t||""));if(!n)throw new Error(`no run ${t}`);const s=(n.threads?.threads||[]).find(a=>a.id===e);if(!s)throw new Error(`no thread ${e}`);if(s.kind==="ask"&&s.status==="waiting")throw new Error("an ask that is waiting cannot be removed — answer it, or stop the run");return this.append(t,[{type:"board.thread-removed",at:this.now(),threadId:e,by:String(r||"person").slice(0,40)}])}checkpoint(t){const e=this.runs.get(String(t||""));if(!e)throw new Error(`no run ${t}`);return B(this._view(e))}handoff(t,{taskId:e,model:r,by:n="person",reason:s=""}={}){const a=this.runs.get(String(t||""));if(!a)throw new Error(`no run ${t}`);if(!a.tasks.some(i=>i.id===e))throw new Error(`no task ${e}`);if(!r)throw new Error("a model is required");return this.append(t,[{type:"task.handoff-requested",at:this.now(),taskId:e,model:String(r).slice(0,120),by:String(n||"person").slice(0,40),reason:String(s||"").slice(0,400)}])}claim(t,{client:e=""}={}){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);return r.client=String(e||r.client||"").slice(0,40),r.stopRequested=null,this.save(),this._changed(r.id),this._view(r)}stop(t){const e=this.runs.get(String(t||""));return e?g.has(e.status)?this.append(t,[{type:"run.stop-requested",at:this.now()}]):this._view(e):null}eventsSince(t,e=-1){const r=this.runs.get(String(t||""));return r?r.events.filter(n=>n.seq>e).map(S):[]}watch(t,e){return this.watchers.has(t)||this.watchers.set(t,new Set),this.watchers.get(t).add(e),()=>this.watchers.get(t)?.delete(e)}watchAll(t){return this.listWatchers.add(t),()=>this.listWatchers.delete(t)}remove(t){const e=this.runs.delete(String(t||""));return e&&(this.watchers.delete(String(t||"")),this.save(),this._changed(String(t||""),!0)),e}get size(){return this.runs.size}}function tt(o){return new V(o).load()}export{L as MAX_EVENTS_PER_RUN,H as MAX_EVENT_BYTES,b as MAX_RUNS,P as STALE_AFTER_MS,V as TeamStore,F as applyEvent,tt as createTeamStore,j as loadOrCreateKey};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.53.2";export{o as VERSION};
1
+ const o="0.55.0";export{o as VERSION};