1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6890],{6890:(e,t,r)=>{r.r(t),r.d(t,{default:()=>l});var n=r(5155),a=r(2115),o=r(9486),c=r(5617);let i={type:"semantic_vad",eagerness:"low",create_response:!0,interrupt_response:!0},s=[{type:"function",name:"buscar_conocimiento",description:"Busca en la base de conocimiento de Openauto (cursos, ECUs, equipos/programadores, mapas, canal de YouTube) Y TAMBI\xc9N en los datos propios del alumno: el estado en vivo de SU veh\xedculo conectado al dongle R2D2 y SUS corridas de dyno guardadas. \xdasala siempre que el alumno pregunte por datos t\xe9cnicos concretos, qu\xe9 curso tomar, compatibilidad de equipos, procedimientos, en qu\xe9 clase est\xe1 algo, C\xd3MO EST\xc1 SU AUTO o CU\xc1NTO DIO ALGUNA DE SUS MEDICIONES. No inventes datos.",parameters:{type:"object",properties:{query:{type:"string",description:"La pregunta del alumno en lenguaje natural."}},required:["query"],additionalProperties:!1}}];function l(e){let{onClose:t,onUpgrade:l,chatId:u,sinInterfaz:d=!1,onEstado:p}=e,[m,f]=(0,a.useState)("connecting"),[h,v]=(0,a.useState)(null),[g,y]=(0,a.useState)(null),[b,x]=(0,a.useState)(0),[w,_]=(0,a.useState)(!1),[k,S]=(0,a.useState)(""),[j,N]=(0,a.useState)(""),T=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=T.current;e&&(e.scrollTop=e.scrollHeight)},[j]);let R=(0,a.useRef)(null);async function C(){try{var e,t;R.current=await (null==(t=navigator.wakeLock)||null==(e=t.request)?void 0:e.call(t,"screen"))}catch(e){}}(0,a.useEffect)(()=>{let e=()=>{if("visible"===document.visibilityState&&!D.current&&A.current){var e;C();let t=L.current;t&&"running"!==t.state&&(null==(e=t.resume)||e.call(t).catch(()=>{}))}};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[]);let O=(0,a.useRef)(null),M=(0,a.useRef)(null),P=(0,a.useRef)(null),E=(0,a.useRef)(null),z=(0,a.useRef)(null),q=(0,a.useRef)("realtime"),I=(0,a.useRef)(null),A=(0,a.useRef)(0),D=(0,a.useRef)(!1),J=(0,a.useRef)("connecting"),U=(0,a.useRef)(!1);(0,a.useEffect)(()=>{J.current=m},[m]),(0,a.useEffect)(()=>{U.current=w},[w]);let L=(0,a.useRef)(null),B=(0,a.useRef)(null),W=(0,a.useRef)(null),F=(0,a.useRef)(0),V=(0,a.useRef)(null),G=(0,a.useRef)(!1),H=(0,a.useRef)(600),[Y,Q]=(0,a.useState)(null),X=(0,a.useRef)({input:0,output:0}),K=(0,a.useRef)(new Set),Z=(0,a.useRef)(new Set),$=new Set(["session.started","session.updated","session.usage.updated","session.delegation.created","rate_limits.updated","response.output_item.done","response.content_part.added","response.content_part.done","response.in_progress","response.output_text.delta","response.output_text.done","response.function_call_arguments.delta","conversation.item.created","error"]),ee=new Set(["buscar_conocimiento","buscar_en_internet","leer_obd_en_vivo"]),et=(0,a.useRef)(new Set),er=(0,a.useRef)(new Map),en=(0,a.useRef)(null),ea=(0,a.useRef)({on:!1,echoPeak:0,frames:0,t0:0}),eo=(0,a.useRef)([]),ec=(0,a.useRef)(!1),ei=(0,a.useRef)(!1),es=(0,a.useRef)(!1),el=(0,a.useRef)(null),eu=(0,a.useRef)(new Map),ed=(0,a.useRef)(0),ep=(0,a.useRef)(0);function em(e){if(!e)return ed.current++;let t=eu.current;return t.has(e)||t.set(e,ed.current++),t.get(e)}let ef=(0,a.useRef)({user:{texto:"",startMs:null,timer:null},assistant:{texto:"",startMs:null,timer:null}}),eh=(0,a.useRef)(null);function ev(e){let t=ef.current[e];clearTimeout(t.timer),t.timer=null;let r=(t.texto||"").trim();t.texto="";let n=t.startMs;t.startMs=null,r&&eo.current.push({role:e,text:r,itemId:null,seq:null!=n?n:ed.current++,at:ep.current++})}function eg(e,t,r){let n=(t||"").trim();if(n){if(r){let t=eo.current.find(t=>t.itemId===r&&t.role===e);if(t){t.text=n;return}}eo.current.push({role:e,text:n,itemId:r||null,seq:em(r),at:ep.current++})}}async function ey(){let{beacon:e=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(ec.current)return el.current;if(ev("user"),ev("assistant"),!eo.current.length)return ec.current=!0,null;let t=[...eo.current].sort((e,t)=>e.seq-t.seq||e.at-t.at).map(e=>{let{role:t,text:r}=e;return{role:t,text:r}});ec.current=!0;let r=JSON.stringify({chatId:u||null,turns:t,model:z.current||null});if(e){try{var n,a;null==(n=(a=navigator).sendBeacon)||n.call(a,"/api/voice/transcript",new Blob([r],{type:"application/json"}))}catch(e){}return null}return el.current=(async()=>{try{let e=await fetch("/api/voice/transcript",{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0});return await e.json().catch(()=>null)}catch(e){return null}})(),el.current}let eb=(0,a.useRef)(new Set);function ex(e,t){!e||eb.current.has(e)||(eb.current.add(e),ew({type:"live"===q.current?"response.item.create":"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),eL())}function ew(e){let t,r=E.current;if(r&&"open"===r.readyState){try{var n,a;t=null==(a=crypto)||null==(n=a.randomUUID)?void 0:n.call(a)}catch(e){t=void 0}try{r.send(JSON.stringify({event_id:t,...e}))}catch(e){}}}let e_=(0,a.useRef)(new Set),ek=(0,a.useRef)(null);function eS(){ek.current&&(clearTimeout(ek.current),ek.current=null)}function ej(){eS(),ek.current=setTimeout(()=>{ek.current=null,eT()},300)}function eN(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"voz";if(e_.current.add(e),!ea.current.on&&en.current){ea.current={on:!0,echoPeak:0,frames:0,t0:performance.now()};
1try{en.current.replaceTrack(null).catch(()=>{})}catch(e){}}}function eT(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"voz";if(e_.current.delete(r),e_.current.size)return;let n=ea.current;if(!n.on)return;n.on=!1;let a=(null==(t=M.current)||null==(e=t.getAudioTracks)?void 0:e.call(t)[0])||null;try{a&&en.current&&en.current.replaceTrack(a).catch(()=>{})}catch(e){}}let eR=(0,a.useRef)({}),eC=(0,a.useRef)(0),eO=(0,a.useRef)(!1),eM=(0,a.useRef)(!1),eP=(0,a.useRef)(null),eE=(0,a.useRef)(null),ez=(0,a.useCallback)(e=>{let t=eR.current[e];if(t){t.__muerto=!0;try{t.pause(),t.currentTime=0}catch(e){}eR.current[e]=null,Object.entries(eR.current).some(e=>{let[t,r]=e;return r&&"espera"!==t})||eT("aviso")}},[]),eq=(0,a.useCallback)(function(e){let{bucle:t=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{ez(e);let r=new Audio("/sounds/voz-".concat(e,".mp3"));r.loop=t,r.volume="espera"===e?.65:.75,eR.current[e]=r,t||eN("aviso"),t||r.addEventListener("ended",()=>ez(e),{once:!0}),t&&(clearTimeout(eE.current),eE.current=setTimeout(()=>{eC.current=0,eO.current=!1,ez(e)},3e4)),r.play().then(()=>{if(r.__muerto)try{r.pause()}catch(e){}}).catch(()=>{eR.current[e]===r&&ez(e)})}catch(e){}},[ez]),eI=(0,a.useCallback)(()=>{(eC.current>0||eO.current)&&!eM.current?eR.current.espera||eq("espera",{bucle:!0}):ez("espera")},[eq,ez]);function eA(){var e,t,r,n,a,o,c,i;let{beacon:s=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(let e of(eS(),eh.current&&(clearTimeout(eh.current),eh.current=null),et.current.clear(),["user","assistant"])){let t=ef.current[e];t.timer&&(clearTimeout(t.timer),t.timer=null)}if(!D.current){D.current=!0,eP.current&&(clearInterval(eP.current),eP.current=null),eC.current=0,eO.current=!1,clearTimeout(eE.current),ez("espera"),ez("lista"),eq("cierre"),function(){let e=I.current,t=A.current?Math.round((Date.now()-A.current)/1e3):0;if(A.current=0,!e&&t<=0)return;let r=JSON.stringify({seconds:t,voice_session_id:I.current,model:z.current,input_tokens:X.current.input||0,output_tokens:X.current.output||0});try{var n,a;if(null==(n=(a=navigator).sendBeacon)?void 0:n.call(a,"/api/voice/end",new Blob([r],{type:"application/json"})))return}catch(e){}fetch("/api/voice/end",{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}).catch(()=>{})}(),ey({beacon:s});try{null==(t=R.current)||null==(e=t.release)||e.call(t)}catch(e){}try{cancelAnimationFrame(F.current)}catch(e){}try{null==(r=L.current)||r.close()}catch(e){}try{null==(a=O.current)||null==(n=a.getSenders)||n.call(a).forEach(e=>e.track&&e.track.stop())}catch(e){}try{null==(o=O.current)||o.close()}catch(e){}try{null==(i=M.current)||null==(c=i.getTracks)||c.call(i).forEach(e=>e.stop())}catch(e){}}}function eD(e,t){try{let r=e.createMediaStreamSource(t),n=e.createAnalyser();return n.fftSize=256,n.smoothingTimeConstant=.8,r.connect(n),n}catch(e){return null}}function eJ(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t)return;let r=L.current||new t;if(L.current=r,"suspended"===r.state&&r.resume().catch(()=>{}),M.current&&!B.current&&(B.current=eD(r,M.current)),e&&(W.current=eD(r,e)),G.current)return;let n=V.current;if(!n)return;G.current=!0;let a=Math.min(2,window.devicePixelRatio||1);n.width=340*a,n.height=340*a;let o=n.getContext("2d");o.scale(a,a);let c="245,166,35",i=new Uint8Array(128),s=new Uint8Array(128),l=e=>{let t=0;for(let r=0;r<64;r++)t+=e[r]*e[r];return Math.sqrt(t/64)/255},u=()=>{let e=performance.now()/1e3,t="thinking"===J.current,r=W.current,n=U.current?null:B.current;r?r.getByteFrequencyData(s):s.fill(0),n?n.getByteFrequencyData(i):i.fill(0);let a=l(s),d=l(i),p=a>.02&&a>=.8*d,m="speaking"===J.current||p,h=p?s:i,v=p?a:d,g=ea.current;if(g.on&&!U.current)if(performance.now()-g.t0<450)g.echoPeak=Math.max(g.echoPeak,d);else{let e=Math.max(.06,2.5*g.echoPeak);g.frames=d>e?g.frames+1:0,g.frames>=8&&function(){let e=ea.current;e&&(e.frames=0,e.t0=performance.now()),eT(),"live"!==q.current&&(ew({type:"output_audio_buffer.clear"}),ew({type:"response.cancel"})),f("active"),eO.current=!1,eM.current=!1,eI()}()}o.clearRect(0,0,340,340);let y=U.current&&!m?.55:1,b=.06*e;for(let e=0;e<48;e++){let t=b+e/48*Math.PI*2,r=t+2*Math.PI/48-.045,n=e>=40;o.beginPath(),o.arc(170,170,158,t,r),o.strokeStyle=n?"rgba(".concat("239,68,68",",").concat((.5+.3*v)*y,")"):"rgba(".concat(c,",").concat((.22+.18*v)*y,")"),o.lineWidth=n?4:3,o.stroke()}for(let e=0;e<60;e++){let t=e/60*Math.PI*2-Math.PI/2,r=e%5==0,n=r?10:5;o.beginPath(),o.moveTo(170+Math.cos(t)*(136-n),170+Math.sin(t)*(136-n)),o.lineTo(170+136*Math.cos(t),170+136*Math.sin(t)),o.strokeStyle="rgba(".concat(c,",").concat((r?.38:.18)*y,")"),o.lineWidth=r?2:1,o.stroke()}for(let t=0;t<56;t++){let r=h[Math.floor(t/56*96)]/255,n=t/56*Math.PI*2-Math.PI/2+.12*e,a=4+40*r;o.beginPath(),o.moveTo(170+80*Math.cos(n),170+80*Math.sin(n)),o.lineTo(170+Math.cos(n)*(80+a),170+Math.sin(n)*(80+a)),o.strokeStyle="rgba(".concat(c,",").concat((.2+.75*r)*y,")"),o.lineWidth=2.5,o.lineCap="round",o.stroke()}let x=t?3.2*e:-(.35*e);o.beginPath(),o.arc(170,170,118,x,x+(t?1.1:4.4)),o.strokeStyle="rgba(".concat(c,",").concat((t?.8:.16)*y,")"),o.lineWidth=t?3:2,o.stroke();let w=56*(1+.03*Math.sin(1.3*e)+.22*v),_=o.createRadialGradient(170,170,.1*w,170,170,w);_.addColorStop(0,"rgba(255,222,166,".concat(.95*y,")")),_.addColorStop(.55,"rgba(".concat(c,",").concat(.85*y,")")),_.addColorStop(1,"rgba(".concat(c,",0)")),o.beginPath(),o.arc(170,170,w,0,2*Math.PI),o.fillStyle=_,o.fill(),F.current=requestAnimationFrame(u)};F.current=requestAnimationFrame(u)}catch(e){}}async function eU(e){var t,n,a,o,c;let i;try{i=JSON.parse(e.data)}catch(e){return}let s=i.type||"";if("response.event"===s&&i.event&&"object"==typeof i.event&&(s=(i=i.event).type||""),"response.completed"===s&&(s="response.done"),"session.input_transcript.delta"===s||"session.output_transcript.delta"===s){let e="session.input_transcript.delta"===s,t=e?"user":"assistant",r=ef.current;null==r[t].startMs&&(r[t].startMs=null!=(n=i.start_ms)?n:0),r[t].texto+=i.delta||"",clearTimeout(r[t].timer),r[t].timer=setTimeout(()=>ev(t),1500),e?S(r.user.texto.trim().slice(-300)):(N(r.assistant.texto.trim().slice(-4e3)),f(e=>"active"===e||"thinking"===e?"speaking":e),eM.current=!0,eI(),clearTimeout(eh.current),eh.current=setTimeout(()=>{f(e=>"speaking"===e?"active":e),eM.current=!1,eI()},700));return}if("conversation.item.created"===s)return void em(null==(a=i.item)?void 0:a.id);if("conversation.item.input_audio_transcription.completed"===s){eg("user",i.transcript,i.item_id),S((i.transcript||"").trim());return}if(s.includes("transcript")&&s.includes("delta")&&!s.includes("input")){let e=i.delta||"";e&&N(t=>(t+e).slice(-4e3));return}if(s.includes("transcript")&&s.endsWith(".done")&&!s.includes("input")){eg("assistant",i.transcript,i.item_id),i.transcript&&N(i.transcript.trim());return}if("response.created"===s){N(""),ei.current=!0;return}if("output_audio_buffer.started"===s){f("speaking"),eS(),eN(),eM.current=!0,eO.current=!1,eI();return}if("output_audio_buffer.stopped"===s||"output_audio_buffer.cleared"===s){f("active"),eM.current=!1,eI(),ej();return}if(s.includes("audio")&&s.includes("delta")&&!s.includes("transcript"))return void f("speaking");if("response.done"===s){let e=null==(o=i.response)?void 0:o.usage;e&&(X.current.input+=Number(e.input_tokens)||0,X.current.output+=Number(e.output_tokens)||0),f("active"),ej(),ei.current=!1,et.current.size&&(eC.current=Math.max(0,eC.current-et.current.size),et.current.clear());let t=es.current;t&&eL(),t||0!==eC.current||(eO.current=!1,eI());return}if("input_audio_buffer.speech_started"===s)return void f("active");if("response.output_item.added"===s&&(null==(t=i.item)?void 0:t.type)==="function_call"){er.current.set(i.item.id,{callId:i.item.call_id,name:i.item.name}),ee.has(i.item.name)&&(et.current.add(i.item.call_id),eC.current+=1,f("thinking"),eI());return}if("response.function_call_arguments.done"===s){let e,t=er.current.get(i.item_id)||{},n=i.call_id||t.callId,a=i.name||t.name;if(!n||K.current.has(n))return;K.current.add(n);let o=setTimeout(()=>{ex(n,{ok:!1,mensaje:"No pude completar la lectura a tiempo. Dilo en voz alta y ofrece intentarlo de nuevo.",_timeout:!0})},15e3),s={};
1try{s=JSON.parse(i.arguments||"{}")}catch(e){}let l={buscar_conocimiento:"/api/voice/rag",buscar_en_internet:"/api/voice/web"}[a];if(l){f("thinking"),et.current.delete(n)||(eC.current+=1),eI();try{let t=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:s.query||""})});e=await t.json()}catch(t){e={summary:"",error:"No pude consultar ahora."}}finally{eC.current=Math.max(0,eC.current-1),eO.current=!0,eI()}}else if("comandar_vehiculo"===a)try{let t=await fetch("/api/voice/comando",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accion:s.accion||"",vehiculo:s.vehiculo||""})});e=await t.json(),t.ok||(null==e?void 0:e.mensaje)||(e={ok:!1,mensaje:"No tiene permiso para mandarle comandos a un veh\xedculo."})}catch(t){e={ok:!1,mensaje:"No pude mandar el comando ahora."}}else if("modo_prueba_alumno"===a)try{let t=await fetch("/api/voice/tool/modo_prueba_alumno",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({activar:!1!==s.activar})});e=await t.json()}catch(t){e={ok:!1,mensaje:"No pude cambiar el modo. Segui como venias."}}else if("guardar_idioma"===a)try{let t=await fetch("/api/voice/idioma",{method:"POST",headers:{"Content-Type":"application/json"}
1,body:JSON.stringify({codigo:s.codigo||""})});e=await t.json()}catch(t){e={ok:!1,nota:"No se pudo guardar. Sigue en el idioma que venias usando."}}else if("iniciar_corrida_dyno"===a)try{if(!eP.current){let e=!1,t=0;eP.current=setInterval(()=>{if(t+=1,eM.current&&(e=!0),e&&!eM.current||!(t<40)){clearInterval(eP.current),eP.current=null;try{window.dispatchEvent(new CustomEvent("oa-corrida-voz"))}catch(e){}try{window.dispatchEvent(new CustomEvent("oa-navegar",{detail:{url:"/escaner?ir=dyno&corrida=voz"}}))}catch(e){}}},500)}e={ok:!0,mensaje:'Listo. Di UNA sola frase que avise las dos cosas: que la corrida arranca y que la llamada se corta ahi (por ejemplo "Arranco la corrida y te dejo: acelera a fondo cuando estes listo"). No hables mas: al terminar la frase se abre el Escaner con la corrida armada y la llamada termina.'}}catch(t){e={ok:!1,mensaje:"No pude abrir el Escaner. Que lo abra a mano desde el menu y la corrida se puede iniciar ahi."}}else if("guardar_perfil"===a)try{let t=await fetch("/api/voice/perfil",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tipo:s.tipo||"",vehiculo:s.vehiculo||""})});e=await t.json()}catch(t){e={ok:!1,nota:"No se pudo guardar. Sigue la conversaci\xf3n normal."}}else if("leer_obd_en_vivo"===a){et.current.delete(n)||(eC.current+=1),f("thinking"),eI();let t=null,a=!1,o=!0===s.en_vivo;try{let[n,c]=await Promise.all([r.e(5883).then(r.bind(r,5883)),r.e(1070).then(r.bind(r,1070))]);if((t=c.sesionCompartida())&&(a=!0),!t&&o)try{t=await Promise.race([n.conectarElm327({sinSelector:!0,conservarRecuerdo:!0}),new Promise((e,t)=>setTimeout(()=>t(Error("timeout")),8e3))])}catch(e){}if(t){let a=s.lectura||"diagnostico";if("dtcs"===a)e={ok:!0,dtcs:await n.leerDtcs(t)};else if("vin"===a)e={ok:!0,vin:await n.leerVin(t)};else if("diagnostico"===a){let r=await n.leerDtcs(t),a=await n.leerEnVivo(t);e={ok:!0,dtcs:r,datos:a}}else e={ok:!0,datos:await n.leerEnVivo(t)};e.transporte=t.transporte||null,e.adaptador=t.nombre||null;try{let{informeObdHablado:t}=await r.e(2618).then(r.bind(r,2618));e.mensaje=t({dtcs:e.dtcs,datos:e.datos,adaptador:e.adaptador,transporte:e.transporte}),e.fuente="adaptador"}catch(e){}try{fetch("/api/escaner/sesiones",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:crypto.randomUUID(),transporte:t.transporte||"bluetooth",adaptador:t.nombre||null,origen:"voz",...e.dtcs?{dtcs:e.dtcs}:{}})}).catch(()=>{})}catch(e){}}else try{let t=await fetch("/api/voice/obd",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lectura:s.lectura||"diagnostico"})});e=await t.json()}catch(t){e={ok:!1,mensaje:"No encontr\xe9 ning\xfan adaptador OBD al alcance ni pude consultar la telemetr\xeda."}}}catch(t){e={ok:!1,mensaje:"No pude leer el veh\xedculo ahora."}}finally{if(!a)try{null==t||null==(c=t.cerrar)||c.call(t)}catch(e){}eC.current=Math.max(0,eC.current-1),eO.current=!0,eI()}}else if("cambiar_mapa"===a||"estado_mapa"===a)try{let t=await fetch("/api/voice/mapa",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accion:"estado_mapa"===a?"estado":"cambiar",mapa:s.mapa||"",vehiculo:s.vehiculo||"",confirmar:!0===s.confirmar,oido:s.oido||""})});e=await t.json(),t.ok||(null==e?void 0:e.mensaje)||(e={ok:!1,mensaje:"No tiene permiso para cambiar mapas."})}catch(t){e={ok:!1,mensaje:"No pude procesar el cambio de mapa ahora."}}else if("repaso"===a)try{let t=await fetch("/api/voice/repaso",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accion:s.accion||"",tema:s.tema||"",tramo:s.tramo||"",flojo:s.flojo||""})});e=await t.json()}catch(t){e={ok:!1,mensaje:"No pude guardar el avance. Sigue el repaso igual."}}else e={error:"herramienta desconocida ".concat(a)};clearTimeout(o),ex(n,e);return}!Z.current.has(s)&&(Z.current.add(s),$.has(s)||console.warn('[voz] evento sin handler: "'.concat(s,'" (motor ').concat(q.current,"). Si algo se cuelga, empieza por ac\xe1."),i))}function eL(){if(ei.current){es.current=!0;return}es.current=!1,ew({type:"response.create"})}async function eB(){let e=await ey();eA(),null==t||t(e)}(0,a.useEffect)(()=>{let e=!0,t=Symbol("voz");return(0,c.tj)(t),(async()=>{let t,r;try{let r=await fetch("/api/voice/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliente:"web"})});if(t=await r.json().catch(()=>({})),403===r.status){e&&(f("blocked"),y("tier"),v(t.message||"La voz en vivo es del plan Pro."));return}if(429===r.status){e&&(f("blocked"),y("cap"),v(t.message||"Alcanzaste tu tiempo de voz de hoy."));return}let n="live"===t.engine;if(!r.ok||!n&&!t.client_secret)throw Error(t.message||"No se pudo iniciar la voz.");q.current=n?"live":"realtime"}catch(t){e&&(f("error"),v(t.message||"No se pudo iniciar la voz."));return}z.current=t.model,I.current=t.voice_session_id||null;let n=Number(t.max_call_seconds||t.remaining_seconds||0);H.current=n>0?n:600;try{r=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(t){eA({beacon:!1}),e&&(f("error"),v((null==t?void 0:t.name)==="NotAllowedError"?"Permiso de micr\xf3fono denegado.":"No se pudo acceder al micr\xf3fono."));return}
1if(!e){r.getTracks().forEach(e=>e.stop()),eA();return}M.current=r;try{let n,a=new RTCPeerConnection;O.current=a,a.onconnectionstatechange=()=>{let t=a.connectionState;("failed"===t||"closed"===t)&&!D.current&&e&&(eA(),f("error"),v("Se cort\xf3 la conexi\xf3n de voz. Revisa la se\xf1al e intenta de nuevo."))},a.ontrack=e=>{let t=P.current;if(t){var r;t.srcObject=e.streams[0],null==(r=t.play)||r.call(t).catch(()=>{})}eJ(e.streams[0])},r.getTracks().forEach(e=>{let t=a.addTrack(e,r);"audio"===e.kind&&(en.current=t)});let o=a.createDataChannel("oai-events");E.current=o,o.onopen=()=>{"live"!==q.current&&ew({type:"session.update",session:{type:"realtime",audio:{input:{turn_detection:i,noise_reduction:{type:"far_field"},...t.transcription?{transcription:t.transcription}:{}}},tool_choice:"auto",tools:Array.isArray(t.tools)&&t.tools.length?t.tools:s}})},o.onmessage=eU;let c=await a.createOffer();if(await a.setLocalDescription(c),"live"===q.current){let e=await fetch(t.live_url||"/api/voice/live",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:c.sdp,voice_session_id:t.voice_session_id})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.sdp)throw Error(r.message||(429===e.status?"La voz est\xe1 saturada. Intenta de nuevo en unos segundos.":"La conexi\xf3n de voz fue rechazada (".concat(e.status,").")));n=r.sdp}else{let e=t.webrtc_url||"https://api.openai.com/v1/realtime/calls",r=await fetch("".concat(e,"?model=").concat(encodeURIComponent(t.model)),{method:"POST",headers:{Authorization:"Bearer ".concat(t.client_secret),"Content-Type":"application/sdp"},body:c.sdp});if(!r.ok)throw Error("La conexi\xf3n de voz fue rechazada (".concat(r.status,")."));n=await r.text()}if(await a.setRemoteDescription({type:"answer",sdp:n}),!e)return;A.current=Date.now(),f("active"),eq("lista"),C(),eJ(null)}catch(t){eA({beacon:!1}),e&&(f("error"),v(t.message||"Fall\xf3 la conexi\xf3n de voz."))}})(),()=>{e=!1,eA(),(0,c.h5)(t)}},[]),(0,a.useEffect)(()=>{if("active"!==m&&"speaking"!==m&&"thinking"!==m)return;let e=setInterval(()=>{let e=A.current?Math.round((Date.now()-A.current)/1e3):0;x(e);let t=H.current-e;Q(t),e>0&&e%30==0&&I.current&&fetch("/api/voice/end",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({voice_session_id:I.current,seconds:e,latido:!0}),keepalive:!0}).catch(()=>{}),t<=0&&!D.current&&(eA({beacon:!1}),f("blocked"),y("cap"),v("La llamada lleg\xf3 a su l\xedmite de tiempo. Todo lo que hablaron qued\xf3 guardado â al cerrar te dejo en esa conversaci\xf3n."))},1e3);return()=>clearInterval(e)},[m]),(0,a.useEffect)(()=>{null==p||p({estado:m,error:h,silenciado:w})},[m,h,w,p]),(0,a.useEffect)(()=>{if(!d||"blocked"!==m&&"error"!==m)return;let e=setTimeout(async()=>null==t?void 0:t(await ey()),2500);return()=>clearTimeout(e)},[d,m,t]);let eW="".concat(String(Math.floor(b/60)).padStart(2,"0"),":").concat(String(b%60).padStart(2,"0")),eF="blocked"===m||"error"===m,eV="speaking"===m?"Openauto est\xe1 hablandoâ¦":"thinking"===m?"Buscando en la baseâ¦":"active"===m?w?"Micr\xf3fono en pausa":"Te escuchoâ¦":"";return(0,n.jsxs)("div",{className:d?"fixed left-0 top-0 h-px w-px overflow-hidden opacity-0 pointer-events-none":"fixed inset-0 z-[120] flex flex-col items-center justify-between bg-ink-950/95 backdrop-blur-xl safe-top safe-bottom px-6 pt-8 pb-10","aria-hidden":d||void 0,children:[(0,n.jsx)("audio",{ref:P,autoPlay:!0,className:"hidden"}),(0,n.jsx)("div",{className:"h-6 text-[13px] font-medium text-slate-300",children:eV}),(0,n.jsx)("div",{className:"flex-1 grid place-items-center w-full",children:eF?(0,n.jsxs)("div",{className:"text-center max-w-xs",children:[(0,n.jsx)("div",{className:"mx-auto mb-4 grid place-items-center h-12 w-12 rounded-2xl bg-white/5 ring-1 ring-white/10 text-slate-400",children:(0,n.jsx)(o.A.Chat,{size:22,strokeWidth:1.6})}),(0,n.jsx)("p",{className:"text-[15px] text-slate-200 leading-relaxed",children:h}),"blocked"===m&&"tier"===g&&l&&(0,n.jsx)("button",{type:"button",onClick:()=>{l(),null==t||t()},className:"mt-6 rounded-full bg-ember-400 hover:bg-ember-300 text-ink-950 font-semibold px-6 py-2.5 text-[14px] transition",children:"Ver plan Pro"}),"blocked"===m&&"cap"===g&&(0,n.jsx)("button",{type:"button",onClick:eB,className:"mt-6 rounded-full bg-ember-400 hover:bg-ember-300 text-ink-950 font-semibold px-6 py-2.5 text-[14px] transition",children:"Ver la conversaci\xf3n"})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center w-full max-w-lg",children:[(0,n.jsxs)("div",{className:"relative grid place-items-center",children:[(0,n.jsx)("canvas",{ref:V,style:{width:340,height:340,maxWidth:"78vw",maxHeight:"78vw"},"aria-hidden":"true"}),(0,n.jsx)("div",{className:"absolute -bottom-5 text-[13px] font-mono tracking-wide",children:"connecting"===m?(0,n.jsx)("span",{className:"text-slate-500",children:"Conectandoâ¦"}):null!=Y&&Y<=60?(0,n.jsxs)("span",{className:"text-ember-300",children:[eW," \xb7 quedan ",Math.max(0,Y),"s de llamada"]}):(0,n.jsx)("span",{className:"text-slate-500",children:eW})})]}),(0,n.jsxs)("div",{className:"mt-9 w-full px-2 min-h-[3.5rem] flex flex-col items-center gap-2 text-center",children:[k&&(0,n.jsxs)("div",{className:"w-full shrink-0",children:[(0,n.jsx)("span",{className:"text-[10px] uppercase tracking-[0.15em] text-ember-400/70",children:"Entend\xed"}),(0,n.jsxs)("p",{className:"text-[13.5px] leading-snug text-slate-400 italic line-clamp-2",children:["â",k,"â"]}
1)]}),j&&(0,n.jsx)("div",{ref:T,className:"w-full max-h-[32vh] overflow-y-auto px-1 text-[15px] leading-relaxed text-slate-100 [scrollbar-width:thin] [scrollbar-color:rgba(245,166,35,0.35)_transparent]",children:j}),!j&&"thinking"===m&&(0,n.jsx)("p",{className:"text-[14px] text-ember-300/80",children:"Buscando en la baseâ¦"})]})]})}),(0,n.jsxs)("div",{className:"flex items-center gap-6",children:[!eF&&"connecting"!==m&&(0,n.jsx)("button",{type:"button",onClick:function(){var e,t;let r=!w;((null==(t=M.current)||null==(e=t.getAudioTracks)?void 0:e.call(t))||[]).forEach(e=>{e.enabled=!r}),_(r)},"aria-label":w?"Reactivar micr\xf3fono":"Silenciar micr\xf3fono",className:"grid place-items-center h-14 w-14 rounded-full transition ".concat(w?"bg-red-500/20 ring-1 ring-red-400/40 text-red-300":"bg-white/10 text-slate-200 hover:bg-white/15"),children:(0,n.jsxs)("span",{className:"relative inline-grid place-items-center",children:[(0,n.jsx)(o.A.Mic,{size:22,strokeWidth:2}),w&&(0,n.jsx)("span",{className:"absolute h-[2px] w-[28px] rotate-45 rounded bg-current","aria-hidden":"true"})]})}),(0,n.jsx)("button",{type:"button",onClick:eB,"aria-label":"Terminar",className:"grid place-items-center h-16 w-16 rounded-full bg-red-500 hover:bg-red-400 text-white transition shadow-[0_10px_30px_-8px_rgba(0,0,0,0.6)]",children:(0,n.jsx)(o.A.X,{size:26,strokeWidth:2.4})})]})]})}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.