@chatpanel/gateway 0.23.2 → 0.39.4
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/package.json +4 -4
- package/src/audio-file.js +4 -0
- package/src/bridge.js +4 -4
- package/src/capabilities.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/cloudevents.js +4 -0
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-tunings.js +1 -0
- package/src/event-stats.js +1 -0
- package/src/event-store.js +15 -0
- package/src/event-sync.js +1 -0
- package/src/event.js +1 -0
- package/src/fusions.js +1 -0
- package/src/images.js +34 -0
- package/src/inference-engines.js +1 -0
- package/src/model-pull.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/order.js +1 -0
- package/src/policy.js +2 -2
- package/src/providers.js +1 -0
- package/src/ref.js +1 -0
- package/src/router.js +1 -1
- package/src/runtime-models.js +1 -1
- package/src/runtime.js +5 -3
- package/src/server.js +28 -17
- package/src/service.js +9 -9
- package/src/sqlite-store.js +1 -1
- package/src/stt-engine.js +1 -1
- package/src/stt-remote.js +1 -0
- package/src/toolrelay.js +3 -3
- package/src/tts-remote.js +1 -1
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
|
|
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,"&").replace(/</g,"<").replace(/>/g,">"),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
|
|
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",
|
|
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
|
|
27
|
-
`)){const n=Number(t.trim());if(!(!n||n===process.pid||n===process.ppid))try{process.kill(n,"SIGTERM")}catch{}}}const
|
|
28
|
-
Description=${
|
|
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=
|
|
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
|
|
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{
|
|
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};
|
package/src/sqlite-store.js
CHANGED
|
@@ -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
|
|
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,
|
|
4
|
-
`)){const
|
|
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
|
|
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};
|