@chatpanel/gateway 0.44.3 → 0.52.3

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,13 +1,13 @@
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
- `),l=Object.entries(r).map(([u,d])=>` <key>${i(u)}</key><string>${i(d)}</string>`).join(`
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(`
3
3
  `);return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5
5
  <plist version="1.0">
6
6
  <dict>
7
- <key>Label</key><string>${o}</string>
7
+ <key>Label</key><string>${i}</string>
8
8
  <key>ProgramArguments</key>
9
9
  <array>
10
- ${a}
10
+ ${c}
11
11
  </array>
12
12
  <key>EnvironmentVariables</key>
13
13
  <dict>
@@ -15,27 +15,28 @@ ${l}
15
15
  </dict>
16
16
  <key>RunAtLoad</key><true/>
17
17
  <key>KeepAlive</key><true/>
18
- <key>StandardOutPath</key><string>${i(n)}</string>
19
- <key>StandardErrorPath</key><string>${i(s)}</string>
18
+ <key>StandardOutPath</key><string>${o(n)}</string>
19
+ <key>StandardErrorPath</key><string>${o(s)}</string>
20
20
  </dict>
21
21
  </plist>
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);'
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);'
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 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}
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]
28
+ Description=${t}
29
29
  After=network.target
30
30
 
31
31
  [Service]
32
- ExecStart=${s}
33
- Restart=on-failure
32
+ ExecStart=${e}
33
+ Restart=always
34
+ RestartSec=2
34
35
 
35
36
  [Install]
