@chatpanel/gateway 0.75.0 → 0.85.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/chatpanel-gateway.js +5 -5
- package/package.json +4 -4
- package/src/capabilities.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-pacer.js +1 -0
- package/src/local-engine-probe.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/pair-prompt.js +12 -0
- package/src/recruiting.js +1 -1
- package/src/redact.js +2 -2
- package/src/retrieval/search-apis.js +1 -0
- package/src/retrieval/search-serp.js +1 -1
- package/src/retrieval/search.js +1 -1
- package/src/router.js +1 -1
- package/src/runtime.js +6 -5
- package/src/search-api.js +1 -0
- package/src/search-outcome.js +1 -0
- package/src/server.js +33 -28
- package/src/service.js +17 -17
- package/src/stt-engine.js +1 -1
- package/src/version.js +1 -1
- package/src/web-search-tool.js +8 -8
- package/src/web-search.js +1 -1
package/src/service.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
import
|
|
2
|
-
`),
|
|
1
|
+
import x from"node:os";import{SERVICE_ENV as xe}from"@chatpanel/events/service-standby.js";import f from"node:path";import{mkdirSync as _,writeFileSync as L,readFileSync as W,rmSync as $,existsSync as g,statSync as $e,realpathSync as J}from"node:fs";import{spawnSync as Se,spawn as U}from"node:child_process";import{loadConfig as ve}from"./config.js";import{VERSION as G}from"./version.js";const A="net.chatpanel.gateway",Pe="ChatPanel Privacy Gateway";function Q(e,t){const n=String(e||"").split(".").map(r=>parseInt(r,10)),s=String(t||"").split(".").map(r=>parseInt(r,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let r=0;r<3;r+=1)if(n[r]!==s[r])return n[r]>s[r]?1:-1;return 0}function E(e,{real:t=J.native||J}={}){if(!e)return e;try{return t(e)}catch{return e}}function be(e,{exists:t=g}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(e||""));if(!n)return e;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return t(s)?s:e}function k({execPath:e=be(E(process.execPath)),argv1:t=E(process.argv[1]||"")}={}){const n=f.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[f.resolve(t)]}:{program:e,args:[]}}function b(){const e=f.join(x.homedir(),".chatpanel");return _(e,{recursive:!0}),{out:f.join(e,"gateway.log"),err:f.join(e,"gateway.err.log")}}function p(e,t,n={}){return Se(e,t,{encoding:"utf8",...n})}const I=()=>f.join(x.homedir(),"Library","LaunchAgents",`${A}.plist`),Ae={MallocLargeCache:"0"};function ee({program:e,args:t,out:n,err:s,env:r={...Ae,...xe},label:i=A}={}){const o=u=>String(u).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),a=[e,...t].map(u=>` <string>${o(u)}</string>`).join(`
|
|
2
|
+
`),c=Object.entries(r).map(([u,d])=>` <key>${o(u)}</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>${
|
|
7
|
+
<key>Label</key><string>${i}</string>
|
|
8
8
|
<key>ProgramArguments</key>
|
|
9
9
|
<array>
|
|
10
10
|
${a}
|
|
11
11
|
</array>
|
|
12
12
|
<key>EnvironmentVariables</key>
|
|
13
13
|
<dict>
|
|
14
|
-
${
|
|
14
|
+
${c}
|
|
15
15
|
</dict>
|
|
16
16
|
<key>RunAtLoad</key><true/>
|
|
17
17
|
<key>KeepAlive</key><true/>
|
|
18
|
-
<key>StandardOutPath</key><string>${
|
|
19
|
-
<key>StandardErrorPath</key><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
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=
|
|
22
|
+
`}function Ee(){const{program:e,args:t}=k(),{out:n,err:s}=b(),r=ee({program:e,args:t,out:n,err:s}),i=I();_(f.dirname(i),{recursive:!0}),L(i,r),p("launchctl",["unload",i]);const o=p("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function ke(){const e=I();p("launchctl",["unload","-w",e]),g(e)&&$(e)}function Ie(){return(p("launchctl",["list"]).stdout||"").includes(A)}function D({execPath:e=E(process.execPath),argv1:t=E(process.argv[1]||""),platform:n=process.platform,isFile:s=V}={}){const r=n==="win32"?f.win32:f.posix,i=r.basename(e).toLowerCase();if(!(i.startsWith("node")||i.startsWith("bun")))return r.dirname(e);const o=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let c=0;c<6;c++){const u=r.dirname(a);if(u===a)break;if(a=u,s(r.join(a,o)))return a;if(s(r.join(a,"bin",o)))return r.join(a,"bin")}return""}const V=e=>{try{return $e(e).isFile()}catch{return!1}};function O(e,t,{delimiter:n=f.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=c=>s==="win32"?c.replace(/%([^%]+)%/g,(u,d)=>r[d]??r[d.toUpperCase()]??u):c,o=c=>{const u=i(c.trim()).replace(/[\\/]+$/,"");return s==="win32"?u.toLowerCase():u},a=String(e||"").split(n).filter(c=>c.trim());return a.some(c=>o(c)===o(t))?null:[...a,t].join(n)}function B({dir:e=D(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=V}={}){if(!e)return"";const r=n==="win32"?f.win32:f.posix,i=n==="win32"?";":":",o=c=>{const u=String(c).trim().replace(/[\\/]+$/,"");return n==="win32"?u.toLowerCase():u},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const c of String(t).split(i)){const u=c.trim();if(u){if(o(u)===o(e))return"";if(a.some(d=>s(r.join(u,d))))return u}}return""}function je({embedded:e="",pathEnv:t=process.env.PATH||"",platform:n=process.platform,real:s=E,read:r=o=>W(o,"utf8"),isFile:i=V}={}){if(!e)return[];const o=n==="win32"?f.win32:f.posix,a=n==="win32"?["chatpanel-bridge.cmd"]:["chatpanel-bridge"],c=[],u=new Set;for(const d of String(t).split(n==="win32"?";":":")){const l=d.trim().replace(/[\\/]+$/,"");if(!l)continue;const h=a.map(y=>o.join(l,y)).find(y=>i(y));if(!h||u.has(h))continue;u.add(h);const R=n==="win32"?[o.join(l,"node_modules","@chatpanel","bridge")]:[o.dirname(o.dirname(s(h))),o.join(o.dirname(l),"lib","node_modules","@chatpanel","bridge")];let w="";for(const y of R)try{const P=JSON.parse(r(o.join(y,"package.json")));if(P?.name==="@chatpanel/bridge"&&P.version){w=String(P.version);break}}catch{}if(!w||Q(w,e)>=0)continue;const C=o.join(l,n==="win32"?"npm.cmd":"npm");c.push({path:h,version:w,remove:`${i(C)?C:"npm"} rm -g @chatpanel/bridge`})}return c}function Ne(e,{embedded:t=""}={}){if(!e?.length)return[];const n=[` ⚠ An older ChatPanel bridge is still installed: ${e.map(s=>`${s.path} (v${s.version})`).join(", ")}.`,` The gateway carries its own bridge${t?` (v${t})`:""} and does not use ${e.length===1?"it":"them"}, but typing \`chatpanel-bridge\` runs the old copy — which starts a second bridge instead of doing what was asked.`];for(const s of e)n.push(` Remove it: ${s.remove}`);return n.push(" To pair a browser: chatpanel-gateway pair"),n}const S="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",M="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",F=()=>f.join(x.homedir(),".chatpanel","gateway-launch.vbs"),te=e=>Buffer.from(e,"utf16le").toString("base64");function q({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=g}={}){return t(f.join(e,"System32","vbscript.dll"))}function ne({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=l=>`"${l}"`;if(i){const l=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${l.replace(/"/g,'""')}", 0, False\r
|
|
23
|
+
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=l=>`'${String(l).replace(/'/g,"''")}'`,c=t.length?` -ArgumentList @(${t.map(l=>a(o(l))).join(", ")})`:"",u=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${c} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",te(u)];return{kind:"powershell",file:"",text:u,runValue:d.join(" "),argv:d}}function Z(e=p){const t=e("reg",["query",S,"/v",m]);if(t.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function Re(e=p){const t=e("reg",["query",M,"/v",m]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function re(e=p){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const Ce=`$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
|
|
28
|
-
Description=${
|
|
26
|
+
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function Te(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=re(t),r=O(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const i=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return i.status!==0?{added:!1,dir:e,error:(i.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",te(Ce)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function _e(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return O(re(t).value,e,{delimiter:";",platform:"win32",env:n})===null||O(s,e,{delimiter:";",platform:"win32",env:n})===null}function Le({pid:e=process.pid}={}){return`${`$keep = @(${e}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function We({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Le({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function K(e=p){for(const[t,n]of We())e(t,n,{timeout:15e3})}function Ue(){return process.platform==="win32"?K():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),ie())}function De(){const{program:e,args:t}=k(),{out:n,err:s}=b(),r=ne({program:e,args:t,out:n,err:s,vbs:F(),vbscript:q()});r.file?L(r.file,r.text):$(F(),{force:!0});const i=p("reg",["add",S,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");p("reg",["delete",M,"/v",m,"/f"]);const o=Te(D());return K(),p("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),p(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:o}}function Oe(){p("reg",["delete",S,"/v",m,"/f"]),$(F(),{force:!0}),K()}function se(){return p("reg",["query",S,"/v",m]).status===0}function v({env:e=process.env,release:t=x.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function j(e=p){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 i=u=>(e("wslpath",["-u",u]).stdout||"").trim(),o=i(r),a=i(s);if(!o||!a)return null;const c=f.posix.join(o,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:o,exe:{reg:f.posix.join(c,"reg.exe"),wscript:f.posix.join(c,"wscript.exe"),powershell:f.posix.join(c,"WindowsPowerShell","v1.0","powershell.exe")}}}const Be=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function oe(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function He({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=oe,depth:s=8}={}){const r=new Set([e]);let i=t;for(let o=0;o<s&&i>1&&!r.has(i);o+=1)r.add(i),i=n(i);return r}function ie({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Be}={}){const r=t||He({parentOf:a=>oe(a,e)}),i=[],o=new Set;for(const a of s){const c=e("pgrep",["-f",a]);for(const u of(c.stdout||"").split(`
|
|
27
|
+
`)){const d=Number(u.trim());if(!(!d||r.has(d)||o.has(d))){o.add(d);try{n(d),i.push(d)}catch{}}}}return i}const ae=()=>ie(),ce=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:f.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ge(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Ve(e){const{program:t,args:n}=k(),{out:s,err:r}=b(),i=h=>`'${String(h).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],c=ce(e),u=ne({program:"wsl.exe",args:[...a,"-u",x.userInfo().username,"--","bash","-lc",o],vbs:c.win,vbscript:q({systemRoot:e.sysUnix})});_(f.dirname(c.unix),{recursive:!0}),u.file?L(c.unix,u.text):$(c.unix,{force:!0});const d=p(e.exe.reg,["add",S,"/v",m,"/t","REG_SZ","/d",u.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");p(e.exe.reg,["delete",M,"/v",m,"/f"]),ae(),Fe(800);const l=Ge(e,u);return p(l[0],l.slice(1),{timeout:2e4}),{launcher:u.kind,wsl:!0,path:{added:!1,dir:D()}}}function Me(e){p(e.exe.reg,["delete",S,"/v",m,"/f"]),$(ce(e).unix,{force:!0}),ae()}function ue(e){return p(e.exe.reg,["query",S,"/v",m]).status===0}function Fe(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const H=()=>f.join(x.homedir(),".config","systemd","user","chatpanel-gateway.service");function le({exec:e,display:t=Pe}={}){return`[Unit]
|
|
28
|
+
Description=${t}
|
|
29
29
|
After=network.target
|
|
30
30
|
|
|
31
31
|
[Service]
|
|
32
|
-
ExecStart=${
|
|
32
|
+
ExecStart=${e}
|
|
33
33
|
Environment=CHATPANEL_SERVICE=1
|
|
34
34
|
Restart=always
|
|
35
35
|
RestartSec=2
|
|
36
36
|
|
|
37
37
|
[Install]
|
|
38
38
|
WantedBy=default.target
|
|
39
|
-
`}function
|
|
40
|
-
`).slice(-
|
|
41
|
-
`):""}catch{return""}}async function
|
|
42
|
-
`).map(
|
|
43
|
-
`)}export{
|
|
39
|
+
`}function qe(){const e=v()?j():null;if(e)return Ve(e);if(v()&&!g("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=k(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=le({exec:s}),i=H();_(f.dirname(i),{recursive:!0}),L(i,r),p("systemctl",["--user","daemon-reload"]);const o=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function Ze(){const e=v()?j():null;e&&Me(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();g(t)&&$(t)}function pe(){const e=v()?j():null;return e&&ue(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Ke({home:e=x.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?f.win32:f.posix;return t==="win32"?[s.join(n.LOCALAPPDATA||s.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(e,".local","bin","chatpanel-bridge")]}const de="net.chatpanel.bridge",Y="ChatPanelBridge";function Ye({platform:e=process.platform,runImpl:t=p,paths:n=Ke(),home:s=x.homedir()}={}){if(e==="win32"){t("reg",["delete",S,"/v",Y,"/f"]),t("schtasks",["/End","/TN",Y]),t("schtasks",["/Delete","/TN",Y,"/F"]);for(const r of n){const i=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",i],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${de}`]);const r=f.join(s,"Library","LaunchAgents",`${de}.plist`);g(r)&&$(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=f.join(s,".config","systemd","user","chatpanel-bridge.service");g(r)&&$(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function N(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function ze({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function at({winInstall:e=""}={}){try{if(process.platform==="darwin")return g(I())?(U("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${A}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=v()?j():null;if(t&&ue(t)){const n=Z((r,i,o)=>p(r==="reg"?t.exe.reg:r,i,o));return n?(U("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return g(H())?(U("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=Z();if(!t)return!1;const n=f.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${f.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,a,c)=>c.indexOf(o)===a).join(";"),U("cmd",["/c",s],ze({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function ct(){try{return N(()=>g(I()),se,pe)}catch{return!1}}function fe(){try{return`http://127.0.0.1:${ve().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function he(e=fe(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:e}}}function ge(e=8){try{const t=W(b().err,"utf8").trimEnd();return t?t.split(`
|
|
40
|
+
`).slice(-e).join(`
|
|
41
|
+
`):""}catch{return""}}function Xe({platform:e=process.platform,text:t=we(),loaded:n=null}={}){if(e!=="darwin"&&e!=="linux")return!1;try{if(e==="linux"&&v())return!1;const{program:s,args:r}=k(),i=e==="darwin"?ee({program:s,args:r,...b()}):le({exec:[s,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" ")});return!t||t!==i?!1:n===null?me():!!n}catch{return!1}}async function ut({waitMs:e=4e4,version:t="",probe:n=he,stop:s=Ue,install:r=()=>N(Ee,De,qe),retire:i=Ye,wait:o=d=>new Promise(l=>setTimeout(l,d)),now:a=()=>Date.now(),force:c=!1,current:u=Xe}={}){const d=fe(),l=await n(d);if(!c&&l.ok&&t&&l.version&&Q(l.version,t)>0)return{ok:!1,newer:!0,health:l,shadow:B()};i();const h=l.ok&&l.managedBy&&l.managedBy!=="gateway"?l.managedBy:"";if(!c&&l.ok&&t&&l.version===t&&!h&&u())return{ok:!0,unchanged:!0,health:l,replaced:"",deferredTo:"",shadow:B(),errLog:""};const R=!!(l.ok&&t&&l.version&&l.version!==t),w=R&&!h;w&&(s(),await o(1200));const C=r()||{},y=w?t:"",P=X=>X.ok&&(!y||X.version===y),ye=a()+e;let T=await n(d);for(;!P(T)&&a()<ye;)await o(500),T=await n(d);const z=P(T);return{...C,health:T,ok:z,replaced:w?l.version:"",deferredTo:R?h:"",shadow:B(),errLog:z?"":ge()}}function lt(){return N(ke,Oe,Ze)}function me(){return N(Ie,se,pe)}function Je(e,t=process.platform){const n=String(e||"");if(t==="darwin"){const r=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(n);if(!r)return[];const i=o=>o.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");return[...r[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map(o=>i(o[1]))}const s=/^ExecStart=(.*)$/m.exec(n);return s?[...s[1].matchAll(/"([^"]*)"|(\S+)/g)].map(r=>r[1]??r[2]):[]}function Qe({text:e,loaded:t,exists:n=g,platform:s=process.platform}){if(!e)return{state:"none",missing:[]};const o=Je(e,s).slice(0,2).filter((a,c)=>c===0||/[\\/]/.test(a)&&!a.startsWith("-")).filter(a=>a.startsWith("/")&&!n(a));return o.length?{state:"gone",missing:o}:{state:t?"ok":"unloaded",missing:[]}}function we(){try{return N(()=>W(I(),"utf8"),()=>"",()=>W(H(),"utf8"))}catch{return""}}async function pt({platform:e=process.platform}={}){const t=[];let n=!1;try{n=me()}catch(c){t.push(`auto-start: ${c.message}`)}const s=e==="win32"?{state:"none",missing:[]}:Qe({text:we(),loaded:n,platform:e});s.state==="gone"?t.push(`auto-start: ✕ registered, but it starts ${s.missing.join(" and ")}, which is gone (a Node upgrade or a version manager removed it) — \`chatpanel-gateway --install\` registers it again with this copy`):s.state==="unloaded"?t.push("auto-start: installed but switched off (the service manager is not running it) — `chatpanel-gateway --install` turns it back on"):t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const r=e==="linux"&&v()?j():null;if(e==="win32"||r){const c=r?(d,l,h)=>p(d==="reg"?r.exe.reg:d,l,h):p,u=n?Z(c):"";u&&t.push(` launcher: ${u.length>120?`${u.slice(0,117)}…`:u}`),u.startsWith("wscript")&&!q(r?{systemRoot:r.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&Re(c)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),r&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const i=D();i&&(e==="win32"?t.push(_e(i)?`command: ${i} (on PATH)`:`command: ${i} — NOT on your PATH; \`--install\` adds it`):t.push(O(process.env.PATH||"",i,{platform:e})===null?`command: ${i} (on PATH)`:`command: ${i} — not on your PATH: export PATH="${i}:$PATH"`));const o=B({platform:e});o&&t.push(` ✕ ${o}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${G}`);const a=await he();try{const c=a.ok?String((await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.bridge?.version||""):"";t.push(...Ne(je({embedded:c,platform:e}),{embedded:c}).map(u=>u.replace(/^ {2}/,"")))}catch{}if(a.ok){const c=a.version===G?"":` — this command is v${G}; \`--install\` makes it the one that runs`;t.push(`running: v${a.version} at ${a.url}${a.managedBy?` (run by ${a.managedBy})`:""}${a.managedBy?"":c}`)}else{t.push(`running: nothing answers at ${a.url}`);const c=ge();c&&t.push(` last of ${b().err}:`,...c.split(`
|
|
42
|
+
`).map(u=>` ${u}`))}return t.join(`
|
|
43
|
+
`)}export{Ae as DARWIN_LAUNCH_ENV,Be as GATEWAY_ARGV_PATTERNS,D as commandDir,Q as compareVersions,ge as errLogTail,ut as installService,v as isWsl,le as linUnitText,ee as macPlistText,B as pathShadow,O as pathWithDir,he as probeHealth,te as psEncode,E as realPath,k as resolveLaunch,at as restartService,Ye as retireStandaloneBridge,He as selfAndAncestors,ct as serviceRegistered,pt as serviceReport,me as serviceStatus,be as stableNodePath,je as staleBridgeCommands,Ne as staleBridgeLines,Ke as standaloneCandidates,ie as stopOtherGateways,Ue as stopService,lt as uninstallService,Xe as unitCurrent,Qe as unitHealth,Je as unitLaunch,q as vbscriptAvailable,_e as winCommandOnPath,Te as winEnsureOnPath,ne as winLauncher,ze as winRelaunchOpts,Re as winStartupDisabled,We as winStopArgs,Le as winStopScript};
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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=3*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};
|
|
1
|
+
import{join as I}from"node:path";import{existsSync as ee,readdirSync as te}from"node:fs";import{randomUUID as ne}from"node:crypto";import{ensureLib as B,modelRoot as Y}from"./ner-engine.js";import{runtimeDtype as v,runtimeName as j,DTYPE_SUFFIX as re}from"./model-runtime.js";import{verifyModelWeights as oe}from"./model-integrity.js";import{DEFAULT_STT_MODEL as W,isEnglishOnly as G,sttModelDtype as z,isKnownSttModel as ie,sttModelEngine as H}from"./stt-models.js";import*as k from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as le}from"./diarize-models.js";import{makeWarmTimer as C}from"./warm-timer.js";const m=16e3,ae=m,se=3*m,ce=2,ue=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 fe(e,t){if(t>ce*m)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ue.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let c="off",p=null,f=null,M=null,A=null,g=null,D=null,_=null;function de(e=p||W,t=z(e)||v()){if(H(e)==="parakeet-tdt")return k.parakeetOnDisk(e,k.parakeetDtype(t));const n=I(Y(),...e.split("/"),"onnx");if(!ee(n))return!1;const r=re[t]??"";try{const o=te(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(l=>l===`decoder_model_merged${r}.onnx`||l===`decoder_model${r}.onnx`)}catch{return!1}}function Ue(){return c}function P(){return c==="ready"&&!!f}function Ke(){return g}function Oe(){return{configured:c!=="off",ok:P(),state:c,model:p,dtype:D,runtime:j(),error:M,warmMs:_?.warmMs??null}}function Xe(){return!!_?.pending()}function b(){return T.size>0||c==="loading"||c==="downloading"}async function U({log:e=()=>{}}={}){if(b())return!1;_?.disarm();const t=f;if(f=null,A=null,D=null,g=null,M=null,c="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 q(e){return e.then(t=>(t&&!b()&&_?.arm(),t))}async function Q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(H(e)==="parakeet-tdt")return me(e,{log:t,allowDownload:n,dtype:r});const o=f,l=p;let a;try{a=await B()}catch(d){return c="error",M=`engine load failed: ${d.message}`,t(`[stt] transformers.js not available (${d.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||z(e)||v(),s=de(e,i);if(a.env.allowRemoteModels=s?!1:!!n,!s&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=a.env.remoteHost,w=!ie(e);if(!s&&w)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=s?"loading":"downloading",s||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${w?", from Hugging Face":""})…`));try{const d=u=>{if(!u)return;const R=typeof u.progress=="number"?Math.round(u.progress):g?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?g={model:e,file:u.file||g?.file||null,pct:R}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let S;try{S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}catch(u){if(s||w||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}if(!s)try{oe(e,{modelsDir:Y(),log:t})}catch(u){try{await S.dispose?.()}catch{}throw u}if(f=S,p=e,c="ready",M=null,g=null,D=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(d){return M=d.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${d.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=y}catch{}}}async function me(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,l=p,a=k.parakeetDtype(r&&r!=="auto"?r:pe()),h=k.parakeetOnDisk(e,a);if(!h&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=h?"loading":"downloading",h||(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:a,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),s=async y=>({text:await i.transcribe(y)});if(s.__parakeet=!0,s.dispose=()=>i.dispose(),f=s,p=e,c="ready",M=null,g=null,D=a,o&&o!==s)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function pe(){return k.PARAKEET_DEFAULT_DTYPE}const ge=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<=ge||e==="download"?{allowDownload:!0}:null}function K(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:le(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Be(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return p=e.model||W,c="loading",_=C({warmMs:e.warmMs,busy:b,log:t,unload:()=>U({log:t})}),A=q(Q(p,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&K(e.speaker,{log:t,warmMs:e.warmMs}),n)),A}async function Ye(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=H(e)==="parakeet-tdt"?k.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:k.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:z(e)||v();if(e===p&&P()&&D===r)return K(t.speaker,{log:n,warmMs:t.warmMs}),!0;_??=C({warmMs:t.warmMs,busy:b,log:n,unload:()=>U({log:n})});const o=await q(Q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&K(t.speaker,{log:n,warmMs:t.warmMs}),o}const ye=8,_e=12e4,we=6e4,Me=1200,V=12,O=700,$=.008,Te=30,T=new Map,x=new Map;let N=Promise.resolve();function je(){return T.size}const ke=300,Ee=3e3;function Se(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ee,Math.max(ke,Math.round(t))):O}function We({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=O,interims:l=!0,remote:a=null,poll:h=!1}={}){if(T.size>=ye){const s=new Error("too many concurrent dictation sessions");throw s.code="too_many_sessions",s}const i={id:ne(),endSilenceMs:Se(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:a||null,interims:l!==!1&&!a,chunks:[],samples:0,listeners:new Set,poll:h?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return T.set(i.id,i),_?.disarm(),i.diarizer&&E.retain(),J(i),{id:i.id}}function X(e){return T.get(String(e||""))||null}function Ge(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function L(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function qe(e){const t=String(e||""),n=T.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=x.get(t);return r?(clearTimeout(r.timer),x.delete(t),r.session.poll.splice(0)):null}function Qe(e){return x.get(String(e||""))?.session||null}function J(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Le(e.id).catch(()=>{}),we),e.idleTimer.unref?.()}function Ve(e,t){const n=X(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,J(n),xe(n))}function Je(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 xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Me-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,N=N.then(()=>Z(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Ae(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 l=t;l<n;l++)r+=e[l]*e[l];return Math.sqrt(r/o)}function De(e){const t=Math.round(.02*m);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 be(e){try{const t=await B(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>m*8?e.subarray(0,m*8):e,o=await f.processor(r),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await f.model({...o,decoder_input_ids:l});let h=null,i=-1/0;for(const[s,y]of Object.entries(n.lang_to_id)){const w=Number(a.logits.data[y]);w>i&&(i=w,h=s)}return h?h.slice(2,-2):null}catch{return null}}async function Z(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!P()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Ae(e),r=Math.round((e.endSilenceMs||O)/1e3*m),o=n.length>r&&F(n,n.length-r)<$;if(F(n)<$){n.length>m*5&&(e.chunks=[n.subarray(n.length-m)],e.samples=m);return}if(!e.interims&&!t&&!o&&n.length<V*m)return;if(!e.remote&&!e.lang&&!e.langTried&&!G(p)&&!f?.__parakeet&&n.length>=m){e.langTried=!0;const i=await be(n);i&&(e.lang=i,L(e,{type:"language",lang:i}))}let l="";try{if(e.remote)l=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=G(p)?{}:{language:e.lang||void 0,task:"transcribe"},s=await f(n,i);l=String(s?.text||"").trim()}}catch(i){L(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!l)return;const a=n.length>=V*m,h=n.length>=Te*m;if(t||o||a||h){const i=t?"flush":o?"silence":h?"overflow":"length",s=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=De(n);if(fe(l,y?y.length:0))return;let w=null;if(e.diarizer)try{const d=e.speakerLabel?null:y,S=d?await E.embed(d):null,u=!!d&&d.length<ae,R=!!d&&d.length<se;w=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:u,thin:R})}catch{}L(e,{type:"final",text:l,reason:i,endOfTurn:s,durationMs:Math.round(n.length/m*1e3),...w?{speaker:w}:{}})}else l!==e.lastInterim&&(e.lastInterim=l,L(e,{type:"interim",text:l}))}async function Le(e){const t=X(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(()=>Z(t,{flush:!0}).catch(()=>{})))}finally{if(L(t,{type:"end"}),t.listeners.clear(),T.delete(t.id),t.poll){const n=setTimeout(()=>x.delete(t.id),_e);n.unref?.(),x.set(t.id,{session:t,timer:n})}t.diarizer&&E.release(),T.size===0&&P()&&_?.arm()}return!0}function Ze(){for(const e of T.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);T.clear();for(const e of x.values())clearTimeout(e.timer);x.clear(),_?.disarm(),_=null,c="off",p=null,f=null,M=null,A=null,g=null}function Ie(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){f=e,p=t,c=e?"ready":"off",D=r,n!==null&&(_=C({warmMs:n,busy:b,unload:()=>U()}),e&&_.arm())}export{ge as AUTO_FETCH_MAX_MB,m as SAMPLE_RATE,se as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,Ze as _reset,Ie as _setPipeForTest,Se as clampEndSilence,We as createSession,qe as drainEvents,Le as endSession,Qe as endedSession,X as getSession,Oe as health,Be as init,P as isReady,fe as looksHallucinated,de as modelOnDisk,Ke as progress,Ve as pushAudio,v as runtimeDtype,j as runtimeName,je as sessionCount,Ye as setModel,he as speakerPlan,Ue as state,Ge as subscribe,Je as toFloat32,U as unload,Xe as warmPending};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.85.2";export{o as VERSION};
|
package/src/web-search-tool.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
const
|
|
2
|
-
`),
|
|
1
|
+
import{summarizeSearch as l,engineLabel as h}from"./search-outcome.js";const d={nothing:"nothing found",blocked:"search blocked",resting:"every engine resting",offline:"offline","no-engines":"no engine on"},c="web_search",y='You can call web_search to look up current information from the web — prices, news, recent events, documentation, or anything time-sensitive or that may have changed since your training. Call it whenever the user asks about such things instead of guessing or saying you are unsure. Cite results inline as markdown links — e.g. ([1](https://…)) — never HTML, <sup>, or bare numbers, and finish with a "Sources" list of the links you used.',g=Object.freeze({name:c,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Search the web and return ranked result snippets with their source URLs. Use this for current events, live prices/quotes, news, product/library docs, or any fact you are unsure about or that may have changed since training — prefer it over guessing.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query — a few keywords work best."}},required:["query"],additionalProperties:!1}});function p(e){if(!e?.results?.length){if(Array.isArray(e?.asked)||Array.isArray(e?.resting)){const{line:r,advice:s}=l(e);return`No web results for "${e?.query||""}"${r?` (${r})`:""}. ${s} Do NOT conclude the information is unavailable; say plainly that the search failed and why.`}const n=(e?.engines||[]).join(", ");return`No web results for "${e?.query||""}"`+(n?` (searched: ${n}).`:".")+" This may mean the engine blocked the request rather than that nothing exists — do NOT conclude the information is unavailable. Try a shorter, more general query (drop dates and qualifiers), and tell the user they can enable another search engine in ChatPanel settings if it keeps failing."}const i=Array.isArray(e.engines)?e.engines:[],u=e.results.map(n=>`[${n.rank}] [${n.title}](${n.url})`).join(`
|
|
2
|
+
`),a=e.results[0].url,t=`Web search results for "${e.query}" (engines: ${i.join(", ")}).
|
|
3
3
|
|
|
4
|
-
Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${
|
|
4
|
+
Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${a})). Cite multiple sources as separate links: ([1](url)) ([3](url)). Do NOT output HTML, <sup>, or bare bracket numbers like [1] — every citation must be a clickable markdown link. Finish with a "Sources" section that repeats, as markdown links, each source you cited.
|
|
5
5
|
|
|
6
6
|
Sources:
|
|
7
|
-
${
|
|
8
|
-
<${
|
|
7
|
+
${u}`,o=e.results.map(n=>`### [${n.rank}] ${n.title}
|
|
8
|
+
<${n.url}>
|
|
9
9
|
|
|
10
|
-
${
|
|
10
|
+
${n.text}`).join(`
|
|
11
11
|
|
|
12
12
|
---
|
|
13
13
|
|
|
14
|
-
`);return`${
|
|
14
|
+
`);return`${t}
|
|
15
15
|
|
|
16
16
|
---
|
|
17
17
|
Result details:
|
|
18
18
|
|
|
19
|
-
${
|
|
19
|
+
${o}`}function m({search:e}={}){if(typeof e!="function")throw new Error("webSearchToolProvider: search required");return{specs:[g],system:y,async execute(i,u){if(i!==c)return JSON.stringify({error:`Unknown tool: ${i}`});const a=String(u?.query||"").trim();if(!a)return"No query provided to web_search.";try{const t=await e(a),o=[...new Set((t?.results||[]).map(s=>s.engine).filter(Boolean))].map(s=>h(s)),n=(o.length?o:t?.engines||[]).join(", "),r=!t?.results?.length&&Array.isArray(t?.asked)?d[l(t).status]:"";return{text:p(t),note:r?`ChatPanel · ${r}`:n?`ChatPanel · ${n}`:"ChatPanel"}}catch(t){return`web_search failed: ${t?.message||t}`}}}}export{g as WEB_SEARCH_SPEC,c as WEB_SEARCH_TOOL_NAME,y as WEB_SEARCH_TOOL_SYSTEM,p as searchResultsToText,m as webSearchToolProvider};
|
package/src/web-search.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const m=Object.freeze([Object.freeze({id:"startpage",name:"Startpage",url:"https://www.startpage.com/sp/search?query=%s",enabled:!0}),Object.freeze({id:"duckduckgo",name:"DuckDuckGo",url:"https://html.duckduckgo.com/html/?q=%s",enabled:!0}),Object.freeze({id:"google",name:"Google",url:"https://www.google.com/search?q=%s",enabled:!1}),Object.freeze({id:"bing",name:"Bing",url:"https://www.bing.com/search?q=%s",enabled:!0})]),d=5;function E(n,t,{assertFetchable:e}={}){const r=String(n||"").trim();if(!/^https:\/\//i.test(r))throw new Error("Search engine URL must start with https://");if(!r.includes("%s")&&!r.includes("{q}"))throw new Error("Search engine URL must contain a %s (or {q}) query placeholder");const s=r.replace(/%s|\{q\}/g,encodeURIComponent(String(t||"").trim()));return typeof e=="function"&&e(s),s}const w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function S(n){let t=0,e=0,r="";for(const s of n){const o=w.indexOf(s);if(o<0)return"";e=e<<6|o,t+=6,t>=8&&(t-=8,r+="%"+(e>>t&255).toString(16).padStart(2,"0"))}try{return decodeURIComponent(r)}catch{return""}}function b(n){try{const t=new URL(n,"https://duckduckgo.com"),e=t.searchParams.get("uddg");if(e)return decodeURIComponent(e);const r=t.searchParams.get("url")||t.searchParams.get("u");if(r&&/^https?:/i.test(r))return r;const s=r&&/^a1[A-Za-z0-9_-]+$/.test(r)?S(r.slice(2)):"";return/^https?:\/\//i.test(s)?s:t.href}catch{return String(n||"")}}const k=/(^|\.)(startpage\.com|startmail\.com|startpage\.dev|mojeek\.com|buttondown\.(com|email)|ecosia\.org|duckduckgo\.com|search\.brave\.com|qwant\.com|admarketplace\.(net|com)|googleadservices\.com|doubleclick\.net)$/i,R=/^\/(aclick|pagead\/aclk|aclk)\b/i;function y(n,t=""){const e=String(n||"").toLowerCase();if(!e||k.test(e))return!1;const r=String(t||"").split(".").slice(-2).join(".").toLowerCase();return!(r&&(e===r||e.endsWith(`.${r}`)))}function L(n,{engineHost:t="",limit:e=d,fallback:r=!1}={}){const s=[],o=new Map;for(const c of n||[]){const a=b(c?.href||"");let i;try{i=new URL(a)}catch{continue}if(i.protocol!=="https:"&&i.protocol!=="http:"||!y(i.hostname,t)||R.test(i.pathname)||r&&c.chrome)continue;const u=String(c?.text||"").replace(/\s+/g," ").trim();if(u.length<6||/^\S+\s+https?:\/\/\S+/.test(u))continue;const h=i.origin+i.pathname;if(o.has(h)){const l=o.get(h);l&&!l.snippet&&u.length>l.title.length+10&&(l.snippet=u);continue}const f={url:a,title:u,snippet:String(c?.snippet||"").replace(/\s+/g," ").trim()};if(o.set(h,f),s.push(f),s.length>=e)break}return s}const x=n=>[...new Set(String(n||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(t=>t.length>=4))],p=n=>n.replace(/(ies|ing|ed|es|s|y)$/u,""),g=(n,t)=>n.includes(t)||p(t).length>=3&&n.includes(p(t));function q(n,t){const e=x(t);if(e.length<2||!n?.length)return!1;const r=n.map(o=>`${o.title||""} ${o.snippet||""} ${o.url||""}`.toLowerCase());if(e.some(o=>o.length>=6&&!r.some(c=>g(c,o))))return!0;const s=Math.ceil(e.length/2);return!r.some(o=>e.filter(c=>g(o,c)).length>=s)}const U=/^(www\.)?(bing|google(\.[a-z]{2,3}){1,2}|duckduckgo|search\.yahoo|yandex|baidu|startpage|search\.brave)\.[a-z.]*$|^(www\.)?google\.[a-z.]+$/i;function z(n){try{const t=new URL(n);return U.test(t.hostname)&&/^\/(search|news\/search|web|html|sp\/search|s)\b/i.test(t.pathname)}catch{return!1}}function C(n,t=8){const e=[],r=new Set;for(const s of n||[])for(const o of s||[]){let c;try{const a=new URL(o.url);c=a.origin+a.pathname}catch{c=o.url}if(!r.has(c)&&(r.add(c),e.push(o),e.length>=t))return e}return e}function O(n=m){const t=(Array.isArray(n)?n:[]).filter(e=>e&&e.url&&!e.retired);return[...t.filter(e=>e.enabled!==!1),...t.filter(e=>e.enabled===!1)]}export{d as RESULTS_PER_ENGINE,m as SEARCH_ENGINES,E as buildSearchUrl,O as engineOrder,y as isResultHost,z as isSearchPage,C as mergeEngineResults,q as offTopic,L as pickResults,b as unwrapRedirect};
|