tz-voice-chat 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +616 -127
- package/bin/tz-voice-chat.js +46 -0
- package/dist/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist/index.cjs +2 -1
- package/dist/index.js +1429 -437
- package/dist/style.css +1 -1
- package/dist-app/assets/index-BDMCgrF_.css +1 -0
- package/dist-app/assets/index-CFWv17S2.js +41 -0
- package/dist-app/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist-app/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist-app/index.html +27 -0
- package/package.json +58 -10
- package/server/chat.js +91 -0
- package/server/elevenlabs.js +40 -0
- package/server/index.js +344 -0
- package/server/openai-stt.js +21 -0
- package/server/run.js +42 -0
- package/server/settings.js +102 -0
- package/server/tts.js +139 -0
- package/server/vendor.js +57 -0
- package/shared/settingsSchema.js +212 -0
- package/vendor/kokoro/kokoro.web.js +1 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
- package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
- package/vendor/ort/ort.wasm.min.js +8 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/transformers/transformers.min.js +2 -0
- package/vendor/transformers/transformers.node.min.mjs +2 -0
- package/vendor/transformers/transformers.node.mjs +36472 -0
- package/vendor/vad/bundle.min.js +2 -0
- package/vendor/vad/silero_vad_legacy.onnx +0 -0
- package/vendor/vad/vad.worklet.bundle.min.js +1 -0
- package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { startServer } from '../server/run.js';
|
|
3
|
+
|
|
4
|
+
const HELP = `tz-voice-chat — voice assistant server + web app
|
|
5
|
+
|
|
6
|
+
Usage: tz-voice-chat [options]
|
|
7
|
+
|
|
8
|
+
-p, --port <n> Port to listen on (default: $PORT or 3000)
|
|
9
|
+
--host <addr> Address to bind to (default: 127.0.0.1)
|
|
10
|
+
--settings <file> Settings file to read/write (default: ~/.tz-voice-chat/settings.json,
|
|
11
|
+
or $TZ_VOICE_CHAT_SETTINGS)
|
|
12
|
+
-h, --help Show this help
|
|
13
|
+
|
|
14
|
+
Open the printed URL and finish setup on the Settings page (chat provider and key).
|
|
15
|
+
Speech-to-text and text-to-speech work out of the box. Settings can also be
|
|
16
|
+
pre-seeded with environment variables (OPENAI_PROVIDER, OPENROUTER_API_KEY, ...).
|
|
17
|
+
`;
|
|
18
|
+
|
|
19
|
+
const args = process.argv.slice(2);
|
|
20
|
+
const opts = { port: Number(process.env.PORT) || 3000, host: '127.0.0.1' };
|
|
21
|
+
for (let i = 0; i < args.length; i++) {
|
|
22
|
+
const a = args[i];
|
|
23
|
+
const next = () => args[++i];
|
|
24
|
+
if (a === '-h' || a === '--help') { console.log(HELP); process.exit(0); }
|
|
25
|
+
else if (a === '-p' || a === '--port') opts.port = Number(next());
|
|
26
|
+
else if (a === '--host') opts.host = next();
|
|
27
|
+
else if (a === '--settings') opts.settingsFile = next();
|
|
28
|
+
else { console.error(`Unknown option: ${a}\n\n${HELP}`); process.exit(1); }
|
|
29
|
+
}
|
|
30
|
+
if (!Number.isInteger(opts.port) || opts.port < 0 || opts.port > 65535) {
|
|
31
|
+
console.error('Invalid --port'); process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
const { url, settings, host } = await startServer(opts);
|
|
36
|
+
console.log(`tz-voice-chat running at ${url}`);
|
|
37
|
+
console.log(`Settings file: ${settings.file}`);
|
|
38
|
+
if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
|
|
39
|
+
console.warn('Warning: listening on a non-loopback address — anyone who can reach this port can read/change the saved API keys.');
|
|
40
|
+
}
|
|
41
|
+
const { missing } = settings.getPublic();
|
|
42
|
+
if (missing.length) console.log(`Needs setup: ${missing.map(m => m.message).join(' ')} Open ${url} and use Settings.`);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
console.error(err.code === 'EADDRINUSE' ? `Port ${opts.port} is already in use (try --port).` : err.message);
|
|
45
|
+
process.exit(1);
|
|
46
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";let t=null,r=null;self.onmessage=async l=>{var n,p;const{type:o,messages:i,modelProxyUrl:g}=l.data;if(o==="init"){try{const{pipeline:e,TextStreamer:a,env:s}=await import("/vendor/transformers/transformers.min.js");s.remoteHost=g||"/api/models/",(p=(n=s==null?void 0:s.backends)==null?void 0:n.onnx)!=null&&p.wasm&&(s.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),r=a,t=await e("text-generation","HuggingFaceTB/SmolLM2-360M-Instruct",{dtype:"q4",progress_callback:({status:c,progress:m}={})=>{self.postMessage({type:"progress",status:c,progress:(m??0)/100})}}),self.postMessage({type:"ready"})}catch(e){self.postMessage({type:"error",message:String((e==null?void 0:e.message)??e)})}return}if(o==="generate"){if(!t||!r){self.postMessage({type:"done"});return}try{const e=new r(t.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:a=>{self.postMessage({type:"token",text:a})}});await t(i,{max_new_tokens:150,do_sample:!1,streamer:e}),self.postMessage({type:"done"})}catch(e){console.error("[LLM worker] generate error:",e),self.postMessage({type:"done"})}}}})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";let i=null,c=Promise.resolve();self.onmessage=async t=>{var m,d;const{type:l,audio:a}=t.data;if(l==="init"){const n=t.data.model||"onnx-community/whisper-tiny.en",e=t.data.device||"wasm",p=e==="cpu"?"wasm":e,g=t.data.modelProxyUrl||"/api/models/";let r=t.data.dtype||"q8";p==="webgpu"&&(r==="q4"||r==="q8")&&(console.warn(`[Whisper worker] dtype "${r}" not supported on WebGPU — using "fp32".`),r="fp32");try{const{pipeline:s,env:o}=await import("/vendor/transformers/transformers.min.js");o.remoteHost=g,(d=(m=o==null?void 0:o.backends)==null?void 0:m.onnx)!=null&&d.wasm&&(o.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),i=await s("automatic-speech-recognition",n,{dtype:r,device:p,progress_callback:({status:y,progress:w}={})=>{self.postMessage({type:"progress",status:y,progress:(w??0)/100})}}),self.postMessage({type:"ready"})}catch(s){self.postMessage({type:"error",message:String((s==null?void 0:s.message)??s)})}return}l==="transcribe"&&(console.log("[Whisper worker] transcribe — samples:",a==null?void 0:a.length),c=c.then(async()=>{var n;try{if(!i){console.warn("[Whisper worker] pipeline not ready, dropping segment"),self.postMessage({type:"transcript",text:""});return}const e=await i(a),p=(e==null?void 0:e.text)??((n=e==null?void 0:e[0])==null?void 0:n.text)??"";self.postMessage({type:"transcript",text:p})}catch(e){console.error("[Whisper worker] transcription error:",e),self.postMessage({type:"transcript",text:""})}}))}})();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var ve=Object.create;var de=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Ie=(e,s,n,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Te(s))!Ae.call(e,t)&&t!==n&&de(e,t,{get:()=>s[t],enumerable:!(r=xe(s,t))||r.enumerable});return e};var he=(e,s,n)=>(n=e!=null?ve(ke(e)):{},Ie(s||!e||!e.__esModule?de(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react"),h=require("react/jsx-runtime");var ie=typeof document<"u"?document.currentScript:null;function me(){let e="";function s(){const n=[];for(;;){const r=/([.!?]{1,3})(\s|$)/.exec(e);if(r){const t=e.slice(0,r.index+r[0].length).trim();if(t.length>=10){n.push(t),e=e.slice(r.index+r[0].length);continue}}if(e.length>=25){const t=/[,;:—–](\s|$)/.exec(e);if(t){const o=e.slice(0,t.index+t[0].length).trim();if(o.length>=20){n.push(o),e=e.slice(t.index+t[0].length);continue}}}if(e.length>=45){const t=e.lastIndexOf(" ",44),o=t>10?t:45;n.push(e.slice(0,o).trim()),e=e.slice(o).trimStart();continue}break}return n}return{write(n){return e+=n,s()},flush(){const n=e.trim();return e="",n}}}async function Ne(e,{dtype:s="q8",device:n="cpu",modelProxyUrl:r="/api/models/"}={}){var u,S;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=r,(S=(u=t==null?void 0:t.backends)==null?void 0:u.onnx)!=null&&S.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const o=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:i}=o;let b=s;n==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),b="fp32");let p=0;const w=d=>{typeof(d==null?void 0:d.progress)=="number"&&(p=Math.max(p,d.progress/100),e==null||e("kokoro",Math.min(.99,p)))};async function c(d,j){return i.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:j,device:d,progress_callback:w})}let a;try{a=await c(n,b)}catch(d){if(n!=="wasm")console.warn(`[modelLoader] Kokoro on "${n}" failed (${d==null?void 0:d.message}) — falling back to WASM.`),p=0,a=await c("wasm",s);else throw d}return e==null||e("kokoro",1),{kokoro:a}}function Le(e,{voice:s="af_bella",onPlayStart:n}={}){const r=new AudioContext,t=[];let o=!1,i=null,b=!1;async function p(a){if(a instanceof AudioBuffer)return a;const u=(a==null?void 0:a.audio)??a;if(u instanceof ArrayBuffer)return await r.decodeAudioData(u.slice(0));if(u instanceof Float32Array){const S=(a==null?void 0:a.samplingRate)??24e3,d=r.createBuffer(1,u.length,S);return d.copyToChannel(u,0),d}throw new Error("Unsupported TTS payload")}async function w(a){await r.resume();const u=r.createBufferSource();return u.buffer=a,u.connect(r.destination),new Promise(S=>{u.onended=()=>{i===u&&(i=null),S()},i=u,u.start(),b||(b=!0,n==null||n())})}async function c(){if(!o){for(o=!0;t.length>0;){const a=t.shift();try{const u=await a;u&&await w(u)}catch(u){console.error("[TtsQueue]",u)}}o=!1}}return{enqueue(a){t.push(e.generate(a,{voice:s}).then(p)),c()},cancel(){if(t.length=0,i){try{i.stop()}catch{}i=null}},async finished(){for(;o||t.length>0;)await new Promise(a=>setTimeout(a,200))}}}function Re({voice:e="",onPlayStart:s,url:n="/api/tts"}={}){const r=new AudioContext,t=[];let o=!1,i=null,b=!1;async function p(a){const u={text:a};e&&(u.voice=e);const S=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!S.ok)throw new Error(`TTS ${S.status}: ${await S.text()}`);return r.decodeAudioData(await S.arrayBuffer())}async function w(a){await r.resume();const u=r.createBufferSource();return u.buffer=a,u.connect(r.destination),new Promise(S=>{u.onended=()=>{i===u&&(i=null),S()},i=u,u.start(),b||(b=!0,s==null||s())})}async function c(){if(!o){for(o=!0;t.length>0;){const a=t.shift();try{await w(await a)}catch(u){console.error("[ServerTTS]",u)}}o=!1}}return{enqueue(a){a!=null&&a.trim()&&(t.push(p(a)),c())},cancel(){if(t.length=0,i){try{i.stop()}catch{}i=null}b=!1},async finished(){for(;o||t.length>0;)await new Promise(a=>setTimeout(a,100))}}}function _e({voice:e="",rate:s=1,pitch:n=1,onPlayStart:r}={}){const t=[];let o=!1,i=!1;function b(){return e?speechSynthesis.getVoices().find(c=>c.name===e||c.voiceURI===e)??null:null}function p(){if(o||t.length===0)return;o=!0;const w=t.shift(),c=new SpeechSynthesisUtterance(w),a=b();a&&(c.voice=a),c.rate=s,c.pitch=n,c.onstart=()=>{i||(i=!0,r==null||r())},c.onend=()=>{o=!1,p()},c.onerror=u=>{console.error("[WebSpeech TTS] error",u.error),o=!1,p()},speechSynthesis.speak(c)}return{enqueue(w){w!=null&&w.trim()&&(t.push(w),p())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,i=!1},async finished(){for(;o||t.length>0;)await new Promise(w=>setTimeout(w,100))}}}async function ze({onSpeechStart:e,onSpeechEnd:s,onError:n,deviceId:r}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...r?{deviceId:{exact:r}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:i=>{console.log("[VAD] onSpeechEnd — samples:",i==null?void 0:i.length),s==null||s(i)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw n==null||n("VAD initialization failed. Falling back to manual microphone capture."),t}}const y={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Ee="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function Me({processInput:e,systemPrompt:s=Ee,ttsProvider:n="server-kokoro",ttsVoice:r="af_bella",ttsServerUrl:t="/api/tts",ttsSpeechRate:o=1,ttsSpeechPitch:i=1,whisperModel:b="onnx-community/whisper-tiny.en",whisperDtype:p="q8",whisperDevice:w="cpu",kokoroDtype:c="q8",kokoroBrowserDevice:a="wasm",modelProxyUrl:u="/api/models/"}={}){const[S,d]=m.useState(y.IDLE),[j,R]=m.useState(!0),[B,k]=m.useState({whisper:0,kokoro:0}),[$,N]=m.useState(null),[Z,ee]=m.useState([]),[te,_]=m.useState(null),[V,z]=m.useState(!1),[F,v]=m.useState(""),[E,U]=m.useState([]),[ne,H]=m.useState(null),O=m.useRef(y.IDLE),W=m.useRef(!1),I=m.useRef(null),D=m.useRef(null),q=m.useRef(null),M=m.useRef(null),C=m.useRef(null),se=m.useRef(null),J=m.useRef([{role:"system",content:s}]),re=m.useRef(e);m.useEffect(()=>{O.current=S},[S]),m.useEffect(()=>{W.current=V},[V]),m.useEffect(()=>{re.current=e},[e]),m.useEffect(()=>{async function g(){try{const x=await navigator.mediaDevices.enumerateDevices();U(x.filter(l=>l.kind==="audioinput"))}catch{}}return g(),navigator.mediaDevices.addEventListener("devicechange",g),()=>navigator.mediaDevices.removeEventListener("devicechange",g)},[V]),m.useEffect(()=>{let g=!1;async function x(){try{const l=()=>{var f;n==="webspeech"&&((f=D.current)==null||f.pause())};if(n==="webspeech")I.current=_e({voice:r,rate:o,pitch:i,onPlayStart:l}),k(f=>({...f,kokoro:1}));else if(n==="kokoro"){const{kokoro:f}=await Ne((T,G)=>k(K=>({...K,[T]:G})),{dtype:c,device:a,modelProxyUrl:u});if(g)return;I.current=Le(f,{voice:r,onPlayStart:l})}else I.current=Re({voice:r,onPlayStart:l,url:t}),k(f=>({...f,kokoro:1}));if(g)return;M.current=new Worker(new URL("./assets/whisperWorker-BJuP9cl9.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ie&&ie.tagName.toUpperCase()==="SCRIPT"&&ie.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),M.current.onmessage=f=>{f.data.type==="transcript"?oe(f.data.text):f.data.type==="progress"?k(T=>({...T,whisper:f.data.progress})):f.data.type==="ready"?(k(T=>({...T,whisper:1})),R(!1)):f.data.type==="error"&&(N(`Whisper: ${f.data.message}`),R(!1))},M.current.onerror=()=>{N("Model load failed. Check WebGPU/WASM browser support."),R(!1)},M.current.postMessage({type:"init",model:b,dtype:p,device:w,modelProxyUrl:u})}catch(l){g||(N("Initialisation failed: "+((l==null?void 0:l.message)??String(l))),R(!1))}}return x(),()=>{var l;g=!0,(l=M.current)==null||l.terminate()}},[n,b,p,w,c,a]);function ce(g,x){ee(l=>[...l,{role:g,content:x,time:new Date().toISOString()}])}async function oe(g){if(!(g!=null&&g.trim())){d(W.current?y.LISTENING:y.IDLE);return}d(y.THINKING),ce("user",g);const x=[...J.current,{role:"user",content:g}];J.current=x,await ge(g,x)}async function ge(g,x){var l,f,T,G,K;(l=q.current)==null||l.abort(),q.current=new AbortController,(f=I.current)==null||f.cancel();try{if(!re.current)throw new Error("processInput is not provided");const P=me();let Y="",ae=!1;_("");for await(const le of re.current(g,x,q.current.signal))Y+=le,_(Y),P.write(le).forEach(Se=>{var fe;ae||(ae=!0,d(y.SPEAKING)),(fe=I.current)==null||fe.enqueue(Se)});const ue=P.flush();ue&&(ae||d(y.SPEAKING),(T=I.current)==null||T.enqueue(ue)),ce("assistant",Y),_(null),J.current=[...J.current,{role:"assistant",content:Y}],await((G=I.current)==null?void 0:G.finished()),n==="webspeech"&&((K=D.current)==null||K.start())}catch(P){_(null),P.name!=="AbortError"&&N(P.message||"Processing failed.")}finally{d(W.current?y.LISTENING:y.IDLE)}}async function we(){var g,x;N(null),O.current===y.SPEAKING&&((g=I.current)==null||g.cancel(),(x=q.current)==null||x.abort());try{d(y.LISTENING),z(!0);try{const l=await navigator.mediaDevices.getUserMedia({audio:F?{deviceId:{exact:F}}:!0,video:!1});se.current=l;const f=new AudioContext;C.current=f;const T=f.createAnalyser();T.fftSize=256,f.createMediaStreamSource(l).connect(T),H(T)}catch(l){console.warn("[TZVoiceChat] waveform analyser unavailable:",l)}D.current=await ze({onSpeechStart:()=>{var l,f;n==="webspeech"&&O.current===y.SPEAKING||(O.current===y.SPEAKING&&((l=I.current)==null||l.cancel(),(f=q.current)==null||f.abort()),d(y.LISTENING))},onSpeechEnd:l=>{var f;n==="webspeech"&&O.current===y.SPEAKING||(d(y.TRANSCRIBING),(f=M.current)==null||f.postMessage({type:"transcribe",audio:l},[l.buffer]))},onError:l=>{N(l),d(y.IDLE)},deviceId:F||void 0})}catch(l){console.error("[TZVoiceChat] startListening failed:",l),N("Microphone access failed. Allow audio permissions and refresh."),d(y.IDLE),z(!1)}}function be(){var g,x,l,f,T;z(!1),(g=D.current)==null||g.destroy(),D.current=null,(x=se.current)==null||x.getTracks().forEach(G=>G.stop()),se.current=null,(l=C.current)==null||l.close(),C.current=null,H(null),(f=I.current)==null||f.cancel(),(T=q.current)==null||T.abort(),d(y.IDLE)}function ye(g){var T;if(!(g!=null&&g.trim()))return;d(y.SPEAKING);const x=me(),l=x.write(g),f=x.flush();[...l,...f?[f]:[]].forEach(G=>{var K;return(K=I.current)==null?void 0:K.enqueue(G)}),(T=I.current)==null||T.finished().then(()=>{d(W.current?y.LISTENING:y.IDLE)})}return{status:S,loading:j,progress:B,error:$,transcript:Z,streamingMessage:te,micEnabled:V,startListening:we,stopListening:be,speak:ye,submitText:oe,liveAnalyser:ne,devices:E,selectedMicId:F,setSelectedMicId:v}}function pe(e){const s=e.replace("#",""),n=s.length===3?s.split("").map(r=>r+r).join(""):s;return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function je(e,s,n){e/=255,s/=255,n/=255;const r=Math.max(e,s,n),t=Math.min(e,s,n),o=(r+t)/2;if(r===t)return[0,0,o*100];const i=r-t,b=o>.5?i/(2-r-t):i/(r+t);let p;switch(r){case e:p=((s-n)/i+(s<n?6:0))/6;break;case s:p=((n-e)/i+2)/6;break;default:p=((e-s)/i+4)/6}return[p*360,b*100,o*100]}function $e(e,s,n){s/=100,n/=100;const r=i=>(i+e/30)%12,t=s*Math.min(n,1-n),o=i=>n-t*Math.max(-1,Math.min(r(i)-3,Math.min(9-r(i),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function L(e,s){const[n,r,t]=pe(e),[o,i,b]=je(n,r,t),[p,w,c]=$e(o,i,Math.max(0,Math.min(100,b+s)));return`rgb(${p}, ${w}, ${c})`}function A(e,s){const[n,r,t]=pe(e);return`rgba(${n}, ${r}, ${t}, ${s})`}function Q(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const X=10;function qe({analyser:e}){const s=m.useRef(null),n=m.useRef(null);return m.useEffect(()=>{if(cancelAnimationFrame(n.current),!e)return;const r=s.current;if(!r)return;const t=r.getContext("2d"),o=e.frequencyBinCount,i=new Uint8Array(o),b=Math.max(1,Math.floor(o/X)),p=getComputedStyle(r),w=+p.getPropertyValue("--bar-hue"),c=+p.getPropertyValue("--bar-hue-range"),a=+p.getPropertyValue("--bar-sat"),u=+p.getPropertyValue("--bar-lit"),S=+p.getPropertyValue("--bar-lit-range"),d=()=>{n.current=requestAnimationFrame(d),e.getByteFrequencyData(i);const j=r.width,R=r.height;t.clearRect(0,0,j,R);const B=(j-(X-1)*2)/X;for(let k=0;k<X;k++){const $=i[k*b]/255,N=Math.max(3,$*R*.88);t.fillStyle=`hsl(${w+$*c}, ${a}%, ${u+$*S}%)`,t.beginPath(),t.roundRect(k*(B+2),(R-N)/2,B,N,[2]),t.fill()}};return d(),()=>cancelAnimationFrame(n.current)},[e]),h.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function De({status:e="idle",active:s=!1,loading:n=!1,analyser:r=null,onToggle:t,devices:o=[],selectedMicId:i="",onDeviceChange:b,inputData:p="",sendData:w,accentColor:c="#f97316",uiColor:a="#64748b",size:u=70,barHue:S=25,barHueRange:d=20,barSat:j=88,barLit:R=65,barLitRange:B=20}){var F;const[k,$]=m.useState(!1),N=m.useRef(null);m.useEffect(()=>{if(!k)return;function v(E){var U;(U=N.current)!=null&&U.contains(E.target)||$(!1)}return document.addEventListener("pointerdown",v),()=>document.removeEventListener("pointerdown",v)},[k]);function Z(v){b==null||b(v),$(!1)}const ee=m.useMemo(()=>{const v=L(c,-8),E=L(c,-15),U=L(c,-22),ne=L(c,-30),H=L(c,-42),O=L(c,8),W=L(c,20),I=L(c,30),D=L(a,-22),q=L(a,-30),M=L(a,18),C=L(a,37);return{"--tz-size":`${u}px`,"--tz-a":c,"--tz-a-d8":v,"--tz-a-d15":E,"--tz-a-d22":U,"--tz-a-d30":ne,"--tz-a-d42":H,"--tz-a-l8":O,"--tz-a-l20":W,"--tz-a-l30":I,"--tz-a-25":A(c,.25),"--tz-a-28":A(c,.28),"--tz-a-30":A(c,.3),"--tz-a-32":A(c,.32),"--tz-a-34":A(c,.34),"--tz-a-35":A(c,.35),"--tz-a-38":A(c,.38),"--tz-a-45":A(c,.45),"--tz-a-50":A(c,.5),"--tz-a-55":A(c,.55),"--tz-a-60":A(c,.6),"--tz-a-65":A(c,.65),"--tz-a-68":A(c,.68),"--tz-u":a,"--tz-u-d22":D,"--tz-u-d30":q,"--tz-u-l18":M,"--tz-u-l37":C,"--tz-u-30":A(a,.3),"--tz-u-55":A(a,.55),"--tz-u-d30-a85":Q(q,.85),"--tz-u-l18-a18":Q(M,.18),"--tz-u-l18-a20":Q(M,.2),"--tz-u-l18-a32":Q(M,.32),"--tz-u-d22-a90":Q(D,.9),"--bar-hue":S,"--bar-hue-range":d,"--bar-sat":j,"--bar-lit":R,"--bar-lit-range":B}},[c,a,u,S,d,j,R,B]),te=((F=o.find(v=>v.deviceId===i))==null?void 0:F.label)||(i?`Mic ${i.slice(0,6)}…`:"Default mic"),_=p.trim().length>0,V=_?"ready":s?e:"off";let z;return _?z=h.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:h.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!s||e==="idle"?z=h.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[h.jsx("path",{fillOpacity:"0.52",d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"}),h.jsx("path",{fill:"white",fillOpacity:"0.98",d:"M14.5 0L15.65 3.45L19.1 4.6L15.65 5.75L14.5 9.2L13.35 5.75L9.9 4.6L13.35 3.45Z"}),h.jsx("path",{fill:"white",fillOpacity:"0.88",d:"M19 8.62L19.75 10.75L21.88 11.5L19.75 12.25L19 14.38L18.25 12.25L16.12 11.5L18.25 10.75Z"})]}):e==="listening"?z=h.jsx(qe,{analyser:r}):e==="transcribing"?z=h.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(v,E)=>h.jsx("span",{style:{animationDelay:`${E*.1}s`}},E))}):e==="thinking"?z=h.jsxs("div",{className:"ai-btn__dots",children:[h.jsx("span",{}),h.jsx("span",{style:{animationDelay:"0.18s"}}),h.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(z=h.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(v,E)=>h.jsx("span",{style:{animationDelay:`${E*.11}s`}},E))})),h.jsxs("div",{className:"ai-btn-root",style:ee,children:[h.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${V}`,"aria-hidden":"true",children:[h.jsx("span",{className:"ai-ring ai-ring--1"}),h.jsx("span",{className:"ai-ring ai-ring--2"})]}),h.jsxs("button",{className:`ai-btn ai-btn--${V}`,disabled:n,onClick:_?()=>w==null?void 0:w(p):t,"aria-label":_?"Send message":s?"Stop assistant":"Start assistant","aria-pressed":_?void 0:s,children:[z,s&&!_&&h.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),h.jsxs("div",{className:`ai-mic-sel${k?" open":""}`,ref:N,children:[h.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>$(v=>!v),title:"Change microphone","aria-label":"Change microphone","aria-expanded":k,children:[h.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[h.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),h.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),h.jsx("span",{className:"ai-mic-sel__label",children:te}),h.jsx("svg",{className:`ai-mic-sel__caret${k?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:h.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),k&&h.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[h.jsx("li",{role:"option",className:`ai-mic-sel__option${i===""?" selected":""}`,onClick:()=>Z(""),"aria-selected":i==="",children:"Default microphone"}),o.map(v=>h.jsx("li",{role:"option",className:`ai-mic-sel__option${i===v.deviceId?" selected":""}`,onClick:()=>Z(v.deviceId),"aria-selected":i===v.deviceId,children:v.label||`Microphone ${v.deviceId.slice(0,8)}`},v.deviceId))]})]})]})}exports.AIAssistantButton=De;exports.STATES=y;exports.TZVoiceChat=Me;
|
|
1
|
+
"use strict";var Je=Object.create;var je=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(e,a,o,c)=>{if(a&&typeof a=="object"||typeof a=="function")for(let t of Ze(a))!et.call(e,t)&&t!==o&&je(e,t,{get:()=>a[t],enumerable:!(c=Qe(a,t))||c.enumerable});return e};var Ie=(e,a,o)=>(o=e!=null?Je(Xe(e)):{},tt(a||!e||!e.__esModule?je(o,"default",{value:e,enumerable:!0}):o,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react"),n=require("react/jsx-runtime");var ne=typeof document<"u"?document.currentScript:null;const be=60,ce=200;function Me(){let e="",a=!0;function o(t,i,r){t.push(i),e=r,a=!1}function c(){const t=[];for(;;){const i=/([.!?]{1,3})(\s|$)/.exec(e);if(i){const r=e.slice(0,i.index+i[0].length).trim();if(r.length>=10){o(t,r,e.slice(i.index+i[0].length));continue}}if(a){if(e.length>=25){const r=/[,;:—–](\s|$)/.exec(e);if(r){const u=e.slice(0,r.index+r[0].length).trim();if(u.length>=20){o(t,u,e.slice(r.index+r[0].length));continue}}}if(e.length>=be){const r=e.lastIndexOf(" ",be-1),u=r>10?r:be;o(t,e.slice(0,u).trim(),e.slice(u).trimStart());continue}}else if(e.length>=ce){const r=e.slice(0,ce),u=Math.max(r.lastIndexOf(", "),r.lastIndexOf("; "),r.lastIndexOf(": ")),l=u>ce/2?u+1:r.lastIndexOf(" ")>10?r.lastIndexOf(" "):ce;o(t,e.slice(0,l).trim(),e.slice(l).trimStart());continue}break}return t}return{write(t){return e+=t,c()},flush(){const t=e.trim();return e="",t}}}async function nt(e,{dtype:a="q8",device:o="cpu",modelProxyUrl:c="/api/models/"}={}){var f,h;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=c,(h=(f=t==null?void 0:t.backends)==null?void 0:f.onnx)!=null&&h.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const i=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:r}=i;let u=a;o==="webgpu"&&(a==="q4"||a==="q8")&&(console.warn(`[modelLoader] dtype "${a}" not supported on WebGPU — using "fp32".`),u="fp32");let l=0;const p=b=>{typeof(b==null?void 0:b.progress)=="number"&&(l=Math.max(l,b.progress/100),e==null||e("kokoro",Math.min(.99,l)))};async function d(b,_){return r.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:_,device:b,progress_callback:p})}let x;try{x=await d(o,u)}catch(b){if(o!=="wasm")console.warn(`[modelLoader] Kokoro on "${o}" failed (${b==null?void 0:b.message}) — falling back to WASM.`),l=0,x=await d("wasm",a);else throw b}return e==null||e("kokoro",1),{kokoro:x}}function ue(e,a,{threshold:o=.01,padMs:c=25}={}){const{numberOfChannels:t,length:i,sampleRate:r}=a;let u=i,l=-1;for(let h=0;h<t;h++){const b=a.getChannelData(h);for(let _=0;_<i;_++)if(Math.abs(b[_])>o){_<u&&(u=_);break}for(let _=i-1;_>=0;_--)if(Math.abs(b[_])>o){_>l&&(l=_);break}}if(l<u)return a;const p=Math.round(c/1e3*r),d=Math.max(0,u-p),x=Math.min(i,l+1+p);if(d===0&&x===i)return a;const f=e.createBuffer(t,x-d,r);for(let h=0;h<t;h++)f.copyToChannel(a.getChannelData(h).subarray(d,x),h);return f}function st(e,{voice:a="af_bella",speed:o=1,onPlayStart:c}={}){const t=new AudioContext,i=[];let r=!1,u=null,l=!1;async function p(f){if(f instanceof AudioBuffer)return ue(t,f);const h=(f==null?void 0:f.audio)??f;if(h instanceof ArrayBuffer)return ue(t,await t.decodeAudioData(h.slice(0)));if(h instanceof Float32Array){const b=(f==null?void 0:f.samplingRate)??24e3,_=t.createBuffer(1,h.length,b);return _.copyToChannel(h,0),ue(t,_)}throw new Error("Unsupported TTS payload")}async function d(f){await t.resume();const h=t.createBufferSource();return h.buffer=f,h.connect(t.destination),new Promise(b=>{h.onended=()=>{u===h&&(u=null),b()},u=h,h.start(),l||(l=!0,c==null||c())})}async function x(){if(!r){for(r=!0;i.length>0;){const f=i.shift();try{const h=await f;h&&await d(h)}catch(h){console.error("[TtsQueue]",h)}}r=!1}}return{enqueue(f){i.push(e.generate(f,{voice:a,speed:o}).then(p)),x()},cancel(){if(i.length=0,l=!1,u){try{u.stop()}catch{}u=null}},async finished(){for(;r||i.length>0;)await new Promise(f=>setTimeout(f,200))}}}function rt({voice:e="",speed:a=1,onPlayStart:o,url:c="/api/tts"}={}){const t=new AudioContext,i=[];let r=!1,u=null,l=!1;async function p(f){const h={text:f};e&&(h.voice=e),a!==1&&(h.speed=a);const b=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!b.ok)throw new Error(`TTS ${b.status}: ${await b.text()}`);return ue(t,await t.decodeAudioData(await b.arrayBuffer()))}async function d(f){await t.resume();const h=t.createBufferSource();return h.buffer=f,h.connect(t.destination),new Promise(b=>{h.onended=()=>{u===h&&(u=null),b()},u=h,h.start(),l||(l=!0,o==null||o())})}async function x(){if(!r){for(r=!0;i.length>0;){const f=i.shift();try{await d(await f)}catch(h){console.error("[ServerTTS]",h)}}r=!1}}return{enqueue(f){f!=null&&f.trim()&&(i.push(p(f)),x())},cancel(){if(i.length=0,u){try{u.stop()}catch{}u=null}l=!1},async finished(){for(;r||i.length>0;)await new Promise(f=>setTimeout(f,100))}}}function at({voice:e="",rate:a=1,pitch:o=1,onPlayStart:c}={}){const t=[];let i=!1,r=!1;function u(){return e?speechSynthesis.getVoices().find(d=>d.name===e||d.voiceURI===e)??null:null}function l(){if(i||t.length===0)return;i=!0;const p=t.shift(),d=new SpeechSynthesisUtterance(p),x=u();x&&(d.voice=x),d.rate=a,d.pitch=o,d.onstart=()=>{r||(r=!0,c==null||c())},d.onend=()=>{i=!1,l()},d.onerror=f=>{console.error("[WebSpeech TTS] error",f.error),i=!1,l()},speechSynthesis.speak(d)}return{enqueue(p){p!=null&&p.trim()&&(t.push(p),l())},cancel(){t.length=0,speechSynthesis.cancel(),i=!1,r=!1},async finished(){for(;i||t.length>0;)await new Promise(p=>setTimeout(p,100))}}}async function ot({onSpeechStart:e,onSpeechEnd:a,onError:o,deviceId:c}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...c?{deviceId:{exact:c}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:r=>{console.log("[VAD] onSpeechEnd — samples:",r==null?void 0:r.length),a==null||a(r)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw o==null||o("VAD initialization failed. Falling back to manual microphone capture."),t}}function it(e,a=16e3){const o=e.length*2,c=new ArrayBuffer(44+o),t=new DataView(c),i=(r,u)=>{for(let l=0;l<u.length;l++)t.setUint8(r+l,u.charCodeAt(l))};i(0,"RIFF"),t.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),t.setUint32(16,16,!0),t.setUint16(20,1,!0),t.setUint16(22,1,!0),t.setUint32(24,a,!0),t.setUint32(28,a*2,!0),t.setUint16(32,2,!0),t.setUint16(34,16,!0),i(36,"data"),t.setUint32(40,o,!0);for(let r=0,u=44;r<e.length;r++,u+=2){const l=Math.max(-1,Math.min(1,e[r]));t.setInt16(u,l<0?l*32768:l*32767,!0)}return new Blob([c],{type:"audio/wav"})}const P={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},ct="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function Te({processInput:e,systemPrompt:a=ct,ttsProvider:o="server-kokoro",ttsVoice:c="af_bella",ttsSpeed:t=1,ttsServerUrl:i="/api/tts",ttsSpeechRate:r=1,ttsSpeechPitch:u=1,sttProvider:l="whisper",sttServerUrl:p="/api/stt",whisperModel:d="onnx-community/whisper-tiny.en",whisperDtype:x="q8",whisperDevice:f="wasm",kokoroDtype:h="q8",kokoroBrowserDevice:b="wasm",modelProxyUrl:_="/api/models/"}={}){const[T,E]=m.useState(P.IDLE),[L,I]=m.useState(!0),[C,D]=m.useState({whisper:0,kokoro:0}),[$,O]=m.useState(null),[s,k]=m.useState([]),[w,S]=m.useState(null),[v,M]=m.useState(!1),[R,K]=m.useState(""),[Q,j]=m.useState([]),[se,ae]=m.useState(null),B=m.useRef(P.IDLE),G=m.useRef(!1),W=m.useRef(null),Y=m.useRef(null),Z=m.useRef(null),J=m.useRef(null),de=m.useRef(null),he=m.useRef(null),X=m.useRef([{role:"system",content:a}]),pe=m.useRef(e),fe=m.useRef(0),_e=m.useRef({id:null,enqueuedAt:null,ttsMs:null}),Ve=m.useRef(1),me=m.useRef({provider:l,url:p});me.current={provider:l,url:p},m.useEffect(()=>{X.current=[{role:"system",content:a},...X.current.slice(1)]},[a]),m.useEffect(()=>{B.current=T},[T]),m.useEffect(()=>{G.current=v},[v]),m.useEffect(()=>{pe.current=e},[e]),m.useEffect(()=>{async function A(){try{const N=await navigator.mediaDevices.enumerateDevices();j(N.filter(g=>g.kind==="audioinput"))}catch{}}return A(),navigator.mediaDevices.addEventListener("devicechange",A),()=>navigator.mediaDevices.removeEventListener("devicechange",A)},[v]),m.useEffect(()=>{let A=!1;I(!0),D({whisper:0,kokoro:0});async function N(){try{const g=()=>{var z;const y=_e.current;y.enqueuedAt!=null&&y.ttsMs==null&&(y.ttsMs=Math.round(performance.now()-y.enqueuedAt),y.id!=null&&Ue(y.id,{timings:{ttsMs:y.ttsMs}})),o==="webspeech"&&((z=Y.current)==null||z.pause())};if(o==="webspeech")W.current=at({voice:c,rate:r,pitch:u,onPlayStart:g}),D(y=>({...y,kokoro:1}));else if(o==="kokoro"){const{kokoro:y}=await nt((z,F)=>D(q=>({...q,[z]:F})),{dtype:h,device:b,modelProxyUrl:_});if(A)return;W.current=st(y,{voice:c,speed:t,onPlayStart:g})}else W.current=rt({voice:c,speed:t,onPlayStart:g,url:i}),D(y=>({...y,kokoro:1}));if(A)return;if(l==="server"){J.current=null,D(y=>({...y,whisper:1})),I(!1);return}J.current=new Worker(new URL("./assets/whisperWorker-D69IwlqW.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ne&&ne.tagName.toUpperCase()==="SCRIPT"&&ne.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),J.current.onmessage=y=>{y.data.type==="transcript"?ve(y.data.text,{transcribeMs:Math.round(performance.now()-fe.current)}):y.data.type==="progress"?D(z=>({...z,whisper:y.data.progress})):y.data.type==="ready"?(D(z=>({...z,whisper:1})),I(!1)):y.data.type==="error"&&(O(`Whisper: ${y.data.message}`),I(!1))},J.current.onerror=()=>{O("Model load failed. Check WebGPU/WASM browser support."),I(!1)},J.current.postMessage({type:"init",model:d,dtype:x,device:f,modelProxyUrl:_})}catch(g){A||(O("Initialisation failed: "+((g==null?void 0:g.message)??String(g))),I(!1))}}return N(),()=>{var g,y;A=!0,(g=J.current)==null||g.terminate(),(y=W.current)==null||y.cancel()}},[o,c,t,r,u,i,l,p,d,x,f,h,b]);function Se(A,N,g){const y=Ve.current++;return k(z=>[...z,{id:y,role:A,content:N,timings:g,time:new Date().toISOString()}]),y}function Ue(A,{timings:N}){k(g=>g.map(y=>y.id===A?{...y,timings:{...y.timings,...N}}:y))}async function Ke(A){const N=fe.current;try{const g=await fetch(me.current.url,{method:"POST",headers:{"Content-Type":"audio/wav"},body:it(A,16e3)});if(!g.ok)throw new Error(`Speech-to-text failed: ${g.status} ${await g.text()}`);const{text:y}=await g.json();await ve(y,{transcribeMs:Math.round(performance.now()-N)})}catch(g){O(g.message||"Speech-to-text failed."),E(G.current?P.LISTENING:P.IDLE)}}async function ve(A,{transcribeMs:N}={}){if(!(A!=null&&A.trim())){E(G.current?P.LISTENING:P.IDLE);return}E(P.THINKING),Se("user",A,N!=null?{transcribeMs:N}:void 0);const g=[...X.current,{role:"user",content:A}];X.current=g,await qe(A,g)}async function qe(A,N){var g,y,z,F;(g=Z.current)==null||g.abort(),Z.current=new AbortController,(y=W.current)==null||y.cancel();try{if(!pe.current)throw new Error("processInput is not provided");const q=Me();let oe="",ye=!1,ge=null;const He=performance.now(),ee={id:null,enqueuedAt:null,ttsMs:null};_e.current=ee;const Ee=ie=>{var we;ee.enqueuedAt==null&&(ee.enqueuedAt=performance.now()),(we=W.current)==null||we.enqueue(ie)};S("");for await(const ie of pe.current(A,N,Z.current.signal))ge==null&&(ge=Math.round(performance.now()-He)),oe+=ie,S(oe),q.write(ie).forEach(Ye=>{ye||(ye=!0,E(P.SPEAKING)),Ee(Ye)});const Ae=q.flush();Ae&&(ye||E(P.SPEAKING),Ee(Ae)),ee.id=Se("assistant",oe,{thinkMs:ge,...ee.ttsMs!=null?{ttsMs:ee.ttsMs}:{}}),S(null),X.current=[...X.current,{role:"assistant",content:oe}],await((z=W.current)==null?void 0:z.finished()),o==="webspeech"&&((F=Y.current)==null||F.start())}catch(q){S(null),q.name!=="AbortError"&&O(q.message||"Processing failed.")}finally{E(G.current?P.LISTENING:P.IDLE)}}async function Be(){var A,N;O(null),B.current===P.SPEAKING&&((A=W.current)==null||A.cancel(),(N=Z.current)==null||N.abort());try{E(P.LISTENING),M(!0);try{const g=await navigator.mediaDevices.getUserMedia({audio:R?{deviceId:{exact:R}}:!0,video:!1});he.current=g;const y=new AudioContext;de.current=y;const z=y.createAnalyser();z.fftSize=256,y.createMediaStreamSource(g).connect(z),ae(z)}catch(g){console.warn("[TZVoiceChat] waveform analyser unavailable:",g)}Y.current=await ot({onSpeechStart:()=>{var g,y;o==="webspeech"&&B.current===P.SPEAKING||(B.current===P.SPEAKING&&((g=W.current)==null||g.cancel(),(y=Z.current)==null||y.abort()),E(P.LISTENING))},onSpeechEnd:g=>{var y;o==="webspeech"&&B.current===P.SPEAKING||(E(P.TRANSCRIBING),fe.current=performance.now(),me.current.provider==="server"?Ke(g):(y=J.current)==null||y.postMessage({type:"transcribe",audio:g},[g.buffer]))},onError:g=>{O(g),E(P.IDLE)},deviceId:R||void 0})}catch(g){console.error("[TZVoiceChat] startListening failed:",g),O("Microphone access failed. Allow audio permissions and refresh."),E(P.IDLE),M(!1)}}function Ge(){var A,N,g,y,z;M(!1),(A=Y.current)==null||A.destroy(),Y.current=null,(N=he.current)==null||N.getTracks().forEach(F=>F.stop()),he.current=null,(g=de.current)==null||g.close(),de.current=null,ae(null),(y=W.current)==null||y.cancel(),(z=Z.current)==null||z.abort(),E(P.IDLE)}function Fe(A){var z;if(!(A!=null&&A.trim()))return;E(P.SPEAKING);const N=Me(),g=N.write(A),y=N.flush();[...g,...y?[y]:[]].forEach(F=>{var q;return(q=W.current)==null?void 0:q.enqueue(F)}),(z=W.current)==null||z.finished().then(()=>{E(G.current?P.LISTENING:P.IDLE)})}return{status:T,loading:L,progress:C,error:$,transcript:s,streamingMessage:w,micEnabled:v,startListening:Be,stopListening:Ge,speak:Fe,submitText:ve,liveAnalyser:se,devices:Q,selectedMicId:R,setSelectedMicId:K}}function Pe(e){const a=e.replace("#",""),o=a.length===3?a.split("").map(c=>c+c).join(""):a;return[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]}function lt(e,a,o){e/=255,a/=255,o/=255;const c=Math.max(e,a,o),t=Math.min(e,a,o),i=(c+t)/2;if(c===t)return[0,0,i*100];const r=c-t,u=i>.5?r/(2-c-t):r/(c+t);let l;switch(c){case e:l=((a-o)/r+(a<o?6:0))/6;break;case a:l=((o-e)/r+2)/6;break;default:l=((e-a)/r+4)/6}return[l*360,u*100,i*100]}function ut(e,a,o){a/=100,o/=100;const c=r=>(r+e/30)%12,t=a*Math.min(o,1-o),i=r=>o-t*Math.max(-1,Math.min(c(r)-3,Math.min(9-c(r),1)));return[Math.round(i(0)*255),Math.round(i(8)*255),Math.round(i(4)*255)]}function U(e,a){const[o,c,t]=Pe(e),[i,r,u]=lt(o,c,t),[l,p,d]=ut(i,r,Math.max(0,Math.min(100,u+a)));return`rgb(${l}, ${p}, ${d})`}function V(e,a){const[o,c,t]=Pe(e);return`rgba(${o}, ${c}, ${t}, ${a})`}function re(e,a){return e.replace("rgb(","rgba(").replace(")",`, ${a})`)}const le=10;function dt({analyser:e}){const a=m.useRef(null),o=m.useRef(null);return m.useEffect(()=>{if(cancelAnimationFrame(o.current),!e)return;const c=a.current;if(!c)return;const t=c.getContext("2d"),i=e.frequencyBinCount,r=new Uint8Array(i),u=Math.max(1,Math.floor(i/le)),l=getComputedStyle(c),p=+l.getPropertyValue("--bar-hue"),d=+l.getPropertyValue("--bar-hue-range"),x=+l.getPropertyValue("--bar-sat"),f=+l.getPropertyValue("--bar-lit"),h=+l.getPropertyValue("--bar-lit-range"),b=()=>{o.current=requestAnimationFrame(b),e.getByteFrequencyData(r);const _=c.width,T=c.height;t.clearRect(0,0,_,T);const E=(_-(le-1)*2)/le;for(let L=0;L<le;L++){const I=r[L*u]/255,C=Math.max(3,I*T*.88);t.fillStyle=`hsl(${p+I*d}, ${x}%, ${f+I*h}%)`,t.beginPath(),t.roundRect(L*(E+2),(T-C)/2,E,C,[2]),t.fill()}};return b(),()=>cancelAnimationFrame(o.current)},[e]),n.jsx("canvas",{ref:a,width:55,height:35,className:"ai-btn__canvas"})}function Ne({status:e="idle",active:a=!1,loading:o=!1,analyser:c=null,onToggle:t,devices:i=[],selectedMicId:r="",onDeviceChange:u,inputData:l="",sendData:p,accentColor:d="#f97316",uiColor:x="#64748b",size:f=70,barHue:h=25,barHueRange:b=20,barSat:_=88,barLit:T=65,barLitRange:E=20}){var S;const[L,I]=m.useState(!1),C=m.useRef(null);m.useEffect(()=>{if(!L)return;function v(M){var R;(R=C.current)!=null&&R.contains(M.target)||I(!1)}return document.addEventListener("pointerdown",v),()=>document.removeEventListener("pointerdown",v)},[L]);function D(v){u==null||u(v),I(!1)}const $=m.useMemo(()=>{const v=U(d,-8),M=U(d,-15),R=U(d,-22),K=U(d,-30),Q=U(d,-42),j=U(d,8),se=U(d,20),ae=U(d,30),B=U(x,-22),G=U(x,-30),W=U(x,18),Y=U(x,37);return{"--tz-size":`${f}px`,"--tz-a":d,"--tz-a-d8":v,"--tz-a-d15":M,"--tz-a-d22":R,"--tz-a-d30":K,"--tz-a-d42":Q,"--tz-a-l8":j,"--tz-a-l20":se,"--tz-a-l30":ae,"--tz-a-25":V(d,.25),"--tz-a-28":V(d,.28),"--tz-a-30":V(d,.3),"--tz-a-32":V(d,.32),"--tz-a-34":V(d,.34),"--tz-a-35":V(d,.35),"--tz-a-38":V(d,.38),"--tz-a-45":V(d,.45),"--tz-a-50":V(d,.5),"--tz-a-55":V(d,.55),"--tz-a-60":V(d,.6),"--tz-a-65":V(d,.65),"--tz-a-68":V(d,.68),"--tz-u":x,"--tz-u-d22":B,"--tz-u-d30":G,"--tz-u-l18":W,"--tz-u-l37":Y,"--tz-u-30":V(x,.3),"--tz-u-55":V(x,.55),"--tz-u-d30-a85":re(G,.85),"--tz-u-l18-a18":re(W,.18),"--tz-u-l18-a20":re(W,.2),"--tz-u-l18-a32":re(W,.32),"--tz-u-d22-a90":re(B,.9),"--bar-hue":h,"--bar-hue-range":b,"--bar-sat":_,"--bar-lit":T,"--bar-lit-range":E}},[d,x,f,h,b,_,T,E]),O=((S=i.find(v=>v.deviceId===r))==null?void 0:S.label)||(r?`Mic ${r.slice(0,6)}…`:"Default mic"),s=l.trim().length>0,k=s?"ready":a?e:"off";let w;return s?w=n.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:n.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!a||e==="idle"?w=n.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[n.jsx("path",{fillOpacity:"0.52",d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"}),n.jsx("path",{fill:"white",fillOpacity:"0.98",d:"M14.5 0L15.65 3.45L19.1 4.6L15.65 5.75L14.5 9.2L13.35 5.75L9.9 4.6L13.35 3.45Z"}),n.jsx("path",{fill:"white",fillOpacity:"0.88",d:"M19 8.62L19.75 10.75L21.88 11.5L19.75 12.25L19 14.38L18.25 12.25L16.12 11.5L18.25 10.75Z"})]}):e==="listening"?w=n.jsx(dt,{analyser:c}):e==="transcribing"?w=n.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(v,M)=>n.jsx("span",{style:{animationDelay:`${M*.1}s`}},M))}):e==="thinking"?w=n.jsxs("div",{className:"ai-btn__dots",children:[n.jsx("span",{}),n.jsx("span",{style:{animationDelay:"0.18s"}}),n.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(w=n.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(v,M)=>n.jsx("span",{style:{animationDelay:`${M*.11}s`}},M))})),n.jsxs("div",{className:"ai-btn-root",style:$,children:[n.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${k}`,"aria-hidden":"true",children:[n.jsx("span",{className:"ai-ring ai-ring--1"}),n.jsx("span",{className:"ai-ring ai-ring--2"})]}),n.jsxs("button",{className:`ai-btn ai-btn--${k}`,disabled:o,onClick:s?()=>p==null?void 0:p(l):t,"aria-label":s?"Send message":a?"Stop assistant":"Start assistant","aria-pressed":s?void 0:a,children:[w,a&&!s&&n.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),n.jsxs("div",{className:`ai-mic-sel${L?" open":""}`,ref:C,children:[n.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>I(v=>!v),title:"Change microphone","aria-label":"Change microphone","aria-expanded":L,children:[n.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[n.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),n.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),n.jsx("span",{className:"ai-mic-sel__label",children:O}),n.jsx("svg",{className:`ai-mic-sel__caret${L?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:n.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),L&&n.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[n.jsx("li",{role:"option",className:`ai-mic-sel__option${r===""?" selected":""}`,onClick:()=>D(""),"aria-selected":r==="",children:"Default microphone"}),i.map(v=>n.jsx("li",{role:"option",className:`ai-mic-sel__option${r===v.deviceId?" selected":""}`,onClick:()=>D(v.deviceId),"aria-selected":r===v.deviceId,children:v.label||`Microphone ${v.deviceId.slice(0,8)}`},v.deviceId))]})]})]})}async function Oe(e,a,o="/api/chat"){var u;const c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},signal:a,body:JSON.stringify({messages:e})});if(!c.ok){const l=await c.text();throw new Error(`Server error: ${c.status} ${l}`)}const t=(u=c.body)==null?void 0:u.getReader();if(!t){const l=await c.json();return{stream:async function*(){yield l.text}}}const i=new TextDecoder;let r="";return{stream:async function*(){var p,d,x;let l="";for(;;){const{value:f,done:h}=await t.read();if(h)break;r+=i.decode(f,{stream:!0});const b=r.split(`
|
|
2
|
+
`);r=b.pop();for(const _ of b){const T=_.trim();if(!T.startsWith("data:"))continue;const E=T.slice(5).trimStart();if(E==="[DONE]")return;try{const I=(x=(d=(p=JSON.parse(E).choices)==null?void 0:p[0])==null?void 0:d.delta)==null?void 0:x.content;I&&(l&&/\w/.test(l)&&/\w/.test(I[0])&&(yield" "),l=I[I.length-1],yield I)}catch{}}}}}}function Re(e,a,o){return{stream:async function*(){const c=[];let t=null,i=!1,r="";const u=({data:p})=>{p.type==="token"?(c.push(p.text),t==null||t(),t=null):p.type==="done"&&(i=!0,t==null||t(),t=null)},l=()=>{i=!0,t==null||t(),t=null};e.addEventListener("message",u),o==null||o.addEventListener("abort",l),e.postMessage({type:"generate",messages:a});try{for(;!i||c.length>0;)if(c.length>0){const p=c.shift();r&&/\w/.test(r)&&/\w/.test(p[0])&&(yield" "),r=p[p.length-1],yield p}else await new Promise(p=>{t=p})}finally{e.removeEventListener("message",u),o==null||o.removeEventListener("abort",l)}}}}function ze({apiBase:e="/api",systemPrompt:a}={}){const[o,c]=m.useState(!0),[t,i]=m.useState(0),[r,u]=m.useState(""),[l,p]=m.useState({}),[d,x]=m.useState(null),[f,h]=m.useState({}),[b,_]=m.useState(0),T=m.useRef(null),E=m.useRef(null),L=m.useCallback(()=>_($=>$+1),[]);m.useEffect(()=>{let $=!1;u(""),i(0);async function O(){let s=null,k={};try{s=await(await fetch(`${e}/config`)).json(),x(s),k={ttsProvider:s.ttsProvider||"kokoro",ttsVoice:s.ttsProvider==="openai"?s.openaiTtsVoice||"alloy":s.ttsProvider==="elevenlabs"?s.elevenlabsVoiceId:s.ttsProvider==="webspeech"?s.webSpeechVoice||"":s.kokoroVoice||"af_bella",ttsSpeed:s.kokoroSpeed??1,ttsServerUrl:`${e}/tts`,ttsSpeechRate:s.webSpeechRate??1,ttsSpeechPitch:s.webSpeechPitch??1,sttProvider:s.sttProvider==="elevenlabs"||s.sttProvider==="openai"?"server":"whisper",sttServerUrl:`${e}/stt`,whisperModel:s.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:s.whisperDtype||"q8",whisperDevice:s.whisperDevice||"wasm",kokoroDtype:s.kokoroDtype||"q8",kokoroBrowserDevice:s.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`,...s.systemPrompt?{systemPrompt:s.systemPrompt}:{}}}catch{k={ttsProvider:"kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(!$){if((s==null?void 0:s.chatProvider)==="local"){c(!0),u("Using SmolLM2-360M-Instruct locally in your browser — slow and simple; pick a cloud model in Settings for better answers.");const w=new Worker(new URL("./assets/llmWorker-CVEGn6yI.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ne&&ne.tagName.toUpperCase()==="SCRIPT"&&ne.src||new URL("index.cjs",document.baseURI).href),{type:"module"});E.current=w,w.onmessage=S=>{S.data.type==="progress"?i(S.data.progress??0):S.data.type==="ready"?(i(1),T.current=async function*(v,M,R){const{stream:K}=Re(w,M,R);yield*K()},p(k),c(!1)):S.data.type==="error"&&c(!1)},w.onerror=()=>c(!1),p(k),w.postMessage({type:"init",modelProxyUrl:`${e}/models/`});return}s!=null&&s.hasApiKey?T.current=async function*(w,S,v){const{stream:M}=await Oe(S,v,`${e}/chat`);yield*M()}:T.current=async function*(){throw new Error("The chat model is not configured yet — open Settings and choose a provider.")},p(k),c(!1)}}return O(),()=>{var s;$=!0,(s=E.current)==null||s.terminate(),E.current=null}},[e,b]);const I=Te({processInput:async function*($,O,s){T.current&&(yield*T.current($,O,s))},...a?{systemPrompt:a}:{},...l});m.useEffect(()=>{let $=!1;async function O(){const k={};typeof performance<"u"&&performance.memory&&(k.browser=performance.memory.usedJSHeapSize);try{const w=await fetch(`${e}/stats`);w.ok&&(k.server=(await w.json()).rss)}catch{}$||h(k)}O();const s=setInterval(O,3e3);return()=>{$=!0,clearInterval(s)}},[e]);const{micEnabled:C,stopListening:D}=I;return m.useEffect(()=>{if(!C)return;const $=O=>{O.key==="Escape"&&D()};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[C,D]),{chat:I,info:d,config:l,memory:f,llmProgress:t,note:r,loading:I.loading||o,missing:(d==null?void 0:d.missing)??[],reload:L}}const ht=["q8","q4","q4f16","fp16","fp32"],te="Local · free",H="Cloud",xe=[{group:"Chat model",fields:[{key:"chatProvider",label:"Provider",type:"select",env:"OPENAI_PROVIDER",default:"local",options:[["","Not configured"],["local","In-browser model (SmolLM2, no key, ~200 MB) — slow and simple",te],["openai-compatible","OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise…)",te],["openrouter","OpenRouter",H],["openai","OpenAI",H],["anthropic","Anthropic (Claude)",H],["huggingface","Hugging Face",H]]},{key:"openrouterApiKey",label:"OpenRouter API key",type:"password",secret:!0,env:"OPENROUTER_API_KEY",showWhen:{chatProvider:"openrouter"},hint:"Get one at https://openrouter.ai/keys"},{key:"openrouterModel",label:"OpenRouter model",type:"text",env:"OPENROUTER_MODEL",default:"gpt-4o-mini",showWhen:{chatProvider:"openrouter"},hint:'e.g. openai/gpt-4o-mini, or a ":free" model'},{key:"openaiApiKey",label:"OpenAI API key",type:"password",secret:!0,env:"OPENAI_API_KEY",showWhenAny:[{chatProvider:"openai"},{sttProvider:"openai"},{ttsProvider:"openai"}],hint:"Used for OpenAI chat, transcription and/or TTS. Get one at https://platform.openai.com/api-keys"},{key:"openaiChatModel",label:"OpenAI model",type:"text",env:"OPENAI_CHAT_MODEL",default:"gpt-4o-mini",showWhen:{chatProvider:"openai"},suggestions:["gpt-4o-mini","gpt-4o","gpt-4.1-mini","gpt-4.1"]},{key:"anthropicApiKey",label:"Anthropic API key",type:"password",secret:!0,env:"ANTHROPIC_API_KEY",showWhen:{chatProvider:"anthropic"},hint:"Get one at https://console.anthropic.com/settings/keys"},{key:"anthropicModel",label:"Anthropic model",type:"text",env:"ANTHROPIC_MODEL",default:"claude-haiku-5-5",showWhen:{chatProvider:"anthropic"},suggestions:["claude-haiku-5-5","claude-sonnet-5-5","claude-opus-5-5","claude-fable-5-2"],hint:"Haiku is the fastest — best for voice"},{key:"huggingfaceApiKey",label:"Hugging Face token",type:"password",secret:!0,env:"HUGGINGFACE_API_KEY",showWhen:{chatProvider:"huggingface"},hint:"A token with read scope"},{key:"compatBaseUrl",label:"Server base URL",type:"text",env:"OPENAI_COMPAT_BASE_URL",default:"http://localhost:11434/v1",showWhen:{chatProvider:"openai-compatible"},suggestions:["http://localhost:11434/v1","http://localhost:1234/v1","http://localhost:8000/v1"],hint:"Must serve /chat/completions. Ollama :11434, LM Studio :1234, vLLM :8000. From inside Docker use host.docker.internal instead of localhost."},{key:"compatModel",label:"Model name",type:"text",env:"OPENAI_COMPAT_MODEL",default:"",showWhen:{chatProvider:"openai-compatible"},hint:"Exactly as the server names it, e.g. llama3.2 or qwen2.5:7b-instruct"},{key:"compatApiKey",label:"API key (optional)",type:"password",secret:!0,env:"OPENAI_COMPAT_API_KEY",showWhen:{chatProvider:"openai-compatible"},hint:"Leave empty if the server needs no key (most local servers)."},{key:"systemPrompt",label:"System prompt",type:"textarea",default:"",hint:"Leave blank for the built-in short, spoken-style prompt."}]},{group:"Speech-to-text",fields:[{key:"sttProvider",label:"Provider",type:"select",env:"STT_PROVIDER",default:"whisper",options:[["whisper","Whisper in the browser",te],["openai","OpenAI transcription",H],["elevenlabs","ElevenLabs Scribe",H]]},{key:"openaiSttModel",label:"OpenAI model",type:"text",env:"OPENAI_STT_MODEL",default:"whisper-1",showWhen:{sttProvider:"openai"},suggestions:["whisper-1","gpt-4o-mini-transcribe","gpt-4o-transcribe"],hint:"Uses the OpenAI API key below"},{key:"openaiSttLanguage",label:"OpenAI language",type:"text",env:"OPENAI_STT_LANGUAGE",default:"",showWhen:{sttProvider:"openai"},hint:"ISO-639-1 code such as en; blank = detect automatically"},{key:"elevenlabsApiKey",label:"ElevenLabs API key",type:"password",secret:!0,env:"ELEVENLABS_API_KEY",showWhenAny:[{sttProvider:"elevenlabs"},{ttsProvider:"elevenlabs"}],hint:"Used for ElevenLabs speech-to-text and/or text-to-speech. Get one at https://elevenlabs.io/app/settings/api-keys"},{key:"elevenlabsSttModel",label:"ElevenLabs model",type:"text",env:"ELEVENLABS_STT_MODEL",default:"scribe_v2",showWhen:{sttProvider:"elevenlabs"},suggestions:["scribe_v2","scribe_v3","scribe_v2_medical"]},{key:"elevenlabsLanguage",label:"ElevenLabs language",type:"text",env:"ELEVENLABS_STT_LANGUAGE",default:"",showWhen:{sttProvider:"elevenlabs"},hint:"ISO code such as en or de; blank = detect automatically"},{key:"whisperModel",label:"Model",type:"select",env:"WHISPER_MODEL",default:"onnx-community/whisper-small.en",showWhen:{sttProvider:"whisper"},allowCustom:!0,options:[["onnx-community/whisper-tiny.en","whisper-tiny.en — fastest, ~40 MB, more errors"],["onnx-community/whisper-base.en","whisper-base.en — better, ~74 MB, recommended"],["onnx-community/whisper-small.en","whisper-small.en — good, ~244 MB, significantly more accurate"]]},{key:"whisperDtype",label:"Precision",type:"select",env:"WHISPER_DTYPE",default:"fp32",showWhen:{sttProvider:"whisper"},options:[["q8","q8"],["q4","q4"],["fp16","fp16 (WebGPU)"],["fp32","fp32"]]},{key:"whisperDevice",label:"Device",type:"select",env:"WHISPER_DEVICE",default:"webgpu",showWhen:{sttProvider:"whisper"},aliases:{cpu:"wasm"},options:[["wasm","wasm (CPU)"],["webgpu","webgpu"]]}]},{group:"Text-to-speech",fields:[{key:"ttsProvider",label:"Provider",type:"select",env:"TTS_PROVIDER",default:"kokoro",options:[["kokoro","Kokoro in the browser",te],["server-kokoro","Kokoro on the server (needs: npm install kokoro-js)",te],["webspeech","Browser Web Speech API (built-in voices)",te],["openai","OpenAI TTS",H],["elevenlabs","ElevenLabs",H]]},{key:"kokoroVoice",label:"Kokoro voice",type:"text",env:"KOKORO_VOICE",default:"af_bella",showWhen:{ttsProvider:["kokoro","server-kokoro"]},hint:"e.g. af_bella, af_sarah, am_adam"},{key:"kokoroSpeed",label:"Kokoro speed",type:"number",env:"KOKORO_SPEED",default:1,showWhen:{ttsProvider:["kokoro","server-kokoro"]},hint:"1 = normal; 1.1–1.2 often sounds more natural"},{key:"kokoroDtype",label:"Kokoro precision",type:"select",env:"KOKORO_DTYPE",default:"fp32",showWhen:{ttsProvider:["kokoro","server-kokoro"]},options:ht.map(e=>[e,e]),hint:"q4/q8 are promoted to fp32 on WebGPU"},{key:"kokoroBrowserDevice",label:"Kokoro device (browser)",type:"select",env:"KOKORO_BROWSER_DEVICE",default:"webgpu",showWhen:{ttsProvider:"kokoro"},options:[["wasm","wasm"],["webgpu","webgpu"]]},{key:"kokoroDevice",label:"Kokoro device (server)",type:"select",env:"KOKORO_DEVICE",default:"cpu",showWhen:{ttsProvider:"server-kokoro"},options:[["cpu","cpu"]]},{key:"openaiTtsModel",label:"OpenAI TTS model",type:"text",env:"OPENAI_TTS_MODEL",default:"tts-1",showWhen:{ttsProvider:"openai"},suggestions:["tts-1","tts-1-hd","gpt-4o-mini-tts"]},{key:"openaiTtsVoice",label:"OpenAI voice",type:"text",env:"OPENAI_TTS_VOICE",default:"alloy",showWhen:{ttsProvider:"openai"},suggestions:["alloy","echo","fable","onyx","nova","shimmer"]},{key:"elevenlabsVoiceId",label:"ElevenLabs voice ID",type:"text",env:"ELEVENLABS_VOICE_ID",default:"21m00Tcm4TlvDq8ikWAM",showWhen:{ttsProvider:"elevenlabs"},hint:`Default is the premade "Rachel" voice. Copy another voice's ID from your ElevenLabs voice library.`},{key:"elevenlabsTtsModel",label:"ElevenLabs model",type:"text",env:"ELEVENLABS_TTS_MODEL",default:"eleven_flash_v2_5",showWhen:{ttsProvider:"elevenlabs"},suggestions:["eleven_flash_v2_5","eleven_turbo_v2_5","eleven_multilingual_v2"],hint:"Flash is the lowest latency — best for voice chat"},{key:"webSpeechVoice",label:"Web Speech voice",type:"text",env:"WEBSPEECH_VOICE",default:"",showWhen:{ttsProvider:"webspeech"},hint:"Exact voice name; blank = browser default"},{key:"webSpeechRate",label:"Web Speech rate",type:"number",env:"WEBSPEECH_RATE",default:1,showWhen:{ttsProvider:"webspeech"},hint:"0.1 – 10"},{key:"webSpeechPitch",label:"Web Speech pitch",type:"number",env:"WEBSPEECH_PITCH",default:1,showWhen:{ttsProvider:"webspeech"},hint:"0 – 2"}]}],$e=xe.flatMap(e=>e.fields);Object.fromEntries($e.map(e=>[e.key,e]));$e.filter(e=>e.secret).map(e=>e.key);function pt(e,a){const o=c=>Object.entries(c).every(([t,i])=>(Array.isArray(i)?i:[i]).includes(a[t]));return e.showWhenAny?e.showWhenAny.some(o):e.showWhen?o(e.showWhen):!0}function De(e,a={}){const o=[],c=r=>!!a[r],t=e.chatProvider;t||o.push({key:"chatProvider",message:"No chat model provider is configured.",scope:"chat"}),t==="openai-compatible"&&(e.compatBaseUrl||o.push({key:"compatBaseUrl",message:"The OpenAI-compatible server URL is missing.",scope:"chat"}),e.compatModel||o.push({key:"compatModel",message:"The model name for the OpenAI-compatible server is missing.",scope:"chat"}));const i=[{key:"openrouterApiKey",name:"OpenRouter API key",uses:[t==="openrouter"&&["chat","chat"]]},{key:"anthropicApiKey",name:"Anthropic API key",uses:[t==="anthropic"&&["chat","chat"]]},{key:"huggingfaceApiKey",name:"Hugging Face token",uses:[t==="huggingface"&&["chat","chat"]]},{key:"openaiApiKey",name:"OpenAI API key",uses:[t==="openai"&&["chat","chat"],e.sttProvider==="openai"&&["speech-to-text","stt"],e.ttsProvider==="openai"&&["text-to-speech","tts"]]},{key:"elevenlabsApiKey",name:"ElevenLabs API key",uses:[e.sttProvider==="elevenlabs"&&["speech-to-text","stt"],e.ttsProvider==="elevenlabs"&&["text-to-speech","tts"]]}];for(const{key:r,name:u,uses:l}of i){const p=l.filter(Boolean);if(!p.length||c(r))continue;const d=p.some(f=>f[1]==="chat")?"chat":p[0][1],x=p.length===1&&p[0][0]==="chat"?`${u} is missing.`:`${u} (for ${p.map(f=>f[0]).join(", ").replace(/, ([^,]*)$/," and $1")}) is missing.`;o.push({key:r,message:x,scope:d})}return o}function Ce({apiBase:e="/api",onSaved:a,onClose:o}){const[c,t]=m.useState(null),[i,r]=m.useState({}),[u,l]=m.useState(null),[p,d]=m.useState(!1),x=m.useRef(null),f=m.useCallback(async()=>{try{const s=await fetch(`${e}/settings`);if(!s.ok)throw new Error(await s.text());t(await s.json())}catch(s){l({kind:"error",text:`Could not load settings: ${s.message}`})}},[e]);if(m.useEffect(()=>{f()},[f]),!c)return n.jsx("section",{className:"tz-va__card",children:u?u.text:"Loading settings…"});const h={...c.values,...Object.fromEntries(Object.entries(i).filter(([,s])=>s!==null))},b={...c.secretsSet};for(const[s,k]of Object.entries(i))s in b&&(b[s]=k===null?!1:k?!0:b[s]);const _=De(h,b),T=new Set(_.map(s=>s.key)),E=Object.keys(i).length>0,L=(s,k)=>r(w=>({...w,[s]:k}));async function I(s,k){var w;d(!0);try{const S=await fetch(`${e}/settings`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!S.ok)throw new Error(await S.text());const v=await S.json();t(v),r({});const M=(w=v.ignored)!=null&&w.length?` Ignored unknown/invalid keys: ${v.ignored.join(", ")}.`:"";l({kind:"ok",text:k+M}),a==null||a(v)}catch(S){l({kind:"error",text:S.message})}finally{d(!1)}}async function C(){try{const s=await fetch(`${e}/settings/export`);if(!s.ok)throw new Error(await s.text());const k=new Blob([JSON.stringify(await s.json(),null,2)],{type:"application/json"}),w=document.createElement("a");w.href=URL.createObjectURL(k),w.download="tz-voice-chat-settings.json",w.click(),URL.revokeObjectURL(w.href),l({kind:"ok",text:"Exported. The file contains your API keys — keep it private."})}catch(s){l({kind:"error",text:`Export failed: ${s.message}`})}}async function D(s){var w;const k=(w=s.target.files)==null?void 0:w[0];if(s.target.value="",!!k)try{const S=JSON.parse(await k.text()),v=S&&typeof S.settings=="object"?S.settings:S;if(!v||typeof v!="object"||Array.isArray(v))throw new Error("not a settings object");await I({settings:v},`Imported ${k.name} and applied it.`)}catch(S){l({kind:"error",text:`Import failed: ${S.message}`})}}function $(s){const k=[];for(const[w,S,v]of s){const M=k[k.length-1],R=n.jsx("option",{value:w,children:S},w);v?M&&M.group===v?M.items.push(R):k.push({group:v,items:[R]}):k.push(R)}return k.map(w=>w.group?n.jsx("optgroup",{label:w.group,children:w.items},w.group):w)}function O(s){const k=`tz-va-set-${s.key}`,w=T.has(s.key);let S;if(s.type==="select")S=n.jsxs("select",{id:k,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value),children:[$(s.options),s.allowCustom&&h[s.key]&&!s.options.some(([v])=>v===h[s.key])&&n.jsxs("option",{value:h[s.key],children:[h[s.key]," (custom)"]})]});else if(s.type==="textarea")S=n.jsx("textarea",{id:k,rows:4,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value)});else if(s.type==="password"){const v=s.key in i,M=i[s.key]===null?"Will be cleared on save":c.secretsSet[s.key]?"Saved — type to replace":"Not set";S=n.jsxs("span",{className:"tz-va__secret",children:[n.jsx("input",{id:k,type:"password",autoComplete:"off",value:i[s.key]??"",placeholder:M,onChange:R=>L(s.key,R.target.value)}),(c.secretsSet[s.key]||v)&&n.jsx("button",{type:"button",className:"tz-va__link",onClick:()=>v?r(R=>{const K={...R};return delete K[s.key],K}):L(s.key,null),children:v?"Undo":"Clear"})]})}else S=n.jsxs(n.Fragment,{children:[n.jsx("input",{id:k,type:s.type==="number"?"number":"text",step:s.type==="number"?"any":void 0,list:s.suggestions?`${k}-list`:void 0,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value)}),s.suggestions&&n.jsx("datalist",{id:`${k}-list`,children:s.suggestions.map(v=>n.jsx("option",{value:v},v))})]});return n.jsxs("div",{className:`tz-va__field${w?" tz-va__field--missing":""}`,children:[n.jsxs("label",{htmlFor:k,children:[s.label,w&&n.jsx("em",{children:" — required"})]}),S,s.hint&&n.jsx("small",{children:s.hint})]},s.key)}return n.jsxs(n.Fragment,{children:[n.jsxs("section",{className:"tz-va__card tz-va__settings",children:[_.length>0&&n.jsxs("div",{className:"tz-va__notice",role:"alert",children:[n.jsx("strong",{children:"Setup incomplete:"})," ",_.map(s=>s.message).join(" ")]}),xe.map(s=>n.jsxs("fieldset",{children:[n.jsx("legend",{children:s.group}),s.fields.filter(k=>pt(k,h)).map(O)]},s.group)),n.jsxs("p",{className:"tz-va__note",children:["Saved to ",n.jsx("code",{children:c.file})," and applied immediately. Environment variables provide the initial values."]}),n.jsxs("div",{className:"tz-va__actions",children:[n.jsx("button",{type:"button",disabled:p||!E,onClick:()=>I(i,"Settings saved and applied."),children:"Save"}),n.jsx("button",{type:"button",className:"tz-va__secondary",disabled:!E,onClick:()=>r({}),children:"Discard"}),n.jsx("span",{className:"tz-va__spacer"}),n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:()=>{var s;return(s=x.current)==null?void 0:s.click()},children:"Import…"}),n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:C,children:"Export"}),n.jsx("input",{ref:x,type:"file",accept:"application/json,.json",hidden:!0,onChange:D})]}),u&&n.jsx("p",{className:`tz-va__status tz-va__status--${u.kind}`,children:u.text})]}),o&&n.jsx("div",{className:"tz-va__actions",children:n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:o,children:"← Back to chat"})})]})}const We=(e,a)=>e==="webgpu"&&(a==="q4"||a==="q8")?"fp32":a,ke=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,Le=e=>`${(e/1048576).toFixed(0)} MB`;function ft(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${e.ttsVoice}`;case"elevenlabs":return`ElevenLabs · ${e.elevenlabsTtsModel} · ${e.ttsVoice}`;case"webspeech":return`Web Speech API · rate ${e.ttsSpeechRate} · pitch ${e.ttsSpeechPitch}`;case"server-kokoro":return`Kokoro (server) · ${e.ttsVoice} · ${e.kokoroDtype}/${e.kokoroDevice}`;default:return`Kokoro (browser) · ${e.ttsVoice} · ${We(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const mt=e=>e.replace(/\b\w/g,a=>a.toUpperCase());function vt({apiBase:e="/api",title:a="Voice Assistant",showInfo:o=!0,systemPrompt:c,className:t=""}={}){const{chat:i,info:r,config:u,memory:l,llmProgress:p,note:d,loading:x,missing:f,reload:h}=ze({apiBase:e,systemPrompt:c}),[b,_]=m.useState("chat"),{status:T,progress:E,error:L,transcript:I,streamingMessage:C,micEnabled:D,startListening:$,stopListening:O,submitText:s,liveAnalyser:k,devices:w,selectedMicId:S,setSelectedMicId:v}=i,[M,R]=m.useState(""),K=m.useRef(null);m.useEffect(()=>{var j;(j=K.current)==null||j.scrollIntoView({behavior:C!==null?"auto":"smooth"})},[I,C]);const Q=r&&u.whisperDevice&&[["STT",r.sttProvider==="elevenlabs"?`ElevenLabs · ${r.elevenlabsSttModel}`:r.sttProvider==="openai"?`OpenAI · ${r.openaiSttModel}`:`Whisper · ${(u.whisperModel||r.whisperModel).split("/").pop()} · ${We(u.whisperDevice,u.whisperDtype)}/${u.whisperDevice}`],["TTS",ft({...r,...u})],["Chat",r.chatProvider==="local"?"SmolLM2-360M-Instruct (in-browser) — slow and simple":r.chatReady?`${r.chatProvider} · ${r.chatModel}`:"not configured"],["Memory",[l.browser!=null?`browser heap ${Le(l.browser)}`:"browser heap n/a",l.server!=null?`server ${Le(l.server)}`:null].filter(Boolean).join(" · ")]];return n.jsxs("div",{className:`tz-va ${t}`.trim(),children:[n.jsxs("section",{className:"tz-va__card tz-va__header",children:[n.jsx("h1",{children:a}),n.jsxs("span",{className:"tz-va__header-right",children:[n.jsx("span",{className:`tz-va__chip tz-va__chip--${T}`,children:mt(T)}),n.jsx("button",{type:"button",className:`tz-va__gear${b==="settings"?" tz-va__gear--on":""}`,"aria-label":"Settings",title:"Settings",onClick:()=>_(j=>j==="settings"?"chat":"settings"),children:n.jsxs("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h0a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h0a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v0a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})]}),f.length>0&&b!=="settings"&&n.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Setup incomplete."})," ",f.map(j=>j.message).join(" ")]}),n.jsx("button",{type:"button",onClick:()=>_("settings"),children:"Open Settings"})]}),b==="settings"?n.jsx(Ce,{apiBase:e,onSaved:h,onClose:()=>_("chat")}):n.jsxs(n.Fragment,{children:[o&&Q&&n.jsx("section",{className:"tz-va__card tz-va__info",children:Q.map(([j,se])=>n.jsxs("div",{className:"tz-va__info-row",children:[n.jsx("span",{className:"tz-va__info-label",children:j}),n.jsx("span",{className:"tz-va__info-value",children:se})]},j))}),n.jsxs("section",{className:"tz-va__card",children:[x&&n.jsxs("div",{className:"tz-va__progress",children:[u.sttProvider!=="server"&&n.jsxs("label",{children:["Whisper STT",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${E.whisper*100}%`}})})]}),n.jsxs("label",{children:["Kokoro TTS",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${E.kokoro*100}%`}})})]}),p>0&&n.jsxs("label",{children:["Local LLM",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${p*100}%`}})})]})]}),n.jsx("div",{className:"tz-va__button",children:n.jsx(Ne,{status:T,active:D,loading:x,analyser:k,onToggle:D?O:$,devices:w,selectedMicId:S,onDeviceChange:v,inputData:M,sendData:j=>{R(""),s(j)}})}),n.jsx("div",{className:"tz-va__input-row",children:n.jsx("input",{type:"text",className:"tz-va__input",value:M,onChange:j=>R(j.target.value),onKeyDown:j=>{j.key==="Enter"&&M.trim()&&(R(""),s(M))},placeholder:"Type a message…",disabled:x})}),n.jsx("p",{className:"tz-va__note",children:x?E.kokoro<1?"Loading Kokoro TTS…":E.whisper<1?"Loading Whisper STT…":p>0&&p<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":"Finishing up…":"Ready."}),d&&n.jsx("p",{className:"tz-va__note",children:d})]}),n.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[I.map(j=>n.jsxs("div",{className:`tz-va__message tz-va__message--${j.role}`,children:[n.jsx("small",{children:j.role==="user"?"You":"Assistant"}),n.jsx("p",{children:j.content}),j.timings&&n.jsxs("div",{className:"tz-va__timings",children:[j.timings.transcribeMs!=null&&n.jsxs("span",{children:["transcribe ",ke(j.timings.transcribeMs)]}),j.timings.thinkMs!=null&&n.jsxs("span",{children:["think ",ke(j.timings.thinkMs)]}),j.timings.ttsMs!=null&&n.jsxs("span",{children:["tts ",ke(j.timings.ttsMs)]})]})]},j.id)),C!==null&&n.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[n.jsx("small",{children:"Assistant"}),n.jsxs("p",{children:[C,n.jsx("span",{className:"tz-va__cursor"})]})]}),n.jsx("div",{ref:K})]}),L?n.jsxs("section",{className:"tz-va__card",children:[n.jsx("strong",{children:"Error:"}),n.jsx("p",{children:L})]}):null]})]})}exports.AIAssistantButton=Ne;exports.SETTINGS_SCHEMA=xe;exports.STATES=P;exports.SettingsPanel=Ce;exports.TZVoiceChat=Te;exports.VoiceAssistant=vt;exports.computeMissing=De;exports.createLocalChatStream=Re;exports.sendChatRequest=Oe;exports.useVoiceAssistant=ze;
|