36
37
  WantedBy=default.target
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
+ `}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
39
  `).slice(-e).join(`
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
- `).map(a=>` ${a}`))}return t.join(`
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};
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};
package/src/shape.js CHANGED
@@ -1,8 +1,8 @@
1
- function r(e){return`${e}_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}const c=()=>Math.floor(Date.now()/1e3),a=e=>`data: ${JSON.stringify(e)}
1
+ function c(e){return`${e}_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}const u=()=>Math.floor(Date.now()/1e3),r=e=>`data: ${JSON.stringify(e)}
2
2
 
3
- `,s=(e,t)=>`event: ${e}
4
- `+a(t);function l(e){const t=r("chatcmpl"),n={id:t,object:"chat.completion.chunk",created:c(),model:e};return{contentType:"application/json",full(o){return JSON.stringify({id:t,object:"chat.completion",created:c(),model:e,choices:[{index:0,message:{role:"assistant",content:o},finish_reason:"stop"}],usage:{}})},sseHead(){return a({...n,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})},sseDelta(o){return a({...n,choices:[{index:0,delta:{content:o},finish_reason:null}]})},sseTail(){return a({...n,choices:[{index:0,delta:{},finish_reason:"stop"}]})+`data: [DONE]
3
+ `,a=(e,o)=>`event: ${e}
4
+ `+r(o);function i(e){if(!e)return null;const o=p=>Math.max(0,Number(p)||0),n=o(e.cacheReadTokens),t=o(e.inputTokens)+n+o(e.cacheWriteTokens),s=o(e.outputTokens);return!t&&!s?null:{prompt_tokens:t,completion_tokens:s,total_tokens:t+s,...n?{prompt_tokens_details:{cached_tokens:n}}:{}}}function l(e){const o=c("chatcmpl"),n={id:o,object:"chat.completion.chunk",created:u(),model:e};return{contentType:"application/json",full(t,s){return JSON.stringify({id:o,object:"chat.completion",created:u(),model:e,choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}],usage:i(s)||{}})},sseHead(){return r({...n,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})},sseDelta(t){return r({...n,choices:[{index:0,delta:{content:t},finish_reason:null}]})},sseUsage(t){const s=i(t);return s?r({...n,choices:[],usage:s}):""},sseTail(t){return r({...n,choices:[{index:0,delta:{},finish_reason:"stop"}]})+this.sseUsage(t)+`data: [DONE]
5
5
 
6
- `},sseActivity(o){return a({...n,choices:[{index:0,delta:{},finish_reason:null}],chatpanel:{kind:"activity",event:o}})},sseToolCalls(o){return a({...n,choices:[{index:0,delta:{tool_calls:o.map((i,p)=>({index:p,id:i.id,type:"function",function:{name:i.name,arguments:i.arguments}}))},finish_reason:null}]})},sseToolFinish(){return a({...n,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]})+`data: [DONE]
6
+ `},sseActivity(t){return r({...n,choices:[{index:0,delta:{},finish_reason:null}],chatpanel:{kind:"activity",event:t}})},sseToolCalls(t){return r({...n,choices:[{index:0,delta:{tool_calls:t.map((s,p)=>({index:p,id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}}))},finish_reason:null}]})},sseToolFinish(t){return r({...n,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]})+this.sseUsage(t)+`data: [DONE]
7
7
 
8
- `}}}function u(e){const t=r("resp");return{contentType:"application/json",full(n){return JSON.stringify({id:t,object:"response",created_at:c(),model:e,status:"completed",output:[{id:r("msg"),type:"message",role:"assistant",content:[{type:"output_text",text:n}]}],output_text:n})},sseHead(){return s("response.created",{type:"response.created",response:{id:t,status:"in_progress",model:e}})},sseDelta(n){return s("response.output_text.delta",{type:"response.output_text.delta",delta:n})},sseTail(){return s("response.completed",{type:"response.completed",response:{id:t,status:"completed",model:e}})}}}function d(e){const t=r("msg");return{contentType:"application/json",full(n){return JSON.stringify({id:t,type:"message",role:"assistant",model:e,content:[{type:"text",text:n}],stop_reason:"end_turn",stop_sequence:null,usage:{}})},sseHead(){return s("message_start",{type:"message_start",message:{id:t,type:"message",role:"assistant",model:e,content:[],stop_reason:null,usage:{}}})+s("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}})},sseDelta(n){return s("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:n}})},sseTail(){return s("content_block_stop",{type:"content_block_stop",index:0})+s("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn"},usage:{}})+s("message_stop",{type:"message_stop"})}}}function _(e,t){return e==="anthropic"?d(t):e==="responses"?u(t):l(t)}export{d as anthropicMessages,l as openaiChat,u as openaiResponses,_ as shaperFor};
8
+ `}}}function _(e){const o=c("resp");return{contentType:"application/json",full(n,t){const s=i(t);return JSON.stringify({id:o,object:"response",created_at:u(),model:e,status:"completed",output:[{id:c("msg"),type:"message",role:"assistant",content:[{type:"output_text",text:n}]}],output_text:n,...s?{usage:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens}}:{}})},sseHead(){return a("response.created",{type:"response.created",response:{id:o,status:"in_progress",model:e}})},sseDelta(n){return a("response.output_text.delta",{type:"response.output_text.delta",delta:n})},sseTail(n){const t=i(n);return a("response.completed",{type:"response.completed",response:{id:o,status:"completed",model:e,...t?{usage:{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,total_tokens:t.total_tokens}}:{}}})}}}function d(e){const o=c("msg");return{contentType:"application/json",full(n,t){const s=i(t);return JSON.stringify({id:o,type:"message",role:"assistant",model:e,content:[{type:"text",text:n}],stop_reason:"end_turn",stop_sequence:null,usage:s?{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens}:{}})},sseHead(){return a("message_start",{type:"message_start",message:{id:o,type:"message",role:"assistant",model:e,content:[],stop_reason:null,usage:{}}})+a("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}})},sseDelta(n){return a("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:n}})},sseTail(n){const t=i(n);return a("content_block_stop",{type:"content_block_stop",index:0})+a("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn"},usage:t?{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens}:{}})+a("message_stop",{type:"message_stop"})}}}function k(e,o){return e==="anthropic"?d(o):e==="responses"?_(o):l(o)}export{d as anthropicMessages,l as openaiChat,_ as openaiResponses,k as shaperFor,i as usageOf};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
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};
1
+ import{join as Z}from"node:path";import{existsSync as I,readdirSync as ee}from"node:fs";import{randomUUID as te}from"node:crypto";import{ensureLib as X,modelRoot as B}from"./ner-engine.js";import{runtimeDtype as L,runtimeName as Y,DTYPE_SUFFIX as ne}from"./model-runtime.js";import{verifyModelWeights as re}from"./model-integrity.js";import{DEFAULT_STT_MODEL as j,isEnglishOnly as W,sttModelDtype as R,isKnownSttModel as oe,sttModelEngine as z}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as ie}from"./diarize-models.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,ae=p,le=2*p,se=2,ce=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 ue(e,t){if(t>se*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ce.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",h=null,d=null,M=null,x=null,g=null,A=null,w=null;function fe(e=h||j,t=R(e)||L()){if(z(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=Z(B(),...e.split("/"),"onnx");if(!I(n))return!1;const r=ne[t]??"";try{const o=ee(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 He(){return s}function v(){return s==="ready"&&!!d}function Ce(){return g}function Ue(){return{configured:s!=="off",ok:v(),state:s,model:h,dtype:A,runtime:Y(),error:M,warmMs:w?.warmMs??null}}function Ke(){return!!w?.pending()}function b(){return k.size>0||s==="loading"||s==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;w?.disarm();const t=d;if(d=null,x=null,A=null,g=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function G(e){return e.then(t=>(t&&!b()&&w?.arm(),t))}async function q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return de(e,{log:t,allowDownload:n,dtype:r});const o=d,a=h;let l;try{l=await X()}catch(m){return s="error",M=`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)||L(),c=fe(e,i);if(l.env.allowRemoteModels=c?!1:!!n,!c&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=l.env.remoteHost,_=!oe(e);if(!c&&_)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const m=f=>{if(!f)return;const F=typeof f.progress=="number"?Math.round(f.progress):g?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?g={model:e,file:f.file||g?.file||null,pct:F}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(f){if(c||_||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{re(e,{modelsDir:B(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(d=S,h=e,s="ready",M=null,g=null,A=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return M=m.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=y}catch{}}}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,a=h,l=T.parakeetDtype(r&&r!=="auto"?r:me()),u=T.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=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 T.loadRecognizer({modelId:e,dtype:l,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(),d=c,h=e,s="ready",M=null,g=null,A=l,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function me(){return T.PARAKEET_DEFAULT_DTYPE}const pe=30;function he({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=pe||e==="download"?{allowDownload:!0}:null}function U(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:ie(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Oe(e={}){if(x)return x;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||j,s="loading",w=H({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),x=G(q(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&U(e.speaker,{log:t,warmMs:e.warmMs}),n)),x}async function Xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||L();if(e===h&&v()&&A===r)return U(t.speaker,{log:n,warmMs:t.warmMs}),!0;w??=H({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})});const o=await G(q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&U(t.speaker,{log:n,warmMs:t.warmMs}),o}const ge=4,ye=6e4,we=1200,Q=12,K=700,$=.008,_e=30,k=new Map;let P=Promise.resolve();function Be(){return k.size}const Me=300,ke=3e3;function Te(e){const t=Number(e);return Number.isFinite(t)?Math.min(ke,Math.max(Me,Math.round(t))):K}function Ye({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=K,interims:a=!0,remote:l=null}={}){if(k.size>=ge){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:te(),endSilenceMs:Te(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 E.Diarizer:null,remote:l||null,interims:a!==!1&&!l,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(u.id,u),w?.disarm(),u.diarizer&&E.retain(),V(u),{id:u.id}}function O(e){return k.get(String(e||""))||null}function je(e,t){const n=O(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 V(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>be(e.id).catch(()=>{}),ye),e.idleTimer.unref?.()}function We(e,t){const n=O(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,V(n),Ee(n))}function Ge(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 Ee(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+we-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>J(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Se(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 N(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 xe(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(N(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(N(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function Ae(e){try{const t=await X(),n=d?.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 d.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await d.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const _=Number(l.logits.data[y]);_>i&&(i=_,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function J(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Se(e),r=Math.round((e.endSilenceMs||K)/1e3*p),o=n.length>r&&N(n,n.length-r)<$;if(N(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&&!W(h)&&!d?.__parakeet&&n.length>=p){e.langTried=!0;const i=await Ae(n);i&&(e.lang=i,D(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=W(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await d(n,i);a=String(c?.text||"").trim()}}catch(i){D(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const l=n.length>=Q*p,u=n.length>=_e*p;if(t||o||l||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=xe(n);if(ue(a,y?y.length:0))return;let _=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,S=m?await E.embed(m):null,f=!!m&&m.length<ae,F=!!m&&m.length<le;_=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:f,thin:F})}catch{}D(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),..._?{speaker:_}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,D(e,{type:"interim",text:a}))}async function be(e){const t=O(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(()=>J(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.diarizer&&E.release(),k.size===0&&v()&&w?.arm()}return!0}function qe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),w?.disarm(),w=null,s="off",h=null,d=null,M=null,x=null,g=null}function Qe(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){d=e,h=t,s=e?"ready":"off",A=r,n!==null&&(w=H({warmMs:n,busy:b,unload:()=>C()}),e&&w.arm())}export{pe as AUTO_FETCH_MAX_MB,p as SAMPLE_RATE,le as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,qe as _reset,Qe as _setPipeForTest,Te as clampEndSilence,Ye as createSession,be as endSession,O as getSession,Ue as health,Oe as init,v as isReady,ue as looksHallucinated,fe as modelOnDisk,Ce as progress,We as pushAudio,L as runtimeDtype,Y as runtimeName,Be as sessionCount,Xe as setModel,he as speakerPlan,He as state,je as subscribe,Ge as toFloat32,C as unload,Ke as warmPending};
package/src/toolrelay.js CHANGED
@@ -1,4 +1,4 @@
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(`
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(()=>_(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function _(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
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};
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";o.type==="usage"&&t.onUsage?.(o)}}}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?h(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 h(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,_ as endRelaySession,q as getRelaySession,P as parseToolCallId,h as permissionResultOf,M as pumpBridgeStream,N as toolsToSpecs,b as touchRelaySession,$ as wantsApprovals};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.44.3";export{o as VERSION};
1
+ const o="0.52.3";export{o as VERSION};