@chatpanel/gateway 0.23.2 → 0.39.11

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,4 +1,4 @@
1
- import g from"node:os";import p from"node:path";import{mkdirSync as P,writeFileSync as b,readFileSync as X,rmSync as w,existsSync as h,statSync as J}from"node:fs";import{spawnSync as Q,spawn as E}from"node:child_process";import{loadConfig as ee}from"./config.js";const v="net.chatpanel.gateway",te="ChatPanel Privacy Gateway";function A(){const e=process.execPath,t=p.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[p.resolve(process.argv[1])]}:{program:e,args:[]}}function S(){const e=p.join(g.homedir(),".chatpanel");return P(e,{recursive:!0}),{out:p.join(e,"gateway.log"),err:p.join(e,"gateway.err.log")}}function c(e,t,n={}){return Q(e,t,{encoding:"utf8",...n})}const k=()=>p.join(g.homedir(),"Library","LaunchAgents",`${v}.plist`),ne={MallocLargeCache:"0"};function re({program:e,args:t,out:n,err:s,env:r=ne,label:o=v}={}){const i=u=>String(u).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[e,...t].map(u=>` <string>${i(u)}</string>`).join(`
1
+ import g from"node:os";import p from"node:path";import{mkdirSync as P,writeFileSync as b,readFileSync as Q,rmSync as w,existsSync as h,statSync as ee,realpathSync as B}from"node:fs";import{spawnSync as te,spawn as A}from"node:child_process";import{loadConfig as ne}from"./config.js";const $="net.chatpanel.gateway",re="ChatPanel Privacy Gateway";function E(e,{real:t=B.native||B}={}){if(!e)return e;try{return t(e)}catch{return e}}function I({execPath:e=E(process.execPath),argv1:t=E(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 S(){const e=p.join(g.homedir(),".chatpanel");return P(e,{recursive:!0}),{out:p.join(e,"gateway.log"),err:p.join(e,"gateway.err.log")}}function c(e,t,n={}){return te(e,t,{encoding:"utf8",...n})}const k=()=>p.join(g.homedir(),"Library","LaunchAgents",`${$}.plist`),se={MallocLargeCache:"0"};function oe({program:e,args:t,out:n,err:s,env:r=se,label:o=$}={}){const i=u=>String(u).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[e,...t].map(u=>` <string>${i(u)}</string>`).join(`
2
2
  `),l=Object.entries(r).map(([u,d])=>` <key>${i(u)}</key><string>${i(d)}</string>`).join(`
3
3
  `);return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -19,13 +19,13 @@ ${l}
19
19
  <key>StandardErrorPath</key><string>${i(s)}</string>
20
20
  </dict>
21
21
  </plist>
22
- `}function se(){const{program:e,args:t}=A(),{out:n,err:s}=S(),r=re({program:e,args:t,out:n,err:s}),o=k();P(p.dirname(o),{recursive:!0}),b(o,r),c("launchctl",["unload",o]);const i=c("launchctl",["load","-w",o]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function oe(){const e=k();c("launchctl",["unload","-w",e]),h(e)&&w(e)}function ie(){return(c("launchctl",["list"]).stdout||"").includes(v)}function j({execPath:e=process.execPath,argv1:t=process.argv[1]||"",platform:n=process.platform,isFile:s=ae}={}){const r=n==="win32"?p.win32:p.posix,o=r.basename(e).toLowerCase();if(!(o.startsWith("node")||o.startsWith("bun")))return r.dirname(e);const i=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const u=r.dirname(a);if(u===a)break;if(a=u,s(r.join(a,i)))return a;if(s(r.join(a,"bin",i)))return r.join(a,"bin")}return""}const ae=e=>{try{return J(e).isFile()}catch{return!1}};function R(e,t,{delimiter:n=p.delimiter,platform:s=process.platform,env:r=process.env}={}){const o=l=>s==="win32"?l.replace(/%([^%]+)%/g,(u,d)=>r[d]??r[d.toUpperCase()]??u):l,i=l=>{const u=o(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?u.toLowerCase():u},a=String(e||"").split(n).filter(l=>l.trim());return a.some(l=>i(l)===i(t))?null:[...a,t].join(n)}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",_="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",f="ChatPanelGateway",C=()=>p.join(g.homedir(),".chatpanel","gateway-launch.vbs"),O=e=>Buffer.from(e,"utf16le").toString("base64");function L({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=h}={}){return t(p.join(e,"System32","vbscript.dll"))}function B({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:o=!0}){const i=m=>`"${m}"`;if(o){const m=`cmd.exe /c "${[e,...t].map(i).join(" ")} >> ${i(n)} 2>> ${i(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${m.replace(/"/g,'""')}", 0, False\r
23
- `,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=m=>`'${String(m).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(m=>a(i(m))).join(", ")})`:"",u=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${l} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",O(u)];return{kind:"powershell",file:"",text:u,runValue:d.join(" "),argv:d}}function N(e=c){const t=e("reg",["query",y,"/v",f]);if(t.status!==0)return"";const n=new RegExp(`${f}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function ce(e=c){const t=e("reg",["query",_,"/v",f]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function H(e=c){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const le=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
22
+ `}function ie(){const{program:e,args:t}=I(),{out:n,err:s}=S(),r=oe({program:e,args:t,out:n,err:s}),o=k();P(p.dirname(o),{recursive:!0}),b(o,r),c("launchctl",["unload",o]);const i=c("launchctl",["load","-w",o]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function ae(){const e=k();c("launchctl",["unload","-w",e]),h(e)&&w(e)}function ce(){return(c("launchctl",["list"]).stdout||"").includes($)}function _({execPath:e=E(process.execPath),argv1:t=E(process.argv[1]||""),platform:n=process.platform,isFile:s=le}={}){const r=n==="win32"?p.win32:p.posix,o=r.basename(e).toLowerCase();if(!(o.startsWith("node")||o.startsWith("bun")))return r.dirname(e);const i=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const u=r.dirname(a);if(u===a)break;if(a=u,s(r.join(a,i)))return a;if(s(r.join(a,"bin",i)))return r.join(a,"bin")}return""}const le=e=>{try{return ee(e).isFile()}catch{return!1}};function R(e,t,{delimiter:n=p.delimiter,platform:s=process.platform,env:r=process.env}={}){const o=l=>s==="win32"?l.replace(/%([^%]+)%/g,(u,d)=>r[d]??r[d.toUpperCase()]??u):l,i=l=>{const u=o(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?u.toLowerCase():u},a=String(e||"").split(n).filter(l=>l.trim());return a.some(l=>i(l)===i(t))?null:[...a,t].join(n)}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",C="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",f="ChatPanelGateway",N=()=>p.join(g.homedir(),".chatpanel","gateway-launch.vbs"),F=e=>Buffer.from(e,"utf16le").toString("base64");function W({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=h}={}){return t(p.join(e,"System32","vbscript.dll"))}function G({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:o=!0}){const i=m=>`"${m}"`;if(o){const m=`cmd.exe /c "${[e,...t].map(i).join(" ")} >> ${i(n)} 2>> ${i(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${m.replace(/"/g,'""')}", 0, False\r
23
+ `,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=m=>`'${String(m).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(m=>a(i(m))).join(", ")})`:"",u=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${l} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",F(u)];return{kind:"powershell",file:"",text:u,runValue:d.join(" "),argv:d}}function L(e=c){const t=e("reg",["query",y,"/v",f]);if(t.status!==0)return"";const n=new RegExp(`${f}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function ue(e=c){const t=e("reg",["query",C,"/v",f]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function M(e=c){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const pe=`$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 ue(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=H(t),r=R(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const o=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return o.status!==0?{added:!1,dir:e,error:(o.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",O(le)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function pe(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return R(H(t).value,e,{delimiter:";",platform:"win32",env:n})===null||R(s,e,{delimiter:";",platform:"win32",env:n})===null}function W(){const e=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} -and $_.ProcessId -ne $PID } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;c("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),c("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function Re(){if(process.platform==="win32")return W();process.platform==="darwin"?c("launchctl",["bootout",`gui/${process.getuid?.()??""}/${v}`]):c("systemctl",["--user","stop","chatpanel-gateway.service"]),c("pkill",["-f","chatpanel-gateway"])}function de(){const{program:e,args:t}=A(),{out:n,err:s}=S(),r=B({program:e,args:t,out:n,err:s,vbs:C(),vbscript:L()});r.file?b(r.file,r.text):w(C(),{force:!0});const o=c("reg",["add",y,"/v",f,"/t","REG_SZ","/d",r.runValue,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");c("reg",["delete",_,"/v",f,"/f"]);const i=ue(j());return W(),c("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),c(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:i}}function fe(){c("reg",["delete",y,"/v",f,"/f"]),w(C(),{force:!0}),W()}function M(){return c("reg",["query",y,"/v",f]).status===0}function x({env:e=process.env,release:t=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function $(e=c){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const u of t){if(n=e(u,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const o=u=>(e("wslpath",["-u",u]).stdout||"").trim(),i=o(r),a=o(s);if(!i||!a)return null;const l=p.posix.join(i,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:i,exe:{reg:p.posix.join(l,"reg.exe"),wscript:p.posix.join(l,"wscript.exe"),powershell:p.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}function F(){const e=c("pgrep",["-f","chatpanel-gateway"]);for(const t of(e.stdout||"").split(`
27
- `)){const n=Number(t.trim());if(!(!n||n===process.pid||n===process.ppid))try{process.kill(n,"SIGTERM")}catch{}}}const G=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:p.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function me(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function he(e){const{program:t,args:n}=A(),{out:s,err:r}=S(),o=z=>`'${String(z).replace(/'/g,"'\\''")}'`,i=`exec ${[t,...n].map(o).join(" ")} >> ${o(s)} 2>> ${o(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=G(e),u=B({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",i],vbs:l.win,vbscript:L({systemRoot:e.sysUnix})});P(p.dirname(l.unix),{recursive:!0}),u.file?b(l.unix,u.text):w(l.unix,{force:!0});const d=c(e.exe.reg,["add",y,"/v",f,"/t","REG_SZ","/d",u.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");c(e.exe.reg,["delete",_,"/v",f,"/f"]),F(),we(800);const m=me(e,u);return c(m[0],m.slice(1),{timeout:2e4}),{launcher:u.kind,wsl:!0,path:{added:!1,dir:j()}}}function ge(e){c(e.exe.reg,["delete",y,"/v",f,"/f"]),w(G(e).unix,{force:!0}),F()}function V(e){return c(e.exe.reg,["query",y,"/v",f]).status===0}function we(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const T=()=>p.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function ye(){const e=x()?$():null;if(e)return he(e);if(x()&&!h("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=A(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=`[Unit]
28
- Description=${te}
26
+ [void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function de(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=M(t),r=R(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const o=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return o.status!==0?{added:!1,dir:e,error:(o.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",F(pe)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function fe(e,{runImpl:t=c,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return R(M(t).value,e,{delimiter:";",platform:"win32",env:n})===null||R(s,e,{delimiter:";",platform:"win32",env:n})===null}function me({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 he({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",me({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function T(e=c){for(const[t,n]of he())e(t,n,{timeout:15e3})}function Ne(){if(process.platform==="win32")return T();process.platform==="darwin"?c("launchctl",["bootout",`gui/${process.getuid?.()??""}/${$}`]):c("systemctl",["--user","stop","chatpanel-gateway.service"]),c("pkill",["-f","chatpanel-gateway"])}function ge(){const{program:e,args:t}=I(),{out:n,err:s}=S(),r=G({program:e,args:t,out:n,err:s,vbs:N(),vbscript:W()});r.file?b(r.file,r.text):w(N(),{force:!0});const o=c("reg",["add",y,"/v",f,"/t","REG_SZ","/d",r.runValue,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");c("reg",["delete",C,"/v",f,"/f"]);const i=de(_());return T(),c("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),c(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:i}}function we(){c("reg",["delete",y,"/v",f,"/f"]),w(N(),{force:!0}),T()}function H(){return c("reg",["query",y,"/v",f]).status===0}function x({env:e=process.env,release:t=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function v(e=c){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const u of t){if(n=e(u,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const o=u=>(e("wslpath",["-u",u]).stdout||"").trim(),i=o(r),a=o(s);if(!i||!a)return null;const l=p.posix.join(i,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:i,exe:{reg:p.posix.join(l,"reg.exe"),wscript:p.posix.join(l,"wscript.exe"),powershell:p.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}function V(){const e=c("pgrep",["-f","chatpanel-gateway"]);for(const t of(e.stdout||"").split(`
27
+ `)){const n=Number(t.trim());if(!(!n||n===process.pid||n===process.ppid))try{process.kill(n,"SIGTERM")}catch{}}}const q=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:p.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function ye(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function xe(e){const{program:t,args:n}=I(),{out:s,err:r}=S(),o=J=>`'${String(J).replace(/'/g,"'\\''")}'`,i=`exec ${[t,...n].map(o).join(" ")} >> ${o(s)} 2>> ${o(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=q(e),u=G({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",i],vbs:l.win,vbscript:W({systemRoot:e.sysUnix})});P(p.dirname(l.unix),{recursive:!0}),u.file?b(l.unix,u.text):w(l.unix,{force:!0});const d=c(e.exe.reg,["add",y,"/v",f,"/t","REG_SZ","/d",u.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");c(e.exe.reg,["delete",C,"/v",f,"/f"]),V(),Se(800);const m=ye(e,u);return c(m[0],m.slice(1),{timeout:2e4}),{launcher:u.kind,wsl:!0,path:{added:!1,dir:_()}}}function $e(e){c(e.exe.reg,["delete",y,"/v",f,"/f"]),w(q(e).unix,{force:!0}),V()}function Z(e){return c(e.exe.reg,["query",y,"/v",f]).status===0}function Se(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const U=()=>p.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function ve(){const e=x()?v():null;if(e)return xe(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}=I(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=`[Unit]
28
+ Description=${re}
29
29
  After=network.target
30
30
 
31
31
  [Service]
@@ -34,8 +34,8 @@ Restart=on-failure
34
34
 
35
35
  [Install]
36
36
  WantedBy=default.target
37
- `,o=T();P(p.dirname(o),{recursive:!0}),b(o,r),c("systemctl",["--user","daemon-reload"]);const i=c("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"systemctl enable failed")}function xe(){const e=x()?$():null;e&&ge(e),c("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=T();h(t)&&w(t)}function q(){const e=x()?$():null;return e&&V(e)?!0:(c("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function ve({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){return t==="win32"?[p.join(n.LOCALAPPDATA||p.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[p.join(e,".local","bin","chatpanel-bridge")]}const Z="net.chatpanel.bridge",U="ChatPanelBridge";function Se({platform:e=process.platform,runImpl:t=c,paths:n=ve(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",U,"/f"]),t("schtasks",["/End","/TN",U]),t("schtasks",["/Delete","/TN",U,"/F"]);for(const r of n){const o=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${Z}`]);const r=p.join(s,"Library","LaunchAgents",`${Z}.plist`);h(r)&&w(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=p.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function I(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Ie({winInstall:e=""}={}){try{if(process.platform==="darwin")return h(k())?(E("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${v}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?$():null;if(t&&V(t)){const n=N((r,o,i)=>c(r==="reg"?t.exe.reg:r,o,i));return n?(E("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return h(T())?(E("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=N();if(!t)return!1;const n=p.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${p.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},o=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[o]=[n,...(r[o]||"").split(";").filter(Boolean)].filter((i,a,l)=>l.indexOf(i)===a).join(";"),E("cmd",["/c",s],{detached:!0,stdio:"ignore",windowsHide:!0,env:r}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function je(){try{return I(()=>h(k()),M,q)}catch{return!1}}function K(){try{return`http://127.0.0.1:${ee().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function D(e=K(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:e}}}function Y(e=8){try{const t=X(S().err,"utf8").trimEnd();return t?t.split(`
37
+ `,o=U();P(p.dirname(o),{recursive:!0}),b(o,r),c("systemctl",["--user","daemon-reload"]);const i=c("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"systemctl enable failed")}function Pe(){const e=x()?v():null;e&&$e(e),c("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=U();h(t)&&w(t)}function K(){const e=x()?v():null;return e&&Z(e)?!0:(c("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function be({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 Y="net.chatpanel.bridge",D="ChatPanelBridge";function Ae({platform:e=process.platform,runImpl:t=c,paths:n=be(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",D,"/f"]),t("schtasks",["/End","/TN",D]),t("schtasks",["/Delete","/TN",D,"/F"]);for(const r of n){const o=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${Y}`]);const r=p.join(s,"Library","LaunchAgents",`${Y}.plist`);h(r)&&w(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=p.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function j(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 Ee({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function We({winInstall:e=""}={}){try{if(process.platform==="darwin")return h(k())?(A("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&&Z(t)){const n=L((r,o,i)=>c(r==="reg"?t.exe.reg:r,o,i));return n?(A("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(U())?(A("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=L();if(!t)return!1;const n=p.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${p.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},o=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[o]=[n,...(r[o]||"").split(";").filter(Boolean)].filter((i,a,l)=>l.indexOf(i)===a).join(";"),A("cmd",["/c",s],Ee({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function Le(){try{return j(()=>h(k()),H,K)}catch{return!1}}function z(){try{return`http://127.0.0.1:${ne().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function O(e=z(),{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 X(e=8){try{const t=Q(S().err,"utf8").trimEnd();return t?t.split(`
38
38
  `).slice(-e).join(`
39
- `):""}catch{return""}}async function _e({waitMs:e=4e4}={}){Se();const t=I(se,de,ye)||{},n=K(),s=Date.now()+e;let r=await D(n);for(;!r.ok&&Date.now()<s;)await new Promise(o=>setTimeout(o,500)),r=await D(n);return{...t,health:r,errLog:r.ok?"":Y()}}function Ce(){return I(oe,fe,xe)}function $e(){return I(ie,M,q)}async function Le({platform:e=process.platform}={}){const t=[];let n=!1;try{n=$e()}catch(i){t.push(`auto-start: ${i.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?$():null;if(e==="win32"||s){const i=s?(l,u,d)=>c(l==="reg"?s.exe.reg:l,u,d):c,a=n?N(i):"";a&&t.push(` launcher: ${a.length>120?`${a.slice(0,117)}…`:a}`),a.startsWith("wscript")&&!L(s?{systemRoot:s.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&ce(i)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),s&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const r=j();r&&(e==="win32"?t.push(pe(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(R(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const o=await D();if(o.ok)t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}`);else{t.push(`running: nothing answers at ${o.url}`);const i=Y();i&&t.push(` last of ${S().err}:`,...i.split(`
39
+ `):""}catch{return""}}async function Te({waitMs:e=4e4}={}){Ae();const t=j(ie,ge,ve)||{},n=z(),s=Date.now()+e;let r=await O(n);for(;!r.ok&&Date.now()<s;)await new Promise(o=>setTimeout(o,500)),r=await O(n);return{...t,health:r,errLog:r.ok?"":X()}}function Ue(){return j(ae,we,Pe)}function Ie(){return j(ce,H,K)}async function De({platform:e=process.platform}={}){const t=[];let n=!1;try{n=Ie()}catch(i){t.push(`auto-start: ${i.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?v():null;if(e==="win32"||s){const i=s?(l,u,d)=>c(l==="reg"?s.exe.reg:l,u,d):c,a=n?L(i):"";a&&t.push(` launcher: ${a.length>120?`${a.slice(0,117)}…`:a}`),a.startsWith("wscript")&&!W(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&&ue(i)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),s&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const r=_();r&&(e==="win32"?t.push(fe(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(R(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const o=await O();if(o.ok)t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}`);else{t.push(`running: nothing answers at ${o.url}`);const i=X();i&&t.push(` last of ${S().err}:`,...i.split(`
40
40
  `).map(a=>` ${a}`))}return t.join(`
41
- `)}export{ne as DARWIN_LAUNCH_ENV,j as commandDir,Y as errLogTail,_e as installService,x as isWsl,re as macPlistText,R as pathWithDir,D as probeHealth,O as psEncode,A as resolveLaunch,Ie as restartService,Se as retireStandaloneBridge,je as serviceRegistered,Le as serviceReport,$e as serviceStatus,ve as standaloneCandidates,Re as stopService,Ce as uninstallService,L as vbscriptAvailable,pe as winCommandOnPath,ue as winEnsureOnPath,B as winLauncher,ce as winStartupDisabled};
41
+ `)}export{se as DARWIN_LAUNCH_ENV,_ as commandDir,X as errLogTail,Te as installService,x as isWsl,oe as macPlistText,R as pathWithDir,O as probeHealth,F as psEncode,E as realPath,I as resolveLaunch,We as restartService,Ae as retireStandaloneBridge,Le as serviceRegistered,De as serviceReport,Ie as serviceStatus,be as standaloneCandidates,Ne as stopService,Ue as uninstallService,W as vbscriptAvailable,fe as winCommandOnPath,de as winEnsureOnPath,G as winLauncher,Ee as winRelaunchOpts,ue as winStartupDisabled,he as winStopArgs,me as winStopScript};
@@ -3,4 +3,4 @@ import{join as E}from"node:path";import{mkdirSync as m,chmodSync as u,existsSync
3
3
  FROM fts JOIN records r ON r.id = fts.id
4
4
  WHERE ${d.join(" AND ")} ORDER BY b LIMIT ? OFFSET ?`,l).map(a=>({id:a.id,score:-a.b,title:a.title,type:a.type,date:a.date,snippet:a.snip||""}))}related(e,{limit:r=5}={}){const t=this.get(e);if(!t)return[];const s=f(`${t.title||""} ${String(t.text||"").slice(0,2e3)}`);if(!s)return[];const n=s.split(" OR ").slice(0,40).join(" OR ");return this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b
5
5
  FROM fts JOIN records r ON r.id = fts.id
6
- WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,[n,e,r]).map(i=>({id:i.id,score:-i.b,title:i.title,type:i.type,date:i.date}))}list({limit:e=50,offset:r=0,type:t=null}={}){const s=t?" WHERE type = ?":"",n=t?[String(t)]:[],o=this.db.get(`SELECT COUNT(*) c FROM records${s}`,n)?.c||0,i=this.db.all(`SELECT id, title, type, date, chars FROM records${s} ORDER BY date DESC LIMIT ? OFFSET ?`,[...n,e,r]);return{total:o,items:i}}get(e,{maxChars:r=null,offset:t=0}={}){const s=this.db.get("SELECT id, title, type, date FROM records WHERE id = ?",[e]);if(!s)return null;const o=this.db.get("SELECT text FROM fts WHERE id = ?",[e])?.text||"";let i=t?o.slice(t):o,d=!1;return r&&i.length>r&&(i=i.slice(0,r),d=!0),{...s,text:i,totalChars:o.length,offset:Number(t)||0,truncated:d}}clear(){const e=this.size;return this.db.exec("DELETE FROM records"),this.db.exec("DELETE FROM fts"),e}}async function w(c={}){try{return await new g(c).init()}catch(e){console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`);const r=new R(c).load();return r.lossless=null,r}}export{g as SqliteHistoryStore,w as createHistoryStore};
6
+ WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,[n,e,r]).map(i=>({id:i.id,score:-i.b,title:i.title,type:i.type,date:i.date}))}list({limit:e=50,offset:r=0,type:t=null}={}){const s=t?" WHERE type = ?":"",n=t?[String(t)]:[],o=this.db.get(`SELECT COUNT(*) c FROM records${s}`,n)?.c||0,i=this.db.all(`SELECT id, title, type, date, chars FROM records${s} ORDER BY date DESC LIMIT ? OFFSET ?`,[...n,e,r]);return{total:o,items:i}}get(e,{maxChars:r=null,offset:t=0}={}){const s=this.db.get("SELECT id, title, type, date FROM records WHERE id = ?",[e]);if(!s)return null;const o=this.db.get("SELECT text FROM fts WHERE id = ?",[e])?.text||"";let i=t?o.slice(t):o,d=!1;return r&&i.length>r&&(i=i.slice(0,r),d=!0),{...s,text:i,totalChars:o.length,offset:Number(t)||0,truncated:d}}clear(){const e=this.size;return this.db.exec("DELETE FROM records"),this.db.exec("DELETE FROM fts"),e}}async function w(c={}){try{return await new g(c).init()}catch(e){console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`);const r=new R(c).load();return r.lossless=null,r}}export{g as SqliteHistoryStore,w as createHistoryStore,O as openDb};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as V}from"node:path";import{existsSync as J,readdirSync as Z}from"node:fs";import{randomUUID as I}from"node:crypto";import{ensureLib as K,modelRoot as X}from"./ner-engine.js";import{runtimeDtype as A,runtimeName as B,DTYPE_SUFFIX as ee}from"./model-runtime.js";import{verifyModelWeights as te}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Y,isEnglishOnly as j,sttModelDtype as N,isKnownSttModel as ne,sttModelEngine as R}from"./stt-models.js";import*as E from"./parakeet-engine.js";import*as L from"./diarize-engine.js";import{makeWarmTimer as z}from"./warm-timer.js";const _=16e3,re=_;let l="off",f=null,u=null,T=null,S=null,m=null,x=null,g=null;function oe(e=f||Y,t=N(e)||A()){if(R(e)==="parakeet-tdt")return E.parakeetOnDisk(e,E.parakeetDtype(t));const n=V(X(),...e.split("/"),"onnx");if(!J(n))return!1;const r=ee[t]??"";try{const o=Z(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function Ae(){return l}function v(){return l==="ready"&&!!u}function Le(){return m}function ve(){return{configured:l!=="off",ok:v(),state:l,model:f,dtype:x,runtime:B(),error:T,warmMs:g?.warmMs??null}}function $e(){return!!g?.pending()}function b(){return M.size>0||l==="loading"||l==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;g?.disarm();const t=u;if(u=null,S=null,x=null,m=null,T=null,l="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((g?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function O(e){return e.then(t=>(t&&!b()&&g?.arm(),t))}async function W(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(R(e)==="parakeet-tdt")return ie(e,{log:t,allowDownload:n,dtype:r});const o=u,i=f;let s;try{s=await K()}catch(w){return l="error",T=`engine load failed: ${w.message}`,t(`[stt] transformers.js not available (${w.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||N(e)||A(),c=oe(e,a);if(s.env.allowRemoteModels=c?!1:!!n,!c&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=s.env.remoteHost,y=!ne(e);if(!c&&y)try{s.env.remoteHost="https://huggingface.co/"}catch{}l=c?"loading":"downloading",c||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${y?", from Hugging Face":""})…`));try{const w=d=>{if(!d)return;const Q=typeof d.progress=="number"?Math.round(d.progress):m?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?m={model:e,file:d.file||m?.file||null,pct:Q}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let k;try{k=await s.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:w})}catch(d){if(c||y||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,k=await s.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:w})}if(!c)try{te(e,{modelsDir:X(),log:t})}catch(d){try{await k.dispose?.()}catch{}throw d}if(u=k,f=e,l="ready",T=null,m=null,x=a,o&&o!==k)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(w){return T=w.message,m=null,o?(u=o,f=i,l="ready"):l="error",t(`[stt] model load failed (${w.message})${o?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=p}catch{}}}async function ie(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=u,i=f,s=E.parakeetDtype(r&&r!=="auto"?r:ae()),h=E.parakeetOnDisk(e,s);if(!h&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;l=h?"loading":"downloading",h||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await E.loadRecognizer({modelId:e,dtype:s,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),c=async p=>({text:await a.transcribe(p)});if(c.__parakeet=!0,c.dispose=()=>a.dispose(),u=c,f=e,l="ready",T=null,m=null,x=s,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return T=a.message,m=null,o?(u=o,f=i,l="ready"):l="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function ae(){return E.PARAKEET_DEFAULT_DTYPE}function Pe(e={}){if(S)return S;const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=e.model||Y,l="loading",g=z({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),S=O(W(f,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})),S}async function Fe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=R(e)==="parakeet-tdt"?E.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:E.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:N(e)||A();return e===f&&v()&&x===r?!0:(g??=z({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})}),O(W(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})))}const se=4,le=6e4,ce=1200,ue=12,H=700,$=.008,de=30,M=new Map;let P=Promise.resolve();function Ne(){return M.size}const fe=300,me=3e3;function pe(e){const t=Number(e);return Number.isFinite(t)?Math.min(me,Math.max(fe,Math.round(t))):H}function Re({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=H}={}){if(M.size>=se){const s=new Error("too many concurrent dictation sessions");throw s.code="too_many_sessions",s}const i={id:I(),endSilenceMs:pe(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new L.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return M.set(i.id,i),g?.disarm(),i.diarizer&&L.retain(),G(i),{id:i.id}}function U(e){return M.get(String(e||""))||null}function ze(e,t){const n=U(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function D(e,t){for(const n of e.listeners)try{n(t)}catch{}}function G(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>we(e.id).catch(()=>{}),le),e.idleTimer.unref?.()}function Ce(e,t){const n=U(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,G(n),ge(n))}function He(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ge(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+ce-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>q(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function he(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function F(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function ye(e){const t=Math.round(.02*_);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(F(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(F(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function _e(e){try{const t=await K(),n=u?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>_*8?e.subarray(0,_*8):e,o=await u.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),s=await u.model({...o,decoder_input_ids:i});let h=null,a=-1/0;for(const[c,p]of Object.entries(n.lang_to_id)){const y=Number(s.logits.data[p]);y>a&&(a=y,h=c)}return h?h.slice(2,-2):null}catch{return null}}async function q(e,{flush:t=!1}={}){if(e.closed&&!t||!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=he(e),r=Math.round((e.endSilenceMs||H)/1e3*_),o=n.length>r&&F(n,n.length-r)<$;if(F(n)<$){n.length>_*5&&(e.chunks=[n.subarray(n.length-_)],e.samples=_);return}if(!e.lang&&!e.langTried&&!j(f)&&!u?.__parakeet&&n.length>=_){e.langTried=!0;const a=await _e(n);a&&(e.lang=a,D(e,{type:"language",lang:a}))}let i="";try{const a=j(f)?{}:{language:e.lang||void 0,task:"transcribe"},c=await u(n,a);i=String(c?.text||"").trim()}catch(a){D(e,{type:"error",code:"decode_failed",message:a.message,fatal:!1});return}if(!i)return;const s=n.length>=ue*_,h=n.length>=de*_;if(t||o||s||h){const a=t?"flush":o?"silence":h?"overflow":"length",c=a==="flush"||a==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const y=e.speakerLabel?null:ye(n),w=y?await L.embed(y):null,k=!!y&&y.length<re;p=e.diarizer.assign(w,{pinnedLabel:e.speakerLabel,weak:k})}catch{}D(e,{type:"final",text:i,reason:a,endOfTurn:c,...p?{speaker:p}:{}})}else i!==e.lastInterim&&(e.lastInterim=i,D(e,{type:"interim",text:i}))}async function we(e){const t=U(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(P=P.then(()=>q(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),M.delete(t.id),t.diarizer&&L.release(),M.size===0&&v()&&g?.arm()}return!0}function Ue(){for(const e of M.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);M.clear(),g?.disarm(),g=null,l="off",f=null,u=null,T=null,S=null,m=null}function Ke(e,t="test/fake",{warmMs:n=null}={}){u=e,f=t,l=e?"ready":"off",n!==null&&(g=z({warmMs:n,busy:b,unload:()=>C()}),e&&g.arm())}export{_ as SAMPLE_RATE,re as WEAK_SPEAKER_SAMPLES,Ue as _reset,Ke as _setPipeForTest,pe as clampEndSilence,Re as createSession,we as endSession,U as getSession,ve as health,Pe as init,v as isReady,oe as modelOnDisk,Le as progress,Ce as pushAudio,A as runtimeDtype,B as runtimeName,Ne as sessionCount,Fe as setModel,Ae as state,ze as subscribe,He as toFloat32,C as unload,$e as warmPending};
1
+ import{join as J}from"node:path";import{existsSync as Z,readdirSync as I}from"node:fs";import{randomUUID as ee}from"node:crypto";import{ensureLib as X,modelRoot as O}from"./ner-engine.js";import{runtimeDtype as D,runtimeName as B,DTYPE_SUFFIX as te}from"./model-runtime.js";import{verifyModelWeights as ne}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Y,isEnglishOnly as j,sttModelDtype as R,isKnownSttModel as re,sttModelEngine as z}from"./stt-models.js";import*as k from"./parakeet-engine.js";import*as L from"./diarize-engine.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,oe=p,ie=2*p,ae=2,se=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function le(e,t){if(t>ae*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?se.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let l="off",h=null,f=null,T=null,S=null,g=null,x=null,_=null;function ce(e=h||Y,t=R(e)||D()){if(z(e)==="parakeet-tdt")return k.parakeetOnDisk(e,k.parakeetDtype(t));const n=J(O(),...e.split("/"),"onnx");if(!Z(n))return!1;const r=te[t]??"";try{const o=I(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(a=>a===`decoder_model_merged${r}.onnx`||a===`decoder_model${r}.onnx`)}catch{return!1}}function Ne(){return l}function v(){return l==="ready"&&!!f}function Pe(){return g}function Fe(){return{configured:l!=="off",ok:v(),state:l,model:h,dtype:x,runtime:B(),error:T,warmMs:_?.warmMs??null}}function Re(){return!!_?.pending()}function A(){return M.size>0||l==="loading"||l==="downloading"}async function C({log:e=()=>{}}={}){if(A())return!1;_?.disarm();const t=f;if(f=null,S=null,x=null,g=null,T=null,l="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((_?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function W(e){return e.then(t=>(t&&!A()&&_?.arm(),t))}async function G(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return ue(e,{log:t,allowDownload:n,dtype:r});const o=f,a=h;let s;try{s=await X()}catch(m){return l="error",T=`engine load failed: ${m.message}`,t(`[stt] transformers.js not available (${m.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||R(e)||D(),c=ce(e,i);if(s.env.allowRemoteModels=c?!1:!!n,!c&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=s.env.remoteHost,w=!re(e);if(!c&&w)try{s.env.remoteHost="https://huggingface.co/"}catch{}l=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${w?", from Hugging Face":""})…`));try{const m=d=>{if(!d)return;const F=typeof d.progress=="number"?Math.round(d.progress):g?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?g={model:e,file:d.file||g?.file||null,pct:F}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let E;try{E=await s.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(d){if(c||w||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,E=await s.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{ne(e,{modelsDir:O(),log:t})}catch(d){try{await E.dispose?.()}catch{}throw d}if(f=E,h=e,l="ready",T=null,g=null,x=i,o&&o!==E)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return T=m.message,g=null,o?(f=o,h=a,l="ready"):l="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=y}catch{}}}async function ue(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,a=h,s=k.parakeetDtype(r&&r!=="auto"?r:de()),u=k.parakeetOnDisk(e,s);if(!u&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;l=u?"loading":"downloading",u||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await k.loadRecognizer({modelId:e,dtype:s,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),c=async y=>({text:await i.transcribe(y)});if(c.__parakeet=!0,c.dispose=()=>i.dispose(),f=c,h=e,l="ready",T=null,g=null,x=s,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return T=i.message,g=null,o?(f=o,h=a,l="ready"):l="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function de(){return k.PARAKEET_DEFAULT_DTYPE}function ze(e={}){if(S)return S;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||Y,l="loading",_=H({warmMs:e.warmMs,busy:A,log:t,unload:()=>C({log:t})}),S=W(G(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})),S}async function He(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?k.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:k.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||D();return e===h&&v()&&x===r?!0:(_??=H({warmMs:t.warmMs,busy:A,log:n,unload:()=>C({log:n})}),W(G(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})))}const fe=4,me=6e4,pe=1200,q=12,U=700,$=.008,he=30,M=new Map;let N=Promise.resolve();function Ce(){return M.size}const ge=300,ye=3e3;function _e(e){const t=Number(e);return Number.isFinite(t)?Math.min(ye,Math.max(ge,Math.round(t))):U}function Ue({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=U,interims:a=!0,remote:s=null}={}){if(M.size>=fe){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:ee(),endSilenceMs:_e(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new L.Diarizer:null,remote:s||null,interims:a!==!1&&!s,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return M.set(u.id,u),_?.disarm(),u.diarizer&&L.retain(),Q(u),{id:u.id}}function K(e){return M.get(String(e||""))||null}function Ke(e,t){const n=K(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function b(e,t){for(const n of e.listeners)try{n(t)}catch{}}function Q(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Ee(e.id).catch(()=>{}),me),e.idleTimer.unref?.()}function Xe(e,t){const n=K(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,Q(n),we(n))}function Oe(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function we(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+pe-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,N=N.then(()=>V(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Te(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function P(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let a=t;a<n;a++)r+=e[a]*e[a];return Math.sqrt(r/o)}function Me(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(P(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(P(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function ke(e){try{const t=await X(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>p*8?e.subarray(0,p*8):e,o=await f.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),s=await f.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const w=Number(s.logits.data[y]);w>i&&(i=w,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function V(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Te(e),r=Math.round((e.endSilenceMs||U)/1e3*p),o=n.length>r&&P(n,n.length-r)<$;if(P(n)<$){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!o&&n.length<q*p)return;if(!e.remote&&!e.lang&&!e.langTried&&!j(h)&&!f?.__parakeet&&n.length>=p){e.langTried=!0;const i=await ke(n);i&&(e.lang=i,b(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=j(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await f(n,i);a=String(c?.text||"").trim()}}catch(i){b(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const s=n.length>=q*p,u=n.length>=he*p;if(t||o||s||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=Me(n);if(le(a,y?y.length:0))return;let w=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,E=m?await L.embed(m):null,d=!!m&&m.length<oe,F=!!m&&m.length<ie;w=e.diarizer.assign(E,{pinnedLabel:e.speakerLabel,weak:d,thin:F})}catch{}b(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),...w?{speaker:w}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,b(e,{type:"interim",text:a}))}async function Ee(e){const t=K(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(N=N.then(()=>V(t,{flush:!0}).catch(()=>{})))}finally{b(t,{type:"end"}),t.listeners.clear(),M.delete(t.id),t.diarizer&&L.release(),M.size===0&&v()&&_?.arm()}return!0}function Be(){for(const e of M.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);M.clear(),_?.disarm(),_=null,l="off",h=null,f=null,T=null,S=null,g=null}function Ye(e,t="test/fake",{warmMs:n=null}={}){f=e,h=t,l=e?"ready":"off",n!==null&&(_=H({warmMs:n,busy:A,unload:()=>C()}),e&&_.arm())}export{p as SAMPLE_RATE,ie as THIN_SPEAKER_SAMPLES,oe as WEAK_SPEAKER_SAMPLES,Be as _reset,Ye as _setPipeForTest,_e as clampEndSilence,Ue as createSession,Ee as endSession,K as getSession,Fe as health,ze as init,v as isReady,le as looksHallucinated,ce as modelOnDisk,Pe as progress,Xe as pushAudio,D as runtimeDtype,B as runtimeName,Ce as sessionCount,He as setModel,Ne as state,Ke as subscribe,Oe as toFloat32,C as unload,Re as warmPending};
@@ -0,0 +1 @@
1
+ const p=16e3;function E(e,i=16e3){const n=e.length,t=Buffer.alloc(44+n*2);t.write("RIFF",0),t.writeUInt32LE(36+n*2,4),t.write("WAVE",8),t.write("fmt ",12),t.writeUInt32LE(16,16),t.writeUInt16LE(1,20),t.writeUInt16LE(1,22),t.writeUInt32LE(i,24),t.writeUInt32LE(i*2,28),t.writeUInt16LE(2,32),t.writeUInt16LE(16,34),t.write("data",36),t.writeUInt32LE(n*2,40);for(let r=0;r<n;r++){const a=Math.max(-1,Math.min(1,e[r]));t.writeInt16LE(a<0?a*32768:a*32767,44+r*2)}return t}const f=Object.freeze(["openai"]);function d(e,{fetchImpl:i,now:n=()=>performance.now()}={}){if(!e||!["remote","container"].includes(e.kind)||!/^https?:\/\//.test(e.url||""))throw new Error("stt-remote: a remote provider needs a url");const t=e.adapter||"openai";if(!f.includes(t))throw new Error(`stt-remote: unknown adapter ${t}`);const r=e.url.replace(/\/+$/,"");return{provider:{kind:e.kind,url:e.url,adapter:t,model:e.model||"whisper-1"},async transcribe(a,{lang:c=null,timeoutMs:l=3e4}={}){const u=n(),o=new FormData;o.append("file",new Blob([E(a)],{type:"audio/wav"}),"segment.wav"),o.append("model",e.model||"whisper-1"),o.append("response_format","json"),c&&o.append("language",c);const s=await i(`${r}/audio/transcriptions`,{method:"POST",headers:{accept:"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:o,signal:AbortSignal.timeout(l)});if(!s.ok){const w=await s.text().catch(()=>"");throw new Error(`${t} transcription ${s.status}${w?`: ${w.slice(0,200)}`:""}`)}const m=await s.json().catch(()=>({}));return{text:String(m?.text||"").trim(),ms:Math.round(n()-u)}}}}export{f as STT_REMOTE_ADAPTERS,d as createRemoteTranscriber,E as wavFromFloat32};
package/src/toolrelay.js CHANGED
@@ -1,4 +1,4 @@
1
- import{randomUUID as p}from"node:crypto";import{restoreDeep as m,redactText as y,createVault as g}from"@chatpanel/pii";const s=new Map,b=(e,t)=>`gwtr_${e}_${t}`;function w(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function _(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}const x=2e5;function h({vault:e,redactOpts:t,bridgeUrl:r,token:n,harness:a=null,idleMs:c=x}){const i=p().slice(0,8),l={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||g(),redactOpts:t||{tier:"basic"},bridgeUrl:r,token:n,harness:a,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return s.set(i,l),u(i),l}const D=e=>s.get(e);function u(e){const t=s.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>S(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function S(e){const t=s.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}s.delete(e)}async function O(e,t){for(;;){let r;for(;(r=e.buf.indexOf(`
1
+ import{randomUUID as x}from"node:crypto";import{restoreDeep as f,redactText as m,createVault as I}from"@chatpanel/pii";import{PERMISSION_TOOL_NAME as T,isPermissionTool as y,permissionAllowed as w}from"@chatpanel/events/agent-permission.js";const a=new Map,g=(e,t)=>`gwtr_${e}_${t}`;function P(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function N(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name&&!y(t.function.name)).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}function $(e){return(Array.isArray(e)?e:[]).some(t=>t?.type==="function"&&y(t.function?.name))}const O=2e5;function k({vault:e,redactOpts:t,bridgeUrl:n,token:r,harness:l=null,idleMs:c=O}){const i=x().slice(0,8),s={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||I(),redactOpts:t||{tier:"basic"},bridgeUrl:n,token:r,harness:l,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return a.set(i,s),b(i),s}const q=e=>a.get(e);function b(e){const t=a.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>h(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function h(e){const t=a.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}a.delete(e)}async function M(e,t){for(;;){let n;for(;(n=e.buf.indexOf(`
2
2
 
3
- `))!==-1;){const c=e.buf.slice(0,r);e.buf=e.buf.slice(r+2);for(const i of c.split(`
4
- `)){const l=i.trim();if(!l.startsWith("data:"))continue;const d=l.slice(5).trim();if(!d||d==="[DONE]")continue;let o;try{o=JSON.parse(d)}catch{continue}if(u(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id;const f=e.harness?e.harness.toTool(o.name,o.input??{}):m(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:f,toolId:b(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done"}}}const{done:n,value:a}=await e.reader.read();if(n)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(a,{stream:!0})}}async function R(e,t){const r=y(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts),n=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:r})});if(!n.ok)throw new Error(`bridge /tool-result HTTP ${n.status}`)}export{x as RELAY_IDLE_MS,h as createRelaySession,R as deliverToolResult,S as endRelaySession,D as getRelaySession,w as parseToolCallId,O as pumpBridgeStream,_ as toolsToSpecs,u as touchRelaySession};
3
+ `))!==-1;){const c=e.buf.slice(0,n);e.buf=e.buf.slice(n+2);for(const i of c.split(`
4
+ `)){const s=i.trim();if(!s.startsWith("data:"))continue;const u=s.slice(5).trim();if(!u||u==="[DONE]")continue;let o;try{o=JSON.parse(u)}catch{continue}if(b(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="permission_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!0;const{type:d,session:v,id:A,...p}=o,S={...p,input:f(p.input??{},e.vault)};return t.onToolRequest({name:T,restoredArgs:S,toolId:g(e.id,o.id)}),"parked"}else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!1;const d=e.harness?e.harness.toTool(o.name,o.input??{}):f(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:d,toolId:g(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done"}}}const{done:r,value:l}=await e.reader.read();if(r)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(l,{stream:!0})}}async function J(e,t){const n=e.pendingPermission?_(t,e):m(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts);e.pendingPermission=!1;const r=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:n})});if(!r.ok)throw new Error(`bridge /tool-result HTTP ${r.status}`)}function _(e,t){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!w(n)){const r=n&&typeof n=="object"&&typeof n.message=="string"&&n.message?m(n.message,t.vault,t.redactOpts):"";return{behavior:"deny",scope:"once",...r?{message:r}:{}}}return{behavior:"allow",scope:n.scope==="chat"?"chat":"once"}}export{O as RELAY_IDLE_MS,k as createRelaySession,J as deliverToolResult,h as endRelaySession,q as getRelaySession,P as parseToolCallId,_ as permissionResultOf,M as pumpBridgeStream,N as toolsToSpecs,b as touchRelaySession,$ as wantsApprovals};
package/src/tts-remote.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as w,segment as T}from"./redact.js";const S=["local","openai","elevenlabs"];function $(e){return S.includes(String(e||""))}function E(e={}){const o=e.tts||{},r=o.provider||"local";if(r==="local"||!$(r))return null;const i=o.remote||{};return{kind:r,baseUrl:String(i.baseUrl||(r==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:i.model||(r==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:i.voice||(r==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:i.redact!==!1}}function k(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}async function P({dest:e,text:o,voice:r,speed:i=1,auth:n,redaction:d,isPro:f=!0,onEgress:v=null,fetchImpl:b=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=r||e.voice;if(!k(l))throw new Error(`invalid remote voice id: ${l}`);let s=String(o),u=0;if(e.redact&&d){const t={text:s},h=await w([T(()=>t.text,y=>{t.text=y})],d,{isPro:f,onEgress:v});s=t.text,u=h?.count||0}const x=b||g,c={"Content-Type":"application/json"};let m,p;if(e.kind==="elevenlabs"){m=`${e.baseUrl}/text-to-speech/${encodeURIComponent(l)}`,p={text:s,model_id:e.model};const t=_(n);t&&(c["xi-api-key"]=t)}else m=`${e.baseUrl}/audio/speech`,p={model:e.model,input:s,voice:l,response_format:"wav",speed:i},n&&(c.Authorization=n.startsWith("Bearer ")?n:`Bearer ${n}`);const a=await x(m,{method:"POST",headers:c,body:JSON.stringify(p)});if(!a.ok){let t=`HTTP ${a.status}`;try{t=(await a.text()).slice(0,300)||t}catch{}throw new Error(`remote tts failed: ${t}`)}return{audio:Buffer.from(await a.arrayBuffer()),contentType:a.headers.get("content-type")||"audio/mpeg",redacted:u}}function _(e){const o=String(e||"").trim();return o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():o}export{S as TTS_PROVIDERS,k as isValidRemoteVoice,$ as isValidTtsProvider,P as synthesizeRemote,E as ttsDestination};
1
+ import{secureFetch as k}from"./secure-fetch.js";import{redactSegments as w,segment as S}from"./redact.js";const $=["local","openai","elevenlabs"];function b(e){return $.includes(String(e||""))}function D(e={}){const r=e.tts||{},t=e.capabilities?.tts;if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const i=t.adapter||"openai";if(t.url&&b(i)){const c=r.remote||{};return{kind:i,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||c.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:c.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||""}}}const n=r.provider||"local";if(n==="local"||!b(n))return null;const a=r.remote||{};return{kind:n,baseUrl:String(a.baseUrl||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(n==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(n==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function _(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}async function E({dest:e,text:r,voice:t,speed:n=1,auth:a,redaction:i,isPro:c=!0,onEgress:h=null,fetchImpl:y=null}={}){const l=a||e?.token||"";if(!e)throw new Error("no remote TTS destination configured");const u=t||e.voice;if(!_(u))throw new Error(`invalid remote voice id: ${u}`);let d=String(r),v=0;if(e.redact&&i){const o={text:d},T=await w([S(()=>o.text,g=>{o.text=g})],i,{isPro:c,onEgress:h});d=o.text,v=T?.count||0}const x=y||k,m={"Content-Type":"application/json"};let p,f;if(e.kind==="elevenlabs"){p=`${e.baseUrl}/text-to-speech/${encodeURIComponent(u)}`,f={text:d,model_id:e.model};const o=U(l);o&&(m["xi-api-key"]=o)}else p=`${e.baseUrl}/audio/speech`,f={model:e.model,input:d,voice:u,response_format:"wav",speed:n},l&&(m.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const s=await x(p,{method:"POST",headers:m,body:JSON.stringify(f)});if(!s.ok){let o=`HTTP ${s.status}`;try{o=(await s.text()).slice(0,300)||o}catch{}throw new Error(`remote tts failed: ${o}`)}return{audio:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")||"audio/mpeg",redacted:v}}function U(e){const r=String(e||"").trim();return r.toLowerCase().startsWith("bearer ")?r.slice(7).trim():r}export{$ as TTS_PROVIDERS,_ as isValidRemoteVoice,b as isValidTtsProvider,E as synthesizeRemote,D as ttsDestination};
package/src/update.js CHANGED
@@ -1 +1 @@
1
- import J from"node:os";import i from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",ye="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||i.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ae(){m={at:0,error:""}}function T(){const e=i.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(i.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?i.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(i.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=i.dirname(process.execPath);return[i.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),i.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[i.dirname(t),...(n[a]||"").split(i.delimiter).filter(Boolean)].filter((r,o,l)=>l.indexOf(r)===o).join(i.delimiter),n}function ce(){const e=$(),t=le(),[n,a]=e?[process.execPath,[e,"install","-g",`${g}@latest`]]:["npm",["install","-g",`${g}@latest`]];return new Promise(r=>{b(n,a,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(o,l,p)=>{const s=`${l||""}${p||""}`.trim();return o?o.killed&&!s?r({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):r({ok:!1,out:s||(e?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):r({ok:!0,out:s})})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,l=!1,p="",s=0;const c=await oe(),h=c&&c.mode===n,C=()=>{r=h&&c.latest||null,o=h&&c.assetUrl||null,s=h&&c.checkedAt||0,l=!0};if(!t&&h&&Date.now()-c.checkedAt<L)r=c.latest,o=c.assetUrl,s=c.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,F=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),I=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest; chatpanel-gateway --install`:`npm i -g ${g}@latest`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:F,assetUrl:o,stale:l,error:p,npmCommand:I,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let w=null,A=null;function be(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(m.at&&Date.now()-m.at<N):Date.now()-w.seenAt>L))&&!A&&(A=H(e).then(a=>{w={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Ee(){w=null,A=null}async function de(e){const t=process.execPath,n=i.dirname(t),a=i.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let l;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);l=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(l.length<5<<20)throw new Error(`the download was only ${(l.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,l),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(c,h)=>s(c?"":String(h||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,i.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function pe(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await de(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await ce();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function _e(){return{...d}}function Se(e,{restart:t=Q,apply:n=pe}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function Te(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Te as _resetUpdateJob,Ee as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,le as npmInstallEnv,x as npmPackageRoot,Ae as resetUpdateBackoff,pe as selfUpdate,Se as startUpdate,_e as updateJob,be as updateStatus};
1
+ import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",be="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ee(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(l.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[l.dirname(t),...(n[a]||"").split(l.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(l.delimiter),n}function ce(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function de(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function pe(){const e=$(),t=le(),n=de(),[a,r]=e?[process.execPath,[e,...n]]:["npm",n];return new Promise(o=>{b(a,r,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,p,s)=>{const i=`${p||""}${s||""}`.trim();return c?c.killed&&!i?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:i||(e?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ce(),o({ok:!0,out:i}))})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,c=!1,p="",s=0;const i=await oe(),w=i&&i.mode===n,C=()=>{r=w&&i.latest||null,o=w&&i.assetUrl||null,s=w&&i.checkedAt||0,c=!0};if(!t&&w&&Date.now()-i.checkedAt<L)r=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,I=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),F=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:I,assetUrl:o,stale:c,error:p,npmCommand:F,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,A=null;function _e(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>L))&&!A&&(A=H(e).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),h?{...h,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Se(){h=null,A=null}async function ue(e){const t=process.execPath,n=l.dirname(t),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let c;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>s(i?"":String(w||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function me(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ue(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await pe();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Te(){return{...d}}function ve(e,{restart:t=Q,apply:n=me}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function xe(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{xe as _resetUpdateJob,Se as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,de as npmInstallArgs,le as npmInstallEnv,x as npmPackageRoot,Ee as resetUpdateBackoff,me as selfUpdate,ve as startUpdate,Te as updateJob,_e as updateStatus};