tz-voice-chat 1.0.2 → 1.1.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/README.md CHANGED
@@ -178,3 +178,34 @@ TZVoiceChat hook
178
178
  AIAssistantButton component
179
179
  └── 5-state animated button with waveform visualiser and mic selector
180
180
  ```
181
+
182
+ ---
183
+
184
+ ## Full assistant in two files (UI + server)
185
+
186
+ Besides the `TZVoiceChat` hook, the package ships a ready-made UI and the matching Express backend.
187
+
188
+ **Client**
189
+
190
+ ```jsx
191
+ import { VoiceAssistant } from 'tz-voice-chat';
192
+ import 'tz-voice-chat/style.css';
193
+
194
+ export default () => <VoiceAssistant />; // props: apiBase='/api', title, showInfo, systemPrompt, className
195
+ ```
196
+
197
+ `VoiceAssistant` (built on the `useVoiceAssistant` hook) renders the status header, an info card (STT / TTS / chat model / memory), the mic button, a typed-message box, and a transcript with per-message timings (`transcribe`, `think`, `tts`). Esc stops listening. It uses the server chat proxy when the server has an API key, otherwise an in-browser SmolLM2 model.
198
+
199
+ **Server** (`express` and, for `TTS_PROVIDER=server-kokoro`, `kokoro-js` are peer dependencies)
200
+
201
+ ```js
202
+ import express from 'express';
203
+ import { createVoiceAssistantRouter } from 'tz-voice-chat/server';
204
+
205
+ const app = express();
206
+ const { router, ready } = createVoiceAssistantRouter(); // options default to env vars
207
+ app.use('/api', router); // /config /stats /chat /tts /models/*
208
+ ready().then(() => app.listen(3000));
209
+ ```
210
+
211
+ Environment variables: `OPENAI_PROVIDER`, `OPENROUTER_API_KEY`, `OPENROUTER_MODEL`, `HUGGINGFACE_API_KEY`, `TTS_PROVIDER`, `KOKORO_VOICE`, `KOKORO_DTYPE`, `KOKORO_DEVICE`, `KOKORO_SPEED`, `KOKORO_BROWSER_DEVICE`, `OPENAI_API_KEY`, `OPENAI_TTS_MODEL`, `OPENAI_TTS_VOICE`, `WHISPER_MODEL`, `WHISPER_DTYPE`, `WHISPER_DEVICE`, `WEBSPEECH_VOICE`, `WEBSPEECH_RATE`, `WEBSPEECH_PITCH`. Any of them can be overridden with the matching camelCase option.
@@ -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"})}}}})();
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 Pe=Object.create;var xe=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var Be=(e,s,r,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Ue(s))!Ge.call(e,t)&&t!==r&&xe(e,t,{get:()=>s[t],enumerable:!(i=Oe(s,t))||i.enumerable});return e};var Se=(e,s,r)=>(r=e!=null?Pe(Ke(e)):{},Be(s||!e||!e.__esModule?xe(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),a=require("react/jsx-runtime");var Z=typeof document<"u"?document.currentScript:null;const he=60,ne=200;function _e(){let e="",s=!0;function r(t,o,n){t.push(o),e=n,s=!1}function i(){const t=[];for(;;){const o=/([.!?]{1,3})(\s|$)/.exec(e);if(o){const n=e.slice(0,o.index+o[0].length).trim();if(n.length>=10){r(t,n,e.slice(o.index+o[0].length));continue}}if(s){if(e.length>=25){const n=/[,;:—–](\s|$)/.exec(e);if(n){const u=e.slice(0,n.index+n[0].length).trim();if(u.length>=20){r(t,u,e.slice(n.index+n[0].length));continue}}}if(e.length>=he){const n=e.lastIndexOf(" ",he-1),u=n>10?n:he;r(t,e.slice(0,u).trim(),e.slice(u).trimStart());continue}}else if(e.length>=ne){const n=e.slice(0,ne),u=Math.max(n.lastIndexOf(", "),n.lastIndexOf("; "),n.lastIndexOf(": ")),c=u>ne/2?u+1:n.lastIndexOf(" ")>10?n.lastIndexOf(" "):ne;r(t,e.slice(0,c).trim(),e.slice(c).trimStart());continue}break}return t}return{write(t){return e+=t,i()},flush(){const t=e.trim();return e="",t}}}async function Fe(e,{dtype:s="q8",device:r="cpu",modelProxyUrl:i="/api/models/"}={}){var d,f;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=i,(f=(d=t==null?void 0:t.backends)==null?void 0:d.onnx)!=null&&f.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:n}=o;let u=s;r==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),u="fp32");let c=0;const h=w=>{typeof(w==null?void 0:w.progress)=="number"&&(c=Math.max(c,w.progress/100),e==null||e("kokoro",Math.min(.99,c)))};async function l(w,g){return n.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:g,device:w,progress_callback:h})}let v;try{v=await l(r,u)}catch(w){if(r!=="wasm")console.warn(`[modelLoader] Kokoro on "${r}" failed (${w==null?void 0:w.message}) — falling back to WASM.`),c=0,v=await l("wasm",s);else throw w}return e==null||e("kokoro",1),{kokoro:v}}function re(e,s,{threshold:r=.01,padMs:i=25}={}){const{numberOfChannels:t,length:o,sampleRate:n}=s;let u=o,c=-1;for(let f=0;f<t;f++){const w=s.getChannelData(f);for(let g=0;g<o;g++)if(Math.abs(w[g])>r){g<u&&(u=g);break}for(let g=o-1;g>=0;g--)if(Math.abs(w[g])>r){g>c&&(c=g);break}}if(c<u)return s;const h=Math.round(i/1e3*n),l=Math.max(0,u-h),v=Math.min(o,c+1+h);if(l===0&&v===o)return s;const d=e.createBuffer(t,v-l,n);for(let f=0;f<t;f++)d.copyToChannel(s.getChannelData(f).subarray(l,v),f);return d}function We(e,{voice:s="af_bella",speed:r=1,onPlayStart:i}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){if(d instanceof AudioBuffer)return re(t,d);const f=(d==null?void 0:d.audio)??d;if(f instanceof ArrayBuffer)return re(t,await t.decodeAudioData(f.slice(0)));if(f instanceof Float32Array){const w=(d==null?void 0:d.samplingRate)??24e3,g=t.createBuffer(1,f.length,w);return g.copyToChannel(f,0),re(t,g)}throw new Error("Unsupported TTS payload")}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,i==null||i())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{const f=await d;f&&await l(f)}catch(f){console.error("[TtsQueue]",f)}}n=!1}}return{enqueue(d){o.push(e.generate(d,{voice:s,speed:r}).then(h)),v()},cancel(){if(o.length=0,c=!1,u){try{u.stop()}catch{}u=null}},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,200))}}}function He({voice:e="",speed:s=1,onPlayStart:r,url:i="/api/tts"}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){const f={text:d};e&&(f.voice=e),s!==1&&(f.speed=s);const w=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!w.ok)throw new Error(`TTS ${w.status}: ${await w.text()}`);return re(t,await t.decodeAudioData(await w.arrayBuffer()))}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,r==null||r())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{await l(await d)}catch(f){console.error("[ServerTTS]",f)}}n=!1}}return{enqueue(d){d!=null&&d.trim()&&(o.push(h(d)),v())},cancel(){if(o.length=0,u){try{u.stop()}catch{}u=null}c=!1},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,100))}}}function Qe({voice:e="",rate:s=1,pitch:r=1,onPlayStart:i}={}){const t=[];let o=!1,n=!1;function u(){return e?speechSynthesis.getVoices().find(l=>l.name===e||l.voiceURI===e)??null:null}function c(){if(o||t.length===0)return;o=!0;const h=t.shift(),l=new SpeechSynthesisUtterance(h),v=u();v&&(l.voice=v),l.rate=s,l.pitch=r,l.onstart=()=>{n||(n=!0,i==null||i())},l.onend=()=>{o=!1,c()},l.onerror=d=>{console.error("[WebSpeech TTS] error",d.error),o=!1,c()},speechSynthesis.speak(l)}return{enqueue(h){h!=null&&h.trim()&&(t.push(h),c())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,n=!1},async finished(){for(;o||t.length>0;)await new Promise(h=>setTimeout(h,100))}}}async function Ze({onSpeechStart:e,onSpeechEnd:s,onError:r,deviceId:i}){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,...i?{deviceId:{exact:i}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:n=>{console.log("[VAD] onSpeechEnd — samples:",n==null?void 0:n.length),s==null||s(n)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw r==null||r("VAD initialization failed. Falling back to manual microphone capture."),t}}const j={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Je="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=Je,ttsProvider:r="server-kokoro",ttsVoice:i="af_bella",ttsSpeed:t=1,ttsServerUrl:o="/api/tts",ttsSpeechRate:n=1,ttsSpeechPitch:u=1,whisperModel:c="onnx-community/whisper-tiny.en",whisperDtype:h="q8",whisperDevice:l="cpu",kokoroDtype:v="q8",kokoroBrowserDevice:d="wasm",modelProxyUrl:f="/api/models/"}={}){const[w,g]=p.useState(j.IDLE),[N,R]=p.useState(!0),[I,x]=p.useState({whisper:0,kokoro:0}),[z,T]=p.useState(null),[q,$]=p.useState([]),[S,E]=p.useState(null),[L,P]=p.useState(!1),[k,b]=p.useState(""),[K,ae]=p.useState([]),[ie,Y]=p.useState(null),W=p.useRef(j.IDLE),H=p.useRef(!1),V=p.useRef(null),G=p.useRef(null),O=p.useRef(null),B=p.useRef(null),oe=p.useRef(null),ce=p.useRef(null),X=p.useRef([{role:"system",content:s}]),le=p.useRef(e),me=p.useRef(0),we=p.useRef({id:null,enqueuedAt:null,ttsMs:null}),Re=p.useRef(1);p.useEffect(()=>{W.current=w},[w]),p.useEffect(()=>{H.current=L},[L]),p.useEffect(()=>{le.current=e},[e]),p.useEffect(()=>{async function _(){try{const A=await navigator.mediaDevices.enumerateDevices();ae(A.filter(y=>y.kind==="audioinput"))}catch{}}return _(),navigator.mediaDevices.addEventListener("devicechange",_),()=>navigator.mediaDevices.removeEventListener("devicechange",_)},[L]),p.useEffect(()=>{let _=!1;async function A(){try{const y=()=>{var M;const m=we.current;m.enqueuedAt!=null&&m.ttsMs==null&&(m.ttsMs=Math.round(performance.now()-m.enqueuedAt),m.id!=null&&ze(m.id,{timings:{ttsMs:m.ttsMs}})),r==="webspeech"&&((M=G.current)==null||M.pause())};if(r==="webspeech")V.current=Qe({voice:i,rate:n,pitch:u,onPlayStart:y}),x(m=>({...m,kokoro:1}));else if(r==="kokoro"){const{kokoro:m}=await Fe((M,F)=>x(U=>({...U,[M]:F})),{dtype:v,device:d,modelProxyUrl:f});if(_)return;V.current=We(m,{voice:i,speed:t,onPlayStart:y})}else V.current=He({voice:i,speed:t,onPlayStart:y,url:o}),x(m=>({...m,kokoro:1}));if(_)return;B.current=new Worker(new URL("./assets/whisperWorker-BJuP9cl9.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),B.current.onmessage=m=>{m.data.type==="transcript"?ye(m.data.text,{transcribeMs:Math.round(performance.now()-me.current)}):m.data.type==="progress"?x(M=>({...M,whisper:m.data.progress})):m.data.type==="ready"?(x(M=>({...M,whisper:1})),R(!1)):m.data.type==="error"&&(T(`Whisper: ${m.data.message}`),R(!1))},B.current.onerror=()=>{T("Model load failed. Check WebGPU/WASM browser support."),R(!1)},B.current.postMessage({type:"init",model:c,dtype:h,device:l,modelProxyUrl:f})}catch(y){_||(T("Initialisation failed: "+((y==null?void 0:y.message)??String(y))),R(!1))}}return A(),()=>{var y;_=!0,(y=B.current)==null||y.terminate()}},[r,c,h,l,v,d]);function ge(_,A,y){const m=Re.current++;return $(M=>[...M,{id:m,role:_,content:A,timings:y,time:new Date().toISOString()}]),m}function ze(_,{timings:A}){$(y=>y.map(m=>m.id===_?{...m,timings:{...m.timings,...A}}:m))}async function ye(_,{transcribeMs:A}={}){if(!(_!=null&&_.trim())){g(H.current?j.LISTENING:j.IDLE);return}g(j.THINKING),ge("user",_,A!=null?{transcribeMs:A}:void 0);const y=[...X.current,{role:"user",content:_}];X.current=y,await $e(_,y)}async function $e(_,A){var y,m,M,F;(y=O.current)==null||y.abort(),O.current=new AbortController,(m=V.current)==null||m.cancel();try{if(!le.current)throw new Error("processInput is not provided");const U=_e();let ee="",ue=!1,fe=null;const Ve=performance.now(),Q={id:null,enqueuedAt:null,ttsMs:null};we.current=Q;const ve=te=>{var de;Q.enqueuedAt==null&&(Q.enqueuedAt=performance.now()),(de=V.current)==null||de.enqueue(te)};E("");for await(const te of le.current(_,A,O.current.signal))fe==null&&(fe=Math.round(performance.now()-Ve)),ee+=te,E(ee),U.write(te).forEach(Ce=>{ue||(ue=!0,g(j.SPEAKING)),ve(Ce)});const be=U.flush();be&&(ue||g(j.SPEAKING),ve(be)),Q.id=ge("assistant",ee,{thinkMs:fe,...Q.ttsMs!=null?{ttsMs:Q.ttsMs}:{}}),E(null),X.current=[...X.current,{role:"assistant",content:ee}],await((M=V.current)==null?void 0:M.finished()),r==="webspeech"&&((F=G.current)==null||F.start())}catch(U){E(null),U.name!=="AbortError"&&T(U.message||"Processing failed.")}finally{g(H.current?j.LISTENING:j.IDLE)}}async function Ee(){var _,A;T(null),W.current===j.SPEAKING&&((_=V.current)==null||_.cancel(),(A=O.current)==null||A.abort());try{g(j.LISTENING),P(!0);try{const y=await navigator.mediaDevices.getUserMedia({audio:k?{deviceId:{exact:k}}:!0,video:!1});ce.current=y;const m=new AudioContext;oe.current=m;const M=m.createAnalyser();M.fftSize=256,m.createMediaStreamSource(y).connect(M),Y(M)}catch(y){console.warn("[TZVoiceChat] waveform analyser unavailable:",y)}G.current=await Ze({onSpeechStart:()=>{var y,m;r==="webspeech"&&W.current===j.SPEAKING||(W.current===j.SPEAKING&&((y=V.current)==null||y.cancel(),(m=O.current)==null||m.abort()),g(j.LISTENING))},onSpeechEnd:y=>{var m;r==="webspeech"&&W.current===j.SPEAKING||(g(j.TRANSCRIBING),me.current=performance.now(),(m=B.current)==null||m.postMessage({type:"transcribe",audio:y},[y.buffer]))},onError:y=>{T(y),g(j.IDLE)},deviceId:k||void 0})}catch(y){console.error("[TZVoiceChat] startListening failed:",y),T("Microphone access failed. Allow audio permissions and refresh."),g(j.IDLE),P(!1)}}function De(){var _,A,y,m,M;P(!1),(_=G.current)==null||_.destroy(),G.current=null,(A=ce.current)==null||A.getTracks().forEach(F=>F.stop()),ce.current=null,(y=oe.current)==null||y.close(),oe.current=null,Y(null),(m=V.current)==null||m.cancel(),(M=O.current)==null||M.abort(),g(j.IDLE)}function qe(_){var M;if(!(_!=null&&_.trim()))return;g(j.SPEAKING);const A=_e(),y=A.write(_),m=A.flush();[...y,...m?[m]:[]].forEach(F=>{var U;return(U=V.current)==null?void 0:U.enqueue(F)}),(M=V.current)==null||M.finished().then(()=>{g(H.current?j.LISTENING:j.IDLE)})}return{status:w,loading:N,progress:I,error:z,transcript:q,streamingMessage:S,micEnabled:L,startListening:Ee,stopListening:De,speak:qe,submitText:ye,liveAnalyser:ie,devices:K,selectedMicId:k,setSelectedMicId:b}}function je(e){const s=e.replace("#",""),r=s.length===3?s.split("").map(i=>i+i).join(""):s;return[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]}function Ye(e,s,r){e/=255,s/=255,r/=255;const i=Math.max(e,s,r),t=Math.min(e,s,r),o=(i+t)/2;if(i===t)return[0,0,o*100];const n=i-t,u=o>.5?n/(2-i-t):n/(i+t);let c;switch(i){case e:c=((s-r)/n+(s<r?6:0))/6;break;case s:c=((r-e)/n+2)/6;break;default:c=((e-s)/n+4)/6}return[c*360,u*100,o*100]}function Xe(e,s,r){s/=100,r/=100;const i=n=>(n+e/30)%12,t=s*Math.min(r,1-r),o=n=>r-t*Math.max(-1,Math.min(i(n)-3,Math.min(9-i(n),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function C(e,s){const[r,i,t]=je(e),[o,n,u]=Ye(r,i,t),[c,h,l]=Xe(o,n,Math.max(0,Math.min(100,u+s)));return`rgb(${c}, ${h}, ${l})`}function D(e,s){const[r,i,t]=je(e);return`rgba(${r}, ${i}, ${t}, ${s})`}function J(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const se=10;function et({analyser:e}){const s=p.useRef(null),r=p.useRef(null);return p.useEffect(()=>{if(cancelAnimationFrame(r.current),!e)return;const i=s.current;if(!i)return;const t=i.getContext("2d"),o=e.frequencyBinCount,n=new Uint8Array(o),u=Math.max(1,Math.floor(o/se)),c=getComputedStyle(i),h=+c.getPropertyValue("--bar-hue"),l=+c.getPropertyValue("--bar-hue-range"),v=+c.getPropertyValue("--bar-sat"),d=+c.getPropertyValue("--bar-lit"),f=+c.getPropertyValue("--bar-lit-range"),w=()=>{r.current=requestAnimationFrame(w),e.getByteFrequencyData(n);const g=i.width,N=i.height;t.clearRect(0,0,g,N);const R=(g-(se-1)*2)/se;for(let I=0;I<se;I++){const x=n[I*u]/255,z=Math.max(3,x*N*.88);t.fillStyle=`hsl(${h+x*l}, ${v}%, ${d+x*f}%)`,t.beginPath(),t.roundRect(I*(R+2),(N-z)/2,R,z,[2]),t.fill()}};return w(),()=>cancelAnimationFrame(r.current)},[e]),a.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function Te({status:e="idle",active:s=!1,loading:r=!1,analyser:i=null,onToggle:t,devices:o=[],selectedMicId:n="",onDeviceChange:u,inputData:c="",sendData:h,accentColor:l="#f97316",uiColor:v="#64748b",size:d=70,barHue:f=25,barHueRange:w=20,barSat:g=88,barLit:N=65,barLitRange:R=20}){var P;const[I,x]=p.useState(!1),z=p.useRef(null);p.useEffect(()=>{if(!I)return;function k(b){var K;(K=z.current)!=null&&K.contains(b.target)||x(!1)}return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[I]);function T(k){u==null||u(k),x(!1)}const q=p.useMemo(()=>{const k=C(l,-8),b=C(l,-15),K=C(l,-22),ae=C(l,-30),ie=C(l,-42),Y=C(l,8),W=C(l,20),H=C(l,30),V=C(v,-22),G=C(v,-30),O=C(v,18),B=C(v,37);return{"--tz-size":`${d}px`,"--tz-a":l,"--tz-a-d8":k,"--tz-a-d15":b,"--tz-a-d22":K,"--tz-a-d30":ae,"--tz-a-d42":ie,"--tz-a-l8":Y,"--tz-a-l20":W,"--tz-a-l30":H,"--tz-a-25":D(l,.25),"--tz-a-28":D(l,.28),"--tz-a-30":D(l,.3),"--tz-a-32":D(l,.32),"--tz-a-34":D(l,.34),"--tz-a-35":D(l,.35),"--tz-a-38":D(l,.38),"--tz-a-45":D(l,.45),"--tz-a-50":D(l,.5),"--tz-a-55":D(l,.55),"--tz-a-60":D(l,.6),"--tz-a-65":D(l,.65),"--tz-a-68":D(l,.68),"--tz-u":v,"--tz-u-d22":V,"--tz-u-d30":G,"--tz-u-l18":O,"--tz-u-l37":B,"--tz-u-30":D(v,.3),"--tz-u-55":D(v,.55),"--tz-u-d30-a85":J(G,.85),"--tz-u-l18-a18":J(O,.18),"--tz-u-l18-a20":J(O,.2),"--tz-u-l18-a32":J(O,.32),"--tz-u-d22-a90":J(V,.9),"--bar-hue":f,"--bar-hue-range":w,"--bar-sat":g,"--bar-lit":N,"--bar-lit-range":R}},[l,v,d,f,w,g,N,R]),$=((P=o.find(k=>k.deviceId===n))==null?void 0:P.label)||(n?`Mic ${n.slice(0,6)}…`:"Default mic"),S=c.trim().length>0,E=S?"ready":s?e:"off";let L;return S?L=a.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!s||e==="idle"?L=a.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.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"}),a.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"}),a.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"?L=a.jsx(et,{analyser:i}):e==="transcribing"?L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.1}s`}},b))}):e==="thinking"?L=a.jsxs("div",{className:"ai-btn__dots",children:[a.jsx("span",{}),a.jsx("span",{style:{animationDelay:"0.18s"}}),a.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.11}s`}},b))})),a.jsxs("div",{className:"ai-btn-root",style:q,children:[a.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${E}`,"aria-hidden":"true",children:[a.jsx("span",{className:"ai-ring ai-ring--1"}),a.jsx("span",{className:"ai-ring ai-ring--2"})]}),a.jsxs("button",{className:`ai-btn ai-btn--${E}`,disabled:r,onClick:S?()=>h==null?void 0:h(c):t,"aria-label":S?"Send message":s?"Stop assistant":"Start assistant","aria-pressed":S?void 0:s,children:[L,s&&!S&&a.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),a.jsxs("div",{className:`ai-mic-sel${I?" open":""}`,ref:z,children:[a.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>x(k=>!k),title:"Change microphone","aria-label":"Change microphone","aria-expanded":I,children:[a.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),a.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"})]}),a.jsx("span",{className:"ai-mic-sel__label",children:$}),a.jsx("svg",{className:`ai-mic-sel__caret${I?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),I&&a.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===""?" selected":""}`,onClick:()=>T(""),"aria-selected":n==="",children:"Default microphone"}),o.map(k=>a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===k.deviceId?" selected":""}`,onClick:()=>T(k.deviceId),"aria-selected":n===k.deviceId,children:k.label||`Microphone ${k.deviceId.slice(0,8)}`},k.deviceId))]})]})]})}async function Ae(e,s,r="/api/chat"){var u;const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:s,body:JSON.stringify({messages:e})});if(!i.ok){const c=await i.text();throw new Error(`Server error: ${i.status} ${c}`)}const t=(u=i.body)==null?void 0:u.getReader();if(!t){const c=await i.json();return{stream:async function*(){yield c.text}}}const o=new TextDecoder;let n="";return{stream:async function*(){var h,l,v;let c="";for(;;){const{value:d,done:f}=await t.read();if(f)break;n+=o.decode(d,{stream:!0});const w=n.split(`
2
+ `);n=w.pop();for(const g of w){const N=g.trim();if(!N.startsWith("data:"))continue;const R=N.slice(5).trimStart();if(R==="[DONE]")return;try{const x=(v=(l=(h=JSON.parse(R).choices)==null?void 0:h[0])==null?void 0:l.delta)==null?void 0:v.content;x&&(c&&/\w/.test(c)&&/\w/.test(x[0])&&(yield" "),c=x[x.length-1],yield x)}catch{}}}}}}function Ne(e,s,r){return{stream:async function*(){const i=[];let t=null,o=!1,n="";const u=({data:h})=>{h.type==="token"?(i.push(h.text),t==null||t(),t=null):h.type==="done"&&(o=!0,t==null||t(),t=null)},c=()=>{o=!0,t==null||t(),t=null};e.addEventListener("message",u),r==null||r.addEventListener("abort",c),e.postMessage({type:"generate",messages:s});try{for(;!o||i.length>0;)if(i.length>0){const h=i.shift();n&&/\w/.test(n)&&/\w/.test(h[0])&&(yield" "),n=h[h.length-1],yield h}else await new Promise(h=>{t=h})}finally{e.removeEventListener("message",u),r==null||r.removeEventListener("abort",c)}}}}function Ie({apiBase:e="/api",systemPrompt:s}={}){const[r,i]=p.useState(!0),[t,o]=p.useState(0),[n,u]=p.useState(""),[c,h]=p.useState({}),[l,v]=p.useState(null),[d,f]=p.useState({}),w=p.useRef(null),g=p.useRef(null);p.useEffect(()=>{let x=!1;async function z(){let T=!0,q={};try{const S=await(await fetch(`${e}/config`)).json();T=S.hasApiKey,v(S),q={ttsProvider:S.ttsProvider||"server-kokoro",ttsVoice:S.ttsProvider==="openai"?S.openaiTtsVoice||"alloy":S.kokoroVoice||"af_bella",ttsServerUrl:`${e}/tts`,ttsSpeed:S.kokoroSpeed??1,ttsSpeechRate:S.webSpeechRate??1,ttsSpeechPitch:S.webSpeechPitch??1,whisperModel:S.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:S.whisperDtype||"q8",whisperDevice:S.whisperDevice||"cpu",kokoroDtype:S.kokoroDtype||"q8",kokoroBrowserDevice:S.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`}}catch{q={ttsProvider:"server-kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(!x)if(T)w.current=async function*($,S,E){const{stream:L}=await Ae(S,E,`${e}/chat`);yield*L()},h(q),i(!1);else{u("No API key — using SmolLM2-360M-Instruct locally in your browser.");const $=new Worker(new URL("./assets/llmWorker-CVEGn6yI.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"});g.current=$,$.onmessage=S=>{S.data.type==="progress"?o(S.data.progress??0):S.data.type==="ready"?(o(1),w.current=async function*(E,L,P){const{stream:k}=Ne($,L,P);yield*k()},h(q),i(!1)):S.data.type==="error"&&i(!1)},$.onerror=()=>i(!1),$.postMessage({type:"init",modelProxyUrl:`${e}/models/`})}}return z(),()=>{var T;x=!0,(T=g.current)==null||T.terminate()}},[e]);const N=Me({processInput:async function*(x,z,T){w.current&&(yield*w.current(x,z,T))},...s?{systemPrompt:s}:{},...c});p.useEffect(()=>{let x=!1;async function z(){const q={};typeof performance<"u"&&performance.memory&&(q.browser=performance.memory.usedJSHeapSize);try{const $=await fetch(`${e}/stats`);$.ok&&(q.server=(await $.json()).rss)}catch{}x||f(q)}z();const T=setInterval(z,3e3);return()=>{x=!0,clearInterval(T)}},[e]);const{micEnabled:R,stopListening:I}=N;return p.useEffect(()=>{if(!R)return;const x=z=>{z.key==="Escape"&&I()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[R,I]),{chat:N,info:l,config:c,memory:d,llmProgress:t,note:n,loading:N.loading||r}}const Le=(e,s)=>e==="webgpu"&&(s==="q4"||s==="q8")?"fp32":s,pe=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,ke=e=>`${(e/1048576).toFixed(0)} MB`;function tt(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${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} · ${Le(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const nt=e=>e.replace(/\b\w/g,s=>s.toUpperCase());function st({apiBase:e="/api",title:s="Voice Assistant",showInfo:r=!0,systemPrompt:i,className:t=""}={}){const{chat:o,info:n,config:u,memory:c,llmProgress:h,note:l,loading:v}=Ie({apiBase:e,systemPrompt:i}),{status:d,progress:f,error:w,transcript:g,streamingMessage:N,micEnabled:R,startListening:I,stopListening:x,submitText:z,liveAnalyser:T,devices:q,selectedMicId:$,setSelectedMicId:S}=o,[E,L]=p.useState(""),P=p.useRef(null);p.useEffect(()=>{var b;(b=P.current)==null||b.scrollIntoView({behavior:N!==null?"auto":"smooth"})},[g,N]);const k=n&&u.whisperDevice&&[["STT",`Whisper · ${(u.whisperModel||n.whisperModel).split("/").pop()} · ${Le(u.whisperDevice,u.whisperDtype)}/${u.whisperDevice}`],["TTS",tt({...n,...u})],["Chat",n.hasApiKey?`${n.chatProvider} · ${n.chatModel}`:"SmolLM2-360M-Instruct (in-browser)"],["Memory",[c.browser!=null?`browser heap ${ke(c.browser)}`:"browser heap n/a",c.server!=null?`server ${ke(c.server)}`:null].filter(Boolean).join(" · ")]];return a.jsxs("div",{className:`tz-va ${t}`.trim(),children:[a.jsxs("section",{className:"tz-va__card tz-va__header",children:[a.jsx("h1",{children:s}),a.jsx("span",{className:`tz-va__chip tz-va__chip--${d}`,children:nt(d)})]}),r&&k&&a.jsx("section",{className:"tz-va__card tz-va__info",children:k.map(([b,K])=>a.jsxs("div",{className:"tz-va__info-row",children:[a.jsx("span",{className:"tz-va__info-label",children:b}),a.jsx("span",{className:"tz-va__info-value",children:K})]},b))}),a.jsxs("section",{className:"tz-va__card",children:[v&&a.jsxs("div",{className:"tz-va__progress",children:[a.jsxs("label",{children:["Whisper STT",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.whisper*100}%`}})})]}),a.jsxs("label",{children:["Kokoro TTS",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.kokoro*100}%`}})})]}),h>0&&a.jsxs("label",{children:["Local LLM",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${h*100}%`}})})]})]}),a.jsx("div",{className:"tz-va__button",children:a.jsx(Te,{status:d,active:R,loading:v,analyser:T,onToggle:R?x:I,devices:q,selectedMicId:$,onDeviceChange:S,inputData:E,sendData:b=>{L(""),z(b)}})}),a.jsx("div",{className:"tz-va__input-row",children:a.jsx("input",{type:"text",className:"tz-va__input",value:E,onChange:b=>L(b.target.value),onKeyDown:b=>{b.key==="Enter"&&E.trim()&&(L(""),z(E))},placeholder:"Type a message…",disabled:v})}),a.jsx("p",{className:"tz-va__note",children:v?f.kokoro<1?"Loading Kokoro TTS…":f.whisper<1?"Loading Whisper STT…":h>0&&h<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":"Finishing up…":"Ready."}),l&&a.jsx("p",{className:"tz-va__note",children:l})]}),a.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[g.map(b=>a.jsxs("div",{className:`tz-va__message tz-va__message--${b.role}`,children:[a.jsx("small",{children:b.role==="user"?"You":"Assistant"}),a.jsx("p",{children:b.content}),b.timings&&a.jsxs("div",{className:"tz-va__timings",children:[b.timings.transcribeMs!=null&&a.jsxs("span",{children:["transcribe ",pe(b.timings.transcribeMs)]}),b.timings.thinkMs!=null&&a.jsxs("span",{children:["think ",pe(b.timings.thinkMs)]}),b.timings.ttsMs!=null&&a.jsxs("span",{children:["tts ",pe(b.timings.ttsMs)]})]})]},b.id)),N!==null&&a.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[a.jsx("small",{children:"Assistant"}),a.jsxs("p",{children:[N,a.jsx("span",{className:"tz-va__cursor"})]})]}),a.jsx("div",{ref:P})]}),w?a.jsxs("section",{className:"tz-va__card",children:[a.jsx("strong",{children:"Error:"}),a.jsx("p",{children:w})]}):null]})}exports.AIAssistantButton=Te;exports.STATES=j;exports.TZVoiceChat=Me;exports.VoiceAssistant=st;exports.createLocalChatStream=Ne;exports.sendChatRequest=Ae;exports.useVoiceAssistant=Ie;