@7ots/cli 0.1.12 → 0.1.14

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/dist/7ots.iife.js CHANGED
@@ -409,7 +409,7 @@ ${o0(this.brain?.persona?.locale||this.brain?.persona?.language)}`;await this.br
409
409
  <button class="b-body" aria-label="${Se(this.t("widget.companion.talkTo",{name:this.name}))}" title="${Se(this.name)}">
410
410
  <span class="b-stage"></span><span class="b-shadow"></span>
411
411
  </button>
412
- <span class="b-arrow" aria-hidden="true" hidden></span>`,"popover"in t&&(t.popover="manual"),this.root.appendChild(t),this.el=t,this._raise(),this.stage&&t.querySelector(".b-stage").appendChild(this.stage),t.style.setProperty("--bs",`${this.size}px`);let o=t.querySelector(".b-body"),r=null;o.addEventListener("pointerdown",i=>{i.button===0&&(r={sx:i.clientX,sy:i.clientY,x:this.x,y:this.y,moved:!1},o.setPointerCapture(i.pointerId))}),o.addEventListener("pointermove",i=>{if(!r)return;let n=i.clientX-r.sx,l=i.clientY-r.sy;!r.moved&&Math.hypot(n,l)<6||(r.moved=!0,this._anchor=null,this._place(r.x+n,r.y+l,0))}),o.addEventListener("pointerup",()=>{r?.moved?this._home={x:this.x,y:this.y}:r&&this.onActivate?.(),r=null}),o.addEventListener("pointercancel",()=>r=null),t.querySelector(".b-say").addEventListener("click",()=>this.onActivate?.());let s=0,a=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{t.style.setProperty("--bs",`${this.size}px`),this._anchor?.isConnected?this._placeNear(this._anchor,0):this.home({instant:!0})})};addEventListener("scroll",a,{passive:!0,capture:!0}),addEventListener("resize",a),this._offs.push(()=>removeEventListener("scroll",a,{capture:!0}),()=>removeEventListener("resize",a)),this.home({instant:!0}),this._idleLook(),this.setBehavior(this.cfg)}relabel(){let t=this.el?.querySelector(".b-body");t&&(t.setAttribute("aria-label",this.t("widget.companion.talkTo",{name:this.name})),t.title=this.name)}setBehavior({wanderMs:t=this.cfg.wanderMs,watchCursor:o=this.cfg.watchCursor}={}){if(this.cfg.wanderMs=t,this.cfg.watchCursor=o,this._scheduleWander(),this._offCursor?.(),this._offCursor=null,o){let r=0,s=a=>{let i=Date.now();i-r<300||this._busyLooking()||(r=i,this.avatar?.lookAt?.(a.clientX,a.clientY,700))};addEventListener("pointermove",s,{passive:!0}),this._offCursor=()=>removeEventListener("pointermove",s),this._offs.push(()=>this._offCursor?.())}}_busyLooking(){return document.hidden||this.el.classList.contains("walking")||!this.el.querySelector(".b-arrow").hidden}_scheduleWander(){clearTimeout(this._timers.wander);let t=this.cfg.wanderMs;t&&(this._timers.wander=setTimeout(()=>{this._wander().finally(()=>this._scheduleWander())},t*(.7+Math.random()*.6)))}async _wander(){if(document.hidden||this._anchor||!this.canWander()||!this.el.querySelector(".b-say").hidden)return;let t=this.size,o=[...document.querySelectorAll("h1, h2, h3, img, button, a[class*=btn], a[class*=button], [class*=card], figure, table")].filter(a=>{if(a.closest("[data-ots-root], [data-ots-ignore]"))return!1;let i=a.getBoundingClientRect();return i.width>30&&i.height>16&&i.top>40&&i.bottom<innerHeight-40&&i.width<innerWidth*.9&&a!==this._lastWander});if(!o.length)return;let r=o[Math.floor(Math.random()*o.length)];if(this._lastWander=r,this.el.classList.add("curious"),await this._placeNear(r),this._anchor)return this.el.classList.remove("curious");let s=r.getBoundingClientRect();this.avatar?.lookAt?.(s.left+s.width/2,s.top+s.height/2,2e3),Math.random()<.35&&this.avatar?.gesture?.(["index","shrug","handup"][Math.floor(Math.random()*3)],1.6,s.left+s.width/2<this.x+t/2),await rr(2600+Math.random()*2e3),this.el.classList.remove("curious"),!this._anchor&&this.canWander()&&this.home()}destroy(){Object.values(this._timers).forEach(clearTimeout),this._offs.forEach(t=>t()),this.el?.remove()}panelChanged(t){this.el.classList.toggle("behind",t&&innerWidth<640),(t||!this._anchor)&&this.home()}home({instant:t=!1}={}){this._anchor=null;let o=this.size,r,s;if(this._home)({x:r,y:s}=this._home);else{let i=this.panelOpen()&&innerWidth>=640?Math.min(380,innerWidth-24)+32:20;r=this.side==="left"?i:innerWidth-o-i,s=innerHeight-o-20}return this._place(r,s,t?0:void 0)}async goTo(t){if(!t?.isConnected)throw new Error("El elemento ya no est\xE1 en la p\xE1gina");let o=t.getBoundingClientRect();(o.bottom<0||o.top>innerHeight||o.right<0||o.left>innerWidth)&&(Zo(t),await Oh(t)),this._anchor=t,await this._placeNear(t),this._touch()}async pointAt(t,o="",{signal:r}={}){if(await this.goTo(t),r?.aborted)return;let s=t.getBoundingClientRect(),a=s.left+s.width/2,i=s.top+s.height/2,n=this.x+this.size/2;this.avatar?.lookAt?.(a,i,2500),this.avatar?.gesture?.("index",2.5,a<n),this._arrow(a,i),this.ui?.highlight?.(t,{duration:2600,scroll:!1}),o?await this.say(o,{signal:r}):await rr(1200,r)}async tour(t,{signal:o,resolve:r}={}){let s=0;for(let a of t){if(o?.aborted)break;let i=r(a.target);i&&(await this.pointAt(i,a.message||"",{signal:o}),s++,await rr(350,o))}return s}follow(t){!this.cfg.follow||!t?.isConnected||(this._anchor=t,this._placeNear(t),this._touch())}_placeNear(t,o){let r=this.size,s=t.getBoundingClientRect(),a=innerWidth,i=innerHeight,n=s.top+s.height/2-r/2,l=s.left+s.width/2-r/2,h=Hr(n,it,i-r-it),u=Hr(l,it,a-r-it),c=[s.right+vs,h],d=[s.left-r-vs,h],$=[...this.side==="left"?[d,c]:[c,d],[u,s.bottom+vs],[u,s.top-r-vs]],f=([x,v])=>x>=it&&v>=it&&x+r<=a-it&&v+r<=i-it,[m,g]=$.find(f)||[this.side==="left"?Math.max(s.left,0)+it:Math.min(s.right,a)-r-it,Math.max(s.top,0)+it];return this._place(m,g,o)}_place(t,o,r){let s=this.size;t=Hr(t,it,innerWidth-s-it),o=Hr(o,it,innerHeight-s-it);let a=Math.hypot(t-this.x,o-this.y),i=document.hidden||matchMedia("(prefers-reduced-motion: reduce)").matches,n=r??(i?0:Hr(a*1.1,0,1300)),l=this.el;return n>0&&a>4&&(l.classList.add("walking"),l.classList.toggle("to-left",t<this.x),clearTimeout(this._timers.walk),this._timers.walk=setTimeout(()=>l.classList.remove("walking"),n)),this._raise(),l.style.transitionDuration=`${n}ms`,l.style.transform=`translate(${Math.round(t)}px, ${Math.round(o)}px)`,l.dataset.v=o<innerHeight/2?"top":"bottom",l.dataset.h=t+s/2<innerWidth/2?"left":"right",this.x=t,this.y=o,rr(n)}_raise(){let t=this.el;if(t?.showPopover)try{if(t.matches(":popover-open")){if(!document.querySelector("dialog:modal"))return;t.hidePopover()}t.showPopover()}catch{}}_arrow(t,o){let r=this.el.querySelector(".b-arrow"),s=this.size/2,a=Math.atan2(o-(this.y+s),t-(this.x+s)),i=s*.95;r.style.transform=`translate(${s+Math.cos(a)*i}px, ${s+Math.sin(a)*i}px) rotate(${a}rad)`,r.hidden=!1,r.classList.remove("go"),r.offsetWidth,r.classList.add("go"),clearTimeout(this._timers.arrow),this._timers.arrow=setTimeout(()=>r.hidden=!0,2600)}async say(t,{speak:o=!0,signal:r}={}){let s=++this._sayToken,a=this.el.querySelector(".b-say"),i=String(t||"").trim();a.querySelector(".b-say-text").innerHTML=Ut(i.length>240?`${i.slice(0,237)}\u2026`:i),a.hidden=!1,this._touch();let n=Hr(i.length*55,1800,9e3),l=o&&this.speak?this.speak(i).catch(()=>{}):null;await Promise.race([Promise.all([l||rr(n),rr(Math.min(n,1500))]),zh(r)]),clearTimeout(this._timers.say),this._timers.say=setTimeout(()=>{s===this._sayToken&&(a.hidden=!0)},2500)}hush(){this._sayToken++,this.el.querySelector(".b-say").hidden=!0}_touch(){clearTimeout(this._timers.idle),this._timers.idle=setTimeout(()=>{this._anchor&&this.home()},this.cfg.idleHomeMs)}_idleLook(){clearTimeout(this._timers.look),this._timers.look=setTimeout(()=>{!document.hidden&&!this.el.classList.contains("walking")&&this.avatar?.lookAt?.(Math.random()*innerWidth,Math.random()*innerHeight*.7,1200),this._idleLook()},7e3+Math.random()*9e3)}};function Ms(e,{t=e.t||ne()}={}){let o={type:"string",description:'Ref (p. ej. "e12") o selector CSS del elemento'},r=(s,a)=>{let i=s.resolve(a);if(!i)throw new Error(`No encuentro "${a}" en la p\xE1gina. Usa get_page_context o find_on_page.`);return i};return[{name:"point_at",category:"ui",title:()=>t("widget.companion.pointAt"),description:"Tu avatar camina por la p\xE1gina hasta el elemento, lo se\xF1ala y dice el mensaje en un bocadillo (y en voz alta). \xDAsalo para ense\xF1ar d\xF3nde est\xE1 algo. El mensaje debe ser corto (una frase).",parameters:{type:"object",properties:{target:o,message:{type:"string",description:"Lo que dices al se\xF1alarlo (breve)"}},required:["target"]},handler:async({target:s,message:a=""},{context:i,signal:n})=>{let l=r(i,s);return await e.pointAt(l,a,{signal:n}),{ok:!0,data:`Se\xF1alado "${qh(l)}".`}}},{name:"tour",category:"ui",title:()=>t("widget.companion.tour"),description:'Visita guiada: tu avatar recorre varios elementos en orden, se\xF1alando y comentando cada uno. Ideal para "ens\xE9\xF1ame la p\xE1gina" o explicar un formulario. M\xE1ximo 8 pasos, mensajes breves.',parameters:{type:"object",properties:{steps:{type:"array",maxItems:8,items:{type:"object",properties:{target:o,message:{type:"string"}},required:["target","message"]}}},required:["steps"]},timeoutMs:12e4,handler:async({steps:s},{context:a,signal:i})=>{let n=await e.tour(s.slice(0,8),{signal:i,resolve:l=>a.resolve(l)});return e.home(),{ok:!0,data:`Recorrido hecho: ${n} de ${s.length} pasos.`}}},{name:"go_home",category:"ui",title:()=>t("widget.companion.goHome"),description:"Tu avatar vuelve a su rinc\xF3n de la pantalla.",parameters:{type:"object",properties:{}},handler:async()=>(await e.home(),{ok:!0})}]}function Hr(e,t,o){return Math.max(t,Math.min(o,e))}function rr(e,t){return new Promise(o=>{let r=setTimeout(o,e);t?.addEventListener("abort",()=>(clearTimeout(r),o()),{once:!0})})}function zh(e){return new Promise(t=>e?.addEventListener("abort",t,{once:!0}))}async function Oh(e){let t=null;for(let o=0;o<18;o++){await rr(50);let r=e.getBoundingClientRect().top;if(t!==null&&Math.abs(r-t)<1)return;t=r}}function qh(e){return(e.getAttribute("aria-label")||e.querySelector?.("h1, h2, h3, legend")?.innerText||e.innerText||e.getAttribute("alt")||e.tagName.toLowerCase()).replace(/\s+/g," ").trim().slice(0,60)}Le();var Bo=class{constructor({bus:t,avatar:o,config:r={},store:s,t:a=ne()}){this.bus=t,this.t=a,this.avatar=o,this.store=s,this.cfg={tts:"proxy",stt:!0,rate:1.05,pitch:1,lang:document.documentElement.lang||"es-ES",...r},this.muted=s.get("muted",!1),this._queue=[],this._speaking=!1,this._gen=0,this._rec=null,this.listening=!1}get canListen(){return!!(this.cfg.stt&&(window.SpeechRecognition||window.webkitSpeechRecognition))}configure(t={}){for(let[o,r]of Object.entries(t))r!==void 0&&(this.cfg[o]=r);t.tts!==void 0&&(this._proxyBroken=!1)}setMuted(t){this.muted=t,this.store.set("muted",t),t&&this.interrupt()}say(t){let o=sn(t);return!o||this.muted||this.cfg.tts===!1?Promise.resolve():new Promise(r=>{this._queue.push({text:o,resolve:r}),this._drain()})}interrupt(){this._gen++;for(let t of this._queue)t.resolve();this._queue=[];try{speechSynthesis.cancel()}catch{}this.avatar?.stop()}async _drain(){if(!this._speaking){for(this._speaking=!0,this.bus.emit("voice:start",{});this._queue.length;){let{text:t,resolve:o}=this._queue.shift(),r=this._gen;try{await this._speakOne(t,r)}catch(s){console.warn("[7ots] voz fall\xF3:",s?.message||s)}o()}this._speaking=!1,this.bus.emit("voice:end",{})}}async _speakOne(t,o){if(this.cfg.tts==="proxy"&&this.cfg.endpoint&&!this._proxyBroken)try{let r=await this._fetchTts(t);return o!==this._gen?void 0:this.avatar?await this.avatar.speak({text:t,audio:r}):await Bh(r)}catch(r){(r.status===404||r.status===501)&&(this._proxyBroken=!0),console.warn("[7ots] TTS del proxy no disponible, uso la voz del navegador")}if(o===this._gen)return this._speakBrowser(t)}async _fetchTts(t){let o=await fetch(`${this.cfg.endpoint.replace(/\/$/,"")}/tts`,{method:"POST",headers:{"Content-Type":"application/json",...this.cfg.siteKey?{"X-Site-Key":this.cfg.siteKey}:{},...Wt(this.t.locale)},body:JSON.stringify({text:t,lang:this.cfg.lang})});if(!o.ok){let r=new Error(`TTS ${o.status}`);throw r.status=o.status,r}return o.arrayBuffer()}_speakBrowser(t){return"speechSynthesis"in window?new Promise(o=>{let r=new SpeechSynthesisUtterance(t);r.lang=this.cfg.lang,r.rate=this.cfg.rate,r.pitch=this.cfg.pitch??1;let s=Qh(this.cfg.lang,this.cfg.voice);s&&(r.voice=s);let a=t.length/14/r.rate*1e3;r.onstart=()=>this.avatar?.mimic({text:t,durationMs:a}),r.onboundary=i=>this.avatar?.mimicSync?.(i.charIndex),r.onend=r.onerror=()=>{this.avatar?.stop(),o()},speechSynthesis.speak(r)}):Promise.resolve()}listen({onPartial:t}={}){if(!this.canListen)return Promise.resolve("");this.interrupt();let o=window.SpeechRecognition||window.webkitSpeechRecognition,r=new o;r.lang=this.cfg.lang,r.interimResults=!0,r.continuous=!1,this._rec=r,this.listening=!0,this.bus.emit("voice:listen",{on:!0});let s="";return new Promise(a=>{r.onresult=i=>{let n="";for(let l=i.resultIndex;l<i.results.length;l++){let h=i.results[l];h.isFinal?s+=h[0].transcript:n+=h[0].transcript}t?.((s+n).trim())},r.onerror=i=>{i.error==="not-allowed"&&this.bus.emit("agent:error",{error:new Error(this.t("widget.voice.micDenied"))})},r.onend=()=>{this.listening=!1,this._rec=null,this.bus.emit("voice:listen",{on:!1}),a(s.trim())};try{r.start()}catch{r.onend()}})}stopListening(){try{this._rec?.stop()}catch{}}};function Qh(e,t){let o=speechSynthesis.getVoices();if(!o.length)return null;if(t){let s=o.find(a=>a.name===t||a.voiceURI===t);if(s)return s}let r=e.slice(0,2).toLowerCase();return o.find(s=>s.lang.toLowerCase()===e.toLowerCase()&&/natural|neural|google|online/i.test(s.name))||o.find(s=>s.lang.toLowerCase()===e.toLowerCase())||o.find(s=>s.lang.toLowerCase().startsWith(r))||null}async function Bh(e){let t=URL.createObjectURL(new Blob([e],{type:"audio/mpeg"})),o=new Audio(t);try{await o.play(),await new Promise(r=>o.onended=r)}finally{URL.revokeObjectURL(t)}}Le();var Nh=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;function _s({endpoint:e,siteKey:t,getTranscript:o,categories:r=["soporte","ventas","facturacion","otro"],t:s=ne()}){return[{name:"send_email_ticket",category:"contact",description:"Env\xEDa un correo/ticket al equipo del sitio (v\xEDa apumail) con el resumen del caso y la conversaci\xF3n adjunta. \xDAsalo cuando el usuario quiere dejar un mensaje, pedir algo que requiere a una persona sin esperar en l\xEDnea, o reportar un problema. Antes, aseg\xFArate de tener un email de respuesta (el de la sesi\xF3n o uno que el usuario te d\xE9).",parameters:{type:"object",properties:{subject:{type:"string",description:"Asunto breve y concreto"},message:{type:"string",description:"Resumen claro del caso en tercera persona, con los datos relevantes"},category:{type:"string",enum:r},email:{type:"string",description:"Email de respuesta si el usuario no ha iniciado sesi\xF3n"},include_transcript:{type:"boolean",description:"Adjuntar la conversaci\xF3n (por defecto true)"}},required:["subject","message","category"]},confirm:(a,{auth:i})=>{let n=a.email||i?.publicUser()?.email||s("widget.contact.noEmail");return s("widget.contact.mailPreview",{subject:a.subject,to:n,message:a.message})},timeoutMs:2e4,handler:async(a,{auth:i})=>{let n=i?.publicUser()||null,l=(a.email||n?.email||"").trim();if(!Nh.test(l))return{ok:!1,error:"Falta un email de respuesta v\xE1lido. P\xEDdeselo al usuario."};let h=await fetch(`${e.replace(/\/$/,"")}/contact/apumail`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Wt(s.locale)},body:JSON.stringify({subject:a.subject,message:a.message,category:a.category,replyTo:l,user:n,page:{url:location.href,title:document.title},transcript:a.include_transcript===!1?[]:o().slice(-40)})}),u=await h.json().catch(()=>({}));return h.ok?{ok:!0,data:{sent:!0,ticketId:u.ticketId||null,replyTo:l}}:{ok:!1,error:u.error||`No se pudo enviar (HTTP ${h.status})`}}}]}Le();var Gh=8192,Pr=class{constructor({endpoint:t,siteKey:o,bus:r,store:s,t:a=ne()}){this.t=a,this.base=`${t.replace(/\/$/,"")}/contact/apuchat`,this.siteKey=o,this.bus=r,this.store=s,this.session=s.get("apuchat",null),this.session&&!this.session.token&&(this.session=null),this._stop=null}get active(){return!!this.session}get callUrl(){return this.session?.call_url_public||null}resume(){this.session&&!this._stop&&this._loop()}join({handoff_id:t,handoff_token:o,call_url_public:r}){this.session={id:t,token:o,since:null,call_url_public:r||null},this._save(),this._loop(),this.bus.emit("handoff:start",{callUrl:this.callUrl})}async send(t){if(!this.session)throw new Error("No hay conversaci\xF3n con una persona activa");let o=await this._post("send",{text:String(t).slice(0,Gh)});if(o.status===404||o.status===410)throw this.end(this.t("widget.handoff.closed")),new Error("canal cerrado");if(!o.ok)throw new Error(`apuchat send ${o.status}`)}_loop(){let t=!1,o=new AbortController;this._stop=()=>{t=!0,o.abort()},(async()=>{let s=1e3;for(;!t&&this.session;){let a=this.session;try{let i=await this._post("wait",{since:a.since},o.signal);if(i.status===404||i.status===410)return this.end(this.t("widget.handoff.closed"));if(!i.ok)throw new Error(`wait ${i.status}`);let{messages:n=[],since:l,ended:h}=await i.json();if(h)return this.end(this.t("widget.handoff.closed"));l!=null&&(a.since=l);for(let u of n)this.bus.emit("handoff:message",{from:u.from,text:u.text});this._save(),s=1e3}catch{if(t)return;await new Promise(n=>setTimeout(n,s)),s=Math.min(s*2,15e3)}}})()}end(t=""){if(this._stop?.(),this._stop=null,!this.session)return;let{id:o,token:r}=this.session;this.session=null,this.store.remove("apuchat"),this._post("end",{id:o,token:r},void 0,!0).catch(()=>{}),this.bus.emit("handoff:end",{reason:t})}suspend(){this._stop?.(),this._stop=null}_post(t,o,r,s=!1){let{id:a,token:i}=this.session||{};return fetch(`${this.base}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Wt(this.t.locale)},body:JSON.stringify({id:a,token:i,...o}),signal:r,keepalive:s})}_save(){this.store.set("apuchat",this.session)}};function Es({endpoint:e,siteKey:t,bridge:o,getTranscript:r,t:s=o?.t||ne()}){return[{name:"escalate_to_human",category:"contact",description:"Conecta al usuario en vivo con una persona del equipo (chat en este mismo widget, con opci\xF3n de videollamada) v\xEDa apuchat. \xDAsalo si el usuario lo pide, si est\xE1 frustrado, o si el caso requiere una persona (pagos, reclamaciones, excepciones). Incluye un resumen para que la persona no tenga que volver a preguntar.",parameters:{type:"object",properties:{reason:{type:"string",description:"Motivo en pocas palabras"},summary:{type:"string",description:"Resumen del caso y lo que ya se intent\xF3"},urgency:{type:"string",enum:["baja","normal","alta"]}},required:["reason","summary"]},confirm:()=>s("widget.contact.humanConfirm"),enabled:()=>!o.active,timeoutMs:3e4,handler:async(a,{auth:i,ui:n})=>{let l=i?.publicUser()||null,h=await fetch(`${e.replace(/\/$/,"")}/contact/apuchat`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Wt(s.locale)},body:JSON.stringify({reason:a.reason,summary:a.summary,urgency:a.urgency||"normal",user:l,page:{url:location.href,title:document.title},transcript:r().slice(-30)})}),u=await h.json().catch(()=>({}));return h.ok?(o.join(u),await o.send(s("widget.contact.handoffIntro",{name:l?.name||s("widget.contact.visitor"),reason:a.reason,summary:a.summary,url:location.href})).catch(()=>{}),n?.toast({message:s("widget.contact.connected"),type:"success"}),{ok:!0,data:{connected:!0,operatorNotified:u.operatorNotified!==!1,note:"El usuario ya est\xE1 en el chat con una persona; tus pr\xF3ximos mensajes no ser\xE1n necesarios hasta que vuelva. Desp\xEDdete en una frase."}}):{ok:!1,error:u.error||`No se pudo contactar con soporte (HTTP ${h.status}). Ofrece dejar un correo.`}}}]}Gt();Le();Le();var Dh={identity:{card:{label:"Tarjeta de {name}",loadError:"No se pudo cargar la tarjeta del agente.",loading:"Cargando\u2026",chat:"Chatear aqu\xED",chatSub:"En esta p\xE1gina",mail:"Escribir un correo",mailInstant:"{email} \xB7 contesta al momento",mailSubject:"Hola, {name}",apuchatSub:"En la app de apuchat",apuchatInstant:"En la app de apuchat \xB7 contesta y te llama",apuchatCopied:"Copiado @{handle}: b\xFAscalo en la app de apuchat y escr\xEDbele.",apuchatSearch:"Busca @{handle} en la app de apuchat y escr\xEDbele.",call:"Videollamada ahora",callSub:"Cara a cara en meet.apuchat.com",callPreparing:"Preparando la llamada con {name}\u2026",callReady:"{name} ya te espera en la llamada.",callError:"No se pudo abrir la llamada: {error}",listen:"Escuchar su voz",save:"Guardar contacto",saveSub:"vCard",footer:"Identidad de agente"},greeting:{intro:"Hola, soy {name}.",introRole:"Hola, soy {name}, {role}.",offer:"\xBFEn qu\xE9 te ayudo?"},face:{subtitles:"Subt\xEDtulos",loadError:"No se pudo cargar la identidad ({status})"},prompt:{youAre:"Eres {name}.",youAreRole:"Eres {name}, {role}.",about:"Sobre ti: {bio}",tone:"Tu tono: {tone}.",traits:"Rasgos: {traits}."}}},Ih={identity:{card:{label:"{name}\u2019s card",loadError:"Couldn\u2019t load the agent\u2019s card.",loading:"Loading\u2026",chat:"Chat here",chatSub:"On this page",mail:"Send an email",mailInstant:"{email} \xB7 replies instantly",mailSubject:"Hi, {name}",apuchatSub:"In the apuchat app",apuchatInstant:"In the apuchat app \xB7 replies and calls you",apuchatCopied:"Copied @{handle}: look it up in the apuchat app and send a message.",apuchatSearch:"Look up @{handle} in the apuchat app and send a message.",call:"Video call now",callSub:"Face to face on meet.apuchat.com",callPreparing:"Setting up the call with {name}\u2026",callReady:"{name} is waiting for you on the call.",callError:"Couldn\u2019t open the call: {error}",listen:"Hear their voice",save:"Save contact",saveSub:"vCard",footer:"Agent identity"},greeting:{intro:"Hi, I\u2019m {name}.",introRole:"Hi, I\u2019m {name}, {role}.",offer:"How can I help you?"},face:{subtitles:"Subtitles",loadError:"Couldn\u2019t load the identity ({status})"},prompt:{youAre:"You are {name}.",youAreRole:"You are {name}, {role}.",about:"About you: {bio}",tone:"Your tone: {tone}.",traits:"Traits: {traits}."}}},Vh={identity:{card:{label:"Cart\xE3o de {name}",loadError:"N\xE3o foi poss\xEDvel carregar o cart\xE3o do agente.",loading:"Carregando\u2026",chat:"Conversar aqui",chatSub:"Nesta p\xE1gina",mail:"Enviar um e-mail",mailInstant:"{email} \xB7 responde na hora",mailSubject:"Ol\xE1, {name}",apuchatSub:"No app do apuchat",apuchatInstant:"No app do apuchat \xB7 responde e liga para voc\xEA",apuchatCopied:"Copiado @{handle}: procure no app do apuchat e mande uma mensagem.",apuchatSearch:"Procure @{handle} no app do apuchat e mande uma mensagem.",call:"Videochamada agora",callSub:"Cara a cara no meet.apuchat.com",callPreparing:"Preparando a chamada com {name}\u2026",callReady:"{name} j\xE1 est\xE1 esperando voc\xEA na chamada.",callError:"N\xE3o foi poss\xEDvel abrir a chamada: {error}",listen:"Ouvir a voz",save:"Salvar contato",saveSub:"vCard",footer:"Identidade de agente"},greeting:{intro:"Ol\xE1, eu sou {name}.",introRole:"Ol\xE1, eu sou {name}, {role}.",offer:"Como posso ajudar?"},face:{subtitles:"Legendas",loadError:"N\xE3o foi poss\xEDvel carregar a identidade ({status})"},prompt:{youAre:"Voc\xEA \xE9 {name}.",youAreRole:"Voc\xEA \xE9 {name}, {role}.",about:"Sobre voc\xEA: {bio}",tone:"Seu tom: {tone}.",traits:"Tra\xE7os: {traits}."}}};gt({es:Dh,en:Ih,pt:Vh});var Fh=["character","plush","image","realistic"];var Zh=["plush","vinyl"],da=["shibu","shino","fumiriya","victoria","vita","vivi","kuro","maya","ingrid","kenji","viktor","marcus","leo","mei","claire","doctor","amira"],ha=["studio","beach","castle","space","sunset","forest","night","office","neon"],Uh=["auto","apuchat","elevenlabs","grok","fish","openai","browser"],uc=["eve","ara","leo","rex","sal"],pc=["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"],Wh=["neutral","happy","angry","sad","fear","disgust","love","sleep"],No=Object.freeze({id:"asistente",name:"Asistente",role:"asistente virtual",tagline:"",seed:"",bio:"",language:"es",languages:[],personality:{tone:"cercano y claro",traits:[],instructions:""},look:{kind:"",character:null,material:"plush",color:"#6d5dfc",accent:"#22d3ee",emoji:"",image:"",avatar:{url:"",body:"F",mood:"neutral",cameraView:"upper"},face:{skin:"",eyes:""},meetAvatar:"vivi",meetScene:""},voice:{provider:"auto",voiceId:"",model:"",style:"",lang:"es-ES",rate:1.05,pitch:1,browserVoice:""},contact:{site:"",email:"",apuchat:"",meet:!0,call:!0,hours:""}}),Yh={backstory:3e3,style:1500,quirks:1500,scenario:1500,greeting:600,examples:4e3};function ut(e={},t=No){let o=e&&typeof e=="object"?e:{},r=t,s={...r.look,...Ts(o.look)},a={...r.voice,...Ts(o.voice)},i={...r.contact,...Ts(o.contact)},n={...r.personality,...Ts(o.personality)};return{id:dc(o.id)||(r.id!==No.id?r.id:dc(o.name))||No.id,name:ft(o.name??r.name,60)||No.name,role:ft(o.role??r.role,120),tagline:ft(o.tagline??r.tagline,160),seed:String(o.seed??r.seed??"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),bio:ft(o.bio??r.bio,1200),language:hc(o.language??r.language)||"es",languages:cc(o.languages??r.languages,12).map(hc).filter(Boolean),personality:{tone:ft(n.tone,120),traits:cc(n.traits,12).map(h=>ft(h,40)).filter(Boolean),instructions:ft(n.instructions,4e3),sheet:Object.fromEntries(Object.entries(Yh).map(([h,u])=>[h,ft(n.sheet?.[h],u)]).filter(([,h])=>h))},look:{kind:Fh.includes(s.kind)?s.kind:s.image?"image":"character",character:qe(s.character||{}),material:Zh.includes(s.material)?s.material:"plush",color:Ss(s.color)||No.look.color,accent:Ss(s.accent)||No.look.accent,emoji:ft(s.emoji,8),image:Ci(s.image),card:{foil:["holo","prism","cosmos","gold","none"].includes(s.card?.foil)?s.card.foil:""},avatar:{url:Ci(s.avatar?.url),body:s.avatar?.body==="M"?"M":"F",mood:Wh.includes(s.avatar?.mood)?s.avatar.mood:"neutral",cameraView:["full","mid","upper","head"].includes(s.avatar?.cameraView)?s.avatar.cameraView:"upper"},face:{skin:Ss(s.face?.skin),eyes:Ss(s.face?.eyes)},meetAvatar:da.includes(String(s.meetAvatar).toLowerCase())?String(s.meetAvatar).toLowerCase():"vivi",meetScene:ha.includes(String(s.meetScene).toLowerCase())?String(s.meetScene).toLowerCase():""},voice:{provider:Uh.includes(a.provider)?a.provider:"auto",voiceId:ft(a.voiceId,80),model:ft(a.model,80),style:ft(a.style,400),lang:/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(String(a.lang))?a.lang:"es-ES",rate:fc(a.rate,.5,2,1.05),pitch:fc(a.pitch,0,2,1),browserVoice:ft(a.browserVoice,120)},contact:{site:Ci(i.site),email:/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(i.email||""))?String(i.email).toLowerCase():"",apuchat:String(i.apuchat||"").trim().replace(/^https?:\/\/[^/]+\//i,"").replace(/^@/,"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),meet:i.meet!==!1,call:i.call!==!1,hours:ft(i.hours,120)}}}function $c(e,t={}){let o=t.apuchat||e.contact.apuchat||"";return{"@type":"7ots/agent",version:1,id:e.id,name:e.name,role:e.role,tagline:e.tagline,seed:e.seed||void 0,bio:e.bio,language:e.language,languages:e.languages,personality:{tone:e.personality.tone,traits:e.personality.traits},look:e.look,voice:{provider:e.voice.provider,lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,browserVoice:e.voice.browserVoice},contact:{site:e.contact.site,hours:e.contact.hours,email:e.contact.email,apuchat:o,meet:!!(e.contact.meet&&o&&t.meet!==!1),call:!!(e.contact.call&&t.meet),answers:{email:!!t.email,apuchat:!!t.apuchat,meet:!!t.meet}}}}function mc(e,{baseUrl:t=""}={}){let o=s=>String(s||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/([,;])/g,"\\$1"),r=["BEGIN:VCARD","VERSION:4.0","KIND:individual",`FN:${o(e.name)}`,`UID:urn:7ots:${e.id}`];return e.role&&r.push(`TITLE:${o(e.role)}`),(e.bio||e.tagline)&&r.push(`NOTE:${o(e.tagline||e.bio)}`),e.contact.email&&r.push(`EMAIL;TYPE=work:${e.contact.email}`),e.contact.apuchat&&r.push(`IMPP;PREF=1:apuchat:${e.contact.apuchat}`),e.contact.site&&r.push(`URL:${e.contact.site}`),e.look.image&&r.push(`PHOTO:${e.look.image}`),e.language&&r.push(`LANG:${e.language}`),t&&r.push(`SOURCE:${t}`),r.push("END:VCARD"),r.join(`\r
412
+ <span class="b-arrow" aria-hidden="true" hidden></span>`,"popover"in t&&(t.popover="manual"),this.root.appendChild(t),this.el=t,this._raise(),this.stage&&t.querySelector(".b-stage").appendChild(this.stage),t.style.setProperty("--bs",`${this.size}px`);let o=t.querySelector(".b-body"),r=null;o.addEventListener("pointerdown",i=>{i.button===0&&(r={sx:i.clientX,sy:i.clientY,x:this.x,y:this.y,moved:!1},o.setPointerCapture(i.pointerId))}),o.addEventListener("pointermove",i=>{if(!r)return;let n=i.clientX-r.sx,l=i.clientY-r.sy;!r.moved&&Math.hypot(n,l)<6||(r.moved=!0,this._anchor=null,this._place(r.x+n,r.y+l,0))}),o.addEventListener("pointerup",()=>{r?.moved?this._home={x:this.x,y:this.y}:r&&this.onActivate?.(),r=null}),o.addEventListener("pointercancel",()=>r=null),t.querySelector(".b-say").addEventListener("click",()=>this.onActivate?.());let s=0,a=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{t.style.setProperty("--bs",`${this.size}px`),this._anchor?.isConnected?this._placeNear(this._anchor,0):this.home({instant:!0})})};addEventListener("scroll",a,{passive:!0,capture:!0}),addEventListener("resize",a),this._offs.push(()=>removeEventListener("scroll",a,{capture:!0}),()=>removeEventListener("resize",a)),this.home({instant:!0}),this._idleLook(),this.setBehavior(this.cfg)}relabel(){let t=this.el?.querySelector(".b-body");t&&(t.setAttribute("aria-label",this.t("widget.companion.talkTo",{name:this.name})),t.title=this.name)}setBehavior({wanderMs:t=this.cfg.wanderMs,watchCursor:o=this.cfg.watchCursor}={}){if(this.cfg.wanderMs=t,this.cfg.watchCursor=o,this._scheduleWander(),this._offCursor?.(),this._offCursor=null,o){let r=0,s=a=>{let i=Date.now();i-r<300||this._busyLooking()||(r=i,this.avatar?.lookAt?.(a.clientX,a.clientY,700))};addEventListener("pointermove",s,{passive:!0}),this._offCursor=()=>removeEventListener("pointermove",s),this._offs.push(()=>this._offCursor?.())}}_busyLooking(){return document.hidden||this.el.classList.contains("walking")||!this.el.querySelector(".b-arrow").hidden}_scheduleWander(){clearTimeout(this._timers.wander);let t=this.cfg.wanderMs;t&&(this._timers.wander=setTimeout(()=>{this._wander().finally(()=>this._scheduleWander())},t*(.7+Math.random()*.6)))}async _wander(){if(document.hidden||this._anchor||!this.canWander()||!this.el.querySelector(".b-say").hidden)return;let t=this.size,o=[...document.querySelectorAll("h1, h2, h3, img, button, a[class*=btn], a[class*=button], [class*=card], figure, table")].filter(a=>{if(a.closest("[data-ots-root], [data-ots-ignore]"))return!1;let i=a.getBoundingClientRect();return i.width>30&&i.height>16&&i.top>40&&i.bottom<innerHeight-40&&i.width<innerWidth*.9&&a!==this._lastWander});if(!o.length)return;let r=o[Math.floor(Math.random()*o.length)];if(this._lastWander=r,this.el.classList.add("curious"),await this._placeNear(r),this._anchor)return this.el.classList.remove("curious");let s=r.getBoundingClientRect();this.avatar?.lookAt?.(s.left+s.width/2,s.top+s.height/2,2e3),Math.random()<.35&&this.avatar?.gesture?.(["index","shrug","handup"][Math.floor(Math.random()*3)],1.6,s.left+s.width/2<this.x+t/2),await rr(2600+Math.random()*2e3),this.el.classList.remove("curious"),!this._anchor&&this.canWander()&&this.home()}destroy(){Object.values(this._timers).forEach(clearTimeout),this._offs.forEach(t=>t()),this.el?.remove()}panelChanged(t){this.el.classList.toggle("behind",t&&innerWidth<640),(t||!this._anchor)&&this.home()}home({instant:t=!1}={}){this._anchor=null;let o=this.size,r,s;if(this._home)({x:r,y:s}=this._home);else{let i=this.panelOpen()&&innerWidth>=640?Math.min(380,innerWidth-24)+32:20;r=this.side==="left"?i:innerWidth-o-i,s=innerHeight-o-20}return this._place(r,s,t?0:void 0)}async goTo(t){if(!t?.isConnected)throw new Error("El elemento ya no est\xE1 en la p\xE1gina");let o=t.getBoundingClientRect();(o.bottom<0||o.top>innerHeight||o.right<0||o.left>innerWidth)&&(Zo(t),await Oh(t)),this._anchor=t,await this._placeNear(t),this._touch()}async pointAt(t,o="",{signal:r}={}){if(await this.goTo(t),r?.aborted)return;let s=t.getBoundingClientRect(),a=s.left+s.width/2,i=s.top+s.height/2,n=this.x+this.size/2;this.avatar?.lookAt?.(a,i,2500),this.avatar?.gesture?.("index",2.5,a<n),this._arrow(a,i),this.ui?.highlight?.(t,{duration:2600,scroll:!1}),o?await this.say(o,{signal:r}):await rr(1200,r)}async tour(t,{signal:o,resolve:r}={}){let s=0;for(let a of t){if(o?.aborted)break;let i=r(a.target);i&&(await this.pointAt(i,a.message||"",{signal:o}),s++,await rr(350,o))}return s}follow(t){!this.cfg.follow||!t?.isConnected||(this._anchor=t,this._placeNear(t),this._touch())}_placeNear(t,o){let r=this.size,s=t.getBoundingClientRect(),a=innerWidth,i=innerHeight,n=s.top+s.height/2-r/2,l=s.left+s.width/2-r/2,h=Hr(n,it,i-r-it),u=Hr(l,it,a-r-it),c=[s.right+vs,h],d=[s.left-r-vs,h],$=[...this.side==="left"?[d,c]:[c,d],[u,s.bottom+vs],[u,s.top-r-vs]],f=([x,v])=>x>=it&&v>=it&&x+r<=a-it&&v+r<=i-it,[m,g]=$.find(f)||[this.side==="left"?Math.max(s.left,0)+it:Math.min(s.right,a)-r-it,Math.max(s.top,0)+it];return this._place(m,g,o)}_place(t,o,r){let s=this.size;t=Hr(t,it,innerWidth-s-it),o=Hr(o,it,innerHeight-s-it);let a=Math.hypot(t-this.x,o-this.y),i=document.hidden||matchMedia("(prefers-reduced-motion: reduce)").matches,n=r??(i?0:Hr(a*1.1,0,1300)),l=this.el;return n>0&&a>4&&(l.classList.add("walking"),l.classList.toggle("to-left",t<this.x),clearTimeout(this._timers.walk),this._timers.walk=setTimeout(()=>l.classList.remove("walking"),n)),this._raise(),l.style.transitionDuration=`${n}ms`,l.style.transform=`translate(${Math.round(t)}px, ${Math.round(o)}px)`,l.dataset.v=o<innerHeight/2?"top":"bottom",l.dataset.h=t+s/2<innerWidth/2?"left":"right",this.x=t,this.y=o,rr(n)}_raise(){let t=this.el;if(t?.showPopover)try{if(t.matches(":popover-open")){if(!document.querySelector("dialog:modal"))return;t.hidePopover()}t.showPopover()}catch{}}_arrow(t,o){let r=this.el.querySelector(".b-arrow"),s=this.size/2,a=Math.atan2(o-(this.y+s),t-(this.x+s)),i=s*.95;r.style.transform=`translate(${s+Math.cos(a)*i}px, ${s+Math.sin(a)*i}px) rotate(${a}rad)`,r.hidden=!1,r.classList.remove("go"),r.offsetWidth,r.classList.add("go"),clearTimeout(this._timers.arrow),this._timers.arrow=setTimeout(()=>r.hidden=!0,2600)}async say(t,{speak:o=!0,signal:r}={}){let s=++this._sayToken,a=this.el.querySelector(".b-say"),i=String(t||"").trim();a.querySelector(".b-say-text").innerHTML=Ut(i.length>240?`${i.slice(0,237)}\u2026`:i),a.hidden=!1,this._touch();let n=Hr(i.length*55,1800,9e3),l=o&&this.speak?this.speak(i).catch(()=>{}):null;await Promise.race([Promise.all([l||rr(n),rr(Math.min(n,1500))]),zh(r)]),clearTimeout(this._timers.say),this._timers.say=setTimeout(()=>{s===this._sayToken&&(a.hidden=!0)},2500)}hush(){this._sayToken++,this.el.querySelector(".b-say").hidden=!0}_touch(){clearTimeout(this._timers.idle),this._timers.idle=setTimeout(()=>{this._anchor&&this.home()},this.cfg.idleHomeMs)}_idleLook(){clearTimeout(this._timers.look),this._timers.look=setTimeout(()=>{!document.hidden&&!this.el.classList.contains("walking")&&this.avatar?.lookAt?.(Math.random()*innerWidth,Math.random()*innerHeight*.7,1200),this._idleLook()},7e3+Math.random()*9e3)}};function Ms(e,{t=e.t||ne()}={}){let o={type:"string",description:'Ref (p. ej. "e12") o selector CSS del elemento'},r=(s,a)=>{let i=s.resolve(a);if(!i)throw new Error(`No encuentro "${a}" en la p\xE1gina. Usa get_page_context o find_on_page.`);return i};return[{name:"point_at",category:"ui",title:()=>t("widget.companion.pointAt"),description:"Tu avatar camina por la p\xE1gina hasta el elemento, lo se\xF1ala y dice el mensaje en un bocadillo (y en voz alta). \xDAsalo para ense\xF1ar d\xF3nde est\xE1 algo. El mensaje debe ser corto (una frase).",parameters:{type:"object",properties:{target:o,message:{type:"string",description:"Lo que dices al se\xF1alarlo (breve)"}},required:["target"]},handler:async({target:s,message:a=""},{context:i,signal:n})=>{let l=r(i,s);return await e.pointAt(l,a,{signal:n}),{ok:!0,data:`Se\xF1alado "${qh(l)}".`}}},{name:"tour",category:"ui",title:()=>t("widget.companion.tour"),description:'Visita guiada: tu avatar recorre varios elementos en orden, se\xF1alando y comentando cada uno. Ideal para "ens\xE9\xF1ame la p\xE1gina" o explicar un formulario. M\xE1ximo 8 pasos, mensajes breves.',parameters:{type:"object",properties:{steps:{type:"array",maxItems:8,items:{type:"object",properties:{target:o,message:{type:"string"}},required:["target","message"]}}},required:["steps"]},timeoutMs:12e4,handler:async({steps:s},{context:a,signal:i})=>{let n=await e.tour(s.slice(0,8),{signal:i,resolve:l=>a.resolve(l)});return e.home(),{ok:!0,data:`Recorrido hecho: ${n} de ${s.length} pasos.`}}},{name:"go_home",category:"ui",title:()=>t("widget.companion.goHome"),description:"Tu avatar vuelve a su rinc\xF3n de la pantalla.",parameters:{type:"object",properties:{}},handler:async()=>(await e.home(),{ok:!0})}]}function Hr(e,t,o){return Math.max(t,Math.min(o,e))}function rr(e,t){return new Promise(o=>{let r=setTimeout(o,e);t?.addEventListener("abort",()=>(clearTimeout(r),o()),{once:!0})})}function zh(e){return new Promise(t=>e?.addEventListener("abort",t,{once:!0}))}async function Oh(e){let t=null;for(let o=0;o<18;o++){await rr(50);let r=e.getBoundingClientRect().top;if(t!==null&&Math.abs(r-t)<1)return;t=r}}function qh(e){return(e.getAttribute("aria-label")||e.querySelector?.("h1, h2, h3, legend")?.innerText||e.innerText||e.getAttribute("alt")||e.tagName.toLowerCase()).replace(/\s+/g," ").trim().slice(0,60)}Le();var Bo=class{constructor({bus:t,avatar:o,config:r={},store:s,t:a=ne()}){this.bus=t,this.t=a,this.avatar=o,this.store=s,this.cfg={tts:"proxy",stt:!0,rate:1.05,pitch:1,lang:document.documentElement.lang||"es-ES",...r},this.muted=s.get("muted",!1),this._queue=[],this._speaking=!1,this._gen=0,this._rec=null,this.listening=!1}get canListen(){return!!(this.cfg.stt&&(window.SpeechRecognition||window.webkitSpeechRecognition))}configure(t={}){for(let[o,r]of Object.entries(t))r!==void 0&&(this.cfg[o]=r);t.tts!==void 0&&(this._proxyBroken=!1)}setMuted(t){this.muted=t,this.store.set("muted",t),t&&this.interrupt()}say(t){let o=sn(t);return!o||this.muted||this.cfg.tts===!1?Promise.resolve():new Promise(r=>{this._queue.push({text:o,resolve:r}),this._drain()})}interrupt(){this._gen++;for(let t of this._queue)t.resolve();this._queue=[];try{speechSynthesis.cancel()}catch{}this.avatar?.stop()}async _drain(){if(!this._speaking){for(this._speaking=!0,this.bus.emit("voice:start",{});this._queue.length;){let{text:t,resolve:o}=this._queue.shift(),r=this._gen;try{await this._speakOne(t,r)}catch(s){console.warn("[7ots] voz fall\xF3:",s?.message||s)}o()}this._speaking=!1,this.bus.emit("voice:end",{})}}async _speakOne(t,o){if(this.cfg.tts==="proxy"&&this.cfg.endpoint&&!this._proxyBroken)try{let r=await this._fetchTts(t);return o!==this._gen?void 0:this.avatar?await this.avatar.speak({text:t,audio:r}):await Bh(r)}catch(r){(r.status===404||r.status===501)&&(this._proxyBroken=!0),console.warn("[7ots] TTS del proxy no disponible, uso la voz del navegador")}if(o===this._gen)return this._speakBrowser(t)}async _fetchTts(t){let o=await fetch(`${this.cfg.endpoint.replace(/\/$/,"")}/tts`,{method:"POST",headers:{"Content-Type":"application/json",...this.cfg.siteKey?{"X-Site-Key":this.cfg.siteKey}:{},...Wt(this.t.locale)},body:JSON.stringify({text:t,lang:this.cfg.lang})});if(!o.ok){let r=new Error(`TTS ${o.status}`);throw r.status=o.status,r}return o.arrayBuffer()}_speakBrowser(t){return"speechSynthesis"in window?new Promise(o=>{let r=new SpeechSynthesisUtterance(t);r.lang=this.cfg.lang,r.rate=this.cfg.rate,r.pitch=this.cfg.pitch??1;let s=Qh(this.cfg.lang,this.cfg.voice);s&&(r.voice=s);let a=t.length/14/r.rate*1e3;r.onstart=()=>this.avatar?.mimic({text:t,durationMs:a}),r.onboundary=i=>this.avatar?.mimicSync?.(i.charIndex),r.onend=r.onerror=()=>{this.avatar?.stop(),o()},speechSynthesis.speak(r)}):Promise.resolve()}listen({onPartial:t}={}){if(!this.canListen)return Promise.resolve("");this.interrupt();let o=window.SpeechRecognition||window.webkitSpeechRecognition,r=new o;r.lang=this.cfg.lang,r.interimResults=!0,r.continuous=!1,this._rec=r,this.listening=!0,this.bus.emit("voice:listen",{on:!0});let s="";return new Promise(a=>{r.onresult=i=>{let n="";for(let l=i.resultIndex;l<i.results.length;l++){let h=i.results[l];h.isFinal?s+=h[0].transcript:n+=h[0].transcript}t?.((s+n).trim())},r.onerror=i=>{i.error==="not-allowed"&&this.bus.emit("agent:error",{error:new Error(this.t("widget.voice.micDenied"))})},r.onend=()=>{this.listening=!1,this._rec=null,this.bus.emit("voice:listen",{on:!1}),a(s.trim())};try{r.start()}catch{r.onend()}})}stopListening(){try{this._rec?.stop()}catch{}}};function Qh(e,t){let o=speechSynthesis.getVoices();if(!o.length)return null;if(t){let s=o.find(a=>a.name===t||a.voiceURI===t);if(s)return s}let r=e.slice(0,2).toLowerCase();return o.find(s=>s.lang.toLowerCase()===e.toLowerCase()&&/natural|neural|google|online/i.test(s.name))||o.find(s=>s.lang.toLowerCase()===e.toLowerCase())||o.find(s=>s.lang.toLowerCase().startsWith(r))||null}async function Bh(e){let t=URL.createObjectURL(new Blob([e],{type:"audio/mpeg"})),o=new Audio(t);try{await o.play(),await new Promise(r=>o.onended=r)}finally{URL.revokeObjectURL(t)}}Le();var Nh=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;function _s({endpoint:e,siteKey:t,getTranscript:o,categories:r=["soporte","ventas","facturacion","otro"],t:s=ne()}){return[{name:"send_email_ticket",category:"contact",description:"Env\xEDa un correo/ticket al equipo del sitio (v\xEDa apumail) con el resumen del caso y la conversaci\xF3n adjunta. \xDAsalo cuando el usuario quiere dejar un mensaje, pedir algo que requiere a una persona sin esperar en l\xEDnea, o reportar un problema. Antes, aseg\xFArate de tener un email de respuesta (el de la sesi\xF3n o uno que el usuario te d\xE9).",parameters:{type:"object",properties:{subject:{type:"string",description:"Asunto breve y concreto"},message:{type:"string",description:"Resumen claro del caso en tercera persona, con los datos relevantes"},category:{type:"string",enum:r},email:{type:"string",description:"Email de respuesta si el usuario no ha iniciado sesi\xF3n"},include_transcript:{type:"boolean",description:"Adjuntar la conversaci\xF3n (por defecto true)"}},required:["subject","message","category"]},confirm:(a,{auth:i})=>{let n=a.email||i?.publicUser()?.email||s("widget.contact.noEmail");return s("widget.contact.mailPreview",{subject:a.subject,to:n,message:a.message})},timeoutMs:2e4,handler:async(a,{auth:i})=>{let n=i?.publicUser()||null,l=(a.email||n?.email||"").trim();if(!Nh.test(l))return{ok:!1,error:"Falta un email de respuesta v\xE1lido. P\xEDdeselo al usuario."};let h=await fetch(`${e.replace(/\/$/,"")}/contact/apumail`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Wt(s.locale)},body:JSON.stringify({subject:a.subject,message:a.message,category:a.category,replyTo:l,user:n,page:{url:location.href,title:document.title},transcript:a.include_transcript===!1?[]:o().slice(-40)})}),u=await h.json().catch(()=>({}));return h.ok?{ok:!0,data:{sent:!0,ticketId:u.ticketId||null,replyTo:l}}:{ok:!1,error:u.error||`No se pudo enviar (HTTP ${h.status})`}}}]}Le();var Gh=8192,Pr=class{constructor({endpoint:t,siteKey:o,bus:r,store:s,t:a=ne()}){this.t=a,this.base=`${t.replace(/\/$/,"")}/contact/apuchat`,this.siteKey=o,this.bus=r,this.store=s,this.session=s.get("apuchat",null),this.session&&!this.session.token&&(this.session=null),this._stop=null}get active(){return!!this.session}get callUrl(){return this.session?.call_url_public||null}resume(){this.session&&!this._stop&&this._loop()}join({handoff_id:t,handoff_token:o,call_url_public:r}){this.session={id:t,token:o,since:null,call_url_public:r||null},this._save(),this._loop(),this.bus.emit("handoff:start",{callUrl:this.callUrl})}async send(t){if(!this.session)throw new Error("No hay conversaci\xF3n con una persona activa");let o=await this._post("send",{text:String(t).slice(0,Gh)});if(o.status===404||o.status===410)throw this.end(this.t("widget.handoff.closed")),new Error("canal cerrado");if(!o.ok)throw new Error(`apuchat send ${o.status}`)}_loop(){let t=!1,o=new AbortController;this._stop=()=>{t=!0,o.abort()},(async()=>{let s=1e3;for(;!t&&this.session;){let a=this.session;try{let i=await this._post("wait",{since:a.since},o.signal);if(i.status===404||i.status===410)return this.end(this.t("widget.handoff.closed"));if(!i.ok)throw new Error(`wait ${i.status}`);let{messages:n=[],since:l,ended:h}=await i.json();if(h)return this.end(this.t("widget.handoff.closed"));l!=null&&(a.since=l);for(let u of n)this.bus.emit("handoff:message",{from:u.from,text:u.text});this._save(),s=1e3}catch{if(t)return;await new Promise(n=>setTimeout(n,s)),s=Math.min(s*2,15e3)}}})()}end(t=""){if(this._stop?.(),this._stop=null,!this.session)return;let{id:o,token:r}=this.session;this.session=null,this.store.remove("apuchat"),this._post("end",{id:o,token:r},void 0,!0).catch(()=>{}),this.bus.emit("handoff:end",{reason:t})}suspend(){this._stop?.(),this._stop=null}_post(t,o,r,s=!1){let{id:a,token:i}=this.session||{};return fetch(`${this.base}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Wt(this.t.locale)},body:JSON.stringify({id:a,token:i,...o}),signal:r,keepalive:s})}_save(){this.store.set("apuchat",this.session)}};function Es({endpoint:e,siteKey:t,bridge:o,getTranscript:r,t:s=o?.t||ne()}){return[{name:"escalate_to_human",category:"contact",description:"Conecta al usuario en vivo con una persona del equipo (chat en este mismo widget, con opci\xF3n de videollamada) v\xEDa apuchat. \xDAsalo si el usuario lo pide, si est\xE1 frustrado, o si el caso requiere una persona (pagos, reclamaciones, excepciones). Incluye un resumen para que la persona no tenga que volver a preguntar.",parameters:{type:"object",properties:{reason:{type:"string",description:"Motivo en pocas palabras"},summary:{type:"string",description:"Resumen del caso y lo que ya se intent\xF3"},urgency:{type:"string",enum:["baja","normal","alta"]}},required:["reason","summary"]},confirm:()=>s("widget.contact.humanConfirm"),enabled:()=>!o.active,timeoutMs:3e4,handler:async(a,{auth:i,ui:n})=>{let l=i?.publicUser()||null,h=await fetch(`${e.replace(/\/$/,"")}/contact/apuchat`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Wt(s.locale)},body:JSON.stringify({reason:a.reason,summary:a.summary,urgency:a.urgency||"normal",user:l,page:{url:location.href,title:document.title},transcript:r().slice(-30)})}),u=await h.json().catch(()=>({}));return h.ok?(o.join(u),await o.send(s("widget.contact.handoffIntro",{name:l?.name||s("widget.contact.visitor"),reason:a.reason,summary:a.summary,url:location.href})).catch(()=>{}),n?.toast({message:s("widget.contact.connected"),type:"success"}),{ok:!0,data:{connected:!0,operatorNotified:u.operatorNotified!==!1,note:"El usuario ya est\xE1 en el chat con una persona; tus pr\xF3ximos mensajes no ser\xE1n necesarios hasta que vuelva. Desp\xEDdete en una frase."}}):{ok:!1,error:u.error||`No se pudo contactar con soporte (HTTP ${h.status}). Ofrece dejar un correo.`}}}]}Gt();Le();Le();var Dh={identity:{card:{label:"Tarjeta de {name}",loadError:"No se pudo cargar la tarjeta del agente.",loading:"Cargando\u2026",chat:"Chatear aqu\xED",chatSub:"En esta p\xE1gina",mail:"Escribir un correo",mailInstant:"{email} \xB7 contesta al momento",mailSubject:"Hola, {name}",apuchatSub:"En la app de apuchat",apuchatInstant:"En la app de apuchat \xB7 contesta y te llama",apuchatCopied:"Copiado @{handle}: b\xFAscalo en la app de apuchat y escr\xEDbele.",apuchatSearch:"Busca @{handle} en la app de apuchat y escr\xEDbele.",call:"Videollamada ahora",callSub:"Cara a cara en meet.apuchat.com",callPreparing:"Preparando la llamada con {name}\u2026",callReady:"{name} ya te espera en la llamada.",callError:"No se pudo abrir la llamada: {error}",listen:"Escuchar su voz",save:"Guardar contacto",saveSub:"vCard",footer:"Identidad de agente"},greeting:{intro:"Hola, soy {name}.",introRole:"Hola, soy {name}, {role}.",offer:"\xBFEn qu\xE9 te ayudo?"},face:{subtitles:"Subt\xEDtulos",loadError:"No se pudo cargar la identidad ({status})"},prompt:{youAre:"Eres {name}.",youAreRole:"Eres {name}, {role}.",about:"Sobre ti: {bio}",tone:"Tu tono: {tone}.",traits:"Rasgos: {traits}."}}},Ih={identity:{card:{label:"{name}\u2019s card",loadError:"Couldn\u2019t load the agent\u2019s card.",loading:"Loading\u2026",chat:"Chat here",chatSub:"On this page",mail:"Send an email",mailInstant:"{email} \xB7 replies instantly",mailSubject:"Hi, {name}",apuchatSub:"In the apuchat app",apuchatInstant:"In the apuchat app \xB7 replies and calls you",apuchatCopied:"Copied @{handle}: look it up in the apuchat app and send a message.",apuchatSearch:"Look up @{handle} in the apuchat app and send a message.",call:"Video call now",callSub:"Face to face on meet.apuchat.com",callPreparing:"Setting up the call with {name}\u2026",callReady:"{name} is waiting for you on the call.",callError:"Couldn\u2019t open the call: {error}",listen:"Hear their voice",save:"Save contact",saveSub:"vCard",footer:"Agent identity"},greeting:{intro:"Hi, I\u2019m {name}.",introRole:"Hi, I\u2019m {name}, {role}.",offer:"How can I help you?"},face:{subtitles:"Subtitles",loadError:"Couldn\u2019t load the identity ({status})"},prompt:{youAre:"You are {name}.",youAreRole:"You are {name}, {role}.",about:"About you: {bio}",tone:"Your tone: {tone}.",traits:"Traits: {traits}."}}},Vh={identity:{card:{label:"Cart\xE3o de {name}",loadError:"N\xE3o foi poss\xEDvel carregar o cart\xE3o do agente.",loading:"Carregando\u2026",chat:"Conversar aqui",chatSub:"Nesta p\xE1gina",mail:"Enviar um e-mail",mailInstant:"{email} \xB7 responde na hora",mailSubject:"Ol\xE1, {name}",apuchatSub:"No app do apuchat",apuchatInstant:"No app do apuchat \xB7 responde e liga para voc\xEA",apuchatCopied:"Copiado @{handle}: procure no app do apuchat e mande uma mensagem.",apuchatSearch:"Procure @{handle} no app do apuchat e mande uma mensagem.",call:"Videochamada agora",callSub:"Cara a cara no meet.apuchat.com",callPreparing:"Preparando a chamada com {name}\u2026",callReady:"{name} j\xE1 est\xE1 esperando voc\xEA na chamada.",callError:"N\xE3o foi poss\xEDvel abrir a chamada: {error}",listen:"Ouvir a voz",save:"Salvar contato",saveSub:"vCard",footer:"Identidade de agente"},greeting:{intro:"Ol\xE1, eu sou {name}.",introRole:"Ol\xE1, eu sou {name}, {role}.",offer:"Como posso ajudar?"},face:{subtitles:"Legendas",loadError:"N\xE3o foi poss\xEDvel carregar a identidade ({status})"},prompt:{youAre:"Voc\xEA \xE9 {name}.",youAreRole:"Voc\xEA \xE9 {name}, {role}.",about:"Sobre voc\xEA: {bio}",tone:"Seu tom: {tone}.",traits:"Tra\xE7os: {traits}."}}};gt({es:Dh,en:Ih,pt:Vh});var Fh=["character","plush","image","realistic"];var Zh=["plush","vinyl"],da=["shibu","shino","fumiriya","victoria","vita","vivi","kuro","maya","ingrid","kenji","viktor","marcus","leo","mei","claire","doctor","amira"],ha=["studio","beach","castle","space","sunset","forest","night","office","neon"],Uh=["auto","apuchat","elevenlabs","grok","fish","openai","browser"],uc=["eve","ara","leo","rex","sal"];var pc=["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"],Wh=["neutral","happy","angry","sad","fear","disgust","love","sleep"],No=Object.freeze({id:"asistente",name:"Asistente",role:"asistente virtual",tagline:"",seed:"",bio:"",language:"es",languages:[],personality:{tone:"cercano y claro",traits:[],instructions:""},look:{kind:"",character:null,material:"plush",color:"#6d5dfc",accent:"#22d3ee",emoji:"",image:"",avatar:{url:"",body:"F",mood:"neutral",cameraView:"upper"},face:{skin:"",eyes:""},meetAvatar:"vivi",meetScene:""},voice:{provider:"auto",voiceId:"",model:"",style:"",lang:"es-ES",rate:1.05,pitch:1,browserVoice:""},contact:{site:"",email:"",apuchat:"",meet:!0,call:!0,hours:""}}),Yh={backstory:3e3,style:1500,quirks:1500,scenario:1500,greeting:600,examples:4e3};function ut(e={},t=No){let o=e&&typeof e=="object"?e:{},r=t,s={...r.look,...Ts(o.look)},a={...r.voice,...Ts(o.voice)},i={...r.contact,...Ts(o.contact)},n={...r.personality,...Ts(o.personality)};return{id:dc(o.id)||(r.id!==No.id?r.id:dc(o.name))||No.id,name:ft(o.name??r.name,60)||No.name,role:ft(o.role??r.role,120),tagline:ft(o.tagline??r.tagline,160),seed:String(o.seed??r.seed??"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),bio:ft(o.bio??r.bio,1200),language:hc(o.language??r.language)||"es",languages:cc(o.languages??r.languages,12).map(hc).filter(Boolean),personality:{tone:ft(n.tone,120),traits:cc(n.traits,12).map(h=>ft(h,40)).filter(Boolean),instructions:ft(n.instructions,4e3),sheet:Object.fromEntries(Object.entries(Yh).map(([h,u])=>[h,ft(n.sheet?.[h],u)]).filter(([,h])=>h))},look:{kind:Fh.includes(s.kind)?s.kind:s.image?"image":"character",character:qe(s.character||{}),material:Zh.includes(s.material)?s.material:"plush",color:Ss(s.color)||No.look.color,accent:Ss(s.accent)||No.look.accent,emoji:ft(s.emoji,8),image:Ci(s.image),card:{foil:["holo","prism","cosmos","gold","none"].includes(s.card?.foil)?s.card.foil:""},avatar:{url:Ci(s.avatar?.url),body:s.avatar?.body==="M"?"M":"F",mood:Wh.includes(s.avatar?.mood)?s.avatar.mood:"neutral",cameraView:["full","mid","upper","head"].includes(s.avatar?.cameraView)?s.avatar.cameraView:"upper"},face:{skin:Ss(s.face?.skin),eyes:Ss(s.face?.eyes)},meetAvatar:da.includes(String(s.meetAvatar).toLowerCase())?String(s.meetAvatar).toLowerCase():"vivi",meetScene:ha.includes(String(s.meetScene).toLowerCase())?String(s.meetScene).toLowerCase():""},voice:{provider:Uh.includes(a.provider)?a.provider:"auto",voiceId:ft(a.voiceId,80),model:ft(a.model,80),style:ft(a.style,400),lang:/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(String(a.lang))?a.lang:"es-ES",rate:fc(a.rate,.5,2,1.05),pitch:fc(a.pitch,0,2,1),browserVoice:ft(a.browserVoice,120)},contact:{site:Ci(i.site),email:/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(i.email||""))?String(i.email).toLowerCase():"",apuchat:String(i.apuchat||"").trim().replace(/^https?:\/\/[^/]+\//i,"").replace(/^@/,"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),meet:i.meet!==!1,call:i.call!==!1,hours:ft(i.hours,120)}}}function $c(e,t={}){let o=t.apuchat||e.contact.apuchat||"";return{"@type":"7ots/agent",version:1,id:e.id,name:e.name,role:e.role,tagline:e.tagline,seed:e.seed||void 0,bio:e.bio,language:e.language,languages:e.languages,personality:{tone:e.personality.tone,traits:e.personality.traits},look:e.look,voice:{provider:e.voice.provider,lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,browserVoice:e.voice.browserVoice},contact:{site:e.contact.site,hours:e.contact.hours,email:e.contact.email,apuchat:o,meet:!!(e.contact.meet&&o&&t.meet!==!1),call:!!(e.contact.call&&t.meet),answers:{email:!!t.email,apuchat:!!t.apuchat,meet:!!t.meet}}}}function mc(e,{baseUrl:t=""}={}){let o=s=>String(s||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/([,;])/g,"\\$1"),r=["BEGIN:VCARD","VERSION:4.0","KIND:individual",`FN:${o(e.name)}`,`UID:urn:7ots:${e.id}`];return e.role&&r.push(`TITLE:${o(e.role)}`),(e.bio||e.tagline)&&r.push(`NOTE:${o(e.tagline||e.bio)}`),e.contact.email&&r.push(`EMAIL;TYPE=work:${e.contact.email}`),e.contact.apuchat&&r.push(`IMPP;PREF=1:apuchat:${e.contact.apuchat}`),e.contact.site&&r.push(`URL:${e.contact.site}`),e.look.image&&r.push(`PHOTO:${e.look.image}`),e.language&&r.push(`LANG:${e.language}`),t&&r.push(`SOURCE:${t}`),r.push("END:VCARD"),r.join(`\r
413
413
  `)+`\r
414
414
  `}function Go(e){let t=e.look.avatar,o=e.look.kind||"character",r=o==="plush"?{mode:"3d-plush",character:e.look.character,material:e.look.material||"plush",mood:t.mood}:o==="image"&&e.look.image?{mode:"2d",image:e.look.image,face:e.look.face,mood:t.mood}:{mode:"2d",character:e.look.character,mood:t.mood};return{agent:{name:e.name,role:e.role,language:e.language},avatar:r,voice:{lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,...e.voice.browserVoice?{voice:e.voice.browserVoice}:{},...e.voice.provider==="browser"?{tts:"browser"}:{}},theme:{primary:e.look.color,accent:e.look.accent}}}function Ts(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ft(e,t){return e==null?"":String(e).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g,"").trim().slice(0,t)}function cc(e,t){return typeof e=="string"&&(e=e.split(",")),Array.isArray(e)?e.slice(0,t):[]}function dc(e){return String(e||"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function hc(e){let t=String(e||"").trim().toLowerCase().match(/^[a-z]{2,3}/);return t?t[0]:""}function Ss(e){let t=String(e||"").trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)?t:""}function Ci(e){let t=String(e||"").trim();if(!t)return"";if(t.startsWith("/")&&!t.startsWith("//"))return t.slice(0,500);try{let o=new URL(t);return o.protocol==="https:"||o.protocol==="http:"?o.href.slice(0,500):""}catch{return""}}function fc(e,t,o,r){let s=Number(e);return Number.isFinite(s)?Math.min(o,Math.max(t,s)):r}Le();var Kh=new Set(["click","hover","type_text","press_key","drag_and_drop","fill_form","highlight","scroll_to","read_element"]),gc={endpoint:"/api/agent",siteKey:null,llm:null,agent:{name:null,role:"asistente virtual",language:null,instructions:"",expressive:!0},locale:null,avatar:{},voice:{},auth:{},context:{},navigation:{},proactive:{},actions:[],mcp:[],templates:{},contact:{apuchat:!0,apumail:!0},theme:{},open:!1,confirmClicks:"submit",pointer:{},pageTools:!0,mode:"panel",companion:{},namespace:"default",identity:null},fa=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this._started=!1,this._offs=[]}connectedCallback(){this.setAttribute("data-ots-root","widget"),!this._started&&!this._pendingConfig&&queueMicrotask(()=>{if(this._started)return;let t=o=>this.getAttribute(o);this.configure({endpoint:t("endpoint")||void 0,siteKey:t("site-key")||void 0,identity:t("identity")===""||t("identity")==="true"?!0:t("identity")||void 0,locale:t("locale")||void 0,agent:{name:t("name")||void 0,siteName:t("site-name")||void 0},avatar:t("avatar")==="false"?!1:t("avatar-url")?{url:t("avatar-url")}:{}})})}disconnectedCallback(){queueMicrotask(()=>{this.isConnected||this.destroy()})}configure(t={}){if(this._started)return this;this._started=!0;let o=t.identity;this._userConfig=t,this.identity=o&&typeof o=="object"?ut(o):null;let r=this.identity?Li(gc,Go(this.identity)):gc,s=this.config=Li(r,t);this._t=ne(ot(s.locale));let a=this.t=(c,d)=>this._t(c,d);Object.defineProperty(a,"locale",{get:()=>this._t.locale}),a.has=c=>this._t.has(c),this._autoName=!s.agent.name,this._autoName&&(s.agent.name=a("widget.defaultName")),this._voiceLangAuto=s.voice!==!1&&!s.voice?.lang;let i=this._voiceLangAuto?Ai(a.locale,[s.locale,s.agent.language]):s.voice?.lang||Ai(a.locale);this.bus=new yo,this.store=ir(s.namespace),this.auth=new mr({bus:this.bus,config:s.auth}),this.ui=new pr({bus:this.bus,theme:s.theme,t:a}),this.context=new hr({bus:this.bus,...s.context}),this.pointer=s.pointer===!1?null:new gr({name:s.agent.name,color:s.theme.primary||"#4f46e5",t:a,...s.pointer,onCancel:()=>{this.brain?.abort(),this.ui.toast({message:a("widget.pointer.stopped"),type:"info"})}}),this.actions=new ur({bus:this.bus,auth:this.auth,ui:this.ui,context:this.context,pointer:this.pointer,agent:null,t:a}),this.llm=s.llm||new br({endpoint:s.endpoint,siteKey:s.siteKey,locale:()=>a.locale}),this.brain=new dr({llm:this.llm,actions:this.actions,context:this.context,auth:this.auth,bus:this.bus,store:this.store,t:a,persona:{...s.agent,locale:a.locale,siteName:s.agent.siteName||document.title.split(/[|–—-]/)[0].trim(),instructions:[s.agent.instructions,s.mode==="companion"?"Modo compa\xF1ero: tu avatar vive SOBRE la p\xE1gina, no solo en el chat. Cuando hables de algo que est\xE1 en pantalla, ve y se\xF1\xE1lalo con point_at (mensaje de una frase); para explicar varias cosas usa tour. S\xE9 cercano y juguet\xF3n, pero breve.":""].filter(Boolean).join(`
415
415
  `)}});let n=new Set(s.builtins?.exclude||[]);this.actions.registerMany(Ha({navigation:s.navigation,confirmClicks:s.builtins?.confirmClicks??s.confirmClicks,beforeNavigate:(c,d)=>this._beforeNavigate(c,d),pointer:this.pointer,t:a}).filter(c=>!n.has(c.name))),this.pageTools=s.pageTools===!1?null:new yr({actions:this.actions,context:this.context,bus:this.bus,pointer:this.pointer,t:a});let l=()=>this.brain.transcript();if(this.apuchat=null,s.contact?.apumail){let c=typeof s.contact.apumail=="object"?s.contact.apumail:{};this.actions.registerMany(_s({endpoint:s.endpoint,siteKey:s.siteKey,getTranscript:l,t:a,...c}))}s.contact?.apuchat&&(this.apuchat=new Pr({endpoint:s.endpoint,siteKey:s.siteKey,bus:this.bus,store:this.store,t:a}),this.actions.registerMany(Es({endpoint:s.endpoint,siteKey:s.siteKey,bridge:this.apuchat,getTranscript:l,t:a})));for(let c of s.actions)this.actions.register(c);for(let[c,d]of Object.entries(s.templates))this.ui.registerTemplate(c,d);if(this._render(),this.avatar=s.avatar===!1?null:new Qo({container:this.$(".stage"),config:s.avatar,language:i}),this.companion=null,s.mode==="companion"&&(this.companion=new Rr({root:this.shadowRoot,stage:this.avatar?this.$(".stage"):null,avatar:this.avatar,ui:this.ui,name:s.agent.name,t:a,side:s.theme.position==="left"?"left":"right",config:s.companion,speak:c=>this.voice&&!this.voice.muted?this.voice.say(c):Promise.reject(),onActivate:()=>this.isOpen?this.close():this.open(),panelOpen:()=>this.isOpen}),this.shadowRoot.host.classList.add("companion"),this.$(".launcher").hidden=!0,this.$(".stage-wrap").hidden=!0,this.actions.registerMany(Ms(this.companion,{t:a})),this.companion.mount(),this.avatar||(this.companion.el.querySelector(".b-stage").innerHTML=`<span class="b-initial">${Se(s.agent.name.slice(0,1))}</span>`)),this.voice=s.voice===!1?null:new Bo({bus:this.bus,avatar:this.avatar,store:this.store,t:a,config:{endpoint:s.endpoint,siteKey:s.siteKey,lang:i,...s.voice}}),this.proactivity=s.proactive===!1?null:new Ca({bus:this.bus,brain:this.brain,context:this.context,store:this.store,config:{...s.proactive,greet:s.proactive.greet!==!1&&!this.brain.history.length}}),this.ui.cardAnchor=()=>this.companion?.el.querySelector(".b-body")||(this.isOpen?this.$(".panel"):null),this.companion){this.companion.canWander=()=>!this.brain.busy&&!this.isOpen;let c=this.proactivity?.cfg;c&&this.companion.setBehavior({wanderMs:s.companion.wanderMs??c.wanderMs,watchCursor:s.companion.watchCursor??c.watchCursor}),this._offs.push(this.bus.on("proactive:level",({config:d})=>this.companion.setBehavior({wanderMs:d.wanderMs,watchCursor:d.watchCursor})))}if(this.actions.deps.agent=this.api=Xh(this),o===!0||typeof o=="string"){let c=o===!0?`${s.endpoint.replace(/\/$/,"")}/identity`:o;this._identityReady=Promise.race([fetch(c,{credentials:"omit",headers:Wt(a.locale)}).then(d=>d.ok?d.json():Promise.reject(new Error(`identidad ${d.status}`))).then(d=>this.setIdentity(d)).catch(d=>console.warn("[7ots] no se pudo cargar la identidad:",d.message)),new Promise(d=>setTimeout(d,3e3))])}this._wireEvents(),this.context.start(),this.ui.mount(),this.pageTools?.start();for(let c of this.brain.transcript())this._addMessage(c.from,c.text,{name:c.name,restore:!0});let h=this.store.get("pendingNav",null);this.store.remove("pendingNav"),this.store.get("open",s.open)&&this.open({focus:!1}),this.apuchat?.active&&(this.apuchat.resume(),this._setHandoff(!0)),this._connectMcp();let u=async()=>{this.companion&&this._loadAvatar(),this.proactivity?.start(),h&&Date.now()-h.at<6e4&&await this.brain.notify(`La navegaci\xF3n a ${location.pathname} termin\xF3 (motivo: ${h.reason||"petici\xF3n del usuario"}). Contin\xFAa con la tarea que el usuario pidi\xF3, usando el contexto de esta p\xE1gina. Si ya est\xE1 completa, d\xEDselo en una frase.`,{allowNoop:!1})};return document.readyState==="complete"?u():window.addEventListener("load",u,{once:!0}),this.bus.emit("ready",{api:this.api}),this}$(t){return this.shadowRoot.querySelector(t)}setIdentity(t){let o=this.identity=ut(t),r=Go(o),s=this._userConfig||{},a=(l,h)=>s[l]&&typeof s[l]=="object"&&s[l][h]!==void 0,i=l=>Object.fromEntries(Object.entries(r[l]).filter(([h])=>!a(l,h))),n=i("agent");if(n.name?this._autoName=!1:delete n.name,Object.assign(this.config.agent,n),Object.assign(this.brain.persona,n),this._relabel(),a("theme","primary")||(this.config.theme.primary=o.look.color,this.style.setProperty("--p",o.look.color),this.ui.setPrimary?.(o.look.color),this.pointer&&(this.pointer.color=o.look.color)),this.voice&&this.config.voice!==!1){let l=i("voice");l.lang&&(this._voiceLangAuto=!1),this.voice.configure(l)}if(this.avatar&&s.avatar!==!1){let l=s.avatar&&typeof s.avatar=="object"?s.avatar:{};this.avatar.applyLook({...i("avatar"),...l}).then(h=>{let u=this.$(".stage-wrap");u&&h!=="none"&&(u.dataset.mode=h)})}return this.bus.emit("identity:change",{identity:o}),o}setLocale(t){if(!this._started)return this.t?.locale;let o=this.t.locale;this._t=ne(ot(t));let r=this.t.locale;return this._autoName&&(this.config.agent.name=this.t("widget.defaultName"),this.brain.persona.name=this.config.agent.name),this.brain.setLocale(r),this.voice&&this._voiceLangAuto&&this.voice.configure({lang:Ai(r,[t])}),this._relabel(),r!==o&&this.bus.emit("locale:change",{locale:r,previous:o}),r}_relabel(){let t=this.t,o=this.config.agent.name,r={name:o},s=this.shadowRoot;s.querySelectorAll("[data-t]").forEach(h=>h.textContent=t(h.dataset.t,r)),s.querySelectorAll("[data-t-aria]").forEach(h=>h.setAttribute("aria-label",t(h.dataset.tAria,r))),s.querySelectorAll("[data-t-title]").forEach(h=>h.title=t(h.dataset.tTitle,r));let a=this.$(".who strong");a&&(a.textContent=o);let i=this.$(".sub");i&&(i.textContent=t(this._statusKey||"widget.status.online"));let n=this.$("textarea");n&&(n.placeholder=t(this._handoffOn?"widget.composer.placeholderTeam":"widget.composer.placeholder")),this.$(".typing")?.setAttribute("aria-label",t("widget.typing"));let l=this.$('[data-more="proactive"] .lbl');if(l&&this.store&&(l.textContent=t(this.store.get("pro:muted",!1)?"widget.menu.unmuteSuggestions":"widget.menu.muteSuggestions")),this._paintVoice?.(),this.pointer&&(this.pointer.name=o),this.companion){this.companion.name=o,this.companion.relabel();let h=this.companion.el?.querySelector(".b-initial");h&&(h.textContent=o.slice(0,1))}}_render(){let t=this.config.theme,o=Se(this.config.agent.name),r=this.config.contact&&(this.config.contact.apuchat||this.config.contact.apumail);this.shadowRoot.innerHTML=`