@fiodos/web-core 0.1.14 → 0.1.17

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.
@@ -1,6 +1,6 @@
1
- "use strict";(()=>{var qi=new Set(["navigate","execute","none"]);function Tt(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!qi.has(n))return null;if(n==="none")return{type:"none"};let o=typeof t.intent=="string"?t.intent.trim():"";return o?{type:n,intent:o,parameters:t.parameters&&typeof t.parameters=="object"?t.parameters:void 0,requireConfirmation:t.requireConfirmation===!0?!0:void 0,confirmationMessage:typeof t.confirmationMessage=="string"&&t.confirmationMessage.trim()?t.confirmationMessage.trim():void 0}:null}var fe="BACK";function Et(e){return e.routes.map(t=>({intent:t.intent,label:t.label,examples:t.examples,...t.description?{description:t.description}:{},...t.audience==="authenticated"?{audience:"authenticated"}:{}}))}function It(e){return e.actions.map(t=>{var i,r,s,a;let n=Object.entries((i=t.parameters)!=null?i:{}),o=(r=t.contextRequirements)==null?void 0:r.custom;return{intent:t.intent,label:t.label,examples:t.examples,...t.kind==="link"?{kind:"link"}:{},...t.kind==="link"&&t.navTarget?{nav_target:t.navTarget}:{},requires_visible_content:((s=t.contextRequirements)==null?void 0:s.requiresVisibleContent)===!0,requires_auth:((a=t.contextRequirements)==null?void 0:a.requiresAuth)===!0,...o&&o.length>0?{requires_context:[...o]}:{},requires_confirmation:t.requireConfirmation,...t.confirmationMessageTemplate?{confirmation_message:t.confirmationMessageTemplate}:{},...n.length>0?{parameters:Object.fromEntries(n.map(([l,c])=>[l,{type:c.type,required:c.required,description:c.description}]))}:{},...t.description?{description:t.description}:{},...t.preconditions?{preconditions:t.preconditions}:{},...t.effect?{effect:t.effect}:{},...t.relatedIntents&&t.relatedIntents.length>0?{related_intents:[...t.relatedIntents]}:{},...t.showcaseRoute?{showcase_route:t.showcaseRoute}:{},...t.audience==="authenticated"?{audience:"authenticated"}:{},...t.requiredCapabilities&&t.requiredCapabilities.length>0?{required_capabilities:[...t.requiredCapabilities]}:{}}})}var Ln=/\{([a-zA-Z0-9_]+)\}/g,Qi="baseUrl";function Rt(e){let t=[];for(let n of e.matchAll(Ln)){let o=n[1];o&&!t.includes(o)&&t.push(o)}return t}function Ot(e){let t=new Set(Rt(e.url)),n=o=>{if(typeof o=="string")for(let i of Rt(o))t.add(i);else Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return e.body&&n(e.body),[...t]}var Oe=class extends Error{};function Ji(e,t,n){return e.replace(Ln,(o,i)=>{if(i===Qi){if(!n)throw new Oe("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let r=t[i];if(r==null)throw new Oe(`Missing parameter '${i}' for URL template`);return encodeURIComponent(String(r))})}function Mn(e,t){if(typeof e=="string"){let n=/^\{([a-zA-Z0-9_]+)\}$/.exec(e);if(n){let o=n[1],i=t[o];if(i==null)throw new Oe(`Missing parameter '${o}' for body template`);return i}return e.replace(Ln,(o,i)=>{let r=t[i];if(r==null)throw new Oe(`Missing parameter '${i}' for body template`);return String(r)})}return Array.isArray(e)?e.map(n=>Mn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Mn(o,t)])):e}function Zi(){let e=globalThis.fetch;return typeof e=="function"?e:null}function er(e){let t=globalThis;if(!t.AbortController||!t.setTimeout)return{cancel:()=>{}};let n=new t.AbortController,o=t.setTimeout(()=>n.abort(),e);return{signal:n.signal,cancel:()=>{var i;return(i=t.clearTimeout)==null?void 0:i.call(t,o)}}}function tr(e,t){var i,r;let n=(i=t.baseUrl)==null?void 0:i.replace(/\/$/,""),o=(r=t.timeoutMs)!=null?r:15e3;return async s=>{var f,m,h,y,w;let a={...(f=e.headers)!=null?f:{}};if(e.authRef){let x=(m=t.authProviders)==null?void 0:m[e.authRef];if(!x)return{success:!1,error:`Auth provider not registered: ${e.authRef}`};try{Object.assign(a,await x())}catch(S){return{success:!1,error:`Auth provider '${e.authRef}' failed: ${S instanceof Error?S.message:"unknown"}`}}}let l,c;try{l=Ji(e.url,s,n),e.body&&(a["Content-Type"]=(h=a["Content-Type"])!=null?h:"application/json",c=JSON.stringify(Mn(e.body,s)))}catch(x){return{success:!1,error:x instanceof Error?x.message:"Template resolution failed"}}let u=(y=t.fetchFn)!=null?y:Zi();if(!u)return{success:!1,error:"No fetch implementation available"};let p=er(o);try{let x=await u(l,{method:e.method,headers:a,...c!==void 0?{body:c}:{},...p.signal?{signal:p.signal}:{}});if(!x.ok){let R="";try{R=(await x.text()).slice(0,200)}catch{}return{success:!1,error:`HTTP ${x.status}${R?`: ${R}`:""}`}}let S;try{if(((w=x.headers.get("content-type"))!=null?w:"").includes("json")){let T=await x.text();if(T){let g=JSON.parse(T);g&&typeof g=="object"&&!Array.isArray(g)&&(S=g)}}}catch{}return{success:!0,...S?{data:S}:{}}}catch(x){return{success:!1,error:`Request failed: ${x instanceof Error?x.message:"unknown"}`}}finally{p.cancel()}}}function kt(e,t={}){var o,i;let n={};for(let r of(o=e.actions)!=null?o:[]){if(!r.execution||r.kind==="link")continue;let s=(i=r.handler)==null?void 0:i.trim();s&&(n[s]=tr(r.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var nr=new Set(["string","number","boolean"]),or=new Set(["standard","strict","disabled"]),ir=new Set(["GET","POST","PUT","PATCH","DELETE"]);function rr(e,t,n){var r,s;let o=e.execution;if(!o)return;if(e.kind==="link"){n.push(`link action '${t}' cannot declare execution`);return}if(o.kind!=="http"&&n.push(`action '${t}' has invalid execution kind '${String(o.kind)}'`),ir.has(o.method)||n.push(`action '${t}' has invalid execution method '${String(o.method)}'`),!((r=o.url)!=null&&r.trim())){n.push(`action '${t}' has an empty execution url`);return}o.authRef!==void 0&&!o.authRef.trim()&&n.push(`action '${t}' has an empty execution authRef`);let i=new Set(Object.keys((s=e.parameters)!=null?s:{}));for(let a of Ot(o))a!=="baseUrl"&&!i.has(a)&&n.push(`action '${t}' execution references undeclared parameter '{${a}}'`)}function he(e){var o,i,r,s,a,l,c,u,p,f,m,h,y,w,x,S,R;let t=[];(o=e.appId)!=null&&o.trim()||t.push("appId is required"),(i=e.appName)!=null&&i.trim()||t.push("appName is required"),(r=e.version)!=null&&r.trim()||t.push("version is required");let n=new Set;for(let T of(s=e.routes)!=null?s:[]){let g=(a=T.intent)==null?void 0:a.trim();if(!g){t.push("route with empty intent");continue}n.has(g)&&t.push(`duplicate intent: ${g}`),n.add(g),(l=T.route)!=null&&l.trim()||t.push(`route intent '${g}' has empty route`),(c=T.examples)!=null&&c.length||t.push(`route intent '${g}' has no examples`)}for(let T of(u=e.actions)!=null?u:[]){let g=(p=T.intent)==null?void 0:p.trim();if(!g){t.push("action with empty intent");continue}n.has(g)&&t.push(`duplicate intent: ${g}`),n.add(g),T.kind==="link"?(f=T.navTarget)!=null&&f.trim()||t.push(`link action '${g}' has empty navTarget`):(m=T.handler)!=null&&m.trim()||t.push(`action '${g}' has empty handler`),(h=T.examples)!=null&&h.length||t.push(`action '${g}' has no examples`),T.doubleConfirmation&&!T.requireConfirmation&&t.push(`action '${g}' declares doubleConfirmation without requireConfirmation`),T.voiceConfirmation!==void 0&&(or.has(T.voiceConfirmation)||t.push(`action '${g}' has invalid voiceConfirmation '${T.voiceConfirmation}'`),T.requireConfirmation||t.push(`action '${g}' declares voiceConfirmation without requireConfirmation`)),T.confirmationPhrase!==void 0&&!T.confirmationPhrase.trim()&&t.push(`action '${g}' has an empty confirmationPhrase`),T.requireConfirmation&&!((y=T.confirmationMessageTemplate)!=null&&y.trim())&&t.push(`action '${g}' requires confirmation but has no confirmationMessageTemplate`);for(let[v,A]of Object.entries((w=T.parameters)!=null?w:{}))nr.has(A.type)||t.push(`action '${g}' parameter '${v}' has invalid type '${A.type}'`),(x=A.description)!=null&&x.trim()||t.push(`action '${g}' parameter '${v}' has empty description`);for(let v of(R=(S=T.contextRequirements)==null?void 0:S.custom)!=null?R:[])v.trim()||t.push(`action '${g}' has an empty custom requirement name`);rr(T,g,t)}return{valid:t.length===0,errors:t}}function Bn(e,t,n,o){var r,s,a,l,c,u,p,f;let i=e.contextRequirements;if(!i)return{ok:!0};if(i.requiresVisibleContent&&!(((s=(r=t.visibleContent)==null?void 0:r.items.length)!=null?s:0)>0))return{ok:!1,reason:"No visible content in context",userMessage:o.messages.needsVisibleContent,recoverable:!0};if(i.requiresAuth){let m=o.isAuthenticated?o.isAuthenticated():null;if(m==null)return(l=(a=globalThis.console)==null?void 0:a.warn)==null||l.call(a,o.isAuthenticated?`[fyodos] Action "${e.intent}" declares requiresAuth but isAuthenticated() returned null/undefined (session state UNKNOWN). The action is blocked (fail-closed). If this is the generated session wiring, the app component that registers the session bridge has not rendered yet \u2014 see src/fyodos/FYODOS_SESSION.md.`:`[fyodos] Action "${e.intent}" declares requiresAuth but the app did not provide isAuthenticated. The action is blocked (fail-closed). Wire it on the mount, e.g. <FiodosAgent isAuthenticated={() => Boolean(session)} \u2026/> \u2014 see FYODOS_ORB_MOUNT.md.`),{ok:!1,reason:o.isAuthenticated?"requiresAuth declared but auth state is unknown (provider returned null)":"requiresAuth declared but no AuthStateProvider registered",userMessage:(c=o.messages.authUnverifiable)!=null?c:o.messages.actionUnavailable,recoverable:!1};if(!m)return{ok:!1,reason:"User not authenticated",userMessage:o.messages.needsAuth,recoverable:!1}}for(let m of(u=i.custom)!=null?u:[]){let h=(p=n.contextValidators)==null?void 0:p[m];if(!h)return{ok:!1,reason:`Context validator not registered: ${m}`,userMessage:o.messages.actionUnavailable,recoverable:!1};let y;try{y=h(t)}catch(w){return{ok:!1,reason:`Context validator '${m}' threw: ${w instanceof Error?w.message:"unknown"}`,userMessage:o.messages.actionUnavailable,recoverable:!1}}if(!y.ok)return{ok:!1,reason:y.reason,userMessage:(f=y.userMessage)!=null?f:o.messages.actionUnavailable,recoverable:!0}}return{ok:!0}}async function Xe(e,t,n,o,i){var l;let r=(l=e.intent)==null?void 0:l.trim();if(!r)return{kind:"done",result:{success:!1,error:"No intent specified"}};let s=t.find(c=>c.intent===r);if(!s)return{kind:"done",result:{success:!1,error:`Unknown action intent: ${r}`}};let a=Bn(s,n,o,i);if(!a.ok)return{kind:"done",result:{success:!1,error:a.reason,message:a.userMessage,recoverable:a.recoverable}};if(s.idempotencyCheck){let c=o.idempotencyCheckers[s.idempotencyCheck];if(c)try{let u=await c(n);if(u.alreadyApplied)return{kind:"done",result:{success:!0,idempotent:!0,message:u.message}}}catch{}}return{kind:"ready",actionConfig:s}}async function qe(e,t,n,o,i){var l;let r=await Xe(e,t,n,o,i);if(r.kind==="done")return r.result;let{actionConfig:s}=r,a=o.handlers[s.handler];if(!a)return{success:!1,error:`Handler not found: ${s.handler}`,message:i.messages.actionUnavailable};try{return await a((l=e.parameters)!=null?l:{},n,s.intent)}catch(c){return{success:!1,error:`Handler failed: ${c instanceof Error?c.message:"unknown"}`,message:i.messages.actionFailed}}}var _o={needsVisibleContent:"For that, I first need the content open on screen. Want me to take you there?",needsAuth:"You need to be signed in to do that.",authUnverifiable:"I can't do that from here yet. Please use the app's own controls.",actionUnavailable:"I can't do that right now. Please try again.",signInAutofillDismissed:"No problem. You can tell me your email and password, or sign in from the login screen.",signInAutofillUnavailable:"I couldn't use the credentials saved on this device. Tell me your email and password, or sign in from the login screen.",actionFailed:"I couldn't do that. Please try again.",navigationFailed:"I couldn't open that screen. Please try again.",alreadyOnScreen:"You're already on that screen.",cancelled:"Cancelled.",confirmationFallbackQuestion:"Do you want me to proceed?",confirmationNotUnderstood:"I didn't catch that.",doubleConfirmationQuestion:"This is a serious action. Do you definitely confirm?",strictConfirmationInstruction:'For safety, to continue say exactly: "{phrase}". To cancel, say no.',strictConfirmationPhraseTemplate:"confirm {label}",strictConfirmationNotMatched:"For safety, I need the exact phrase.",strictConfirmationModalHint:'To confirm by voice, say exactly: "{phrase}".',contextTruncationSuffix:"\u2026[content truncated to optimize the response]",visibleContentHeader:"Items currently visible on screen ({count}):",visibleContentEmpty:"No content is currently loaded on screen.",visibleContentFocusedTag:"[ON SCREEN NOW]",visibleContentReferenceHint:'If the user says "this one" or "this item", they mean the one tagged ON SCREEN NOW (or the only visible one). Never read internal ids aloud.',currentScreenLabel:'Current screen: "{label}"',currentScreenActions:"From here the user can: {actions}",bubblePromptFromExample:"Want to {phrase}?",bubblePromptFromAction:"Want to {action}?",bubblePromptFromLabel:"Want to open {label}?"};var Po={needsVisibleContent:"Para eso necesito que abras primero el contenido en pantalla. \xBFTe llevo hasta \xE9l?",needsAuth:"Necesitas haber iniciado sesi\xF3n para hacer eso.",authUnverifiable:"Todav\xEDa no puedo hacer eso desde aqu\xED. Usa los controles de la propia app.",actionUnavailable:"No puedo hacer eso ahora mismo. Int\xE9ntalo de nuevo.",signInAutofillDismissed:"Sin problema. Puedes decirme tu email y contrase\xF1a, o iniciar sesi\xF3n desde la pantalla de acceso.",signInAutofillUnavailable:"No he podido usar las credenciales guardadas en este dispositivo. Dime tu email y contrase\xF1a, o inicia sesi\xF3n desde la pantalla de acceso.",actionFailed:"No he podido hacerlo. Int\xE9ntalo de nuevo.",navigationFailed:"No he podido abrir esa pantalla. Int\xE9ntalo de nuevo.",alreadyOnScreen:"Ya est\xE1s en esa pantalla.",cancelled:"Cancelado.",confirmationFallbackQuestion:"\xBFQuieres que lo haga?",confirmationNotUnderstood:"No te he entendido.",doubleConfirmationQuestion:"Es una acci\xF3n seria. \xBFLo confirmas definitivamente?",strictConfirmationInstruction:"Por seguridad, para continuar di exactamente: \xAB{phrase}\xBB. Para cancelar, di no.",strictConfirmationPhraseTemplate:"confirmar {label}",strictConfirmationNotMatched:"Por seguridad necesito la frase exacta.",strictConfirmationModalHint:"Para confirmar por voz, di exactamente: \xAB{phrase}\xBB.",contextTruncationSuffix:"\u2026[contenido recortado para optimizar la respuesta]",visibleContentHeader:"Elementos visibles en pantalla ({count}):",visibleContentEmpty:"Todav\xEDa no hay contenido cargado en pantalla.",visibleContentFocusedTag:"[EN PANTALLA AHORA]",visibleContentReferenceHint:'Si el usuario dice "esto" o "este elemento", se refiere al marcado como EN PANTALLA AHORA (o al \xFAnico visible). Nunca leas identificadores internos en voz alta.',currentScreenLabel:"Pantalla actual: \xAB{label}\xBB",currentScreenActions:"Desde aqu\xED el usuario puede: {actions}",bubblePromptFromExample:"\xBFQuieres {phrase}?",bubblePromptFromAction:"\xBFQuieres {action}?",bubblePromptFromLabel:"\xBFQuieres ir a {label}?"};var Qe={en:_o,es:Po};function ar(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function _t(e,t={}){var s,a,l;let n=(s=t.catalogs)!=null?s:{},o=(a=n[e])!=null?a:Qe[e],i=ar(e),r=(l=o!=null?o:n[i])!=null?l:Qe[i];if(!r){let c=[...new Set([...Object.keys(Qe),...Object.keys(n)])].join(", ");throw new Error(`[fyodos] No message catalog for locale "${e}". Available locales: ${c}. Register a catalog for your locale via resolveMessages(locale, { catalogs }) or pick a supported one.`)}return t.overrides?{...r,...t.overrides}:r}function ee(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n)}function xe(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var Mo=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function cr(e){let t=xe(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||Mo.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&Mo.test(n[0]))}function lr(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Nn(e){return lr(e)==="es"}var Lo=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function ur(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function dr(e,t){var i;let n=(i=e.actionIntents)!=null?i:[];if(n.length===0||!(t!=null&&t.length))return null;let o=new Map(t.map(r=>[r.intent,r]));for(let r of n){let s=o.get(r);if(s)return s}return null}function pr(e,t){var c;let n=Nn(t),o=xe(e.label),i=xe(e.description),r=o.toLowerCase(),l=n?{"add todo":"a\xF1adir una tarea","delete todo":"eliminar una tarea","toggle todo":"marcar una tarea como hecha","complete todo":"marcar una tarea como hecha","search users":"buscar un usuario","create user":"crear un usuario","sign in":"iniciar sesi\xF3n","sign out":"cerrar sesi\xF3n","log in":"iniciar sesi\xF3n","log out":"cerrar sesi\xF3n",checkout:"finalizar la compra","add to cart":"a\xF1adir algo al carrito","place order":"hacer tu pedido"}:{"add todo":"add a task","delete todo":"delete a task","toggle todo":"mark a task done","complete todo":"mark a task done","search users":"search for a user","create user":"create a user","sign in":"sign in","sign out":"sign out","log in":"sign in","log out":"sign out",checkout:"check out","add to cart":"add something to your cart","place order":"place your order"};if(l[r])return l[r];if(i){let u=i.match(/^(adds?|creates?|deletes?|removes?|updates?|sends?|opens?|shows?|lists?|marks?|completes?|toggles?|searches?|finds?|places?|submits?)\s+(.+?)(?:\.|$)/i);if(u){let p=u[1].toLowerCase().replace(/s$/,""),f=u[2].toLowerCase();return n?`${(c={add:"a\xF1adir",create:"crear",delete:"eliminar",remove:"quitar",update:"actualizar",send:"enviar",open:"abrir",show:"ver",list:"ver",mark:"marcar",complete:"completar",toggle:"cambiar",search:"buscar",find:"buscar",place:"hacer",submit:"enviar"}[p])!=null?c:p} ${f}`.slice(0,48):`${p} ${f}`.slice(0,48)}}if(o){let u=o.split(/\s+/);return u.length>=2?`${u[0].toLowerCase()} ${u.slice(1).join(" ").toLowerCase()}`:o.toLowerCase()}return xe(e.intent).replace(/_/g," ")}function fr(e,t,n){let o=pr(e,n);return ee(t.bubblePromptFromAction,{action:o})}function hr(e,t){let n=e.toLowerCase(),o=Nn(t),i=e.match(/from here (?:you|the user|users?) (?:can|may|could)\s+(.+?)(?:[.;]|$)/i);if(i!=null&&i[1]){let r=i[1].trim().replace(/[.;]+$/,"");if(r.length>=4&&r.length<=56)return o?`\xBFQuieres ${r.toLowerCase()}?`:`Want to ${r.toLowerCase()}?`}return/sign(?:\s|-)?in|log(?:\s|-)?in|authenticate|iniciar ses/i.test(n)?o?"\xBFQuieres iniciar sesi\xF3n?":"Want to sign in?":/sign(?:\s|-)?up|register|create an account|registr/i.test(n)?o?"\xBFQuieres registrarte?":"Want to create an account?":/cart|checkout|check out|finalizar compra|pagar/i.test(n)?o?"\xBFFinalizar tu compra?":"Ready to checkout?":/user|account|people|person|usuario|cuenta/i.test(n)&&/list|search|browse|manage|ver|buscar/i.test(n)?o?"\xBFBuscar un usuario?":"Looking for a user?":/product|item|catalog|tienda|producto/i.test(n)&&/list|browse|shop|search|ver|buscar/i.test(n)?o?"\xBFBuscar un producto?":"Browse products?":/task|todo|tarea/i.test(n)&&/add|create|list|manage|añadir|crear/i.test(n)?o?"\xBFA\xF1adir una tarea?":"Want to add a task?":/setting|preference|ajuste|configur/i.test(n)?o?"\xBFCambiar alg\xFAn ajuste?":"Need to change a setting?":/profile|perfil/i.test(n)?o?"\xBFActualizar tu perfil?":"Update your profile?":/bill|invoice|payment|factur|pago/i.test(n)?o?"\xBFVer tu facturaci\xF3n?":"Check your billing?":/password|contrase/i.test(n)?o?"\xBFCambiar tu contrase\xF1a?":"Change your password?":/message|chat|conversation/i.test(n)?o?"\xBFEnviar un mensaje?":"Send a message?":/order|pedido/i.test(n)?o?"\xBFVer tus pedidos?":"Check your orders?":null}function mr(e,t){let n=Nn(t),o=ur(e.intent),i=xe(e.label).toLowerCase();if(Lo.has(o)||Lo.has(i.replace(/\s+/g,"_")))return null;let r=`${o} ${i}`;return/login|sign_in|signin|auth/.test(r)?n?"\xBFQuieres iniciar sesi\xF3n?":"Want to sign in?":/register|signup|sign_up|sign-up/.test(r)?n?"\xBFQuieres registrarte?":"Want to create an account?":/cart|checkout|basket/.test(r)?n?"\xBFFinalizar tu compra?":"Ready to checkout?":/user|users|account|people|member/.test(r)?n?"\xBFBuscar un usuario?":"Looking for a user?":/product|catalog|shop|store|item/.test(r)?n?"\xBFBuscar un producto?":"Browse products?":/todo|task/.test(r)?n?"\xBFA\xF1adir una tarea?":"Want to add a task?":/setting|preference|config/.test(r)?n?"\xBFCambiar alg\xFAn ajuste?":"Need to change a setting?":/profile|account_overview/.test(r)?n?"\xBFActualizar tu perfil?":"Update your profile?":/bill|invoice|payment|subscription|pricing/.test(r)?n?"\xBFVer tu facturaci\xF3n?":"Check your billing?":/search|find|lookup/.test(r)?n?"\xBFQu\xE9 buscas?":"What are you looking for?":/chat|message|inbox|conversation/.test(r)?n?"\xBFEnviar un mensaje?":"Send a message?":/password|security/.test(r)?n?"\xBFCambiar tu contrase\xF1a?":"Change your password?":/order|transaction|history/.test(r)?n?"\xBFVer tu historial?":"Review your history?":/wallet|budget|saving|finance|balance/.test(r)?n?"\xBFRevisar tus finanzas?":"Review your finances?":/note|editor|write|compose|new_chat/.test(r)?n?"\xBFEscribir algo nuevo?":"Write something new?":null}function gr(e,t,n){var r;let o=((r=e.examples)!=null?r:[]).map(xe).find(s=>s.length>0&&cr(s));if(!o)return null;let i=o.replace(/\?+$/,"").trim();return/^(take me|go to|open|show me|navigate|ir a|abrir|mostrar|llévame)/i.test(i)?null:ee(t.bubblePromptFromExample,{phrase:i})}function Pt(e,t,n){var l;let o=(l=n==null?void 0:n.locale)!=null?l:"en",i=n==null?void 0:n.actions,r=dr(e,i);if(r)return fr(r,t,o);let s=xe(e.description);if(s){let c=hr(s,o);if(c)return c}let a=mr(e,o);return a||gr(e,t,o)}function X(e){let t=String(e!=null?e:"").trim();return t?(t=t.split("?")[0].split("#")[0],t=t.replace(/\([^)]*\)/g,""),t=t.replace(/\/{2,}/g,"/").replace(/^\/+|\/+$/g,""),t=t.replace(/(^|\/)index$/i,""),t=t.replace(/^\/+|\/+$/g,""),t.toLowerCase()):""}function Bo(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}function Je(e,t){if(e==null||!t||t.length===0)return null;let n=String(e).trim();if(!n)return null;let o=X(n),i=t.filter(s=>s&&s.route&&s.route!==fe);if(i.length===0)return null;for(let s of i)if(X(s.route)===o)return s;if(o){let s=null;for(let a of i){let l=X(a.route);if(!l)continue;(o===l||o.startsWith(`${l}/`)||l.startsWith(`${o}/`)||o.endsWith(`/${l}`)||l.endsWith(`/${o}`))&&(!s||l.length>s.len)&&(s={route:a,len:l.length})}if(s)return s.route}let r=Bo(o)||o;if(r){for(let s of i)if(X(s.intent)===r||X(s.label)===r||Bo(X(s.route))===r)return s;for(let s of i)if(X(s.intent)===o||X(s.label)===o)return s}return null}function $n(e,t){var l,c,u,p,f;if(!e)return null;let n=((l=e.label)==null?void 0:l.trim())||((c=e.intent)==null?void 0:c.trim());if(!n)return null;let{messages:o,actions:i}=t,r=[ee(o.currentScreenLabel,{label:n})],s=(u=e.description)==null?void 0:u.trim();s&&r.push(s);let a=(p=e.actionIntents)!=null?p:[];if(a.length>0&&i&&i.length>0){let m=new Map(i.map(w=>[w.intent,w])),h=[],y=new Set;for(let w of a){let x=m.get(w),S=(f=x==null?void 0:x.label)==null?void 0:f.trim();S&&!y.has(S)&&(y.add(S),h.push(S))}h.length>0&&r.push(ee(o.currentScreenActions,{actions:h.join(", ")}))}return r.join(" \u2014 ")}function br(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Mt(e,t,n){if(!e)return null;let o=br(e.bubblePrompt);if(o)return o;let i=Pt(e,t,{locale:n==null?void 0:n.locale,actions:n==null?void 0:n.actions});return i||null}function Lt(e,t,n){let o=Je(e,t.routes);return $n(o,{messages:n,actions:t.actions})}var yr=/(^|[\s_.-])(log[\s_-]?in|sign[\s_-]?in|iniciar[\s_-]?sesi[oó]n|inicia[\s_-]?sesi[oó]n)([\s_.-]|$)|\b(login|signin|acceder|autenticar|authenticate)\b/i,xr=/log[\s_-]?out|sign[\s_-]?out|sign[\s_-]?up|signup|register|registr|cerrar[\s_-]?sesi[oó]n|crear[\s_-]?cuenta|reset|recover|recuperar|forgot|olvid/i,vr=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,Cr=/pass(word)?|contrase|clave|pwd/i;function Fn(e){var o,i;if(e.kind==="link"||(o=e.contextRequirements)!=null&&o.requiresAuth)return!1;let t=`${e.intent} ${e.label} ${(i=e.handler)!=null?i:""}`;if(xr.test(t)||!yr.test(t))return!1;let n=Bt(e);return n.usernameParam!==null&&n.passwordParam!==null}function Bt(e){var o;let t=null,n=null;for(let[i,r]of Object.entries((o=e.parameters)!=null?o:{}))if(r.type==="string"){if(n===null&&Cr.test(i)){n=i;continue}t===null&&vr.test(i)&&(t=i)}return{usernameParam:t,passwordParam:n}}function Dn(e){return typeof e=="string"?e.trim().length>0:e!=null}async function Nt(e,t,n,o){var c;if(!n)return{kind:"not-applicable"};let i=!1;try{i=n.isSupported()===!0}catch{i=!1}if(!i)return{kind:"not-applicable"};if(!Fn(t))return{kind:"not-applicable"};if((o==null?void 0:o())===!0)return{kind:"not-applicable"};let{usernameParam:r,passwordParam:s}=Bt(t);if(!r||!s)return{kind:"not-applicable"};let a=(c=e.parameters)!=null?c:{};if(Dn(a[r])&&Dn(a[s]))return{kind:"not-applicable"};let l;try{l=await n.requestCredentials()}catch{l={status:"unavailable"}}return l.status==="success"&&l.username&&l.password?{kind:"proceed",action:{...e,parameters:{...a,[r]:Dn(a[r])?a[r]:l.username,[s]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}function $t(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(i){var a,l;let r=(a=i.intent)==null?void 0:a.trim();if(!r)return{success:!1,error:"No intent specified"};let s=e.manifest.routes.find(c=>c.intent===r);if(!s)return{success:!1,error:`Unknown intent: ${r}`};if(s.route!==fe&&e.messages.alreadyOnScreen)try{let c=e.navigation.getCurrentRoute();if(c!=null&&String(c).trim()!==""&&X(c)===X(s.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return s.route===fe?e.navigation.back():e.navigation.navigate(s.route),{success:!0}}catch(c){return{success:!1,error:`Navigation failed: ${c instanceof Error?c.message:"unknown"}`,message:(l=e.messages.navigationFailed)!=null?l:e.messages.actionFailed}}}function o(i,r){if(!(i!=null&&i.showcaseRoute)||!r.success||r.recoverable)return;let s=e.manifest.routes.find(a=>a.intent===i.showcaseRoute);if(!(!s||s.route===fe))try{let a=e.navigation.getCurrentRoute();if(a!=null&&String(a).trim()!==""&&X(a)===X(s.route))return;e.navigation.navigate(s.route)}catch{}}return{async execute(i,r={}){var s,a;if(!i||i.type==="none")return{success:!0};if(i.type==="navigate")return n(i);if(i.type==="execute"){let l=e.manifest.actions.find(u=>{var p;return u.intent===((p=i.intent)==null?void 0:p.trim())});if(l){let u=await Nt(i,l,e.credentialAutofill,e.isAuthenticated);if(u.kind==="proceed"){let p=await qe(u.action,e.manifest.actions,r,e.registries,t);return o(l,p),p}if(u.kind==="dismissed"||u.kind==="unavailable"){let p=u.kind==="dismissed"?(s=e.messages.signInAutofillDismissed)!=null?s:e.messages.cancelled:(a=e.messages.signInAutofillUnavailable)!=null?a:e.messages.actionUnavailable;return{success:!1,error:`sign_in_autofill_${u.kind}`,message:p}}}let c=await qe(i,e.manifest.actions,r,e.registries,t);return o(l,c),c}return{success:!1,error:`Action type not implemented: ${i.type}`}},async precheck(i,r={}){return Xe(i,e.manifest.actions,r,e.registries,t)}}}function ke(e,t){var i;let n=(i=t.maxChars)!=null?i:1500;if(e.length<=n)return e;let o=Math.max(0,n-t.truncationSuffix.length);return e.slice(0,o)+t.truncationSuffix}function Ze(e,t,n){var l;let o=(l=n.maxChars)!=null?l:1500,i=(e==null?void 0:e.trim())||null,r=(t==null?void 0:t.trim())||null;if(!i&&!r)return null;if(!r)return ke(i,{...n,maxChars:o});if(!i)return ke(r,{...n,maxChars:o});let s=`
1
+ "use strict";(()=>{var dr=new Set(["navigate","execute","none"]);function kt(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!dr.has(n))return null;if(n==="none")return{type:"none"};let o=typeof t.intent=="string"?t.intent.trim():"";return o?{type:n,intent:o,parameters:t.parameters&&typeof t.parameters=="object"?t.parameters:void 0,requireConfirmation:t.requireConfirmation===!0?!0:void 0,confirmationMessage:typeof t.confirmationMessage=="string"&&t.confirmationMessage.trim()?t.confirmationMessage.trim():void 0}:null}var fe="BACK";function _t(e){return e.routes.map(t=>({intent:t.intent,label:t.label,examples:t.examples,...t.description?{description:t.description}:{},...t.audience==="authenticated"?{audience:"authenticated"}:{}}))}function Pt(e){return e.actions.map(t=>{var i,r,s,a;let n=Object.entries((i=t.parameters)!=null?i:{}),o=(r=t.contextRequirements)==null?void 0:r.custom;return{intent:t.intent,label:t.label,examples:t.examples,...t.kind==="link"?{kind:"link"}:{},...t.kind==="link"&&t.navTarget?{nav_target:t.navTarget}:{},requires_visible_content:((s=t.contextRequirements)==null?void 0:s.requiresVisibleContent)===!0,requires_auth:((a=t.contextRequirements)==null?void 0:a.requiresAuth)===!0,...o&&o.length>0?{requires_context:[...o]}:{},requires_confirmation:t.requireConfirmation,...t.confirmationMessageTemplate?{confirmation_message:t.confirmationMessageTemplate}:{},...n.length>0?{parameters:Object.fromEntries(n.map(([l,c])=>[l,{type:c.type,required:c.required,description:c.description}]))}:{},...t.description?{description:t.description}:{},...t.preconditions?{preconditions:t.preconditions}:{},...t.effect?{effect:t.effect}:{},...t.relatedIntents&&t.relatedIntents.length>0?{related_intents:[...t.relatedIntents]}:{},...t.showcaseRoute?{showcase_route:t.showcaseRoute}:{},...t.audience==="authenticated"?{audience:"authenticated"}:{},...t.requiredCapabilities&&t.requiredCapabilities.length>0?{required_capabilities:[...t.requiredCapabilities]}:{}}})}var Un=/\{([a-zA-Z0-9_]+)\}/g,pr="baseUrl";function Mt(e){let t=[];for(let n of e.matchAll(Un)){let o=n[1];o&&!t.includes(o)&&t.push(o)}return t}function Lt(e){let t=new Set(Mt(e.url)),n=o=>{if(typeof o=="string")for(let i of Mt(o))t.add(i);else Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return e.body&&n(e.body),[...t]}var Oe=class extends Error{};function fr(e,t,n){return e.replace(Un,(o,i)=>{if(i===pr){if(!n)throw new Oe("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let r=t[i];if(r==null)throw new Oe(`Missing parameter '${i}' for URL template`);return encodeURIComponent(String(r))})}function Wn(e,t){if(typeof e=="string"){let n=/^\{([a-zA-Z0-9_]+)\}$/.exec(e);if(n){let o=n[1],i=t[o];if(i==null)throw new Oe(`Missing parameter '${o}' for body template`);return i}return e.replace(Un,(o,i)=>{let r=t[i];if(r==null)throw new Oe(`Missing parameter '${i}' for body template`);return String(r)})}return Array.isArray(e)?e.map(n=>Wn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Wn(o,t)])):e}function hr(){let e=globalThis.fetch;return typeof e=="function"?e:null}function mr(e){let t=globalThis;if(!t.AbortController||!t.setTimeout)return{cancel:()=>{}};let n=new t.AbortController,o=t.setTimeout(()=>n.abort(),e);return{signal:n.signal,cancel:()=>{var i;return(i=t.clearTimeout)==null?void 0:i.call(t,o)}}}function gr(e,t){var i,r;let n=(i=t.baseUrl)==null?void 0:i.replace(/\/$/,""),o=(r=t.timeoutMs)!=null?r:15e3;return async s=>{var f,m,h,x,T;let a={...(f=e.headers)!=null?f:{}};if(e.authRef){let v=(m=t.authProviders)==null?void 0:m[e.authRef];if(!v)return{success:!1,error:`Auth provider not registered: ${e.authRef}`};try{Object.assign(a,await v())}catch(S){return{success:!1,error:`Auth provider '${e.authRef}' failed: ${S instanceof Error?S.message:"unknown"}`}}}let l,c;try{l=fr(e.url,s,n),e.body&&(a["Content-Type"]=(h=a["Content-Type"])!=null?h:"application/json",c=JSON.stringify(Wn(e.body,s)))}catch(v){return{success:!1,error:v instanceof Error?v.message:"Template resolution failed"}}let u=(x=t.fetchFn)!=null?x:hr();if(!u)return{success:!1,error:"No fetch implementation available"};let p=mr(o);try{let v=await u(l,{method:e.method,headers:a,...c!==void 0?{body:c}:{},...p.signal?{signal:p.signal}:{}});if(!v.ok){let I="";try{I=(await v.text()).slice(0,200)}catch{}return{success:!1,error:`HTTP ${v.status}${I?`: ${I}`:""}`}}let S;try{if(((T=v.headers.get("content-type"))!=null?T:"").includes("json")){let E=await v.text();if(E){let g=JSON.parse(E);g&&typeof g=="object"&&!Array.isArray(g)&&(S=g)}}}catch{}return{success:!0,...S?{data:S}:{}}}catch(v){return{success:!1,error:`Request failed: ${v instanceof Error?v.message:"unknown"}`}}finally{p.cancel()}}}function Bt(e,t={}){var o,i;let n={};for(let r of(o=e.actions)!=null?o:[]){if(!r.execution||r.kind==="link")continue;let s=(i=r.handler)==null?void 0:i.trim();s&&(n[s]=gr(r.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var br=new Set(["string","number","boolean"]),yr=new Set(["standard","strict","disabled"]),xr=new Set(["GET","POST","PUT","PATCH","DELETE"]);function vr(e,t,n){var r,s;let o=e.execution;if(!o)return;if(e.kind==="link"){n.push(`link action '${t}' cannot declare execution`);return}if(o.kind!=="http"&&n.push(`action '${t}' has invalid execution kind '${String(o.kind)}'`),xr.has(o.method)||n.push(`action '${t}' has invalid execution method '${String(o.method)}'`),!((r=o.url)!=null&&r.trim())){n.push(`action '${t}' has an empty execution url`);return}o.authRef!==void 0&&!o.authRef.trim()&&n.push(`action '${t}' has an empty execution authRef`);let i=new Set(Object.keys((s=e.parameters)!=null?s:{}));for(let a of Lt(o))a!=="baseUrl"&&!i.has(a)&&n.push(`action '${t}' execution references undeclared parameter '{${a}}'`)}function he(e){var o,i,r,s,a,l,c,u,p,f,m,h,x,T,v,S,I;let t=[];(o=e.appId)!=null&&o.trim()||t.push("appId is required"),(i=e.appName)!=null&&i.trim()||t.push("appName is required"),(r=e.version)!=null&&r.trim()||t.push("version is required");let n=new Set;for(let E of(s=e.routes)!=null?s:[]){let g=(a=E.intent)==null?void 0:a.trim();if(!g){t.push("route with empty intent");continue}n.has(g)&&t.push(`duplicate intent: ${g}`),n.add(g),(l=E.route)!=null&&l.trim()||t.push(`route intent '${g}' has empty route`),(c=E.examples)!=null&&c.length||t.push(`route intent '${g}' has no examples`)}for(let E of(u=e.actions)!=null?u:[]){let g=(p=E.intent)==null?void 0:p.trim();if(!g){t.push("action with empty intent");continue}n.has(g)&&t.push(`duplicate intent: ${g}`),n.add(g),E.kind==="link"?(f=E.navTarget)!=null&&f.trim()||t.push(`link action '${g}' has empty navTarget`):(m=E.handler)!=null&&m.trim()||t.push(`action '${g}' has empty handler`),(h=E.examples)!=null&&h.length||t.push(`action '${g}' has no examples`),E.doubleConfirmation&&!E.requireConfirmation&&t.push(`action '${g}' declares doubleConfirmation without requireConfirmation`),E.voiceConfirmation!==void 0&&(yr.has(E.voiceConfirmation)||t.push(`action '${g}' has invalid voiceConfirmation '${E.voiceConfirmation}'`),E.requireConfirmation||t.push(`action '${g}' declares voiceConfirmation without requireConfirmation`)),E.confirmationPhrase!==void 0&&!E.confirmationPhrase.trim()&&t.push(`action '${g}' has an empty confirmationPhrase`),E.requireConfirmation&&!((x=E.confirmationMessageTemplate)!=null&&x.trim())&&t.push(`action '${g}' requires confirmation but has no confirmationMessageTemplate`);for(let[C,A]of Object.entries((T=E.parameters)!=null?T:{}))br.has(A.type)||t.push(`action '${g}' parameter '${C}' has invalid type '${A.type}'`),(v=A.description)!=null&&v.trim()||t.push(`action '${g}' parameter '${C}' has empty description`);for(let C of(I=(S=E.contextRequirements)==null?void 0:S.custom)!=null?I:[])C.trim()||t.push(`action '${g}' has an empty custom requirement name`);vr(E,g,t)}return{valid:t.length===0,errors:t}}function Hn(e,t,n,o){var r,s,a,l,c,u,p,f;let i=e.contextRequirements;if(!i)return{ok:!0};if(i.requiresVisibleContent&&!(((s=(r=t.visibleContent)==null?void 0:r.items.length)!=null?s:0)>0))return{ok:!1,reason:"No visible content in context",userMessage:o.messages.needsVisibleContent,recoverable:!0};if(i.requiresAuth){let m=o.isAuthenticated?o.isAuthenticated():null;if(m==null)return(l=(a=globalThis.console)==null?void 0:a.warn)==null||l.call(a,o.isAuthenticated?`[fyodos] Action "${e.intent}" declares requiresAuth but isAuthenticated() returned null/undefined (session state UNKNOWN). The action is blocked (fail-closed). If this is the generated session wiring, the app component that registers the session bridge has not rendered yet \u2014 see src/fyodos/FYODOS_SESSION.md.`:`[fyodos] Action "${e.intent}" declares requiresAuth but the app did not provide isAuthenticated. The action is blocked (fail-closed). Wire it on the mount, e.g. <FiodosAgent isAuthenticated={() => Boolean(session)} \u2026/> \u2014 see FYODOS_ORB_MOUNT.md.`),{ok:!1,reason:o.isAuthenticated?"requiresAuth declared but auth state is unknown (provider returned null)":"requiresAuth declared but no AuthStateProvider registered",userMessage:(c=o.messages.authUnverifiable)!=null?c:o.messages.actionUnavailable,recoverable:!1};if(!m)return{ok:!1,reason:"User not authenticated",userMessage:o.messages.needsAuth,recoverable:!1}}for(let m of(u=i.custom)!=null?u:[]){let h=(p=n.contextValidators)==null?void 0:p[m];if(!h)return{ok:!1,reason:`Context validator not registered: ${m}`,userMessage:o.messages.actionUnavailable,recoverable:!1};let x;try{x=h(t)}catch(T){return{ok:!1,reason:`Context validator '${m}' threw: ${T instanceof Error?T.message:"unknown"}`,userMessage:o.messages.actionUnavailable,recoverable:!1}}if(!x.ok)return{ok:!1,reason:x.reason,userMessage:(f=x.userMessage)!=null?f:o.messages.actionUnavailable,recoverable:!0}}return{ok:!0}}async function Je(e,t,n,o,i){var l;let r=(l=e.intent)==null?void 0:l.trim();if(!r)return{kind:"done",result:{success:!1,error:"No intent specified"}};let s=t.find(c=>c.intent===r);if(!s)return{kind:"done",result:{success:!1,error:`Unknown action intent: ${r}`}};let a=Hn(s,n,o,i);if(!a.ok)return{kind:"done",result:{success:!1,error:a.reason,message:a.userMessage,recoverable:a.recoverable}};if(s.idempotencyCheck){let c=o.idempotencyCheckers[s.idempotencyCheck];if(c)try{let u=await c(n);if(u.alreadyApplied)return{kind:"done",result:{success:!0,idempotent:!0,message:u.message}}}catch{}}return{kind:"ready",actionConfig:s}}async function Ze(e,t,n,o,i){var l;let r=await Je(e,t,n,o,i);if(r.kind==="done")return r.result;let{actionConfig:s}=r,a=o.handlers[s.handler];if(!a)return{success:!1,error:`Handler not found: ${s.handler}`,message:i.messages.actionUnavailable};try{return await a((l=e.parameters)!=null?l:{},n,s.intent)}catch(c){return{success:!1,error:`Handler failed: ${c instanceof Error?c.message:"unknown"}`,message:i.messages.actionFailed}}}var Fo={needsVisibleContent:"For that, I first need the content open on screen. Want me to take you there?",needsAuth:"You need to be signed in to do that.",authUnverifiable:"I can't do that from here yet. Please use the app's own controls.",actionUnavailable:"I can't do that right now. Please try again.",signInAutofillDismissed:"No problem. You can tell me your email and password, or sign in from the login screen.",signInAutofillUnavailable:"I couldn't use the credentials saved on this device. Tell me your email and password, or sign in from the login screen.",actionFailed:"I couldn't do that. Please try again.",navigationFailed:"I couldn't open that screen. Please try again.",alreadyOnScreen:"You're already on that screen.",cancelled:"Cancelled.",confirmationFallbackQuestion:"Do you want me to proceed?",confirmationNotUnderstood:"I didn't catch that.",doubleConfirmationQuestion:"This is a serious action. Do you definitely confirm?",strictConfirmationInstruction:'For safety, to continue say exactly: "{phrase}". To cancel, say no.',strictConfirmationPhraseTemplate:"confirm {label}",strictConfirmationNotMatched:"For safety, I need the exact phrase.",strictConfirmationModalHint:'To confirm by voice, say exactly: "{phrase}".',contextTruncationSuffix:"\u2026[content truncated to optimize the response]",visibleContentHeader:"Items currently visible on screen ({count}):",visibleContentEmpty:"No content is currently loaded on screen.",visibleContentFocusedTag:"[ON SCREEN NOW]",visibleContentReferenceHint:'If the user says "this one" or "this item", they mean the one tagged ON SCREEN NOW (or the only visible one). Never read internal ids aloud.',currentScreenLabel:'Current screen: "{label}"',currentScreenActions:"From here the user can: {actions}",bubblePromptFromExample:"Want to {phrase}?",bubblePromptFromAction:"Want to {action}?",bubblePromptFromLabel:"Want to open {label}?"};var Wo={needsVisibleContent:"Para eso necesito que abras primero el contenido en pantalla. \xBFTe llevo hasta \xE9l?",needsAuth:"Necesitas haber iniciado sesi\xF3n para hacer eso.",authUnverifiable:"Todav\xEDa no puedo hacer eso desde aqu\xED. Usa los controles de la propia app.",actionUnavailable:"No puedo hacer eso ahora mismo. Int\xE9ntalo de nuevo.",signInAutofillDismissed:"Sin problema. Puedes decirme tu email y contrase\xF1a, o iniciar sesi\xF3n desde la pantalla de acceso.",signInAutofillUnavailable:"No he podido usar las credenciales guardadas en este dispositivo. Dime tu email y contrase\xF1a, o inicia sesi\xF3n desde la pantalla de acceso.",actionFailed:"No he podido hacerlo. Int\xE9ntalo de nuevo.",navigationFailed:"No he podido abrir esa pantalla. Int\xE9ntalo de nuevo.",alreadyOnScreen:"Ya est\xE1s en esa pantalla.",cancelled:"Cancelado.",confirmationFallbackQuestion:"\xBFQuieres que lo haga?",confirmationNotUnderstood:"No te he entendido.",doubleConfirmationQuestion:"Es una acci\xF3n seria. \xBFLo confirmas definitivamente?",strictConfirmationInstruction:"Por seguridad, para continuar di exactamente: \xAB{phrase}\xBB. Para cancelar, di no.",strictConfirmationPhraseTemplate:"confirmar {label}",strictConfirmationNotMatched:"Por seguridad necesito la frase exacta.",strictConfirmationModalHint:"Para confirmar por voz, di exactamente: \xAB{phrase}\xBB.",contextTruncationSuffix:"\u2026[contenido recortado para optimizar la respuesta]",visibleContentHeader:"Elementos visibles en pantalla ({count}):",visibleContentEmpty:"Todav\xEDa no hay contenido cargado en pantalla.",visibleContentFocusedTag:"[EN PANTALLA AHORA]",visibleContentReferenceHint:'Si el usuario dice "esto" o "este elemento", se refiere al marcado como EN PANTALLA AHORA (o al \xFAnico visible). Nunca leas identificadores internos en voz alta.',currentScreenLabel:"Pantalla actual: \xAB{label}\xBB",currentScreenActions:"Desde aqu\xED el usuario puede: {actions}",bubblePromptFromExample:"\xBFQuieres {phrase}?",bubblePromptFromAction:"\xBFQuieres {action}?",bubblePromptFromLabel:"\xBFQuieres ir a {label}?"};var et={en:Fo,es:Wo};function Ar(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Nt(e,t={}){var s,a,l;let n=(s=t.catalogs)!=null?s:{},o=(a=n[e])!=null?a:et[e],i=Ar(e),r=(l=o!=null?o:n[i])!=null?l:et[i];if(!r){let c=[...new Set([...Object.keys(et),...Object.keys(n)])].join(", ");throw new Error(`[fyodos] No message catalog for locale "${e}". Available locales: ${c}. Register a catalog for your locale via resolveMessages(locale, { catalogs }) or pick a supported one.`)}return t.overrides?{...r,...t.overrides}:r}function ee(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n)}function xe(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var Uo=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function Sr(e){let t=xe(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||Uo.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&Uo.test(n[0]))}function wr(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Vn(e){return wr(e)==="es"}var Ho=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function Tr(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function Er(e,t){var i;let n=(i=e.actionIntents)!=null?i:[];if(n.length===0||!(t!=null&&t.length))return null;let o=new Map(t.map(r=>[r.intent,r]));for(let r of n){let s=o.get(r);if(s)return s}return null}function Rr(e,t){var c;let n=Vn(t),o=xe(e.label),i=xe(e.description),r=o.toLowerCase(),l=n?{"add todo":"a\xF1adir una tarea","delete todo":"eliminar una tarea","toggle todo":"marcar una tarea como hecha","complete todo":"marcar una tarea como hecha","search users":"buscar un usuario","create user":"crear un usuario","sign in":"iniciar sesi\xF3n","sign out":"cerrar sesi\xF3n","log in":"iniciar sesi\xF3n","log out":"cerrar sesi\xF3n",checkout:"finalizar la compra","add to cart":"a\xF1adir algo al carrito","place order":"hacer tu pedido"}:{"add todo":"add a task","delete todo":"delete a task","toggle todo":"mark a task done","complete todo":"mark a task done","search users":"search for a user","create user":"create a user","sign in":"sign in","sign out":"sign out","log in":"sign in","log out":"sign out",checkout:"check out","add to cart":"add something to your cart","place order":"place your order"};if(l[r])return l[r];if(i){let u=i.match(/^(adds?|creates?|deletes?|removes?|updates?|sends?|opens?|shows?|lists?|marks?|completes?|toggles?|searches?|finds?|places?|submits?)\s+(.+?)(?:\.|$)/i);if(u){let p=u[1].toLowerCase().replace(/s$/,""),f=u[2].toLowerCase();return n?`${(c={add:"a\xF1adir",create:"crear",delete:"eliminar",remove:"quitar",update:"actualizar",send:"enviar",open:"abrir",show:"ver",list:"ver",mark:"marcar",complete:"completar",toggle:"cambiar",search:"buscar",find:"buscar",place:"hacer",submit:"enviar"}[p])!=null?c:p} ${f}`.slice(0,48):`${p} ${f}`.slice(0,48)}}if(o){let u=o.split(/\s+/);return u.length>=2?`${u[0].toLowerCase()} ${u.slice(1).join(" ").toLowerCase()}`:o.toLowerCase()}return xe(e.intent).replace(/_/g," ")}function Ir(e,t,n){let o=Rr(e,n);return ee(t.bubblePromptFromAction,{action:o})}function Or(e,t){let n=e.toLowerCase(),o=Vn(t),i=e.match(/from here (?:you|the user|users?) (?:can|may|could)\s+(.+?)(?:[.;]|$)/i);if(i!=null&&i[1]){let r=i[1].trim().replace(/[.;]+$/,"");if(r.length>=4&&r.length<=56)return o?`\xBFQuieres ${r.toLowerCase()}?`:`Want to ${r.toLowerCase()}?`}return/sign(?:\s|-)?in|log(?:\s|-)?in|authenticate|iniciar ses/i.test(n)?o?"\xBFQuieres iniciar sesi\xF3n?":"Want to sign in?":/sign(?:\s|-)?up|register|create an account|registr/i.test(n)?o?"\xBFQuieres registrarte?":"Want to create an account?":/cart|checkout|check out|finalizar compra|pagar/i.test(n)?o?"\xBFFinalizar tu compra?":"Ready to checkout?":/user|account|people|person|usuario|cuenta/i.test(n)&&/list|search|browse|manage|ver|buscar/i.test(n)?o?"\xBFBuscar un usuario?":"Looking for a user?":/product|item|catalog|tienda|producto/i.test(n)&&/list|browse|shop|search|ver|buscar/i.test(n)?o?"\xBFBuscar un producto?":"Browse products?":/task|todo|tarea/i.test(n)&&/add|create|list|manage|añadir|crear/i.test(n)?o?"\xBFA\xF1adir una tarea?":"Want to add a task?":/setting|preference|ajuste|configur/i.test(n)?o?"\xBFCambiar alg\xFAn ajuste?":"Need to change a setting?":/profile|perfil/i.test(n)?o?"\xBFActualizar tu perfil?":"Update your profile?":/bill|invoice|payment|factur|pago/i.test(n)?o?"\xBFVer tu facturaci\xF3n?":"Check your billing?":/password|contrase/i.test(n)?o?"\xBFCambiar tu contrase\xF1a?":"Change your password?":/message|chat|conversation/i.test(n)?o?"\xBFEnviar un mensaje?":"Send a message?":/order|pedido/i.test(n)?o?"\xBFVer tus pedidos?":"Check your orders?":null}function kr(e,t){let n=Vn(t),o=Tr(e.intent),i=xe(e.label).toLowerCase();if(Ho.has(o)||Ho.has(i.replace(/\s+/g,"_")))return null;let r=`${o} ${i}`;return/login|sign_in|signin|auth/.test(r)?n?"\xBFQuieres iniciar sesi\xF3n?":"Want to sign in?":/register|signup|sign_up|sign-up/.test(r)?n?"\xBFQuieres registrarte?":"Want to create an account?":/cart|checkout|basket/.test(r)?n?"\xBFFinalizar tu compra?":"Ready to checkout?":/user|users|account|people|member/.test(r)?n?"\xBFBuscar un usuario?":"Looking for a user?":/product|catalog|shop|store|item/.test(r)?n?"\xBFBuscar un producto?":"Browse products?":/todo|task/.test(r)?n?"\xBFA\xF1adir una tarea?":"Want to add a task?":/setting|preference|config/.test(r)?n?"\xBFCambiar alg\xFAn ajuste?":"Need to change a setting?":/profile|account_overview/.test(r)?n?"\xBFActualizar tu perfil?":"Update your profile?":/bill|invoice|payment|subscription|pricing/.test(r)?n?"\xBFVer tu facturaci\xF3n?":"Check your billing?":/search|find|lookup/.test(r)?n?"\xBFQu\xE9 buscas?":"What are you looking for?":/chat|message|inbox|conversation/.test(r)?n?"\xBFEnviar un mensaje?":"Send a message?":/password|security/.test(r)?n?"\xBFCambiar tu contrase\xF1a?":"Change your password?":/order|transaction|history/.test(r)?n?"\xBFVer tu historial?":"Review your history?":/wallet|budget|saving|finance|balance/.test(r)?n?"\xBFRevisar tus finanzas?":"Review your finances?":/note|editor|write|compose|new_chat/.test(r)?n?"\xBFEscribir algo nuevo?":"Write something new?":null}function _r(e,t,n){var r;let o=((r=e.examples)!=null?r:[]).map(xe).find(s=>s.length>0&&Sr(s));if(!o)return null;let i=o.replace(/\?+$/,"").trim();return/^(take me|go to|open|show me|navigate|ir a|abrir|mostrar|llévame)/i.test(i)?null:ee(t.bubblePromptFromExample,{phrase:i})}function $t(e,t,n){var l;let o=(l=n==null?void 0:n.locale)!=null?l:"en",i=n==null?void 0:n.actions,r=Er(e,i);if(r)return Ir(r,t,o);let s=xe(e.description);if(s){let c=Or(s,o);if(c)return c}let a=kr(e,o);return a||_r(e,t,o)}function q(e){let t=String(e!=null?e:"").trim();return t?(t=t.split("?")[0].split("#")[0],t=t.replace(/\([^)]*\)/g,""),t=t.replace(/\/{2,}/g,"/").replace(/^\/+|\/+$/g,""),t=t.replace(/(^|\/)index$/i,""),t=t.replace(/^\/+|\/+$/g,""),t.toLowerCase()):""}function Vo(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}function tt(e,t){if(e==null||!t||t.length===0)return null;let n=String(e).trim();if(!n)return null;let o=q(n),i=t.filter(s=>s&&s.route&&s.route!==fe);if(i.length===0)return null;for(let s of i)if(q(s.route)===o)return s;if(o){let s=null;for(let a of i){let l=q(a.route);if(!l)continue;(o===l||o.startsWith(`${l}/`)||l.startsWith(`${o}/`)||o.endsWith(`/${l}`)||l.endsWith(`/${o}`))&&(!s||l.length>s.len)&&(s={route:a,len:l.length})}if(s)return s.route}let r=Vo(o)||o;if(r){for(let s of i)if(q(s.intent)===r||q(s.label)===r||Vo(q(s.route))===r)return s;for(let s of i)if(q(s.intent)===o||q(s.label)===o)return s}return null}function zn(e,t){var l,c,u,p,f;if(!e)return null;let n=((l=e.label)==null?void 0:l.trim())||((c=e.intent)==null?void 0:c.trim());if(!n)return null;let{messages:o,actions:i}=t,r=[ee(o.currentScreenLabel,{label:n})],s=(u=e.description)==null?void 0:u.trim();s&&r.push(s);let a=(p=e.actionIntents)!=null?p:[];if(a.length>0&&i&&i.length>0){let m=new Map(i.map(T=>[T.intent,T])),h=[],x=new Set;for(let T of a){let v=m.get(T),S=(f=v==null?void 0:v.label)==null?void 0:f.trim();S&&!x.has(S)&&(x.add(S),h.push(S))}h.length>0&&r.push(ee(o.currentScreenActions,{actions:h.join(", ")}))}return r.join(" \u2014 ")}function Go(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function zo(e){return String(e!=null?e:"").split(/[-_]/)[0].trim().toLowerCase()}function Pr(e,t){let n=e.bubblePrompts;if(!n||typeof n!="object")return null;let o=zo(t);if(!o)return null;for(let[i,r]of Object.entries(n))if(zo(i)===o){let s=Go(r);if(s)return s}return null}function Dt(e,t,n){if(!e)return null;let o=Pr(e,n==null?void 0:n.locale);if(o)return o;let i=Go(e.bubblePrompt);if(i)return i;let r=$t(e,t,{locale:n==null?void 0:n.locale,actions:n==null?void 0:n.actions});return r||null}function Ft(e,t,n){let o=tt(e,t.routes);return zn(o,{messages:n,actions:t.actions})}var Mr=/(^|[\s_.-])(log[\s_-]?in|sign[\s_-]?in|iniciar[\s_-]?sesi[oó]n|inicia[\s_-]?sesi[oó]n)([\s_.-]|$)|\b(login|signin|acceder|autenticar|authenticate)\b/i,Lr=/log[\s_-]?out|sign[\s_-]?out|sign[\s_-]?up|signup|register|registr|cerrar[\s_-]?sesi[oó]n|crear[\s_-]?cuenta|reset|recover|recuperar|forgot|olvid/i,Br=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,Nr=/pass(word)?|contrase|clave|pwd/i;function Kn(e){var o,i;if(e.kind==="link"||(o=e.contextRequirements)!=null&&o.requiresAuth)return!1;let t=`${e.intent} ${e.label} ${(i=e.handler)!=null?i:""}`;if(Lr.test(t)||!Mr.test(t))return!1;let n=Wt(e);return n.usernameParam!==null&&n.passwordParam!==null}function Wt(e){var o;let t=null,n=null;for(let[i,r]of Object.entries((o=e.parameters)!=null?o:{}))if(r.type==="string"){if(n===null&&Nr.test(i)){n=i;continue}t===null&&Br.test(i)&&(t=i)}return{usernameParam:t,passwordParam:n}}function Gn(e){return typeof e=="string"?e.trim().length>0:e!=null}async function Ut(e,t,n,o){var c;if(!n)return{kind:"not-applicable"};let i=!1;try{i=n.isSupported()===!0}catch{i=!1}if(!i)return{kind:"not-applicable"};if(!Kn(t))return{kind:"not-applicable"};if((o==null?void 0:o())===!0)return{kind:"not-applicable"};let{usernameParam:r,passwordParam:s}=Wt(t);if(!r||!s)return{kind:"not-applicable"};let a=(c=e.parameters)!=null?c:{};if(Gn(a[r])&&Gn(a[s]))return{kind:"not-applicable"};let l;try{l=await n.requestCredentials()}catch{l={status:"unavailable"}}return l.status==="success"&&l.username&&l.password?{kind:"proceed",action:{...e,parameters:{...a,[r]:Gn(a[r])?a[r]:l.username,[s]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}function Ht(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(i){var a,l;let r=(a=i.intent)==null?void 0:a.trim();if(!r)return{success:!1,error:"No intent specified"};let s=e.manifest.routes.find(c=>c.intent===r);if(!s)return{success:!1,error:`Unknown intent: ${r}`};if(s.route!==fe&&e.messages.alreadyOnScreen)try{let c=e.navigation.getCurrentRoute();if(c!=null&&String(c).trim()!==""&&q(c)===q(s.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return s.route===fe?e.navigation.back():e.navigation.navigate(s.route),{success:!0}}catch(c){return{success:!1,error:`Navigation failed: ${c instanceof Error?c.message:"unknown"}`,message:(l=e.messages.navigationFailed)!=null?l:e.messages.actionFailed}}}function o(i,r){if(!(i!=null&&i.showcaseRoute)||!r.success||r.recoverable)return;let s=e.manifest.routes.find(a=>a.intent===i.showcaseRoute);if(!(!s||s.route===fe))try{let a=e.navigation.getCurrentRoute();if(a!=null&&String(a).trim()!==""&&q(a)===q(s.route))return;e.navigation.navigate(s.route)}catch{}}return{async execute(i,r={}){var s,a;if(!i||i.type==="none")return{success:!0};if(i.type==="navigate")return n(i);if(i.type==="execute"){let l=e.manifest.actions.find(u=>{var p;return u.intent===((p=i.intent)==null?void 0:p.trim())});if(l){let u=await Ut(i,l,e.credentialAutofill,e.isAuthenticated);if(u.kind==="proceed"){let p=await Ze(u.action,e.manifest.actions,r,e.registries,t);return o(l,p),p}if(u.kind==="dismissed"||u.kind==="unavailable"){let p=u.kind==="dismissed"?(s=e.messages.signInAutofillDismissed)!=null?s:e.messages.cancelled:(a=e.messages.signInAutofillUnavailable)!=null?a:e.messages.actionUnavailable;return{success:!1,error:`sign_in_autofill_${u.kind}`,message:p}}}let c=await Ze(i,e.manifest.actions,r,e.registries,t);return o(l,c),c}return{success:!1,error:`Action type not implemented: ${i.type}`}},async precheck(i,r={}){return Je(i,e.manifest.actions,r,e.registries,t)}}}function Vt(e,t){var o,i;if(e.kind==="link"||e.execution)return!0;let n=((o=e.handler)!=null?o:"").trim();return n?typeof((i=t.handlers)==null?void 0:i[n])=="function":!1}var Ko=new Set;function zt(e,t){var s,a,l;if(!t)return e;let n=(s=e.actions)!=null?s:[],o=n.filter(c=>Vt(c,t));if(o.length===n.length)return e;let i=n.filter(c=>!Vt(c,t)).map(c=>c.intent).sort(),r=i.join(",");return Ko.has(r)||(Ko.add(r),(l=(a=globalThis.console)==null?void 0:a.warn)==null||l.call(a,`[fyodos] ${i.length} manifest action(s) have no live handler in this app and were hidden from the agent so it never promises them: ${i.join(", ")}. To restore them, finish their wiring (see src/fyodos/FYODOS_HANDLERS.md) or re-run \`npx @fiodos/cli rewire .\` in the app repo.`)),{...e,actions:o}}function Yn(e,t){if(typeof e=="string")return e.length>300?`${e.slice(0,300)}\u2026`:e;if(e===null||typeof e!="object")return e;if(t>=5)return Array.isArray(e)?"[\u2026]":"{\u2026}";if(Array.isArray(e)){let n=e.slice(0,6).map(o=>Yn(o,t+1));return e.length>6&&n.push(`\u2026(${e.length-6} more)`),n}return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Yn(o,t+1)]))}function Gt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return;let t;try{t=Yn(e,0);let n=JSON.stringify(t);if(n.length>6e3){let o=Object.entries(t).sort((i,r)=>JSON.stringify(r[1]).length-JSON.stringify(i[1]).length);for(;n.length>6e3&&o.length>1;){let[i]=o.shift();delete t[i],t[i]="\u2026(omitted)",n=JSON.stringify(t)}if(n.length>6e3)return}}catch{return}return t}function ke(e,t){var i;let n=(i=t.maxChars)!=null?i:1500;if(e.length<=n)return e;let o=Math.max(0,n-t.truncationSuffix.length);return e.slice(0,o)+t.truncationSuffix}function nt(e,t,n){var l;let o=(l=n.maxChars)!=null?l:1500,i=(e==null?void 0:e.trim())||null,r=(t==null?void 0:t.trim())||null;if(!i&&!r)return null;if(!r)return ke(i,{...n,maxChars:o});if(!i)return ke(r,{...n,maxChars:o});let s=`
2
2
 
3
- `,a=o-i.length-s.length;return a<=n.truncationSuffix.length?ke(i,{...n,maxChars:o}):i+s+ke(r,{...n,maxChars:a})}var Wn=[{type:"email",regex:/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,replacement:"[REDACTED:EMAIL]"},{type:"payment_card",regex:/\b\d(?:[ -]?\d){12,18}\b/g,replacement:"[REDACTED:CARD]"},{type:"phone",regex:/(?:\+\d{1,3}[\s.-]?)?\b\d(?:[\s.-]?\d){8,13}\b/g,replacement:"[REDACTED:PHONE]"}],Dt={ES:[{type:"iban_es",regex:/\bES[\s-]?\d{2}(?:[\s-]?\d){20}\b/g,replacement:"[REDACTED:IBAN]"},{type:"national_id_es",regex:/\b\d{8}[A-Za-z]\b/g,replacement:"[REDACTED:NATIONAL_ID]"}],US:[{type:"ssn_us",regex:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g,replacement:"[REDACTED:NATIONAL_ID]"}]};function Un(e={}){var i,r;let t=((i=e.countryPacks)!=null?i:[]).flatMap(s=>{let a=Dt[s.toUpperCase()];if(!a)throw new Error(`[fyodos] Unknown PII country pack "${s}". Available packs: ${Object.keys(Dt).join(", ")}. Use customPatterns to add your own.`);return a}),[n,...o]=Wn;return[n,...(r=e.customPatterns)!=null?r:[],...t,...o]}function Ft(e={}){let t=Un(e);return n=>{let o=n,i=[];for(let{type:r,regex:s,replacement:a}of t)s.test(o)&&(i.push(r),o=o.replace(s,a)),s.lastIndex=0;return o=o.replace(/\+\s?\[REDACTED:PHONE\]/g,"[REDACTED:PHONE]"),{sanitized:o,redactions:i}}}function Sr(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function wr(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Tr(e){return wr(e)==="es"}function Hn(e){return e.replace(/^[¿¡]+/,"").replace(/[?!.…]+$/,"").trim()}function Er(e,t,n){var f;let o=Hn(e),i=Hn(t),r=i.match(/\{(\w+)\}/);if(!r||r.index==null)return null;let s=r[1],a=i.slice(0,r.index).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=i.slice(r.index+r[0].length).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${a}(?<value>.+?)${l}$`,"i"),u=o.match(c);if(!((f=u==null?void 0:u.groups)!=null&&f.value))return null;let p=u.groups.value.trim();return n.replace(`{${s}}`,p)}var Ir=[[/^want to (.+)$/i,"I want to $1"],[/^ready to checkout$/i,"I want to checkout"],[/^ready to (.+)$/i,"I want to $1"],[/^looking for (.+)$/i,"I'm looking for $1"],[/^browse (.+)$/i,"I want to browse $1"],[/^check your (.+)$/i,"I want to check my $1"],[/^need to (.+)$/i,"I need to $1"],[/^update your (.+)$/i,"I want to update my $1"],[/^send (.+)$/i,"I want to send $1"],[/^change your (.+)$/i,"I want to change my $1"],[/^review your (.+)$/i,"I want to review my $1"],[/^write (.+)$/i,"I want to write $1"],[/^what are you looking for$/i,"I'm looking for something"]],Rr=[[/^quieres ir a (.+)$/i,"Quiero ir a $1"],[/^quieres (.+)$/i,"Quiero $1"],[/^finalizar tu compra$/i,"Quiero finalizar mi compra"],[/^buscar un usuario$/i,"Quiero buscar un usuario"],[/^buscar un producto$/i,"Quiero buscar un producto"],[/^buscar (.+)$/i,"Quiero buscar $1"],[/^ver tu (.+)$/i,"Quiero ver mi $1"],[/^ver tus (.+)$/i,"Quiero ver mis $1"],[/^cambiar algún ajuste$/i,"Quiero cambiar un ajuste"],[/^cambiar tu (.+)$/i,"Quiero cambiar mi $1"],[/^actualizar tu perfil$/i,"Quiero actualizar mi perfil"],[/^añadir una tarea$/i,"Quiero a\xF1adir una tarea"],[/^añadir (.+)$/i,"Quiero a\xF1adir $1"],[/^enviar un mensaje$/i,"Quiero enviar un mensaje"],[/^revisar tus finanzas$/i,"Quiero revisar mis finanzas"],[/^revisar tu historial$/i,"Quiero revisar mi historial"],[/^escribir algo nuevo$/i,"Quiero escribir algo nuevo"],[/^qué buscas$/i,"Busco algo"]];function Wt(e,t){var c;let n=Sr(e);if(!n)return"";let o=(c=t==null?void 0:t.locale)!=null?c:"en",i=Tr(o),r=t==null?void 0:t.messages,s=Hn(n);if(r){let u=i?[[r.bubblePromptFromExample,"Quiero {phrase}"],[r.bubblePromptFromAction,"Quiero {action}"],[r.bubblePromptFromLabel,"Quiero ir a {label}"]]:[[r.bubblePromptFromExample,"I want to {phrase}"],[r.bubblePromptFromAction,"I want to {action}"],[r.bubblePromptFromLabel,"I want to open {label}"]];for(let[p,f]of u){let m=Er(n,p,f);if(m)return m}}let a=i?Rr:Ir;for(let[u,p]of a)if(u.test(s))return s.replace(u,p);return i?`Quiero ${s.charAt(0).toLowerCase()+s.slice(1)}`:`I want to ${s.charAt(0).toLowerCase()+s.slice(1)}`}function zn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function Ut(e){var o;let t=zn(e.appId,(o=e.version)!=null?o:1),{storage:n}=e;return{storageKey:t,async hasConsented(){try{let i=await n.getItem(t);return i?JSON.parse(i).granted===!0:!1}catch{return!1}},async grant(){let i=JSON.stringify({granted:!0,grantedAt:new Date().toISOString()});await n.setItem(t,i)},async revoke(){await n.removeItem(t)}}}function Ht(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function zt(e,t){let n=Ht(e);if(!n)return{matched:!1,command:""};for(let o of t){let i=Ht(o);if(!i)continue;let r=n.indexOf(i);if(r===-1)continue;return{matched:!0,command:n.slice(r+i.length).trim(),phrase:i}}return{matched:!1,command:""}}function Vt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var No=40;function Gt(e){return typeof e!="number"||Number.isNaN(e)?No:Math.max(0,Math.min(100,Math.round(e)))}function $o(e,t){let n=Gt(t);if(n<=0)return 0;let o=n/100,i=r=>Math.max(1,Math.round(r*o));switch(e){case"response":return[0,i(12),40,i(12)];case"orbTap":return i(18);case"listenStart":return i(14);case"listenStop":return i(8);default:return i(10)}}function Vn(e){let t=()=>typeof e=="function"?e():e;return{trigger(n){try{let i=globalThis.navigator,r=$o(n,t());!(r===0||Array.isArray(r)&&r.every(a=>a===0))&&i&&typeof i.vibrate=="function"&&i.vibrate(r)}catch{}}}}var et={en:{affirmative:["yes","yeah","yep","sure","confirm","confirmed","go ahead","do it","ok","okay","correct","exactly","absolutely","affirmative"],negative:["no","nope","cancel","cancel it","stop","wait","dont","never mind","nevermind","forget it","negative"]},es:{affirmative:["si","s\xED","confirma","confirmo","adelante","hazlo","vale","ok","okey","correcto","exacto","claro","efectivamente","dale"],negative:["no","cancela","cancelar","cancelalo","canc\xE9lalo","para","espera","detente","mejor no","olvidalo","olv\xEDdalo","nada"]}};function Kt(e){var o,i,r;let t=(i=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?i:e.toLowerCase(),n=(r=et[e])!=null?r:et[t];if(!n)throw new Error(`[fyodos] No confirmation lexicon for locale "${e}". Built-in locales: ${Object.keys(et).join(", ")}. Pass a custom ConfirmationLexicon for your locale.`);return n}function _e(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Do(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function Gn(e,t){let n=_e(e);return n?t.affirmative.some(o=>Do(n,_e(o))):!1}function Yt(e,t){let n=_e(e);return n?t.negative.some(o=>Do(n,_e(o))):!1}function jt(e,t){let n=Yt(e,t),o=Gn(e,t);return n?"negative":o?"affirmative":"ambiguous"}function jr(e,t){return t?` ${e} `.includes(` ${t} `):!1}function Xt(e,t,n){let o=_e(e);return o?Yt(e,n)?"negative":jr(o,_e(t))?"affirmative":"ambiguous":"ambiguous"}var Kn={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},tt={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Me(e,t=!1){let n=t?tt:void 0;return e==null||typeof e!="number"||Number.isNaN(e)?n?{...n}:void 0:e<=0?{...n,sessionIdleMs:Number.POSITIVE_INFINITY}:{...n,sessionIdleMs:Math.round(e*6e4)}}var ve=5,Pe=200;function Fo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Wo(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Uo(e,t,n){let o=t.map(i=>i.role==="user"?`User: ${Fo(i.content,120)}`:`Assistant: ${Fo(i.content,120)}`).join(" | ");return Wo(e?`${e} | ${o}`:o,n)}function Yn(e){return{...Kn,...e}}function Le(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function Be(e,t=Date.now(),n){var i;let{sessionIdleMs:o}=Yn(n);return e.turns.length===0&&!e.summary&&!((i=e.uiArchive)!=null&&i.length)?(e.lastActivityAt=t,!1):t-e.lastActivityAt<=o?!1:(e.turns=[],e.summary=null,e.uiArchive=[],e.lastActivityAt=t,!0)}function jn(e,t=null,n){let{maxRecentTurns:o}=Yn(n);return e.length===0?{history:[],summary:(t==null?void 0:t.trim())||null}:{history:e.slice(-o),summary:(t==null?void 0:t.trim())||null}}function nt(e,t=Date.now(),n){return Be(e,t,n),e.lastActivityAt=t,jn(e.turns,e.summary,n)}function Xr(e,t){let{maxRecentTurns:n,summarizeAfterTurns:o,maxSummaryChars:i,maxStoredTurns:r}=t;if(e.turns.length>o){let s=e.turns.length-n,a=e.turns.slice(0,s);e.summary=Uo(e.summary,a,i),e.turns=e.turns.slice(s)}if(e.turns.length>r){let s=e.turns.slice(0,e.turns.length-n);e.summary=Uo(e.summary,s,i),e.turns=e.turns.slice(-n)}}function ot(e,t,n,o=Date.now(),i){var l;let r=Yn(i),s=t.trim(),a=n.trim();!s||!a||(e.turns.push({role:"user",content:s},{role:"assistant",content:a}),e.uiArchive=(l=e.uiArchive)!=null?l:[],e.uiArchive.push({userText:s,replyText:a}),e.uiArchive.length>Pe&&(e.uiArchive=e.uiArchive.slice(-Pe)),e.lastActivityAt=o,Xr(e,r))}function qr(e,t){var r,s,a,l;let n;if((r=e.uiArchive)!=null&&r.length)n=e.uiArchive;else{n=[];for(let c=0;c<e.turns.length;c+=2){let u=e.turns[c],p=e.turns[c+1];(u==null?void 0:u.role)==="user"&&(p==null?void 0:p.role)==="assistant"&&n.push({userText:u.content,replyText:p.content})}}if(!((s=t==null?void 0:t.userText)!=null&&s.trim()))return n;let o=n[n.length-1];return o!=null&&o.userText===t.userText&&o.replyText===((a=t.replyText)!=null?a:"")?t.replyText&&o.replyText!==t.replyText?[...n.slice(0,-1),t]:n:[...n,{userText:t.userText,replyText:(l=t.replyText)!=null?l:""}]}function it(e,t,n=ve,o){Be(e,Date.now(),o);let i=qr(e,t),r=Math.max(1,n);return{exchanges:i.slice(-r),hasOlder:i.length>r,totalCount:i.length}}var ce="anon";function rt(e){let t=(e!=null?e:"").trim();if(!t)return ce;let n=2166136261;for(let o=0;o<t.length;o++)n^=t.charCodeAt(o),n=Math.imul(n,16777619);return`u_${(n>>>0).toString(36)}`}function st(e,t="public",n=ce){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===ce?o:`${o}/${n}`}function Qr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-tt.maxStoredTurns)){let o=n==null?void 0:n.role,i=n==null?void 0:n.content;(o==="user"||o==="assistant")&&typeof i=="string"&&i&&t.push({role:o,content:i})}return t}function Jr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Pe)){let o=n==null?void 0:n.userText,i=n==null?void 0:n.replyText;typeof o=="string"&&o&&typeof i=="string"&&t.push({userText:o,replyText:i})}return t}async function qt(e,t,n,o=null,i="public",r=ce){var a,l;let s=st(t,i,r);try{if(n.turns.length===0&&!n.summary&&!((a=n.uiArchive)!=null&&a.length)){await e.removeItem(s);return}let u={v:1,turns:n.turns,summary:n.summary,lastActivityAt:n.lastActivityAt,uiArchive:(l=n.uiArchive)!=null?l:[],retentionMinutes:o,owner:r};await e.setItem(s,JSON.stringify(u))}catch{}}async function Qt(e,t,n=Date.now(),o="public",i=ce){var s;let r=st(t,o,i);try{let a=await e.getItem(r);if(!a)return null;let l=JSON.parse(a);if((l==null?void 0:l.v)!==1)return await e.removeItem(r),null;if((typeof l.owner=="string"?l.owner:ce)!==i)return null;let u={turns:Qr(l.turns),summary:typeof l.summary=="string"&&l.summary?l.summary:null,lastActivityAt:typeof l.lastActivityAt=="number"&&Number.isFinite(l.lastActivityAt)?l.lastActivityAt:0,uiArchive:Jr(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return Be(u,n,Me(p))||u.turns.length===0&&!u.summary&&!((s=u.uiArchive)!=null&&s.length)?(await e.removeItem(r),null):(u.lastActivityAt=n,u)}catch{return null}}async function Jt(e,t,n="public",o=ce){try{await e.removeItem(st(t,n,o))}catch{}}function Ne(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function Xn(e,t){let n=Ne(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function qn(e,t){return Xn(e,t)}var $e=35,at="rgba(255,255,255,0.1)",ct="#ffffff";function De(e){return e==null||Number.isNaN(Number(e))?$e:Math.max(0,Math.min(100,Number(e)))}function Qn(e,t){let n=De(t)/100;return n<=0?0:e*(.002+n*.012)}function lt(e){let t=e==null?void 0:e.trim();if(!t)return at;if(t.startsWith("rgba")||t.startsWith("rgb"))return t;if(t.startsWith("#")){let n=t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t.slice(0,7),o=parseInt(n.slice(1,3),16),i=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return[o,i,r].some(s=>Number.isNaN(s))?at:`rgba(${o},${i},${r},0.12)`}return at}function ut(e,t,n){let o=e,i=Qn(e,n),r=qn(e,t),s=o+2*i,a=o+2*i+2*r;return{fillPx:o,interiorPx:i,exteriorPx:r,totalPx:a,fillRadius:o/2,midPx:s}}function Zt(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function en(e){let t=e/150;return[`inset -${Math.round(8*t)}px -${Math.round(12*t)}px ${Math.round(28*t)}px rgba(0,0,0,0.36)`,`inset ${Math.round(6*t)}px ${Math.round(8*t)}px ${Math.round(20*t)}px rgba(255,255,255,0.07)`].join(", ")}var te={accent:"#2f6bff",glow:"#5aa2ff",background:"rgba(0,0,0,0.72)",waveform:"#ffffff",colorKey:"azul"},Ho={colorKey:te.colorKey,glowKey:te.colorKey,accentColor:te.accent,glowColor:te.glow,backgroundColor:te.background,waveformColor:te.waveform,waveformColorKey:"custom",speed:42,glowIntensity:100,innerBorderColor:ct,innerBorderWidth:$e,borderWidth:1.5,waveformHeight:26,size:52},zo={size:30,shape:"circle",backgroundColor:te.background,borderColor:te.accent,iconColor:te.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:ct,innerBorderWidth:$e,borderWidth:100},dt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},Vo={cardBackgroundColor:"#16181d",cardBorderColor:"rgba(255,255,255,0.14)",userTextColor:"rgba(255,255,255,0.75)",replyTextColor:"#ffffff",accentColor:te.accent,inputBackgroundColor:"#ffffff",borderRadius:18,sendButtonRadius:16};function tn(e){let t=Go(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function nn(e){let t=Go(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function Go(e){if(!e)return null;let t=e.trim().toLowerCase(),n,o,i,r=t.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/);if(r){let s=r[1];s.length===3?(n=parseInt(s[0]+s[0],16),o=parseInt(s[1]+s[1],16),i=parseInt(s[2]+s[2],16)):(n=parseInt(s.slice(0,2),16),o=parseInt(s.slice(2,4),16),i=parseInt(s.slice(4,6),16))}else{let s=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(!s)return null;n=Number(s[1]),o=Number(s[2]),i=Number(s[3])}return(.299*n+.587*o+.114*i)/255}var on={bars:[.42,.72,1,.72,.42],color:"#eaf1ff",barWidthRatio:.06,gapRatio:.05,heightRatio:.4};function Jn(e){let{bars:t,barWidthRatio:n,gapRatio:o,heightRatio:i,color:r}=on,s=e*n,a=e*o,l=e*i,c=t.length*s+(t.length-1)*a,u=(e-c)/2;return{bars:t.map((f,m)=>{let h=Math.max(s,l*f);return{x:u+m*(s+a),y:(e-h)/2,width:s,height:h}}),color:r,radius:s/2}}function rn(e){let{bars:t,color:n,radius:o}=Jn(e),i=e/2,r=e*on.heightRatio/2;return{color:n,radius:o,bars:t.map(s=>({...s,baseHalfHeight:s.height/2,centerY:i,maxHalfHeight:r}))}}function sn(e,t,n,o){let i=.5+.5*((.5+.5*Math.sin(e*1.6))*.6+(.5+.5*Math.sin(e*.9+1.1))*.4),r=.35+.65*(.5+.5*Math.sin(e*7+t*.95))*(.55+.45*Math.sin(e*3.1+t*.6)),s=n*(.5+r*i);return Math.max(n*.35,Math.min(s,o))}var os=["pill","rounded","square","cloud"];function Ko(e,t,n,o,i,r,s){let a=[];for(let l=0;l<=s;l++){let c=i+(r-i)*l/s;a.push([e+n*Math.cos(c),t+o*Math.sin(c)])}return a}function is(e,t,n,o,i){let r=[];for(let s=0;s<=i;s++){let a=Math.PI-Math.PI*s/i;r.push([e+n*Math.cos(a),t-o*Math.sin(a)])}return r}function rs(e,t,n,o,i){let r=[];for(let s=0;s<=i;s++){let a=Math.PI*s/i;r.push([e+n*Math.cos(a),t+o*Math.sin(a)])}return r}function an(e,t,n){n&&t.shift(),e.push(...t)}var ss=1.28,as=38;function jo(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function eo(e){if(!Number.isFinite(e)||e<=0)return 5;let t=e*.88;return jo(t/as,3,7)}function Xo(e=5){let l=jo(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];an(f,Ko(6,50,u,p,Math.PI/2,Math.PI*3/2,10),!1);for(let h=0;h<l;h++){let y=6+c+2*c*h;an(f,is(y,18,c,14,8),!0)}an(f,Ko(94,50,u,p,-Math.PI/2,Math.PI/2,10),!0);for(let h=l-1;h>=0;h--){let y=6+c+2*c*h;an(f,rs(y,83,c,12,8),!0)}return`polygon(${f.map(([h,y])=>`${h.toFixed(2)}% ${y.toFixed(2)}%`).join(", ")})`}var to=Xo(5);function no(e){return Xo(eo(e))}function pt(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Zn(e,t){return typeof e=="string"&&e.trim()?e:t}function cn(e){let t=String(e!=null?e:"").toLowerCase();return t==="circle"||t==="round"?"cloud":os.includes(t)?t:dt.shape}function ft(e,t){if(e!=null)return`${Math.round(e*t)}px`}function Fe(e){let t=e!=null?e:{},n=dt,o=pt(t.textSize,pt(t.size,n.textSize));return{backgroundColor:Zn(t.backgroundColor,n.backgroundColor),textColor:Zn(t.textColor,n.textColor),borderColor:Zn(t.borderColor,n.borderColor),borderWidth:pt(t.borderWidth,n.borderWidth),shape:cn(t.shape),borderRadius:pt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:pt(t.bubbleScale,n.bubbleScale)}}var oo=38,io=14,Yo=4;function ht(e){let t=e.textSize,n=e.bubbleScale,o=Math.round(io*n),i=Math.round(t*1.25),r=Math.max(Math.round(oo*n),i+Yo*2);cn(e.shape)==="cloud"&&(r=Math.round(r*ss));let s=Math.max(Yo,Math.round((r-i)/2));return{fontPx:t,padV:s,padH:o,approxHeight:r}}function cs(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var qo=999;function ro(e,t,n){switch(cn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:qo};case"cloud":{let i=cs(t),r=typeof n=="number"&&n>0?no(n):to;return{...i,clipPath:r}}default:return{borderRadius:Math.min(e.borderRadius,Math.round(t/2))}}}function ln(e,t,n=1,o){var s;let i=cn(e.shape),r=ro({...e,shape:i},t,o);if(i==="pill"){let a=`${Math.round(qo*n)}px`;return{borderRadius:a,borderTopLeftRadius:a,borderTopRightRadius:a,borderBottomLeftRadius:a,borderBottomRightRadius:a,clipPath:"none"}}return i==="square"?{borderRadius:"0px",borderTopLeftRadius:"0px",borderTopRightRadius:"0px",borderBottomLeftRadius:"0px",borderBottomRightRadius:"0px",clipPath:"none"}:{borderRadius:ft(r.borderRadius,n),borderTopLeftRadius:ft(r.borderTopLeftRadius,n),borderTopRightRadius:ft(r.borderTopRightRadius,n),borderBottomLeftRadius:ft(r.borderBottomLeftRadius,n),borderBottomRightRadius:ft(r.borderBottomRightRadius,n),clipPath:(s=r.clipPath)!=null?s:"none"}}function un(e,t){if(!e)return;let n=(o,i)=>{if(!i){e.style.removeProperty(o);return}e.style.setProperty(o,i,"important")};n("border-radius",t.borderRadius),n("border-top-left-radius",t.borderTopLeftRadius),n("border-top-right-radius",t.borderTopRightRadius),n("border-bottom-left-radius",t.borderBottomLeftRadius),n("border-bottom-right-radius",t.borderBottomRightRadius),n("clip-path",t.clipPath)}function dn(e){return Math.round(e*.5)}function pn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function fn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function hn(e,t,n="#ffffff"){let o=(e!=null?e:n).trim(),i=t.trim();if(!o)return n;let r=s=>{let a=s.toLowerCase();return a.startsWith("#")&&a.length>=7?a.slice(0,7):a};return r(o)===r(i)?n:o}var ls=[[8,11],[11,11],[14,11],[17,11],[8,14],[11,14],[14,14],[17,14]],Qo={keyboard:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:4,minY:7,maxX:20,maxY:18},keyboardFrame:{x:4,y:7,w:16,h:11,rx:2},keyDots:ls},pen:{viewBox:"0 0 24 24",paths:[{d:"M4 20h4l10.5-10.5a1.5 1.5 0 0 0 0-2.12l-2.38-2.38a1.5 1.5 0 0 0-2.12 0L4 15.5V20z",fill:!1},{d:"M13.5 6.5l4 4",fill:!1}],contentBBox:{minX:4,minY:6.5,maxX:17.5,maxY:20}},chat:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:5,minY:4,maxX:19,maxY:18.5},chatFrame:{x:5,y:4,w:14,h:10,rx:2.5},chatTail:{left:7.5,right:10.5,tipX:5,tipY:18.5},chatLines:[{y:8,w:6},{y:10,w:6}]}};function mn(e="keyboard"){var t;return(t=Qo[e])!=null?t:Qo.keyboard}function gn(e){var l,c;let t=e.viewBox.split(/\s+/).map(Number),n=(l=t[2])!=null?l:24,o=(c=t[3])!=null?c:24,{minX:i,minY:r,maxX:s,maxY:a}=e.contentBBox;return{x:n/2-(i+s)/2,y:o/2-(r+a)/2}}var us=["keyboard","pen","chat"];function We(e){return us.includes(e)?e:"keyboard"}var Ce={x:1,y:1};function le(e){if(e==null)return{...Ce};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Ce.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Ce.y}}function so(e){var f,m,h,y,w;let t=le(e.position),n=(f=e.safeAreaTop)!=null?f:0,o=(m=e.safeAreaBottom)!=null?m:0,i=(h=e.safeAreaLeft)!=null?h:0,r=(y=e.safeAreaRight)!=null?y:0,s=(w=e.margin)!=null?w:16,a=e.orbDiameter,l=Math.max(0,e.viewportWidth-i-r-2*s-a),c=Math.max(0,e.viewportHeight-n-o-2*s-a),u=i+s+t.x*l,p=n+s+t.y*c;return{right:e.viewportWidth-u-a,bottom:e.viewportHeight-p-a}}function bn(e){var u,p,f;let t=(u=e.contentWidth)!=null?u:e.viewportWidth,n=(p=e.contentHeight)!=null?p:e.viewportHeight,o=e.orbDiameter,i=(f=e.edgeGap)!=null?f:8,r=so({viewportWidth:t,viewportHeight:n,orbDiameter:o,margin:e.margin,position:e.position,safeAreaTop:e.safeAreaTop,safeAreaBottom:e.safeAreaBottom,safeAreaLeft:e.safeAreaLeft,safeAreaRight:e.safeAreaRight}),s=t-r.right-o,a=n-r.bottom-o,l=Math.max(i,t-o-i),c=Math.max(i,n-o-i);return{left:Math.min(l,Math.max(i,s)),top:Math.min(c,Math.max(i,a))}}function mt(e){let t=le(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function yn(e){let t=le(e);return{x:t.x>=.5?1:0,y:t.y}}function xn(e){var m,h,y,w,x;let t=(m=e.safeAreaTop)!=null?m:0,n=(h=e.safeAreaBottom)!=null?h:0,o=(y=e.safeAreaLeft)!=null?y:0,i=(w=e.safeAreaRight)!=null?w:0,r=(x=e.margin)!=null?x:16,s=e.orbDiameter,a=Math.max(0,e.viewportWidth-o-i-2*r-s),l=Math.max(0,e.viewportHeight-t-n-2*r-s),c=e.centerX-s/2,u=e.centerY-s/2,p=a>0?(c-o-r)/a:0,f=l>0?(u-t-r)/l:0;return le({x:p,y:f})}var Jo={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},gt="rgba(0,0,0,0.72)";function bt(e){var o,i,r;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&Jo[t])return Jo[t];let n=(i=e.backgroundColor)==null?void 0:i.trim();return n&&n!==gt?n:(r=e.accentColor)!=null&&r.trim()?e.accentColor.trim():n||gt}function vn(e){var s,a,l,c,u,p,f,m;let t=bt(e),n=e.keyboardChip,o=(s=n==null?void 0:n.backgroundColor)==null?void 0:s.trim(),i=(a=e.glowColor)!=null?a:e.accentColor,r=n?{...n,icon:We(n.icon),backgroundColor:!o||o===gt?t:o,borderColor:(l=n.borderColor)!=null?l:i,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:De(n.innerBorderWidth),borderWidth:Ne(n.borderWidth)}:void 0;return{accentColor:e.accentColor,backgroundColor:t,glowColor:i,colorKey:e.colorKey,glowKey:e.glowKey,speed:(u=e.speed)!=null?u:42,glowIntensity:Ne(e.glowIntensity),hapticIntensity:Gt(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:De(e.innerBorderWidth),size:e.size,borderWidth:(p=e.borderWidth)!=null?p:2,waveformHeight:(f=e.waveformHeight)!=null?f:26,waveformColor:(m=e.waveformColor)!=null?m:e.accentColor,keyboardChip:r}}function yt(e){var n,o;return{theme:vn(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:le(e.orbTheme.screenPosition)}}var ds=/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|0\.0\.0\.0$)/;function ao(e){let t=(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"");return t?t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="::"||t.endsWith(".local")?!0:ds.test(t):!1}function Cn(e,t=!1,n){var r;if(!e||t)return!1;let o=globalThis.location,i=n!=null?n:o?(r=o.hostname)!=null?r:"":null;return i==null?!1:!ao(i)}var H=class extends Error{constructor(t,n,o){super(n!=null?n:t),this.name="AgentApiError",this.code=t,this.status=o}};var da=15e3,pa=12e3;async function An(e,t,n,o){let i=new AbortController,r=!1,s=setTimeout(()=>{r=!0,i.abort()},n);o&&(o.aborted?i.abort():o.addEventListener("abort",()=>i.abort()));try{return await fetch(e,{...t,signal:i.signal})}catch(a){if(r)throw new H("timeout");if(o!=null&&o.aborted)throw new H("cancelled");let l=a instanceof Error?a.message:String(a);throw new H("network",l)}finally{clearTimeout(s)}}async function Zo(e){let t={};try{let o=await e.text();o&&(t=JSON.parse(o))}catch{}let n=typeof t.detail=="string"?t.detail:typeof t.error=="string"?t.error:t.message;if(e.status===401||e.status===403)return new H("unauthorized",n,e.status);if(e.status===429){let o=typeof t.remaining=="number"||(n!=null?n:"").toLowerCase().includes("quota");return new H(o?"quota_exceeded":"rate_limited",n,e.status)}return e.status===404?new H("not_found",n,e.status):e.status>=500?new H("server_error",n,e.status):new H("unknown",n!=null?n:e.statusText,e.status)}function ei(e){var r,s;let t=e.baseUrl.replace(/\/$/,""),n=(r=e.turnTimeoutMs)!=null?r:da,o=(s=e.ttsTimeoutMs)!=null?s:pa;function i(){var l,c;let a=(l=e.getUserId)==null?void 0:l.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...a?{"x-user-id":a}:{},...(c=e.headers)!=null?c:{}}}return{async sendTurn(a,l){var h,y,w,x,S,R,T,g,v,A,B;let c={message:a.message.trim(),language:a.language,manifest_version:a.manifestVersion,manifest_routes:a.manifestRoutes,manifest_actions:a.manifestActions,app_name:a.appName,app_description:a.appDescription};(h=a.appType)!=null&&h.trim()&&(c.app_type=a.appType.trim()),(y=a.appFlow)!=null&&y.trim()&&(c.app_flow=a.appFlow.trim()),a.voice&&(c.voice=a.voice),(w=a.screenContext)!=null&&w.trim()&&(c.screen_context=a.screenContext.trim()),(x=a.currentRoute)!=null&&x.trim()&&(c.current_route=a.currentRoute.trim()),(S=a.conversationHistory)!=null&&S.length&&(c.conversation_history=a.conversationHistory.map(q=>({role:q.role,content:q.content.trim()}))),(R=a.conversationSummary)!=null&&R.trim()&&(c.conversation_summary=a.conversationSummary.trim()),(T=a.llmModel)!=null&&T.trim()&&(c.llm_model=a.llmModel.trim()),(g=a.sessionId)!=null&&g.trim()&&(c.session_id=a.sessionId.trim()),(v=a.platformCapabilities)!=null&&v.credentialAutofill&&(c.platform_capabilities={credential_autofill:!0}),a.sessionContext&&(c.session_context={authenticated:a.sessionContext.authenticated,...a.sessionContext.capabilities?{capabilities:a.sessionContext.capabilities}:{}}),a.isContinuation&&(c.is_continuation=!0,typeof a.chainStep=="number"&&(c.chain_step=a.chainStep),a.lastStep&&(c.last_step={type:a.lastStep.type,intent:a.lastStep.intent,...a.lastStep.label?{label:a.lastStep.label}:{},success:a.lastStep.success}));let u=await An(`${t}/assistant/chat`,{method:"POST",headers:i(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await Zo(u);let p;try{p=await u.json()}catch{throw new H("invalid_response")}let f=typeof p.task_status=="string"?p.task_status:"",m=f==="in_progress"||f==="blocked"?f:"complete";return{reply:((A=p.reply)!=null?A:"").trim(),audioBase64:(B=p.audio_base64)!=null?B:null,action:Tt(p.action),wasTruncated:p.was_truncated===!0,taskStatus:m}},async previewTts(a,l){var c;try{let u=await An(`${t}/assistant/preview-tts`,{method:"POST",headers:i(),body:JSON.stringify({voice:a,text:l})},o);if(!u.ok)return null;let p=await u.json();return(c=p.audio_base64)!=null&&c.length?p.audio_base64:null}catch{return null}},async warmUp(){try{await An(`${t}/health`,{method:"GET",headers:i()},5e3)}catch{}},async fetchPublishedConfig(){let a=await An(`${t}/v1/client/config`,{method:"GET",headers:i()},8e3);if(!a.ok)throw await Zo(a);return await a.json()}}}function co(e){return{manifestVersion:e.version,manifestRoutes:Et(e),manifestActions:It(e),appName:e.appName,appDescription:e.appDescription,...e.appType?{appType:e.appType}:{},...e.appFlow?{appFlow:e.appFlow}:{}}}function fa(e){var o,i;let t=(o=e.intentDetected)!=null?o:null,n=(i=e.sessionId)!=null?i:null;switch(e.eventType){case"agent_session_started":return[{type:"session",session_id:n}];case"action_executed":{let r=[{type:"action",intent:t,session_id:n}];return e.actionExecuted!=null&&e.actionExecuted.confirmed===!0&&r.push({type:"confirmation_completed",intent:t,session_id:n}),r}case"action_confirmation_requested":return[{type:"confirmation_requested",intent:t,session_id:n}];default:return[]}}function ti(e){var c,u;let t=e.baseUrl.replace(/\/$/,""),n=(c=e.flushIntervalMs)!=null?c:4e3,o=(u=e.maxBatch)!=null?u:20,i=[],r=null;function s(){var f,m;let p=(f=e.getUserId)==null?void 0:f.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...p?{"x-user-id":p}:{},...(m=e.headers)!=null?m:{}}}function a(){if(r&&(clearTimeout(r),r=null),i.length===0)return;let p=i;i=[],(async()=>{try{await fetch(`${t}/v1/agent/events`,{method:"POST",headers:s(),body:JSON.stringify({events:p})})}catch{}})()}function l(){r||(r=setTimeout(a,n))}return{logEvent(p){let f=fa(p);if(f.length!==0){for(let m of f)i.push(m);i.length>=o?a():l()}}}}var ha="BACK";function ma(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function ni(e){let t=null,n=!1;return{navigate(o){if(!o||o===ha){this.back();return}n=!0,e.navigate(o)},back(){var o;if(e.back){e.back();return}if(n&&typeof window!="undefined"&&((o=window.history)==null?void 0:o.length)>1){window.history.back();return}e.backFallbackRoute&&e.navigate(e.backFallbackRoute)},getCurrentRoute(){return t!=null?t:e.getCurrentRoute?e.getCurrentRoute():ma()},setCurrentRoute(o){t=o}}}function ga(e){if(e)return e;try{if(typeof window!="undefined"&&window.localStorage){let n="__fyodos_probe__";return window.localStorage.setItem(n,"1"),window.localStorage.removeItem(n),window.localStorage}}catch{}let t=new Map;return{getItem:n=>t.has(n)?t.get(n):null,setItem:(n,o)=>{t.set(n,o)},removeItem:n=>{t.delete(n)}}}function oi(e={}){let t=ga(e.backend);return{async getItem(n){try{return t.getItem(n)}catch{return null}},async setItem(n,o){try{t.setItem(n,o)}catch{}},async removeItem(n){try{t.removeItem(n)}catch{}}}}function ba(e){let t=e.getVoices();return t.length?Promise.resolve(t):new Promise(n=>{let o=!1,i=()=>{o||(o=!0,n(e.getVoices()))};try{e.addEventListener("voiceschanged",i,{once:!0})}catch{}setTimeout(i,600)})}function ya(e,t){var i,r,s,a,l;if(!e.length)return;let n=t.toLowerCase(),o=(i=n.split("-")[0])!=null?i:n;return(l=(a=(s=(r=e.find(c=>{var u;return((u=c.lang)==null?void 0:u.toLowerCase())===n}))!=null?r:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(`${o}-`)}))!=null?s:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(o)}))!=null?a:e.find(c=>c.default))!=null?l:e[0]}function ii(){var t,n;if(typeof window=="undefined")return null;let e=window;return(n=(t=e.SpeechRecognition)!=null?t:e.webkitSpeechRecognition)!=null?n:null}function ri(){if(typeof navigator=="undefined")return!1;let e=navigator.userAgent||"",t=/iPad|iPhone|iPod/.test(e),n=/Macintosh/.test(e)&&typeof document!="undefined"&&"ontouchend"in document;return t||n}function si(e={}){let t=ii(),n=null,o="",i=null,r=!1,s=!1,a=null,l=null,c=null,u=!1,p=!1,f=[],m="",h=null,y=null;function w(){y&&(clearTimeout(y),y=null)}function x(){if(w(),c){c.onresult=null,c.onerror=null,c.onend=null,c.onstart=null;try{c.abort()}catch{}}c=null}function S(){w(),!(!u||p)&&(y=setTimeout(()=>{y=null,u&&!p&&R()},600))}function R(){let O=ii();if(!O||!u||p)return;if(typeof document!="undefined"&&document.hidden){S();return}let b=new O;c=b,b.lang=m,b.continuous=!0,b.interimResults=!0,b.maxAlternatives=1,b.onresult=E=>{var F;if(!u||p)return;let $="";for(let M=0;M<E.results.length;M+=1){let Q=E.results[M];if(!Q)continue;let j=Q[0];$=`${$} ${(F=j==null?void 0:j.transcript)!=null?F:""}`.trim()}let L=zt($,f);if(!L.matched)return;p=!0;let Y=h;x(),Y==null||Y.onDetected(L.command)},b.onerror=E=>{var $;E.error==="aborted"||E.error==="no-speech"||!u||p||($=h==null?void 0:h.onError)==null||$.call(h,new Error(E.error||"wake recognition error"))},b.onend=()=>{!u||p||S()};try{b.start()}catch{S()}}let T=null,g=null;function v(){var b,E;if(typeof window=="undefined")return null;let O=window;return(E=(b=O.AudioContext)!=null?b:O.webkitAudioContext)!=null?E:null}function A(){if(T)return T;let O=v();if(!O)return null;try{T=new O}catch{T=null}return T}function B(O){let b=atob(O),E=b.length,$=new Uint8Array(E);for(let L=0;L<E;L+=1)$[L]=b.charCodeAt(L);return $.buffer}function q(){if(g){try{g.onended=null,g.stop()}catch{}g=null}}async function N(O){let b=A();if(!b)return!1;try{b.state==="suspended"&&await b.resume();let E=await b.decodeAudioData(B(O));return await new Promise($=>{q();let L=b.createBufferSource();g=L,L.buffer=E,L.connect(b.destination),L.onended=()=>{L.onended=null,g===L&&(g=null),$(!0)},L.start()})}catch{return!1}}function K(){i&&(clearTimeout(i),i=null)}function ue(){K(),n&&(n.onresult=null,n.onerror=null,n.onend=null,n.onstart=null),n=null}return{isRecognitionAvailable(){return t!=null},async startListening(O,b){var $,L,Y;if(!t){($=b.onError)==null||$.call(b,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,h=null,x()),n){r=!0;try{n.abort()}catch{}ue()}o="",r=!1,s=!1;let E=new t;n=E,E.lang=O.locale,E.continuous=(L=O.continuous)!=null?L:!0,E.interimResults=!0,E.maxAlternatives=1,E.onresult=F=>{var j,me;let M="";for(let de=F.resultIndex;de<F.results.length;de+=1){let ge=F.results[de];if(!ge)continue;let J=ge[0],Ae=(j=J==null?void 0:J.transcript)!=null?j:"";ge.isFinal?o=`${o} ${Ae}`.trim():M=`${M} ${Ae}`.trim()}let Q=`${o} ${M}`.trim();Q&&((me=b.onInterim)==null||me.call(b,Q))},E.onerror=F=>{var M;F.error==="aborted"||r||F.error!=="no-speech"&&(s=!0,(M=b.onError)==null||M.call(b,new Error(F.error||"speech recognition error")))},E.onend=()=>{var Q,j,me,de;K();let F=r,M=o.trim();if(ue(),s){(Q=b.onEnd)==null||Q.call(b);return}if(F){(j=b.onEnd)==null||j.call(b);return}M?(me=b.onFinal)==null||me.call(b,M):(de=b.onEnd)==null||de.call(b)};try{E.start()}catch(F){ue(),(Y=b.onError)==null||Y.call(b,F);return}O.maxSeconds&&O.maxSeconds>0&&(i=setTimeout(()=>{try{E.stop()}catch{}},O.maxSeconds*1e3))},stopListening(){if(K(),n)try{n.stop()}catch{}},cancelListening(){if(K(),r=!0,n)try{n.abort()}catch{}},primePlayback(){let O=A();if(O)try{O.state==="suspended"&&O.resume();let b=O.createBuffer(1,1,O.sampleRate),E=O.createBufferSource();E.buffer=b,E.connect(O.destination),E.start(0)}catch{}if(!e.disableDeviceTtsFallback&&typeof window!="undefined"&&window.speechSynthesis)try{let b=window.speechSynthesis;b.getVoices(),b.paused&&b.resume();let E=new SpeechSynthesisUtterance(" ");E.volume=0,b.speak(E)}catch{}},async playAudioBase64Mp3(O){if(typeof window!="undefined"&&(this.stopPlayback(),!await N(O)&&typeof Audio!="undefined"))return new Promise(b=>{try{let E=new Audio(`data:audio/mp3;base64,${O}`);a=E;let $=()=>{E.onended=null,E.onerror=null,a===E&&(a=null),b()};E.onended=$,E.onerror=$,E.play().catch(()=>$())}catch{b()}})},async speakWithDeviceTts(O,b){if(e.disableDeviceTtsFallback||typeof window=="undefined"||!window.speechSynthesis)return;let E=window.speechSynthesis,$=await ba(E);return new Promise(L=>{let Y=null,F=()=>{Y&&(clearInterval(Y),Y=null)};try{E.cancel();let M=new SpeechSynthesisUtterance(O);M.lang=b.locale;let Q=ya($,b.locale);Q&&(M.voice=Q),M.volume=1,M.rate=1,M.pitch=1,l=M;let j=()=>{F(),M.onstart=null,M.onend=null,M.onerror=null,l===M&&(l=null),L()};M.onend=j,M.onerror=j,E.speak(M),E.resume(),Y=setInterval(()=>{if(!E.speaking&&!E.pending){F();return}E.pause(),E.resume()},9e3)}catch{F(),L()}})},stopPlayback(){if(q(),a){try{a.pause()}catch{}a=null}if(typeof window!="undefined"&&window.speechSynthesis)try{window.speechSynthesis.cancel()}catch{}},supportsWakeWordDetection(){return t!=null&&!ri()},isWakeWordListening(){return u},async startWakeWordDetection(O,b){var E;if(!t||ri()){(E=b.onError)==null||E.call(b,new Error("wake_word_unsupported"));return}f=O.phrases,m=O.locale,h=b,u=!0,p=!1,R()},stopWakeWordDetection(){u=!1,p=!1,h=null,x()}}}function ai(){if(typeof navigator=="undefined")return null;let e=navigator;return e.credentials&&typeof e.credentials.get=="function"?e.credentials:null}function ci(){if(typeof window=="undefined")return!1;let e=window;return typeof e.PasswordCredential=="function"&&e.isSecureContext!==!1}function li(){return{isSupported(){return ai()!==null&&ci()},async requestCredentials(){let e=ai();if(!e||!ci())return{status:"unavailable"};let t;try{t=await e.get({password:!0,mediation:"required"})}catch{return{status:"unavailable"}}let n=t;return n?n.type==="password"&&n.id&&typeof n.password=="string"&&n.password?{status:"success",username:n.id,password:n.password}:{status:"unavailable"}:{status:"dismissed"}}}}function lo(e,t){let n=t.startsWith("es");if(e instanceof H){switch(e.code){case"timeout":return n?"La respuesta tard\xF3 demasiado. Comprueba tu conexi\xF3n e int\xE9ntalo de nuevo.":"The response took too long. Check your connection and try again.";case"network":return n?"No pude conectar con el servidor de Fiodos. \xBFEst\xE1 el backend en marcha y la URL correcta?":"Could not reach the Fiodos server. Is the backend running and the URL correct?";case"unauthorized":return n?"La API key fue rechazada. Comprueba que coincide con la del proyecto en el dashboard.":"The API key was rejected. Check it matches the project key in your dashboard.";case"quota_exceeded":return n?"Has alcanzado el l\xEDmite de uso de IA de tu plan. Mej\xF3ralo en el dashboard para seguir.":"You reached your plan\u2019s AI usage limit. Upgrade in the dashboard to continue.";case"rate_limited":return n?"Demasiadas peticiones seguidas. Espera un momento e int\xE9ntalo de nuevo.":"Too many requests. Wait a moment and try again.";case"server_error":return n?"El servidor no pudo responder. Revisa que la IA est\xE9 configurada en el backend.":"The server could not respond. Check that the AI is configured on the backend.";case"cancelled":return n?"Cancelado.":"Cancelled.";default:break}if(e.message&&e.message!==e.code)return e.message}return e instanceof Error&&e.message?e.message:n?"No pude responder. Int\xE9ntalo de nuevo.":"I could not reply. Please try again."}function Sn(e){let t=null;return{set(n,o){t={ownerId:n,snapshot:o}},clear(n){(t==null?void 0:t.ownerId)===n&&(t=null)},getText(){var i,r,s;let n=(i=t==null?void 0:t.snapshot.text)==null?void 0:i.trim();return n||((s=(r=e.routeFallback)==null?void 0:r.call(e,e.getCurrentRoute()))==null?void 0:s.trim())||null},getSnapshot(){var n;return(n=t==null?void 0:t.snapshot)!=null?n:null}}}function ui(e){let{adapter:t,locale:n,maxSeconds:o}=e,i={state:"idle",interimText:"",volumeLevel:0},r=new Set;function s(l){i={...i,...l};for(let c of r)c(i)}function a(){s({state:"idle",interimText:"",volumeLevel:0})}return{getSnapshot(){return i},subscribe(l){return r.add(l),()=>r.delete(l)},async start(){i.state==="idle"&&(s({state:"recording",interimText:"",volumeLevel:.85}),await t.startListening({locale:n,continuous:!0,maxSeconds:o},{onInterim:l=>s({interimText:l}),onFinal:l=>{a(),l.trim()&&e.onTranscript(l)},onEnd:()=>{i.state!=="idle"&&a()},onError:l=>{var c;a(),(c=e.onError)==null||c.call(e,l)}}))},stop(){i.state==="recording"&&(s({state:"transcribing",volumeLevel:0}),t.stopListening())},cancel(){t.cancelListening(),a()},dispose(){t.cancelListening(),r.clear()}}}function xa(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function di(e){var a,l,c,u,p,f,m;let{action:t,manifest:n,executor:o,context:i,messages:r,userMessage:s}=e;if(!t||t.type==="none")return{kind:"noop"};if(t.type==="navigate")return{kind:"executed",result:await o.execute(t)};if(t.type==="execute"){let h=xa(n,t.intent);if(!((h==null?void 0:h.requireConfirmation)===!0))return{kind:"executed",result:await o.execute(t,i)};let w=await o.precheck(t,i);if(w.kind==="done")return{kind:"precheck-resolved",result:w.result};let x=(a=h==null?void 0:h.voiceConfirmation)!=null?a:"standard",S=x==="strict"?(u=h==null?void 0:h.confirmationPhrase)!=null?u:ee(r.strictConfirmationPhraseTemplate,{label:((c=(l=h==null?void 0:h.label)!=null?l:t.intent)!=null?c:"").toLowerCase()}):null;return{kind:"needs-confirmation",pending:{action:t,context:i,question:(f=(p=h==null?void 0:h.confirmationMessageTemplate)!=null?p:t.confirmationMessage)!=null?f:r.confirmationFallbackQuestion,voiceMode:x,strictPhrase:S,remainingConfirmations:(h==null?void 0:h.doubleConfirmation)===!0?2:1,userMessage:s,intent:(m=t.intent)!=null?m:""}}}return{kind:"noop"}}function pi(e,t,n,o={}){if(t.voiceMode==="disabled"||o.silent)return"ambiguous";let i=e.trim();return i.length<2?"ambiguous":t.voiceMode==="strict"&&t.strictPhrase!=null?Xt(i,t.strictPhrase,n):jt(i,n)}var fi={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},hi={enabled:!1,maxSteps:6,dwellMs:450};var gi={orbLabel:"Voice assistant",confirmTitle:"Confirm",confirmLabel:"Confirm",cancelLabel:"Cancel",consentTitle:"Voice assistant",consentBody:"This assistant uses your microphone to understand voice commands and may navigate or perform actions in this app on your behalf. Your speech is processed to answer you and is not stored as a transcript.",consentAccept:"Allow",consentDecline:"Not now",textPlaceholder:"Type a message\u2026",keyboardChipLabel:"Type instead of talking",sendLabel:"Send",micLabel:"Dictate message",micStopLabel:"Stop dictating",voiceUnavailable:"Voice input is not available in this browser. You can type instead.",activityThinking:"Thinking\u2026",activityNavigating:"Navigating to {label}\u2026",activityExecuting:"Running {label}\u2026",activityWaitingConfirmation:"Waiting for your confirmation\u2026"},va={orbLabel:"Asistente de voz",confirmTitle:"Confirmar",confirmLabel:"Confirmar",cancelLabel:"Cancelar",consentTitle:"Asistente de voz",consentBody:"Este asistente usa tu micr\xF3fono para entender comandos de voz y puede navegar o realizar acciones en esta app en tu nombre. Tu voz se procesa para responderte y no se guarda como transcripci\xF3n.",consentAccept:"Permitir",consentDecline:"Ahora no",textPlaceholder:"Escribe un mensaje\u2026",keyboardChipLabel:"Escribir en lugar de hablar",sendLabel:"Enviar",micLabel:"Dictar mensaje",micStopLabel:"Detener dictado",voiceUnavailable:"La entrada por voz no est\xE1 disponible en este navegador. Puedes escribir.",activityThinking:"Pensando\u2026",activityNavigating:"Navegando a {label}\u2026",activityExecuting:"Ejecutando {label}\u2026",activityWaitingConfirmation:"Esperando tu confirmaci\xF3n\u2026"},mi={en:gi,es:va};function Ca(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function bi(e,t={}){var r,s,a,l,c;let n=(r=t.catalogs)!=null?r:{},o=Ca(e),i=(c=(l=(a=(s=n[e])!=null?s:mi[e])!=null?a:n[o])!=null?l:mi[o])!=null?c:gi;return t.overrides?{...i,...t.overrides}:i}function Aa(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Sa=e=>new Promise(t=>setTimeout(t,e)),Ue=class{constructor(t){this.enabled=!0;this.phase="idle";this.lastExchange=null;this.pendingTurnText=null;this.confirmationMessage=null;this.confirmationVoiceHint=null;this.consentModalVisible=!1;this.sessionId=Aa();this.sessionStarted=!1;this.conversation=Le();this.pending=null;this.confirmationReasked=!1;this.confirmationVoiceActive=!1;this.silentTurn=!1;this.voiceBlocked=!1;this.abort=null;this.watchdog=null;this.confirmWindow=null;this.speakTimer=null;this.serverTtsUnavailable=!1;this.pendingConsentIntent=null;this.chainState=null;this.liveActivity=null;this.chainActive=!1;this.bubbleWindowSize=ve;this.conversationRetentionMinutes=null;this.conversationScope="public";this.removeIdentityListeners=null;this.loadingOlderExchanges=!1;this.loadOlderTimer=null;this.listeners=new Set;this.unsubscribeSpeech=null;var o,i,r,s,a,l,c,u,p;he(t.manifest),this.config=t,this.messages=_t(t.locale,{catalogs:(o=t.messages)==null?void 0:o.catalogs,overrides:(i=t.messages)==null?void 0:i.overrides}),this.ui=bi(t.locale,t.uiMessages),this.lexicon=(r=t.confirmationLexicon)!=null?r:Kt(t.locale),this.sanitizer=(s=t.sanitizer)!=null?s:Ft(),this.telemetry=Vt(t.telemetry),this.consent=Ut({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?li():t.credentialAutofill,this.executor=$t({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...fi,...t.timings};let n={...hi,...t.chaining};if(this.chaining={enabled:n.enabled===!0,maxSteps:Math.max(1,Math.min(6,Math.floor(n.maxSteps||6))),dwellMs:Math.max(0,Math.min(3e3,Math.floor((a=n.dwellMs)!=null?a:450)))},this.ttsLocale=(l=t.ttsLocale)!=null?l:t.sttLocale,this.notifyError=(c=t.notifyError)!=null?c:(f=>{console.error(`[fyodos] ${f}`)}),this.screenStore=Sn({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Lt(f,t.manifest,this.messages))}),this.speech=ui({adapter:t.voice,locale:t.sttLocale,maxSeconds:this.timings.maxListeningSeconds,onTranscript:f=>this.onTranscript(f),onError:f=>this.onSpeechError(f)}),this.unsubscribeSpeech=this.speech.subscribe(()=>this.emit()),this.conversationIdentity=rt((p=t.getUserId)==null?void 0:p.call(t)),this.restorePersistedConversation(),typeof window!="undefined"){let f=()=>{this.syncConversationIdentity()};window.addEventListener("focus",f),document.addEventListener("visibilitychange",f),this.removeIdentityListeners=()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",f)}}}async restorePersistedConversation(){var o;let t=this.conversationIdentity,n=await Qt(this.config.storage,this.config.manifest.appId,Date.now(),this.conversationScope,t);!n||this.conversationIdentity!==t||this.conversation.turns.length>0||(o=this.conversation.uiArchive)!=null&&o.length||(this.conversation.turns=n.turns,this.conversation.summary=n.summary,this.conversation.uiArchive=n.uiArchive,this.conversation.lastActivityAt=n.lastActivityAt,this.emit())}persistConversation(){qt(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=rt((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=Le(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=Le(),this.lastExchange=null,Jt(this.config.storage,this.config.manifest.appId,this.conversationScope,this.conversationIdentity),this.emit()}getState(){let t=this.speech.getSnapshot(),n=(this.phase==="listening"||this.phase==="confirming")&&t.state==="recording",o=this.phase==="thinking"||this.phase==="listening"&&t.state==="transcribing",i=it(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions);return{phase:this.phase,interimText:t.interimText,volumeLevel:t.volumeLevel,showWaveform:n,showThinking:o,isBusy:o||this.phase==="speaking",isListening:this.phase==="listening"&&t.state!=="idle",lastExchange:this.lastExchange,recentExchanges:i.exchanges,hasOlderExchanges:i.hasOlder,loadingOlderExchanges:this.loadingOlderExchanges,confirmationMessage:this.confirmationMessage,confirmationVoiceHint:this.confirmationVoiceHint,consentModalVisible:this.consentModalVisible,voiceBlocked:this.voiceBlocked,liveActivity:this.liveActivity,chainActive:this.chainActive}}setActivity(t){let n=this.liveActivity;n===t||n&&t&&n.kind===t.kind&&n.label===t.label||(this.liveActivity=t,this.emit())}setChainActive(t){this.chainActive!==t&&(this.chainActive=t,this.emit())}get voiceAvailable(){return this.config.voice.isRecognitionAvailable()&&!this.voiceBlocked}primeAudio(){var t,n;(n=(t=this.config.voice).primePlayback)==null||n.call(t)}markVoiceBlocked(t){this.voiceBlocked!==t&&(this.voiceBlocked=t,this.emit())}loadOlderExchanges(){this.loadingOlderExchanges||!it(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=ve,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Me(t,n),this.conversationRetentionMinutes=typeof t=="number"?t:null;let o=n?"internal":"public";o!==this.conversationScope&&(this.conversationScope=o,this.restorePersistedConversation())}resetBubbleWindow(){this.loadOlderTimer&&(clearTimeout(this.loadOlderTimer),this.loadOlderTimer=null),this.loadingOlderExchanges=!1,this.bubbleWindowSize=ve}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(){let t=this.getState();for(let n of this.listeners)n(t)}setEnabled(t){this.enabled=t,t||this.cancelAll()}getTtsVoice(){return typeof this.config.ttsVoice=="function"?this.config.ttsVoice():this.config.ttsVoice}setPhase(t){var o,i;let n=this.phase;n!==t&&(this.phase=t,(i=(o=this.config).onPhaseChange)==null||i.call(o,t,n),this.emit())}clearWatchdog(){this.watchdog&&(clearTimeout(this.watchdog),this.watchdog=null)}clearConfirmWindow(){this.confirmWindow&&(clearTimeout(this.confirmWindow),this.confirmWindow=null),this.confirmationVoiceActive=!1}clearSpeakTimer(){this.speakTimer&&(clearTimeout(this.speakTimer),this.speakTimer=null)}async speakReply(t,n){var o;if(!this.silentTurn&&!(!t&&!n)){this.setPhase("speaking");try{let i=n;if(i&&(this.serverTtsUnavailable=!1),!i&&t&&!this.serverTtsUnavailable)try{i=await this.config.backend.previewTts((o=this.getTtsVoice())!=null?o:"",t),i||(this.serverTtsUnavailable=!0)}catch{i=null,this.serverTtsUnavailable=!0}let r=i?this.config.voice.playAudioBase64Mp3(i):t?this.config.voice.speakWithDeviceTts(t,{locale:this.ttsLocale}):Promise.resolve();await this.raceSpeakingWatchdog(r,t)}catch{}finally{this.clearSpeakTimer(),this.phase==="speaking"&&this.setPhase("idle")}}}raceSpeakingWatchdog(t,n){let o=Math.min(6e4,5e3+n.length*90);return new Promise(i=>{let r=!1,s=()=>{r||(r=!0,this.clearSpeakTimer(),i())};this.clearSpeakTimer(),this.speakTimer=setTimeout(()=>{this.config.voice.stopPlayback(),s()},o),t.then(s,s)})}beginConfirmationVoiceWindow(){let t=this.pending;!t||t.silent||t.voiceMode==="disabled"||this.config.voice.isRecognitionAvailable()&&(this.clearConfirmWindow(),this.setPhase("confirming"),this.confirmationVoiceActive=!0,this.speech.start(),this.confirmWindow=setTimeout(()=>{this.speech.stop(),this.confirmationVoiceActive=!1},this.timings.confirmationVoiceWindowMs))}async confirmPendingAction(){var i,r;this.clearConfirmWindow();let t=this.pending;if(!t){this.confirmationMessage=null,this.confirmationVoiceHint=null,this.emit();return}if(t.remainingConfirmations>1){t.remainingConfirmations-=1,this.confirmationReasked=!1;let s=this.messages.doubleConfirmationQuestion;this.confirmationMessage=s,this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:s}),this.emit(),await this.speakReply(s,null),this.pending&&this.beginConfirmationVoiceWindow();return}this.pending=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.phase==="confirming"&&this.setPhase("idle"),this.emit(),this.setActivity({kind:"executing",label:(i=this.actionLabel(t.intent))!=null?i:t.intent});let n=await this.executor.execute(t.action,t.context);this.telemetry.logEvent({eventType:n.success?"action_executed":"action_failed",intentDetected:t.intent,sessionId:this.sessionId,actionExecuted:{intent:t.intent,confirmed:!0}}),n.message&&(this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:n.message}),this.emit(),await this.speakReply(n.message,null));let o=this.chainState;o&&(this.chainState=null,n.success&&this.chaining.enabled?(this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:t.intent,sessionId:this.sessionId,chainStep:o.step}),o.pendingKey&&o.visitedKeys.add(o.pendingKey),await this.runChainLoop({userMessage:o.userMessage,step:o.step,lastStep:(r=o.pendingStep)!=null?r:o.lastStep,visitedKeys:o.visitedKeys})):n.success||this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainAbortReason:"error"})),this.pending||this.setActivity(null)}cancelPendingAction(){this.clearConfirmWindow();let t=this.pending;this.pending=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.setActivity(null),this.phase==="confirming"&&this.setPhase("idle"),this.emit();let n=this.chainState;this.chainState=null,n&&this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainAbortReason:"user_interrupt"}),t&&(this.telemetry.logEvent({eventType:"action_cancelled",intentDetected:t.intent,sessionId:this.sessionId}),this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:this.messages.cancelled}),this.emit(),this.speakReply(this.messages.cancelled,null))}async handleConfirmationTranscript(t){this.confirmationVoiceActive=!1,this.clearConfirmWindow();let n=this.pending;if(this.phase==="confirming"&&this.setPhase("idle"),!n||n.voiceMode==="disabled"||n.silent)return;let o=pi(t,n,this.lexicon,{silent:n.silent});if(o==="affirmative"){await this.confirmPendingAction();return}if(o==="negative"){this.cancelPendingAction();return}if(!this.confirmationReasked){this.confirmationReasked=!0;let i=`${this.messages.confirmationNotUnderstood} ${n.question}`.trim();this.confirmationMessage=i,this.emit(),await this.speakReply(i,null),this.pending&&this.beginConfirmationVoiceWindow()}}platformCapabilities(){var n;let t=!1;try{t=((n=this.credentialAutofill)==null?void 0:n.isSupported())===!0}catch{t=!1}return t?{credentialAutofill:!0}:void 0}sessionContext(){let{isAuthenticated:t,getSessionCapabilities:n}=this.config;if(!t&&!n)return;let o=null;try{let r=t==null?void 0:t();o=r==null?null:!!r}catch{o=null}let i;try{let r=n==null?void 0:n();if(r&&typeof r=="object"){let s={};for(let[a,l]of Object.entries(r))typeof l=="boolean"&&(s[a]=l);Object.keys(s).length>0&&(i=s)}}catch{i=void 0}return{authenticated:o,...i?{capabilities:i}:{}}}routeLabel(t){var n;return(n=this.config.manifest.routes.find(o=>o.intent===t))==null?void 0:n.label}actionLabel(t){var n;return(n=this.config.manifest.actions.find(o=>o.intent===t))==null?void 0:n.label}async applyOutcome(t,n,o,i){var y,w,x,S,R,T,g,v,A,B,q;let r=t.reply,s=t.audioBase64;r&&(this.serverTtsUnavailable=!s);let a=await di({action:t.action,manifest:this.config.manifest,executor:this.executor,context:o,messages:this.messages,userMessage:i}),l=!1,c,u,p=!1,f=!1,m,h;if(a.kind==="executed"){let N=a.result;if(N.success&&((y=t.action)==null?void 0:y.type)==="navigate"?this.setActivity({kind:"navigating",label:(S=(x=this.routeLabel((w=t.action.intent)!=null?w:""))!=null?x:t.action.intent)!=null?S:""}):N.success&&!N.recoverable&&((R=t.action)==null?void 0:R.type)==="execute"&&this.setActivity({kind:"executing",label:(v=(g=this.actionLabel((T=t.action.intent)!=null?T:""))!=null?g:t.action.intent)!=null?v:""}),((A=t.action)==null?void 0:A.type)==="navigate"?this.telemetry.logEvent({eventType:N.success?"navigation_executed":"navigation_failed",intentDetected:t.action.intent,sessionId:this.sessionId,currentRoute:n!=null?n:void 0}):((B=t.action)==null?void 0:B.type)==="execute"&&this.telemetry.logEvent({eventType:N.recoverable?"action_needs_context":N.success?"action_executed":"action_failed",intentDetected:t.action.intent,sessionId:this.sessionId,actionExecuted:{intent:t.action.intent,confirmed:!1}}),N.recoverable||N.message&&(r=N.message,s=null),t.action&&(t.action.type==="navigate"||t.action.type==="execute")&&N.success&&!N.recoverable){let K=(q=t.action.intent)!=null?q:"";c={type:t.action.type,intent:K,label:t.action.type==="navigate"?this.routeLabel(K):this.actionLabel(K),success:!0},u=`${t.action.type}:${K}`,l=t.taskStatus==="in_progress"}}else if(a.kind==="precheck-resolved")a.result.message&&!a.result.recoverable&&(r=a.result.message,s=null);else if(a.kind==="needs-confirmation"){this.pending={...a.pending,silent:this.silentTurn},this.confirmationReasked=!1,this.confirmationMessage=a.pending.question,this.confirmationVoiceHint=a.pending.voiceMode==="strict"&&a.pending.strictPhrase&&!this.silentTurn?ee(this.messages.strictConfirmationModalHint,{phrase:a.pending.strictPhrase}):null,this.emit(),this.telemetry.logEvent({eventType:"action_confirmation_requested",intentDetected:a.pending.intent,sessionId:this.sessionId}),this.setActivity({kind:"waiting_confirmation"}),p=!0,f=t.taskStatus==="in_progress";let N=a.pending.intent||"";m={type:"execute",intent:N,label:this.actionLabel(N),success:!0},h=`execute:${N}`}return{reply:r,audioBase64:s,hasPending:p,canContinue:l,lastStep:c,actionKey:u,pendingInProgress:f,pendingStep:m,pendingKey:h}}async runChainLoop(t){var r,s,a,l,c,u,p,f,m,h,y;let n=t.step,o=t.lastStep,i=t.visitedKeys;this.setChainActive(!0);try{for(;n<this.chaining.maxSteps;){if(n+=1,this.chaining.dwellMs>0&&await Sa(this.chaining.dwellMs),this.pending!=null)return;let w=this.config.navigation.getCurrentRoute(),x=this.screenStore.getSnapshot(),S=Ze((a=(s=(r=this.config).getUserContextText)==null?void 0:s.call(r))!=null?a:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),R=S?this.sanitizer(S).sanitized:void 0,T=nt(this.conversation,Date.now(),this.conversationOptions);this.setPhase("thinking"),this.setActivity({kind:"thinking"});let g=new AbortController;this.abort=g;let v;try{let A=await this.config.backend.sendTurn({message:t.userMessage,language:this.config.locale,voice:this.getTtsVoice(),screenContext:R,currentRoute:w!=null?w:void 0,conversationHistory:T.history,conversationSummary:(l=T.summary)!=null?l:void 0,sessionId:this.sessionId,isContinuation:!0,chainStep:n,lastStep:o,platformCapabilities:this.platformCapabilities(),sessionContext:this.sessionContext(),...co(this.config.manifest)},{signal:g.signal});v=await this.applyOutcome(A,w,(c=x==null?void 0:x.context)!=null?c:{},t.userMessage)}catch(A){this.abort=null;let B=A instanceof H&&A.code==="cancelled";if(B)this.phase==="thinking"&&this.setPhase("idle");else{A instanceof H&&A.code==="quota_exceeded"&&((p=(u=this.config).onQuotaExceeded)==null||p.call(u));let q=lo(A,this.config.locale);this.lastExchange={userText:t.userMessage,replyText:q},this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(q)}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:B?"user_interrupt":"error"});return}if(this.abort=null,v.reply&&(this.lastExchange={userText:t.userMessage,replyText:v.reply},this.emit(),ot(this.conversation,t.userMessage,v.reply,Date.now(),this.conversationOptions),this.persistConversation()),await this.speakReply(v.reply,v.audioBase64),this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:(y=(h=(f=v.lastStep)==null?void 0:f.intent)!=null?h:(m=v.pendingStep)==null?void 0:m.intent)!=null?y:null,sessionId:this.sessionId,chainStep:n}),v.hasPending){this.chainState=v.pendingInProgress?{userMessage:t.userMessage,step:n,lastStep:o,visitedKeys:i,pendingKey:v.pendingKey,pendingStep:v.pendingStep}:null,this.beginConfirmationVoiceWindow();return}if(this.phase!=="speaking"&&this.setPhase("idle"),v.actionKey&&i.has(v.actionKey)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(v.actionKey&&i.add(v.actionKey),!v.canContinue){this.telemetry.logEvent({eventType:"agent_chain_completed",sessionId:this.sessionId,chainStep:n});return}o=v.lastStep}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"max_steps"})}finally{this.setChainActive(!1)}}async handleTranscript(t){var f,m,h,y,w,x,S,R,T;let n=t.trim();if(!this.enabled||n.length<this.timings.minTranscriptChars){this.phase==="thinking"&&this.setPhase("idle");return}this.syncConversationIdentity(),this.setPhase("thinking"),this.setActivity({kind:"thinking"}),this.pendingTurnText=n,this.lastExchange={userText:n,replyText:""},this.emit(),this.clearWatchdog(),this.watchdog=setTimeout(()=>{var g;if(this.phase==="thinking"){this.telemetry.logEvent({eventType:"agent_watchdog_reset",sessionId:this.sessionId});let v=(g=this.pendingTurnText)!=null?g:n,A=this.config.locale.startsWith("es")?"La respuesta tard\xF3 demasiado. Int\xE9ntalo de nuevo.":"The response took too long. Please try again.";this.lastExchange={userText:v,replyText:A},this.pendingTurnText=null,this.setActivity(null),this.setPhase("idle"),this.emit()}},this.timings.thinkingWatchdogMs);let o=this.config.navigation.getCurrentRoute();this.sessionStarted||(this.sessionStarted=!0,this.telemetry.logEvent({eventType:"agent_session_started",sessionId:this.sessionId})),this.telemetry.logEvent({eventType:"agent_invoked",sessionId:this.sessionId,currentRoute:o});let i=this.screenStore.getSnapshot(),r=Ze((h=(m=(f=this.config).getUserContextText)==null?void 0:m.call(f))!=null?h:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),s=r?this.sanitizer(r).sanitized:void 0,a=nt(this.conversation,Date.now(),this.conversationOptions),l=new AbortController;this.abort=l;let c=null;try{let g=await this.config.backend.sendTurn({message:n,language:this.config.locale,voice:this.getTtsVoice(),screenContext:s,currentRoute:o!=null?o:void 0,conversationHistory:a.history,conversationSummary:(y=a.summary)!=null?y:void 0,sessionId:this.sessionId,platformCapabilities:this.platformCapabilities(),sessionContext:this.sessionContext(),...co(this.config.manifest)},{signal:l.signal});c=await this.applyOutcome(g,o,(w=i==null?void 0:i.context)!=null?w:{},n)}catch(g){if(this.clearWatchdog(),this.abort=null,this.setActivity(null),g instanceof H&&g.code==="cancelled"){this.phase==="thinking"&&this.setPhase("idle"),this.pendingTurnText=null;return}g instanceof H&&g.code==="quota_exceeded"&&((S=(x=this.config).onQuotaExceeded)==null||S.call(x));let v=lo(g,this.config.locale);this.lastExchange={userText:n,replyText:v},this.pendingTurnText=null,this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(v);return}if(this.clearWatchdog(),this.abort=null,this.pendingTurnText=null,!c)return;let u=c.reply;if(u)this.lastExchange={userText:n,replyText:u},this.emit(),ot(this.conversation,n,u,Date.now(),this.conversationOptions),this.persistConversation();else{let g=this.config.locale.startsWith("es")?"No recib\xED respuesta del servidor. Int\xE9ntalo de nuevo.":"No reply from the server. Please try again.";this.lastExchange={userText:n,replyText:g},this.emit()}let p=c.hasPending;if(await this.speakReply(u,c.audioBase64),p?(this.beginConfirmationVoiceWindow(),this.chaining.enabled&&c.pendingInProgress&&(this.telemetry.logEvent({eventType:"agent_chain_started",sessionId:this.sessionId,chainStep:1}),this.chainState={userMessage:n,step:1,lastStep:c.pendingStep,visitedKeys:new Set,pendingKey:c.pendingKey,pendingStep:c.pendingStep})):this.phase!=="speaking"&&this.setPhase("idle"),this.chaining.enabled&&c.canContinue&&!p){this.telemetry.logEvent({eventType:"agent_chain_started",sessionId:this.sessionId,chainStep:1});let g=new Set;c.actionKey&&g.add(c.actionKey),await this.runChainLoop({userMessage:n,step:1,lastStep:c.lastStep,visitedKeys:g})}this.pending||this.setActivity(null),(T=(R=this.config).onTurnCompleted)==null||T.call(R)}onTranscript(t){if(this.confirmationVoiceActive||this.pending){this.handleConfirmationTranscript(t);return}this.handleTranscript(t)}onSpeechError(t){this.telemetry.logEvent({eventType:"agent_stt_failed",sessionId:this.sessionId}),(this.phase==="listening"||this.phase==="confirming")&&this.setPhase("idle");let n=t instanceof Error?t.message:String(t),o=n.toLowerCase();if(o.includes("not-allowed")||o.includes("not allowed")||o.includes("service-not-allowed")||o.includes("audio-capture")||o.includes("permission")){this.markVoiceBlocked(!0);return}this.notifyError(n)}async beginListening(){var n,o;if(!this.enabled)return;if(!this.config.voice.isRecognitionAvailable()){this.telemetry.logEvent({eventType:"agent_stt_failed",sessionId:this.sessionId}),this.notifyError(this.ui.voiceUnavailable);return}let t=(o=(n=this.config).gateTurn)==null?void 0:o.call(n);if(t&&!t.ok){t.message&&this.notifyError(t.message);return}this.config.voice.stopPlayback(),this.silentTurn=!1,this.setPhase("listening"),await this.speech.start()}async toggleListening(){if(!this.enabled||this.phase==="confirming")return;if(this.phase==="listening"){this.speech.stop(),this.setPhase("thinking");return}if(this.phase==="speaking"){this.cancelAll();return}if(this.phase==="thinking")return;if(!await this.consent.hasConsented()){this.pendingConsentIntent="voice",this.consentModalVisible=!0,this.emit();return}await this.beginListening()}async submitTextTurn(t,n){var r,s;if(!this.enabled)return;let o=t.trim();if(!o)return;let i=(s=(r=this.config).gateTurn)==null?void 0:s.call(r);if(i&&!i.ok){i.message&&this.notifyError(i.message);return}if(this.pending&&!this.pending.silent){await this.handleConfirmationTranscript(o);return}this.silentTurn=(n==null?void 0:n.speak)!==!0,await this.handleTranscript(o)}async acceptConsent(){await this.consent.grant(),this.consentModalVisible=!1,this.emit(),this.telemetry.logEvent({eventType:"agent_consent_granted",sessionId:this.sessionId});let t=this.pendingConsentIntent;this.pendingConsentIntent=null,t==="voice"&&await this.beginListening()}declineConsent(){this.consentModalVisible=!1,this.pendingConsentIntent=null,this.emit(),this.telemetry.logEvent({eventType:"agent_consent_declined",sessionId:this.sessionId})}cancelAll(){var n;(n=this.abort)==null||n.abort(),this.abort=null,this.clearWatchdog(),this.clearConfirmWindow(),this.clearSpeakTimer(),this.speech.cancel(),this.config.voice.stopPlayback(),this.pending=null,this.chainState=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.liveActivity=null,this.chainActive=!1;let t=this.pendingTurnText;return t&&(this.pendingTurnText=null,this.lastExchange=null),this.setPhase("idle"),this.emit(),t}warmUp(){var t,n;(n=(t=this.config.backend).warmUp)==null||n.call(t)}dispose(){var t,n;this.cancelAll(),(t=this.removeIdentityListeners)==null||t.call(this),this.removeIdentityListeners=null,this.loadOlderTimer&&(clearTimeout(this.loadOlderTimer),this.loadOlderTimer=null),(n=this.unsubscribeSpeech)==null||n.call(this),this.unsubscribeSpeech=null,this.speech.dispose(),this.listeners.clear()}};var wa="http://www.w3.org/2000/svg",se={accentColor:"#4f8cff",backgroundColor:"#1b2a4a",colorKey:"azul",glowIntensity:100,size:56};function ne(e,t){let n=document.createElementNS(wa,e);for(let[o,i]of Object.entries(t))n.setAttribute(o,String(i));return n}function vi(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:i,fillRadius:r,midPx:s}=ut(e.fillDiameter,e.exteriorWidthSlider,e.interiorWidthSlider),a=typeof e.borderRadius=="number",l=a?`${r}px`:String(e.borderRadius),c=a?`${s/2}px`:String(e.borderRadius),u=a?`${i/2}px`:String(e.borderRadius),p=e.outerGlow!==!1,f=e.fillDepth!==!1,m=document.createElement("div");Object.assign(m.style,{boxSizing:"content-box",border:o>0?`${o}px solid ${e.exteriorColor}`:"",borderRadius:u,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:"0",boxShadow:p&&o>0?Zt(i,e.exteriorColor):""});let h=document.createElement("div");Object.assign(h.style,{boxSizing:"content-box",border:n>0?`${n}px solid ${e.interiorColor}`:"",borderRadius:c,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});let y=document.createElement("div");return Object.assign(y.style,{width:`${t}px`,height:`${t}px`,borderRadius:l,background:e.fill,overflow:"hidden",position:"relative",flexShrink:"0",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:f&&t>0?en(e.fillDiameter):""}),h.appendChild(y),m.appendChild(h),{root:m,fill:y}}function Ta(e){let{bars:t,color:n,radius:o}=rn(e),i=ne("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,"aria-hidden":"true"});i.style.display="block";let r=t.map(a=>{let l=ne("rect",{x:a.x,y:a.y,width:a.width,height:a.height,rx:o,ry:o,fill:n});return i.appendChild(l),l}),s=0;return{el:i,start(){let a=performance.now(),l=c=>{s=requestAnimationFrame(l);let u=(c-a)/1e3;t.forEach((p,f)=>{let m=sn(u,f,p.baseHalfHeight,p.maxHalfHeight);r[f].setAttribute("y",(p.centerY-m).toFixed(2)),r[f].setAttribute("height",(2*m).toFixed(2))})};s=requestAnimationFrame(l)},stop(){cancelAnimationFrame(s)}}}var Ea=9,Ia=[.25,.45,.65,.85,1,.85,.65,.45,.25],yi=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],Ra=26;function Oa(e,t){let n=t/Ra,o=3*n,i=3*n,r=3*n,s=document.createElement("div");Object.assign(s.style,{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:`${i}px`,height:`${t}px`,width:"100%",maxWidth:"88%"});let a=[];for(let h=0;h<Ea;h++){let y=document.createElement("div");Object.assign(y.style,{width:`${o}px`,height:`${t}px`,borderRadius:`${Math.max(1,2*n)}px`,backgroundColor:e,transformOrigin:"center center",transform:`scaleY(${r/t})`,flexShrink:"0"}),a.push(y),s.appendChild(y)}let l=0,c=0,u=0,p=0,f=r/t,m=h=>{l=requestAnimationFrame(m),!(h-u<80)&&(u=h,c+=.22,a.forEach((y,w)=>{var S,R,T;let x;if(p<.05){let g=(Math.sin(c+((S=yi[w])!=null?S:0))+1)/2;x=f+g*(.22-f)}else{let g=Math.sin(c*2.3+((R=yi[w])!=null?R:0))*.18+.82+Math.random()*.18;x=f+p*((T=Ia[w])!=null?T:.5)*(1-f)*g}y.style.transform=`scaleY(${Math.min(1,Math.max(f,x))})`}))};return{el:s,start(){l||(u=typeof performance!="undefined"?performance.now():Date.now(),l=requestAnimationFrame(m))},stop(){l&&cancelAnimationFrame(l),l=0},setVolume(h){p=h}}}var xi=8,Ci=68,ka=360-Ci,_a=Ci/2,Pa=[.15,.25,.35,.5,.65,.78,.88,1];function Ma(e,t){var a;let n=Math.max(28,e*.52),o=document.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"});let i=document.createElement("div");Object.assign(i.style,{width:`${n}px`,height:`${n}px`,animation:"fy-spin 0.92s linear infinite"}),i.setAttribute("role","progressbar"),i.setAttribute("aria-label","Loading");let r=ne("svg",{width:n,height:n,viewBox:"0 0 40 40","aria-hidden":"true"}),s=ka/(xi-1);for(let l=0;l<xi;l++){let c=_a+s*l;r.appendChild(ne("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(a=Pa[l])!=null?a:1,transform:`rotate(${c} 20 20)`}))}return i.appendChild(r),o.appendChild(i),o}var La=118/380,Ba=30/380,Na=2/380;function $a(e,t){let n=document.createElement("div");Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"});let o=e*La,i=Math.max(1,e*Na);for(let a of[0,.85]){let l=document.createElement("div");Object.assign(l.style,{position:"absolute",width:`${o}px`,height:`${o}px`,borderRadius:"50%",border:`${i}px solid ${t}`,opacity:"0.55",animation:`fy-voice 1.7s ease-out infinite ${a}s`}),n.appendChild(l)}let r=e*Ba,s=document.createElement("div");return Object.assign(s.style,{width:`${r}px`,height:`${r}px`,borderRadius:"50%",background:t,opacity:"0.9",animation:"fy-opulse 1s ease-in-out infinite"}),n.appendChild(s),n}function Da(e,t,n){let o=mn(e),i=1.8,{x:r,y:s}=gn(o),a=ne("svg",{width:t,height:t,viewBox:o.viewBox,fill:"none","aria-hidden":"true"});a.style.display="block",a.style.pointerEvents="none";let l=ne("g",{transform:`translate(${r} ${s})`});if(o.keyboardFrame&&o.keyDots){let c=o.keyboardFrame;l.appendChild(ne("rect",{x:c.x,y:c.y,width:c.w,height:c.h,rx:c.rx,stroke:n,"stroke-width":i}));for(let[u,p]of o.keyDots)l.appendChild(ne("rect",{x:u-.6,y:p-.6,width:1.2,height:1.2,rx:.2,fill:n}))}else if(o.chatFrame&&o.chatLines){let c=o.chatFrame,u=c.x+c.w/2,p=c.y+c.h,f=Math.max(1.15,i*.65);if(l.appendChild(ne("rect",{x:c.x,y:c.y,width:c.w,height:c.h,rx:c.rx,stroke:n,"stroke-width":i})),o.chatTail){let m=o.chatTail;l.appendChild(ne("polygon",{points:`${m.left},${p} ${m.tipX},${m.tipY} ${m.right},${p}`,fill:n}))}for(let{y:m,w:h}of o.chatLines)l.appendChild(ne("line",{x1:u-h/2,y1:m,x2:u+h/2,y2:m,stroke:n,"stroke-width":f,"stroke-linecap":"round"}))}else for(let c of o.paths)l.appendChild(ne("path",{d:c.d,stroke:n,fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round"}));return a.appendChild(l),a}function Ai(e){var y,w,x,S,R,T,g;let{theme:t}=e,n=(y=t.size)!=null?y:30,o=(w=t.shape)!=null?w:"circle",i=o==="circle"?"50%":`${fn(o,n)}px`,r=(x=t.backgroundColor)!=null?x:e.backgroundColor,s=(S=t.borderColor)!=null?S:e.accentColor,a=hn(t.iconColor,r,e.accentColor),l=We(t.icon),c=pn((R=t.iconScale)!=null?R:1),u=Math.round(dn(n)*c),p=ut(n,(T=t.borderWidth)!=null?T:100,t.innerBorderWidth),f=document.createElement("button");f.type="button",f.setAttribute("aria-label",e.label),Object.assign(f.style,{border:"none",background:"transparent",padding:"0",cursor:"pointer",lineHeight:"0",flexShrink:"0",width:`${p.totalPx}px`,height:`${p.totalPx}px`,display:"flex",alignItems:"center",justifyContent:"center"}),f.onclick=e.onClick;let{root:m,fill:h}=vi({fillDiameter:n,borderRadius:i,exteriorColor:s,exteriorWidthSlider:(g=t.borderWidth)!=null?g:100,interiorColor:lt(t.innerBorderColor),interiorWidthSlider:t.innerBorderWidth,fill:r,outerGlow:!1,fillDepth:!1});if(t.iconImageDataUrl){let v=document.createElement("img");v.src=t.iconImageDataUrl,v.alt="",Object.assign(v.style,{width:`${u}px`,height:`${u}px`,objectFit:"contain",display:"block"}),h.appendChild(v)}else h.appendChild(Da(l,u,a));return f.appendChild(m),f}function Si(e){let t=document.createElement("div");t.style.display="inline-flex";let n=e,o="idle",i=0,r=null,s=null,a=null;function l(){var w,x,S,R;let u=(w=n.size)!=null?w:se.size,p=bt({colorKey:(x=n.colorKey)!=null?x:se.colorKey,backgroundColor:n.backgroundColor,accentColor:n.accentColor}),f=(S=n.glowColor)!=null&&S.startsWith("#")?n.glowColor:n.accentColor,m=lt(n.innerBorderColor);s==null||s.stop(),s=null,a==null||a.stop(),a=null,t.replaceChildren();let{root:h,fill:y}=vi({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(R=n.glowIntensity)!=null?R:se.glowIntensity,interiorColor:m,interiorWidthSlider:n.innerBorderWidth,fill:p});r=y,t.appendChild(h),c()}function c(){var f,m;if(!r)return;let u=(f=n.size)!=null?f:se.size,p=(m=n.waveformColor)!=null?m:"#ffffff";if(s==null||s.stop(),s=null,a==null||a.stop(),a=null,r.replaceChildren(),t.style.animation="",o==="thinking"){r.appendChild(Ma(u,p));return}if(o==="listening"){s=Oa(p,Math.round(u*.46)),s.setVolume(i),r.appendChild(s.el),s.start();return}if(n.logoDataUrl){let h=document.createElement("img");h.src=n.logoDataUrl,h.alt="",h.draggable=!1,h.addEventListener("dragstart",y=>y.preventDefault()),Object.assign(h.style,{width:"64%",height:"64%",objectFit:"contain",pointerEvents:"none",userSelect:"none",webkitUserSelect:"none",webkitUserDrag:"none",animation:o==="speaking"?"fy-opulse 1s ease-in-out infinite":""}),r.appendChild(h);return}if(o==="speaking"){r.appendChild($a(u,p));return}o==="idle"&&(a=Ta(u),r.appendChild(a.el),a.start())}return l(),{element:t,applyAppearance(u){n=u,l()},applyState(u,p){i=p,u!==o?(o=u,c()):o==="listening"&&(s==null||s.setVolume(i))}}}var uo="fyodos:published-config:v1";function Fa(){try{if(typeof window=="undefined"||!window.localStorage)return null;let e=window.localStorage.getItem(uo);return e?JSON.parse(e):null}catch{return null}}function wi(e){try{if(typeof window=="undefined"||!window.localStorage)return;e?window.localStorage.setItem(uo,JSON.stringify(e)):window.localStorage.removeItem(uo)}catch{}}function Ti(e,t){var r,s,a,l;let n=t.orbEnabled!==!1,o=e.theme;return{appearance:{accentColor:(r=o.accentColor)!=null?r:se.accentColor,backgroundColor:(s=o.backgroundColor)!=null?s:se.backgroundColor,glowColor:o.glowColor,colorKey:o.colorKey,glowIntensity:o.glowIntensity,hapticIntensity:o.hapticIntensity,innerBorderColor:o.innerBorderColor,innerBorderWidth:o.innerBorderWidth,size:(a=o.size)!=null?a:se.size,waveformColor:o.waveformColor,logoDataUrl:e.logoDataUrl},keyboardChip:(l=o.keyboardChip)!=null?l:null,modalTheme:e.modalTheme,screenPosition:e.screenPosition,bubbleTheme:Fe(t.bubbleTheme),bubbleEnabled:t.bubbleEnabled!==!1,voiceInputEnabled:t.voiceInputEnabled!==!1,thinkingStepsEnabled:t.agentThinkingStepsEnabled===!0,enabled:n,conversationRetentionMinutes:typeof t.conversationRetentionMinutes=="number"?t.conversationRetentionMinutes:null,internalProfile:t.orbProfile==="internal"}}function Ei(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,i=Fa();i&&t.onChange(Ti(yt(i),i));let r=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange(Ti(yt(c.published),c.published)),wi(c.published)):(t.onChange(null),wi(null))}catch{}};r();let s=(l=t.pollMs)!=null?l:12e3,a=s>0?setInterval(()=>{r()},s):null;return()=>{o=!0,a&&clearInterval(a)}}function Wa(){var t,n;if(typeof window=="undefined")return null;let e=window;return(n=(t=e.SpeechRecognition)!=null?t:e.webkitSpeechRecognition)!=null?n:null}function Ua(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function xt(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Ii(e){let t=Wa(),n=null,o=!1,i="",r=()=>{n==null||n.stop()};return{isSupported:()=>t!=null,isListening:()=>o,stop:r,dispose:()=>{r(),n=null,o=!1},toggle(a,l){if(!t)return;if(o){r();return}i=a();let c=new t;c.lang=Ua(e),c.interimResults=!0,c.continuous=!0;let u="";c.onresult=p=>{var y,w;let f="";for(let x=p.resultIndex;x<p.results.length;x+=1){let S=p.results[x];if(!S)continue;let R=(w=(y=S[0])==null?void 0:y.transcript)!=null?w:"";S.isFinal?u+=R:f+=R}let m=`${u}${f}`.trimStart(),h=i?`${i}${i.endsWith(" ")?"":" "}${m}`:m;l(h)},c.onend=()=>{o=!1,n=null},c.onerror=()=>{o=!1,n=null},n=c,o=!0,c.start()}}}var Ri="fyodos-orb-styles",Ha=`
3
+ `,a=o-i.length-s.length;return a<=n.truncationSuffix.length?ke(i,{...n,maxChars:o}):i+s+ke(r,{...n,maxChars:a})}var jn=[{type:"email",regex:/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,replacement:"[REDACTED:EMAIL]"},{type:"payment_card",regex:/\b\d(?:[ -]?\d){12,18}\b/g,replacement:"[REDACTED:CARD]"},{type:"phone",regex:/(?:\+\d{1,3}[\s.-]?)?\b\d(?:[\s.-]?\d){8,13}\b/g,replacement:"[REDACTED:PHONE]"}],Kt={ES:[{type:"iban_es",regex:/\bES[\s-]?\d{2}(?:[\s-]?\d){20}\b/g,replacement:"[REDACTED:IBAN]"},{type:"national_id_es",regex:/\b\d{8}[A-Za-z]\b/g,replacement:"[REDACTED:NATIONAL_ID]"}],US:[{type:"ssn_us",regex:/\b\d{3}[- ]\d{2}[- ]\d{4}\b/g,replacement:"[REDACTED:NATIONAL_ID]"}]};function Xn(e={}){var i,r;let t=((i=e.countryPacks)!=null?i:[]).flatMap(s=>{let a=Kt[s.toUpperCase()];if(!a)throw new Error(`[fyodos] Unknown PII country pack "${s}". Available packs: ${Object.keys(Kt).join(", ")}. Use customPatterns to add your own.`);return a}),[n,...o]=jn;return[n,...(r=e.customPatterns)!=null?r:[],...t,...o]}function Yt(e={}){let t=Xn(e);return n=>{let o=n,i=[];for(let{type:r,regex:s,replacement:a}of t)s.test(o)&&(i.push(r),o=o.replace(s,a)),s.lastIndex=0;return o=o.replace(/\+\s?\[REDACTED:PHONE\]/g,"[REDACTED:PHONE]"),{sanitized:o,redactions:i}}}function Dr(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Fr(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Wr(e){return Fr(e)==="es"}function qn(e){return e.replace(/^[¿¡]+/,"").replace(/[?!.…]+$/,"").trim()}function Ur(e,t,n){var f;let o=qn(e),i=qn(t),r=i.match(/\{(\w+)\}/);if(!r||r.index==null)return null;let s=r[1],a=i.slice(0,r.index).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=i.slice(r.index+r[0].length).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${a}(?<value>.+?)${l}$`,"i"),u=o.match(c);if(!((f=u==null?void 0:u.groups)!=null&&f.value))return null;let p=u.groups.value.trim();return n.replace(`{${s}}`,p)}var Hr=[[/^want to (.+)$/i,"I want to $1"],[/^ready to checkout$/i,"I want to checkout"],[/^ready to (.+)$/i,"I want to $1"],[/^looking for (.+)$/i,"I'm looking for $1"],[/^browse (.+)$/i,"I want to browse $1"],[/^check your (.+)$/i,"I want to check my $1"],[/^need to (.+)$/i,"I need to $1"],[/^update your (.+)$/i,"I want to update my $1"],[/^send (.+)$/i,"I want to send $1"],[/^change your (.+)$/i,"I want to change my $1"],[/^review your (.+)$/i,"I want to review my $1"],[/^write (.+)$/i,"I want to write $1"],[/^what are you looking for$/i,"I'm looking for something"]],Vr=[[/^quieres ir a (.+)$/i,"Quiero ir a $1"],[/^quieres (.+)$/i,"Quiero $1"],[/^finalizar tu compra$/i,"Quiero finalizar mi compra"],[/^buscar un usuario$/i,"Quiero buscar un usuario"],[/^buscar un producto$/i,"Quiero buscar un producto"],[/^buscar (.+)$/i,"Quiero buscar $1"],[/^ver tu (.+)$/i,"Quiero ver mi $1"],[/^ver tus (.+)$/i,"Quiero ver mis $1"],[/^cambiar algún ajuste$/i,"Quiero cambiar un ajuste"],[/^cambiar tu (.+)$/i,"Quiero cambiar mi $1"],[/^actualizar tu perfil$/i,"Quiero actualizar mi perfil"],[/^añadir una tarea$/i,"Quiero a\xF1adir una tarea"],[/^añadir (.+)$/i,"Quiero a\xF1adir $1"],[/^enviar un mensaje$/i,"Quiero enviar un mensaje"],[/^revisar tus finanzas$/i,"Quiero revisar mis finanzas"],[/^revisar tu historial$/i,"Quiero revisar mi historial"],[/^escribir algo nuevo$/i,"Quiero escribir algo nuevo"],[/^qué buscas$/i,"Busco algo"]];function jt(e,t){var c;let n=Dr(e);if(!n)return"";let o=(c=t==null?void 0:t.locale)!=null?c:"en",i=Wr(o),r=t==null?void 0:t.messages,s=qn(n);if(r){let u=i?[[r.bubblePromptFromExample,"Quiero {phrase}"],[r.bubblePromptFromAction,"Quiero {action}"],[r.bubblePromptFromLabel,"Quiero ir a {label}"]]:[[r.bubblePromptFromExample,"I want to {phrase}"],[r.bubblePromptFromAction,"I want to {action}"],[r.bubblePromptFromLabel,"I want to open {label}"]];for(let[p,f]of u){let m=Ur(n,p,f);if(m)return m}}let a=i?Vr:Hr;for(let[u,p]of a)if(u.test(s))return s.replace(u,p);return i?`Quiero ${s.charAt(0).toLowerCase()+s.slice(1)}`:`I want to ${s.charAt(0).toLowerCase()+s.slice(1)}`}function Qn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function Xt(e){var o;let t=Qn(e.appId,(o=e.version)!=null?o:1),{storage:n}=e;return{storageKey:t,async hasConsented(){try{let i=await n.getItem(t);return i?JSON.parse(i).granted===!0:!1}catch{return!1}},async grant(){let i=JSON.stringify({granted:!0,grantedAt:new Date().toISOString()});await n.setItem(t,i)},async revoke(){await n.removeItem(t)}}}function qt(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Qt(e,t){let n=qt(e);if(!n)return{matched:!1,command:""};for(let o of t){let i=qt(o);if(!i)continue;let r=n.indexOf(i);if(r===-1)continue;return{matched:!0,command:n.slice(r+i.length).trim(),phrase:i}}return{matched:!1,command:""}}function Jt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var Yo=40;function Zt(e){return typeof e!="number"||Number.isNaN(e)?Yo:Math.max(0,Math.min(100,Math.round(e)))}function jo(e,t){let n=Zt(t);if(n<=0)return 0;let o=n/100,i=r=>Math.max(1,Math.round(r*o));switch(e){case"response":return[0,i(12),40,i(12)];case"orbTap":return i(18);case"listenStart":return i(14);case"listenStop":return i(8);default:return i(10)}}function Jn(e){let t=()=>typeof e=="function"?e():e;return{trigger(n){try{let i=globalThis.navigator,r=jo(n,t());!(r===0||Array.isArray(r)&&r.every(a=>a===0))&&i&&typeof i.vibrate=="function"&&i.vibrate(r)}catch{}}}}var ot={en:{affirmative:["yes","yeah","yep","sure","confirm","confirmed","go ahead","do it","ok","okay","correct","exactly","absolutely","affirmative"],negative:["no","nope","cancel","cancel it","stop","wait","dont","never mind","nevermind","forget it","negative"]},es:{affirmative:["si","s\xED","confirma","confirmo","adelante","hazlo","vale","ok","okey","correcto","exacto","claro","efectivamente","dale"],negative:["no","cancela","cancelar","cancelalo","canc\xE9lalo","para","espera","detente","mejor no","olvidalo","olv\xEDdalo","nada"]}};function en(e){var o,i,r;let t=(i=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?i:e.toLowerCase(),n=(r=ot[e])!=null?r:ot[t];if(!n)throw new Error(`[fyodos] No confirmation lexicon for locale "${e}". Built-in locales: ${Object.keys(ot).join(", ")}. Pass a custom ConfirmationLexicon for your locale.`);return n}function _e(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Xo(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function Zn(e,t){let n=_e(e);return n?t.affirmative.some(o=>Xo(n,_e(o))):!1}function tn(e,t){let n=_e(e);return n?t.negative.some(o=>Xo(n,_e(o))):!1}function nn(e,t){let n=tn(e,t),o=Zn(e,t);return n?"negative":o?"affirmative":"ambiguous"}function ls(e,t){return t?` ${e} `.includes(` ${t} `):!1}function on(e,t,n){let o=_e(e);return o?tn(e,n)?"negative":ls(o,_e(t))?"affirmative":"ambiguous":"ambiguous"}var eo={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},it={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Me(e,t=!1){let n=t?it:void 0;return e==null||typeof e!="number"||Number.isNaN(e)?n?{...n}:void 0:e<=0?{...n,sessionIdleMs:Number.POSITIVE_INFINITY}:{...n,sessionIdleMs:Math.round(e*6e4)}}var ve=5,Pe=200;function qo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Qo(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Jo(e,t,n){let o=t.map(i=>i.role==="user"?`User: ${qo(i.content,120)}`:`Assistant: ${qo(i.content,120)}`).join(" | ");return Qo(e?`${e} | ${o}`:o,n)}function to(e){return{...eo,...e}}function Le(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function Be(e,t=Date.now(),n){var i;let{sessionIdleMs:o}=to(n);return e.turns.length===0&&!e.summary&&!((i=e.uiArchive)!=null&&i.length)?(e.lastActivityAt=t,!1):t-e.lastActivityAt<=o?!1:(e.turns=[],e.summary=null,e.uiArchive=[],e.lastActivityAt=t,!0)}function no(e,t=null,n){let{maxRecentTurns:o}=to(n);return e.length===0?{history:[],summary:(t==null?void 0:t.trim())||null}:{history:e.slice(-o),summary:(t==null?void 0:t.trim())||null}}function rt(e,t=Date.now(),n){return Be(e,t,n),e.lastActivityAt=t,no(e.turns,e.summary,n)}function us(e,t){let{maxRecentTurns:n,summarizeAfterTurns:o,maxSummaryChars:i,maxStoredTurns:r}=t;if(e.turns.length>o){let s=e.turns.length-n,a=e.turns.slice(0,s);e.summary=Jo(e.summary,a,i),e.turns=e.turns.slice(s)}if(e.turns.length>r){let s=e.turns.slice(0,e.turns.length-n);e.summary=Jo(e.summary,s,i),e.turns=e.turns.slice(-n)}}function st(e,t,n,o=Date.now(),i){var l;let r=to(i),s=t.trim(),a=n.trim();!s||!a||(e.turns.push({role:"user",content:s},{role:"assistant",content:a}),e.uiArchive=(l=e.uiArchive)!=null?l:[],e.uiArchive.push({userText:s,replyText:a}),e.uiArchive.length>Pe&&(e.uiArchive=e.uiArchive.slice(-Pe)),e.lastActivityAt=o,us(e,r))}function ds(e,t){var r,s,a,l;let n;if((r=e.uiArchive)!=null&&r.length)n=e.uiArchive;else{n=[];for(let c=0;c<e.turns.length;c+=2){let u=e.turns[c],p=e.turns[c+1];(u==null?void 0:u.role)==="user"&&(p==null?void 0:p.role)==="assistant"&&n.push({userText:u.content,replyText:p.content})}}if(!((s=t==null?void 0:t.userText)!=null&&s.trim()))return n;let o=n[n.length-1];return o!=null&&o.userText===t.userText&&o.replyText===((a=t.replyText)!=null?a:"")?t.replyText&&o.replyText!==t.replyText?[...n.slice(0,-1),t]:n:[...n,{userText:t.userText,replyText:(l=t.replyText)!=null?l:""}]}function at(e,t,n=ve,o){Be(e,Date.now(),o);let i=ds(e,t),r=Math.max(1,n);return{exchanges:i.slice(-r),hasOlder:i.length>r,totalCount:i.length}}var le="anon";function ct(e){let t=(e!=null?e:"").trim();if(!t)return le;let n=2166136261;for(let o=0;o<t.length;o++)n^=t.charCodeAt(o),n=Math.imul(n,16777619);return`u_${(n>>>0).toString(36)}`}function lt(e,t="public",n=le){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===le?o:`${o}/${n}`}function ps(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-it.maxStoredTurns)){let o=n==null?void 0:n.role,i=n==null?void 0:n.content;(o==="user"||o==="assistant")&&typeof i=="string"&&i&&t.push({role:o,content:i})}return t}function fs(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Pe)){let o=n==null?void 0:n.userText,i=n==null?void 0:n.replyText;typeof o=="string"&&o&&typeof i=="string"&&t.push({userText:o,replyText:i})}return t}async function rn(e,t,n,o=null,i="public",r=le){var a,l;let s=lt(t,i,r);try{if(n.turns.length===0&&!n.summary&&!((a=n.uiArchive)!=null&&a.length)){await e.removeItem(s);return}let u={v:1,turns:n.turns,summary:n.summary,lastActivityAt:n.lastActivityAt,uiArchive:(l=n.uiArchive)!=null?l:[],retentionMinutes:o,owner:r};await e.setItem(s,JSON.stringify(u))}catch{}}async function sn(e,t,n=Date.now(),o="public",i=le){var s;let r=lt(t,o,i);try{let a=await e.getItem(r);if(!a)return null;let l=JSON.parse(a);if((l==null?void 0:l.v)!==1)return await e.removeItem(r),null;if((typeof l.owner=="string"?l.owner:le)!==i)return null;let u={turns:ps(l.turns),summary:typeof l.summary=="string"&&l.summary?l.summary:null,lastActivityAt:typeof l.lastActivityAt=="number"&&Number.isFinite(l.lastActivityAt)?l.lastActivityAt:0,uiArchive:fs(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return Be(u,n,Me(p))||u.turns.length===0&&!u.summary&&!((s=u.uiArchive)!=null&&s.length)?(await e.removeItem(r),null):(u.lastActivityAt=n,u)}catch{return null}}async function an(e,t,n="public",o=le){try{await e.removeItem(lt(t,n,o))}catch{}}function Ne(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function oo(e,t){let n=Ne(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function io(e,t){return oo(e,t)}var $e=35,ut="rgba(255,255,255,0.1)",dt="#ffffff";function De(e){return e==null||Number.isNaN(Number(e))?$e:Math.max(0,Math.min(100,Number(e)))}function ro(e,t){let n=De(t)/100;return n<=0?0:e*(.002+n*.012)}function pt(e){let t=e==null?void 0:e.trim();if(!t)return ut;if(t.startsWith("rgba")||t.startsWith("rgb"))return t;if(t.startsWith("#")){let n=t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t.slice(0,7),o=parseInt(n.slice(1,3),16),i=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return[o,i,r].some(s=>Number.isNaN(s))?ut:`rgba(${o},${i},${r},0.12)`}return ut}function ft(e,t,n){let o=e,i=ro(e,n),r=io(e,t),s=o+2*i,a=o+2*i+2*r;return{fillPx:o,interiorPx:i,exteriorPx:r,totalPx:a,fillRadius:o/2,midPx:s}}function cn(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function ln(e){let t=e/150;return[`inset -${Math.round(8*t)}px -${Math.round(12*t)}px ${Math.round(28*t)}px rgba(0,0,0,0.36)`,`inset ${Math.round(6*t)}px ${Math.round(8*t)}px ${Math.round(20*t)}px rgba(255,255,255,0.07)`].join(", ")}var te={accent:"#2f6bff",glow:"#5aa2ff",background:"rgba(0,0,0,0.72)",waveform:"#ffffff",colorKey:"azul"},Zo={colorKey:te.colorKey,glowKey:te.colorKey,accentColor:te.accent,glowColor:te.glow,backgroundColor:te.background,waveformColor:te.waveform,waveformColorKey:"custom",speed:42,glowIntensity:100,innerBorderColor:dt,innerBorderWidth:$e,borderWidth:1.5,waveformHeight:26,size:52},ei={size:30,shape:"circle",backgroundColor:te.background,borderColor:te.accent,iconColor:te.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:dt,innerBorderWidth:$e,borderWidth:100},mt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},ti={cardBackgroundColor:"#16181d",cardBorderColor:"rgba(255,255,255,0.14)",userTextColor:"rgba(255,255,255,0.75)",replyTextColor:"#ffffff",accentColor:te.accent,inputBackgroundColor:"#ffffff",borderRadius:18,sendButtonRadius:16};function Fe(e){let t=ni(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function un(e){let t=ni(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function ni(e){if(!e)return null;let t=e.trim().toLowerCase(),n,o,i,r=t.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/);if(r){let s=r[1];s.length===3?(n=parseInt(s[0]+s[0],16),o=parseInt(s[1]+s[1],16),i=parseInt(s[2]+s[2],16)):(n=parseInt(s.slice(0,2),16),o=parseInt(s.slice(2,4),16),i=parseInt(s.slice(4,6),16))}else{let s=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(!s)return null;n=Number(s[1]),o=Number(s[2]),i=Number(s[3])}return(.299*n+.587*o+.114*i)/255}var ht={bars:[.42,.72,1,.72,.42],color:"#eaf1ff",barWidthRatio:.06,gapRatio:.05,heightRatio:.4};function so(e,t){let{bars:n,barWidthRatio:o,gapRatio:i,heightRatio:r}=ht,s=(t!=null?t:"").trim()||ht.color,a=e*o,l=e*i,c=e*r,u=n.length*a+(n.length-1)*l,p=(e-u)/2;return{bars:n.map((m,h)=>{let x=Math.max(a,c*m);return{x:p+h*(a+l),y:(e-x)/2,width:a,height:x}}),color:s,radius:a/2}}function dn(e,t){let{bars:n,color:o,radius:i}=so(e,t),r=e/2,s=e*ht.heightRatio/2;return{color:o,radius:i,bars:n.map(a=>({...a,baseHalfHeight:a.height/2,centerY:r,maxHalfHeight:s}))}}function pn(e,t,n,o){let i=.5+.5*((.5+.5*Math.sin(e*1.6))*.6+(.5+.5*Math.sin(e*.9+1.1))*.4),r=.35+.65*(.5+.5*Math.sin(e*7+t*.95))*(.55+.45*Math.sin(e*3.1+t*.6)),s=n*(.5+r*i);return Math.max(n*.35,Math.min(s,o))}var ys=["pill","rounded","square","cloud"];function oi(e,t,n,o,i,r,s){let a=[];for(let l=0;l<=s;l++){let c=i+(r-i)*l/s;a.push([e+n*Math.cos(c),t+o*Math.sin(c)])}return a}function xs(e,t,n,o,i){let r=[];for(let s=0;s<=i;s++){let a=Math.PI-Math.PI*s/i;r.push([e+n*Math.cos(a),t-o*Math.sin(a)])}return r}function vs(e,t,n,o,i){let r=[];for(let s=0;s<=i;s++){let a=Math.PI*s/i;r.push([e+n*Math.cos(a),t+o*Math.sin(a)])}return r}function fn(e,t,n){n&&t.shift(),e.push(...t)}var Cs=1.28,As=38;function ri(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function co(e){if(!Number.isFinite(e)||e<=0)return 5;let t=e*.88;return ri(t/As,3,7)}function si(e=5){let l=ri(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];fn(f,oi(6,50,u,p,Math.PI/2,Math.PI*3/2,10),!1);for(let h=0;h<l;h++){let x=6+c+2*c*h;fn(f,xs(x,18,c,14,8),!0)}fn(f,oi(94,50,u,p,-Math.PI/2,Math.PI/2,10),!0);for(let h=l-1;h>=0;h--){let x=6+c+2*c*h;fn(f,vs(x,83,c,12,8),!0)}return`polygon(${f.map(([h,x])=>`${h.toFixed(2)}% ${x.toFixed(2)}%`).join(", ")})`}var lo=si(5);function uo(e){return si(co(e))}function gt(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function ao(e,t){return typeof e=="string"&&e.trim()?e:t}function hn(e){let t=String(e!=null?e:"").toLowerCase();return t==="circle"||t==="round"?"cloud":ys.includes(t)?t:mt.shape}function bt(e,t){if(e!=null)return`${Math.round(e*t)}px`}function We(e){let t=e!=null?e:{},n=mt,o=gt(t.textSize,gt(t.size,n.textSize));return{backgroundColor:ao(t.backgroundColor,n.backgroundColor),textColor:ao(t.textColor,n.textColor),borderColor:ao(t.borderColor,n.borderColor),borderWidth:gt(t.borderWidth,n.borderWidth),shape:hn(t.shape),borderRadius:gt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:gt(t.bubbleScale,n.bubbleScale)}}var po=38,fo=14,ii=4;function yt(e){let t=e.textSize,n=e.bubbleScale,o=Math.round(fo*n),i=Math.round(t*1.25),r=Math.max(Math.round(po*n),i+ii*2);hn(e.shape)==="cloud"&&(r=Math.round(r*Cs));let s=Math.max(ii,Math.round((r-i)/2));return{fontPx:t,padV:s,padH:o,approxHeight:r}}function Ss(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var ai=999;function ho(e,t,n){switch(hn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:ai};case"cloud":{let i=Ss(t),r=typeof n=="number"&&n>0?uo(n):lo;return{...i,clipPath:r}}default:return{borderRadius:Math.min(e.borderRadius,Math.round(t/2))}}}function mn(e,t,n=1,o){var s;let i=hn(e.shape),r=ho({...e,shape:i},t,o);if(i==="pill"){let a=`${Math.round(ai*n)}px`;return{borderRadius:a,borderTopLeftRadius:a,borderTopRightRadius:a,borderBottomLeftRadius:a,borderBottomRightRadius:a,clipPath:"none"}}return i==="square"?{borderRadius:"0px",borderTopLeftRadius:"0px",borderTopRightRadius:"0px",borderBottomLeftRadius:"0px",borderBottomRightRadius:"0px",clipPath:"none"}:{borderRadius:bt(r.borderRadius,n),borderTopLeftRadius:bt(r.borderTopLeftRadius,n),borderTopRightRadius:bt(r.borderTopRightRadius,n),borderBottomLeftRadius:bt(r.borderBottomLeftRadius,n),borderBottomRightRadius:bt(r.borderBottomRightRadius,n),clipPath:(s=r.clipPath)!=null?s:"none"}}function gn(e,t){if(!e)return;let n=(o,i)=>{if(!i){e.style.removeProperty(o);return}e.style.setProperty(o,i,"important")};n("border-radius",t.borderRadius),n("border-top-left-radius",t.borderTopLeftRadius),n("border-top-right-radius",t.borderTopRightRadius),n("border-bottom-left-radius",t.borderBottomLeftRadius),n("border-bottom-right-radius",t.borderBottomRightRadius),n("clip-path",t.clipPath)}function bn(e){return Math.round(e*.5)}function yn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function xn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function vn(e,t,n="#ffffff"){let o=(e!=null?e:n).trim(),i=t.trim();if(!o)return n;let r=s=>{let a=s.toLowerCase();return a.startsWith("#")&&a.length>=7?a.slice(0,7):a};return r(o)===r(i)?n:o}var ws=[[8,11],[11,11],[14,11],[17,11],[8,14],[11,14],[14,14],[17,14]],ci={keyboard:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:4,minY:7,maxX:20,maxY:18},keyboardFrame:{x:4,y:7,w:16,h:11,rx:2},keyDots:ws},pen:{viewBox:"0 0 24 24",paths:[{d:"M4 20h4l10.5-10.5a1.5 1.5 0 0 0 0-2.12l-2.38-2.38a1.5 1.5 0 0 0-2.12 0L4 15.5V20z",fill:!1},{d:"M13.5 6.5l4 4",fill:!1}],contentBBox:{minX:4,minY:6.5,maxX:17.5,maxY:20}},chat:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:5,minY:4,maxX:19,maxY:18.5},chatFrame:{x:5,y:4,w:14,h:10,rx:2.5},chatTail:{left:7.5,right:10.5,tipX:5,tipY:18.5},chatLines:[{y:8,w:6},{y:10,w:6}]}};function Cn(e="keyboard"){var t;return(t=ci[e])!=null?t:ci.keyboard}function An(e){var l,c;let t=e.viewBox.split(/\s+/).map(Number),n=(l=t[2])!=null?l:24,o=(c=t[3])!=null?c:24,{minX:i,minY:r,maxX:s,maxY:a}=e.contentBBox;return{x:n/2-(i+s)/2,y:o/2-(r+a)/2}}var Ts=["keyboard","pen","chat"];function Ue(e){return Ts.includes(e)?e:"keyboard"}var Ce={x:1,y:1};function ue(e){if(e==null)return{...Ce};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Ce.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Ce.y}}function mo(e){var f,m,h,x,T;let t=ue(e.position),n=(f=e.safeAreaTop)!=null?f:0,o=(m=e.safeAreaBottom)!=null?m:0,i=(h=e.safeAreaLeft)!=null?h:0,r=(x=e.safeAreaRight)!=null?x:0,s=(T=e.margin)!=null?T:16,a=e.orbDiameter,l=Math.max(0,e.viewportWidth-i-r-2*s-a),c=Math.max(0,e.viewportHeight-n-o-2*s-a),u=i+s+t.x*l,p=n+s+t.y*c;return{right:e.viewportWidth-u-a,bottom:e.viewportHeight-p-a}}function Sn(e){var u,p,f;let t=(u=e.contentWidth)!=null?u:e.viewportWidth,n=(p=e.contentHeight)!=null?p:e.viewportHeight,o=e.orbDiameter,i=(f=e.edgeGap)!=null?f:8,r=mo({viewportWidth:t,viewportHeight:n,orbDiameter:o,margin:e.margin,position:e.position,safeAreaTop:e.safeAreaTop,safeAreaBottom:e.safeAreaBottom,safeAreaLeft:e.safeAreaLeft,safeAreaRight:e.safeAreaRight}),s=t-r.right-o,a=n-r.bottom-o,l=Math.max(i,t-o-i),c=Math.max(i,n-o-i);return{left:Math.min(l,Math.max(i,s)),top:Math.min(c,Math.max(i,a))}}function xt(e){let t=ue(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function wn(e){let t=ue(e);return{x:t.x>=.5?1:0,y:t.y}}function Tn(e){var m,h,x,T,v;let t=(m=e.safeAreaTop)!=null?m:0,n=(h=e.safeAreaBottom)!=null?h:0,o=(x=e.safeAreaLeft)!=null?x:0,i=(T=e.safeAreaRight)!=null?T:0,r=(v=e.margin)!=null?v:16,s=e.orbDiameter,a=Math.max(0,e.viewportWidth-o-i-2*r-s),l=Math.max(0,e.viewportHeight-t-n-2*r-s),c=e.centerX-s/2,u=e.centerY-s/2,p=a>0?(c-o-r)/a:0,f=l>0?(u-t-r)/l:0;return ue({x:p,y:f})}var li={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},vt="rgba(0,0,0,0.72)";function Ct(e){var o,i,r;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&li[t])return li[t];let n=(i=e.backgroundColor)==null?void 0:i.trim();return n&&n!==vt?n:(r=e.accentColor)!=null&&r.trim()?e.accentColor.trim():n||vt}function En(e){var s,a,l,c,u,p,f,m;let t=Ct(e),n=e.keyboardChip,o=(s=n==null?void 0:n.backgroundColor)==null?void 0:s.trim(),i=(a=e.glowColor)!=null?a:e.accentColor,r=n?{...n,icon:Ue(n.icon),backgroundColor:!o||o===vt?t:o,borderColor:(l=n.borderColor)!=null?l:i,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:De(n.innerBorderWidth),borderWidth:Ne(n.borderWidth)}:void 0;return{accentColor:e.accentColor,backgroundColor:t,glowColor:i,colorKey:e.colorKey,glowKey:e.glowKey,speed:(u=e.speed)!=null?u:42,glowIntensity:Ne(e.glowIntensity),hapticIntensity:Zt(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:De(e.innerBorderWidth),size:e.size,borderWidth:(p=e.borderWidth)!=null?p:2,waveformHeight:(f=e.waveformHeight)!=null?f:26,waveformColor:(m=e.waveformColor)!=null?m:e.accentColor,keyboardChip:r}}function At(e){var n,o;return{theme:En(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:ue(e.orbTheme.screenPosition)}}var Es=/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|0\.0\.0\.0$)/;function go(e){let t=(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"");return t?t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="::"||t.endsWith(".local")?!0:Es.test(t):!1}function Rn(e,t=!1,n){var r;if(!e||t)return!1;let o=globalThis.location,i=n!=null?n:o?(r=o.hostname)!=null?r:"":null;return i==null?!1:!go(i)}var V=class extends Error{constructor(t,n,o){super(n!=null?n:t),this.name="AgentApiError",this.code=t,this.status=o}};var Ea=15e3,Ra=12e3;async function In(e,t,n,o){let i=new AbortController,r=!1,s=setTimeout(()=>{r=!0,i.abort()},n);o&&(o.aborted?i.abort():o.addEventListener("abort",()=>i.abort()));try{return await fetch(e,{...t,signal:i.signal})}catch(a){if(r)throw new V("timeout");if(o!=null&&o.aborted)throw new V("cancelled");let l=a instanceof Error?a.message:String(a);throw new V("network",l)}finally{clearTimeout(s)}}async function ui(e){let t={};try{let o=await e.text();o&&(t=JSON.parse(o))}catch{}let n=typeof t.detail=="string"?t.detail:typeof t.error=="string"?t.error:t.message;if(e.status===401||e.status===403)return new V("unauthorized",n,e.status);if(e.status===429){let o=typeof t.remaining=="number"||(n!=null?n:"").toLowerCase().includes("quota");return new V(o?"quota_exceeded":"rate_limited",n,e.status)}return e.status===404?new V("not_found",n,e.status):e.status>=500?new V("server_error",n,e.status):new V("unknown",n!=null?n:e.statusText,e.status)}function di(e){var r,s;let t=e.baseUrl.replace(/\/$/,""),n=(r=e.turnTimeoutMs)!=null?r:Ea,o=(s=e.ttsTimeoutMs)!=null?s:Ra;function i(){var l,c;let a=(l=e.getUserId)==null?void 0:l.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...a?{"x-user-id":a}:{},...(c=e.headers)!=null?c:{}}}return{async sendTurn(a,l){var h,x,T,v,S,I,E,g,C,A,N;let c={message:a.message.trim(),language:a.language,manifest_version:a.manifestVersion,manifest_routes:a.manifestRoutes,manifest_actions:a.manifestActions,app_name:a.appName,app_description:a.appDescription};(h=a.appType)!=null&&h.trim()&&(c.app_type=a.appType.trim()),(x=a.appFlow)!=null&&x.trim()&&(c.app_flow=a.appFlow.trim()),a.voice&&(c.voice=a.voice),(T=a.screenContext)!=null&&T.trim()&&(c.screen_context=a.screenContext.trim()),(v=a.currentRoute)!=null&&v.trim()&&(c.current_route=a.currentRoute.trim()),(S=a.conversationHistory)!=null&&S.length&&(c.conversation_history=a.conversationHistory.map(Q=>({role:Q.role,content:Q.content.trim()}))),(I=a.conversationSummary)!=null&&I.trim()&&(c.conversation_summary=a.conversationSummary.trim()),(E=a.llmModel)!=null&&E.trim()&&(c.llm_model=a.llmModel.trim()),(g=a.sessionId)!=null&&g.trim()&&(c.session_id=a.sessionId.trim()),(C=a.platformCapabilities)!=null&&C.credentialAutofill&&(c.platform_capabilities={credential_autofill:!0}),a.sessionContext&&(c.session_context={authenticated:a.sessionContext.authenticated,...a.sessionContext.capabilities?{capabilities:a.sessionContext.capabilities}:{}}),a.isContinuation&&(c.is_continuation=!0,typeof a.chainStep=="number"&&(c.chain_step=a.chainStep),a.lastStep&&(c.last_step={type:a.lastStep.type,intent:a.lastStep.intent,...a.lastStep.label?{label:a.lastStep.label}:{},success:a.lastStep.success,...a.lastStep.data?{data:a.lastStep.data}:{}}));let u=await In(`${t}/assistant/chat`,{method:"POST",headers:i(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await ui(u);let p;try{p=await u.json()}catch{throw new V("invalid_response")}let f=typeof p.task_status=="string"?p.task_status:"",m=f==="in_progress"||f==="blocked"?f:"complete";return{reply:((A=p.reply)!=null?A:"").trim(),audioBase64:(N=p.audio_base64)!=null?N:null,action:kt(p.action),wasTruncated:p.was_truncated===!0,taskStatus:m}},async previewTts(a,l){var c;try{let u=await In(`${t}/assistant/preview-tts`,{method:"POST",headers:i(),body:JSON.stringify({voice:a,text:l})},o);if(!u.ok)return null;let p=await u.json();return(c=p.audio_base64)!=null&&c.length?p.audio_base64:null}catch{return null}},async warmUp(){try{await In(`${t}/health`,{method:"GET",headers:i()},5e3)}catch{}},async fetchPublishedConfig(){let a=await In(`${t}/v1/client/config`,{method:"GET",headers:i()},8e3);if(!a.ok)throw await ui(a);return await a.json()}}}function bo(e,t){let n=zt(e,t);return{manifestVersion:n.version,manifestRoutes:_t(n),manifestActions:Pt(n),appName:n.appName,appDescription:n.appDescription,...n.appType?{appType:n.appType}:{},...n.appFlow?{appFlow:n.appFlow}:{}}}function Ia(e){var o,i;let t=(o=e.intentDetected)!=null?o:null,n=(i=e.sessionId)!=null?i:null;switch(e.eventType){case"agent_session_started":return[{type:"session",session_id:n}];case"action_executed":{let r=[{type:"action",intent:t,session_id:n}];return e.actionExecuted!=null&&e.actionExecuted.confirmed===!0&&r.push({type:"confirmation_completed",intent:t,session_id:n}),r}case"action_confirmation_requested":return[{type:"confirmation_requested",intent:t,session_id:n}];default:return[]}}function pi(e){var c,u;let t=e.baseUrl.replace(/\/$/,""),n=(c=e.flushIntervalMs)!=null?c:4e3,o=(u=e.maxBatch)!=null?u:20,i=[],r=null;function s(){var f,m;let p=(f=e.getUserId)==null?void 0:f.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...p?{"x-user-id":p}:{},...(m=e.headers)!=null?m:{}}}function a(){if(r&&(clearTimeout(r),r=null),i.length===0)return;let p=i;i=[],(async()=>{try{await fetch(`${t}/v1/agent/events`,{method:"POST",headers:s(),body:JSON.stringify({events:p})})}catch{}})()}function l(){r||(r=setTimeout(a,n))}return{logEvent(p){let f=Ia(p);if(f.length!==0){for(let m of f)i.push(m);i.length>=o?a():l()}}}}var Oa="BACK";function ka(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function fi(e){let t=null,n=!1;return{navigate(o){if(!o||o===Oa){this.back();return}n=!0,e.navigate(o)},back(){var o;if(e.back){e.back();return}if(n&&typeof window!="undefined"&&((o=window.history)==null?void 0:o.length)>1){window.history.back();return}e.backFallbackRoute&&e.navigate(e.backFallbackRoute)},getCurrentRoute(){return t!=null?t:e.getCurrentRoute?e.getCurrentRoute():ka()},setCurrentRoute(o){t=o}}}function _a(e){if(e)return e;try{if(typeof window!="undefined"&&window.localStorage){let n="__fyodos_probe__";return window.localStorage.setItem(n,"1"),window.localStorage.removeItem(n),window.localStorage}}catch{}let t=new Map;return{getItem:n=>t.has(n)?t.get(n):null,setItem:(n,o)=>{t.set(n,o)},removeItem:n=>{t.delete(n)}}}function hi(e={}){let t=_a(e.backend);return{async getItem(n){try{return t.getItem(n)}catch{return null}},async setItem(n,o){try{t.setItem(n,o)}catch{}},async removeItem(n){try{t.removeItem(n)}catch{}}}}function Pa(e){let t=e.getVoices();return t.length?Promise.resolve(t):new Promise(n=>{let o=!1,i=()=>{o||(o=!0,n(e.getVoices()))};try{e.addEventListener("voiceschanged",i,{once:!0})}catch{}setTimeout(i,600)})}function Ma(e,t){var i,r,s,a,l;if(!e.length)return;let n=t.toLowerCase(),o=(i=n.split("-")[0])!=null?i:n;return(l=(a=(s=(r=e.find(c=>{var u;return((u=c.lang)==null?void 0:u.toLowerCase())===n}))!=null?r:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(`${o}-`)}))!=null?s:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(o)}))!=null?a:e.find(c=>c.default))!=null?l:e[0]}function mi(){var t,n;if(typeof window=="undefined")return null;let e=window;return(n=(t=e.SpeechRecognition)!=null?t:e.webkitSpeechRecognition)!=null?n:null}function gi(){if(typeof navigator=="undefined")return!1;let e=navigator.userAgent||"",t=/iPad|iPhone|iPod/.test(e),n=/Macintosh/.test(e)&&typeof document!="undefined"&&"ontouchend"in document;return t||n}function bi(e={}){let t=mi(),n=null,o="",i=null,r=!1,s=!1,a=null,l=null,c=null,u=!1,p=!1,f=[],m="",h=null,x=null;function T(){x&&(clearTimeout(x),x=null)}function v(){if(T(),c){c.onresult=null,c.onerror=null,c.onend=null,c.onstart=null;try{c.abort()}catch{}}c=null}function S(){T(),!(!u||p)&&(x=setTimeout(()=>{x=null,u&&!p&&I()},600))}function I(){let O=mi();if(!O||!u||p)return;if(typeof document!="undefined"&&document.hidden){S();return}let b=new O;c=b,b.lang=m,b.continuous=!0,b.interimResults=!0,b.maxAlternatives=1,b.onresult=R=>{var F;if(!u||p)return;let $="";for(let P=0;P<R.results.length;P+=1){let J=R.results[P];if(!J)continue;let X=J[0];$=`${$} ${(F=X==null?void 0:X.transcript)!=null?F:""}`.trim()}let L=Qt($,f);if(!L.matched)return;p=!0;let j=h;v(),j==null||j.onDetected(L.command)},b.onerror=R=>{var $;R.error==="aborted"||R.error==="no-speech"||!u||p||($=h==null?void 0:h.onError)==null||$.call(h,new Error(R.error||"wake recognition error"))},b.onend=()=>{!u||p||S()};try{b.start()}catch{S()}}let E=null,g=null;function C(){var b,R;if(typeof window=="undefined")return null;let O=window;return(R=(b=O.AudioContext)!=null?b:O.webkitAudioContext)!=null?R:null}function A(){if(E)return E;let O=C();if(!O)return null;try{E=new O}catch{E=null}return E}function N(O){let b=atob(O),R=b.length,$=new Uint8Array(R);for(let L=0;L<R;L+=1)$[L]=b.charCodeAt(L);return $.buffer}function Q(){if(g){try{g.onended=null,g.stop()}catch{}g=null}}async function B(O){let b=A();if(!b)return!1;try{b.state==="suspended"&&await b.resume();let R=await b.decodeAudioData(N(O));return await new Promise($=>{Q();let L=b.createBufferSource();g=L,L.buffer=R,L.connect(b.destination),L.onended=()=>{L.onended=null,g===L&&(g=null),$(!0)},L.start()})}catch{return!1}}function Y(){i&&(clearTimeout(i),i=null)}function oe(){Y(),n&&(n.onresult=null,n.onerror=null,n.onend=null,n.onstart=null),n=null}return{isRecognitionAvailable(){return t!=null},async startListening(O,b){var $,L,j;if(!t){($=b.onError)==null||$.call(b,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,h=null,v()),n){r=!0;try{n.abort()}catch{}oe()}o="",r=!1,s=!1;let R=new t;n=R,R.lang=O.locale,R.continuous=(L=O.continuous)!=null?L:!0,R.interimResults=!0,R.maxAlternatives=1,R.onresult=F=>{var X,me;let P="";for(let de=F.resultIndex;de<F.results.length;de+=1){let ge=F.results[de];if(!ge)continue;let Z=ge[0],Ae=(X=Z==null?void 0:Z.transcript)!=null?X:"";ge.isFinal?o=`${o} ${Ae}`.trim():P=`${P} ${Ae}`.trim()}let J=`${o} ${P}`.trim();J&&((me=b.onInterim)==null||me.call(b,J))},R.onerror=F=>{var P;F.error==="aborted"||r||F.error!=="no-speech"&&(s=!0,(P=b.onError)==null||P.call(b,new Error(F.error||"speech recognition error")))},R.onend=()=>{var J,X,me,de;Y();let F=r,P=o.trim();if(oe(),s){(J=b.onEnd)==null||J.call(b);return}if(F){(X=b.onEnd)==null||X.call(b);return}P?(me=b.onFinal)==null||me.call(b,P):(de=b.onEnd)==null||de.call(b)};try{R.start()}catch(F){oe(),(j=b.onError)==null||j.call(b,F);return}O.maxSeconds&&O.maxSeconds>0&&(i=setTimeout(()=>{try{R.stop()}catch{}},O.maxSeconds*1e3))},stopListening(){if(Y(),n)try{n.stop()}catch{}},cancelListening(){if(Y(),r=!0,n)try{n.abort()}catch{}},primePlayback(){let O=A();if(O)try{O.state==="suspended"&&O.resume();let b=O.createBuffer(1,1,O.sampleRate),R=O.createBufferSource();R.buffer=b,R.connect(O.destination),R.start(0)}catch{}if(!e.disableDeviceTtsFallback&&typeof window!="undefined"&&window.speechSynthesis)try{let b=window.speechSynthesis;b.getVoices(),b.paused&&b.resume();let R=new SpeechSynthesisUtterance(" ");R.volume=0,b.speak(R)}catch{}},async playAudioBase64Mp3(O){if(typeof window!="undefined"&&(this.stopPlayback(),!await B(O)&&typeof Audio!="undefined"))return new Promise(b=>{try{let R=new Audio(`data:audio/mp3;base64,${O}`);a=R;let $=()=>{R.onended=null,R.onerror=null,a===R&&(a=null),b()};R.onended=$,R.onerror=$,R.play().catch(()=>$())}catch{b()}})},async speakWithDeviceTts(O,b){if(e.disableDeviceTtsFallback||typeof window=="undefined"||!window.speechSynthesis)return;let R=window.speechSynthesis,$=await Pa(R);return new Promise(L=>{let j=null,F=()=>{j&&(clearInterval(j),j=null)};try{R.cancel();let P=new SpeechSynthesisUtterance(O);P.lang=b.locale;let J=Ma($,b.locale);J&&(P.voice=J),P.volume=1,P.rate=1,P.pitch=1,l=P;let X=()=>{F(),P.onstart=null,P.onend=null,P.onerror=null,l===P&&(l=null),L()};P.onend=X,P.onerror=X,R.speak(P),R.resume(),j=setInterval(()=>{if(!R.speaking&&!R.pending){F();return}R.pause(),R.resume()},9e3)}catch{F(),L()}})},stopPlayback(){if(Q(),a){try{a.pause()}catch{}a=null}if(typeof window!="undefined"&&window.speechSynthesis)try{window.speechSynthesis.cancel()}catch{}},supportsWakeWordDetection(){return t!=null&&!gi()},isWakeWordListening(){return u},async startWakeWordDetection(O,b){var R;if(!t||gi()){(R=b.onError)==null||R.call(b,new Error("wake_word_unsupported"));return}f=O.phrases,m=O.locale,h=b,u=!0,p=!1,I()},stopWakeWordDetection(){u=!1,p=!1,h=null,v()}}}function yi(){if(typeof navigator=="undefined")return null;let e=navigator;return e.credentials&&typeof e.credentials.get=="function"?e.credentials:null}function xi(){if(typeof window=="undefined")return!1;let e=window;return typeof e.PasswordCredential=="function"&&e.isSecureContext!==!1}function vi(){return{isSupported(){return yi()!==null&&xi()},async requestCredentials(){let e=yi();if(!e||!xi())return{status:"unavailable"};let t;try{t=await e.get({password:!0,mediation:"required"})}catch{return{status:"unavailable"}}let n=t;return n?n.type==="password"&&n.id&&typeof n.password=="string"&&n.password?{status:"success",username:n.id,password:n.password}:{status:"unavailable"}:{status:"dismissed"}}}}function yo(e,t){let n=t.startsWith("es");if(e instanceof V){switch(e.code){case"timeout":return n?"La respuesta tard\xF3 demasiado. Comprueba tu conexi\xF3n e int\xE9ntalo de nuevo.":"The response took too long. Check your connection and try again.";case"network":return n?"No pude conectar con el servidor de Fiodos. \xBFEst\xE1 el backend en marcha y la URL correcta?":"Could not reach the Fiodos server. Is the backend running and the URL correct?";case"unauthorized":return n?"La API key fue rechazada. Comprueba que coincide con la del proyecto en el dashboard.":"The API key was rejected. Check it matches the project key in your dashboard.";case"quota_exceeded":return n?"Has alcanzado el l\xEDmite de uso de IA de tu plan. Mej\xF3ralo en el dashboard para seguir.":"You reached your plan\u2019s AI usage limit. Upgrade in the dashboard to continue.";case"rate_limited":return n?"Demasiadas peticiones seguidas. Espera un momento e int\xE9ntalo de nuevo.":"Too many requests. Wait a moment and try again.";case"server_error":return n?"El servidor no pudo responder. Revisa que la IA est\xE9 configurada en el backend.":"The server could not respond. Check that the AI is configured on the backend.";case"cancelled":return n?"Cancelado.":"Cancelled.";default:break}if(e.message&&e.message!==e.code)return e.message}return e instanceof Error&&e.message?e.message:n?"No pude responder. Int\xE9ntalo de nuevo.":"I could not reply. Please try again."}function On(e){let t=null;return{set(n,o){t={ownerId:n,snapshot:o}},clear(n){(t==null?void 0:t.ownerId)===n&&(t=null)},getText(){var i,r,s;let n=(i=t==null?void 0:t.snapshot.text)==null?void 0:i.trim();return n||((s=(r=e.routeFallback)==null?void 0:r.call(e,e.getCurrentRoute()))==null?void 0:s.trim())||null},getSnapshot(){var n;return(n=t==null?void 0:t.snapshot)!=null?n:null}}}function Ci(e){let{adapter:t,locale:n,maxSeconds:o}=e,i={state:"idle",interimText:"",volumeLevel:0},r=new Set;function s(l){i={...i,...l};for(let c of r)c(i)}function a(){s({state:"idle",interimText:"",volumeLevel:0})}return{getSnapshot(){return i},subscribe(l){return r.add(l),()=>r.delete(l)},async start(){i.state==="idle"&&(s({state:"recording",interimText:"",volumeLevel:.85}),await t.startListening({locale:n,continuous:!0,maxSeconds:o},{onInterim:l=>s({interimText:l}),onFinal:l=>{a(),l.trim()&&e.onTranscript(l)},onEnd:()=>{i.state!=="idle"&&a()},onError:l=>{var c;a(),(c=e.onError)==null||c.call(e,l)}}))},stop(){i.state==="recording"&&(s({state:"transcribing",volumeLevel:0}),t.stopListening())},cancel(){t.cancelListening(),a()},dispose(){t.cancelListening(),r.clear()}}}function La(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function Ai(e){var a,l,c,u,p,f,m;let{action:t,manifest:n,executor:o,context:i,messages:r,userMessage:s}=e;if(!t||t.type==="none")return{kind:"noop"};if(t.type==="navigate")return{kind:"executed",result:await o.execute(t)};if(t.type==="execute"){let h=La(n,t.intent);if(!((h==null?void 0:h.requireConfirmation)===!0))return{kind:"executed",result:await o.execute(t,i)};let T=await o.precheck(t,i);if(T.kind==="done")return{kind:"precheck-resolved",result:T.result};let v=(a=h==null?void 0:h.voiceConfirmation)!=null?a:"standard",S=v==="strict"?(u=h==null?void 0:h.confirmationPhrase)!=null?u:ee(r.strictConfirmationPhraseTemplate,{label:((c=(l=h==null?void 0:h.label)!=null?l:t.intent)!=null?c:"").toLowerCase()}):null;return{kind:"needs-confirmation",pending:{action:t,context:i,question:(f=(p=h==null?void 0:h.confirmationMessageTemplate)!=null?p:t.confirmationMessage)!=null?f:r.confirmationFallbackQuestion,voiceMode:v,strictPhrase:S,remainingConfirmations:(h==null?void 0:h.doubleConfirmation)===!0?2:1,userMessage:s,intent:(m=t.intent)!=null?m:""}}}return{kind:"noop"}}function Si(e,t,n,o={}){if(t.voiceMode==="disabled"||o.silent)return"ambiguous";let i=e.trim();return i.length<2?"ambiguous":t.voiceMode==="strict"&&t.strictPhrase!=null?on(i,t.strictPhrase,n):nn(i,n)}var wi={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},Ti={enabled:!1,maxSteps:6,dwellMs:450};var Ri={orbLabel:"Voice assistant",confirmTitle:"Confirm",confirmLabel:"Confirm",cancelLabel:"Cancel",consentTitle:"Voice assistant",consentBody:"This assistant uses your microphone to understand voice commands and may navigate or perform actions in this app on your behalf. Your speech is processed to answer you and is not stored as a transcript.",consentAccept:"Allow",consentDecline:"Not now",textPlaceholder:"Type a message\u2026",keyboardChipLabel:"Type instead of talking",sendLabel:"Send",micLabel:"Dictate message",micStopLabel:"Stop dictating",voiceUnavailable:"Voice input is not available in this browser. You can type instead.",activityThinking:"Thinking\u2026",activityNavigating:"Navigating to {label}\u2026",activityExecuting:"Running {label}\u2026",activityWaitingConfirmation:"Waiting for your confirmation\u2026"},Ba={orbLabel:"Asistente de voz",confirmTitle:"Confirmar",confirmLabel:"Confirmar",cancelLabel:"Cancelar",consentTitle:"Asistente de voz",consentBody:"Este asistente usa tu micr\xF3fono para entender comandos de voz y puede navegar o realizar acciones en esta app en tu nombre. Tu voz se procesa para responderte y no se guarda como transcripci\xF3n.",consentAccept:"Permitir",consentDecline:"Ahora no",textPlaceholder:"Escribe un mensaje\u2026",keyboardChipLabel:"Escribir en lugar de hablar",sendLabel:"Enviar",micLabel:"Dictar mensaje",micStopLabel:"Detener dictado",voiceUnavailable:"La entrada por voz no est\xE1 disponible en este navegador. Puedes escribir.",activityThinking:"Pensando\u2026",activityNavigating:"Navegando a {label}\u2026",activityExecuting:"Ejecutando {label}\u2026",activityWaitingConfirmation:"Esperando tu confirmaci\xF3n\u2026"},Ei={en:Ri,es:Ba};function Na(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Ii(e,t={}){var r,s,a,l,c;let n=(r=t.catalogs)!=null?r:{},o=Na(e),i=(c=(l=(a=(s=n[e])!=null?s:Ei[e])!=null?a:n[o])!=null?l:Ei[o])!=null?c:Ri;return t.overrides?{...i,...t.overrides}:i}function $a(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Da=e=>new Promise(t=>setTimeout(t,e)),He=class{constructor(t){this.enabled=!0;this.phase="idle";this.lastExchange=null;this.pendingTurnText=null;this.confirmationMessage=null;this.confirmationVoiceHint=null;this.consentModalVisible=!1;this.sessionId=$a();this.sessionStarted=!1;this.conversation=Le();this.pending=null;this.confirmationReasked=!1;this.confirmationVoiceActive=!1;this.silentTurn=!1;this.voiceBlocked=!1;this.abort=null;this.watchdog=null;this.confirmWindow=null;this.speakTimer=null;this.serverTtsUnavailable=!1;this.pendingConsentIntent=null;this.chainState=null;this.liveActivity=null;this.chainActive=!1;this.bubbleWindowSize=ve;this.conversationRetentionMinutes=null;this.conversationScope="public";this.removeIdentityListeners=null;this.loadingOlderExchanges=!1;this.loadOlderTimer=null;this.listeners=new Set;this.unsubscribeSpeech=null;var o,i,r,s,a,l,c,u,p;he(t.manifest),this.config=t,this.messages=Nt(t.locale,{catalogs:(o=t.messages)==null?void 0:o.catalogs,overrides:(i=t.messages)==null?void 0:i.overrides}),this.ui=Ii(t.locale,t.uiMessages),this.lexicon=(r=t.confirmationLexicon)!=null?r:en(t.locale),this.sanitizer=(s=t.sanitizer)!=null?s:Yt(),this.telemetry=Jt(t.telemetry),this.consent=Xt({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?vi():t.credentialAutofill,this.executor=Ht({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...wi,...t.timings};let n={...Ti,...t.chaining};if(this.chaining={enabled:n.enabled===!0,maxSteps:Math.max(1,Math.min(6,Math.floor(n.maxSteps||6))),dwellMs:Math.max(0,Math.min(3e3,Math.floor((a=n.dwellMs)!=null?a:450)))},this.ttsLocale=(l=t.ttsLocale)!=null?l:t.sttLocale,this.notifyError=(c=t.notifyError)!=null?c:(f=>{console.error(`[fyodos] ${f}`)}),this.screenStore=On({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Ft(f,t.manifest,this.messages))}),this.speech=Ci({adapter:t.voice,locale:t.sttLocale,maxSeconds:this.timings.maxListeningSeconds,onTranscript:f=>this.onTranscript(f),onError:f=>this.onSpeechError(f)}),this.unsubscribeSpeech=this.speech.subscribe(()=>this.emit()),this.conversationIdentity=ct((p=t.getUserId)==null?void 0:p.call(t)),this.restorePersistedConversation(),typeof window!="undefined"){let f=()=>{this.syncConversationIdentity()};window.addEventListener("focus",f),document.addEventListener("visibilitychange",f),this.removeIdentityListeners=()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",f)}}}async restorePersistedConversation(){var o;let t=this.conversationIdentity,n=await sn(this.config.storage,this.config.manifest.appId,Date.now(),this.conversationScope,t);!n||this.conversationIdentity!==t||this.conversation.turns.length>0||(o=this.conversation.uiArchive)!=null&&o.length||(this.conversation.turns=n.turns,this.conversation.summary=n.summary,this.conversation.uiArchive=n.uiArchive,this.conversation.lastActivityAt=n.lastActivityAt,this.emit())}persistConversation(){rn(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=ct((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=Le(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=Le(),this.lastExchange=null,an(this.config.storage,this.config.manifest.appId,this.conversationScope,this.conversationIdentity),this.emit()}getState(){let t=this.speech.getSnapshot(),n=(this.phase==="listening"||this.phase==="confirming")&&t.state==="recording",o=this.phase==="thinking"||this.phase==="listening"&&t.state==="transcribing",i=at(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions);return{phase:this.phase,interimText:t.interimText,volumeLevel:t.volumeLevel,showWaveform:n,showThinking:o,isBusy:o||this.phase==="speaking",isListening:this.phase==="listening"&&t.state!=="idle",lastExchange:this.lastExchange,recentExchanges:i.exchanges,hasOlderExchanges:i.hasOlder,loadingOlderExchanges:this.loadingOlderExchanges,confirmationMessage:this.confirmationMessage,confirmationVoiceHint:this.confirmationVoiceHint,consentModalVisible:this.consentModalVisible,voiceBlocked:this.voiceBlocked,liveActivity:this.liveActivity,chainActive:this.chainActive}}setActivity(t){let n=this.liveActivity;n===t||n&&t&&n.kind===t.kind&&n.label===t.label||(this.liveActivity=t,this.emit())}setChainActive(t){this.chainActive!==t&&(this.chainActive=t,this.emit())}get voiceAvailable(){return this.config.voice.isRecognitionAvailable()&&!this.voiceBlocked}primeAudio(){var t,n;(n=(t=this.config.voice).primePlayback)==null||n.call(t)}markVoiceBlocked(t){this.voiceBlocked!==t&&(this.voiceBlocked=t,this.emit())}loadOlderExchanges(){this.loadingOlderExchanges||!at(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=ve,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Me(t,n),this.conversationRetentionMinutes=typeof t=="number"?t:null;let o=n?"internal":"public";o!==this.conversationScope&&(this.conversationScope=o,this.restorePersistedConversation())}resetBubbleWindow(){this.loadOlderTimer&&(clearTimeout(this.loadOlderTimer),this.loadOlderTimer=null),this.loadingOlderExchanges=!1,this.bubbleWindowSize=ve}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(){let t=this.getState();for(let n of this.listeners)n(t)}setEnabled(t){this.enabled=t,t||this.cancelAll()}getTtsVoice(){return typeof this.config.ttsVoice=="function"?this.config.ttsVoice():this.config.ttsVoice}setPhase(t){var o,i;let n=this.phase;n!==t&&(this.phase=t,(i=(o=this.config).onPhaseChange)==null||i.call(o,t,n),this.emit())}clearWatchdog(){this.watchdog&&(clearTimeout(this.watchdog),this.watchdog=null)}clearConfirmWindow(){this.confirmWindow&&(clearTimeout(this.confirmWindow),this.confirmWindow=null),this.confirmationVoiceActive=!1}clearSpeakTimer(){this.speakTimer&&(clearTimeout(this.speakTimer),this.speakTimer=null)}async speakReply(t,n){var o;if(!this.silentTurn&&!(!t&&!n)){this.setPhase("speaking");try{let i=n;if(i&&(this.serverTtsUnavailable=!1),!i&&t&&!this.serverTtsUnavailable)try{i=await this.config.backend.previewTts((o=this.getTtsVoice())!=null?o:"",t),i||(this.serverTtsUnavailable=!0)}catch{i=null,this.serverTtsUnavailable=!0}let r=i?this.config.voice.playAudioBase64Mp3(i):t?this.config.voice.speakWithDeviceTts(t,{locale:this.ttsLocale}):Promise.resolve();await this.raceSpeakingWatchdog(r,t)}catch{}finally{this.clearSpeakTimer(),this.phase==="speaking"&&this.setPhase("idle")}}}raceSpeakingWatchdog(t,n){let o=Math.min(6e4,5e3+n.length*90);return new Promise(i=>{let r=!1,s=()=>{r||(r=!0,this.clearSpeakTimer(),i())};this.clearSpeakTimer(),this.speakTimer=setTimeout(()=>{this.config.voice.stopPlayback(),s()},o),t.then(s,s)})}beginConfirmationVoiceWindow(){let t=this.pending;!t||t.silent||t.voiceMode==="disabled"||this.config.voice.isRecognitionAvailable()&&(this.clearConfirmWindow(),this.setPhase("confirming"),this.confirmationVoiceActive=!0,this.speech.start(),this.confirmWindow=setTimeout(()=>{this.speech.stop(),this.confirmationVoiceActive=!1},this.timings.confirmationVoiceWindowMs))}async confirmPendingAction(){var i,r;this.clearConfirmWindow();let t=this.pending;if(!t){this.confirmationMessage=null,this.confirmationVoiceHint=null,this.emit();return}if(t.remainingConfirmations>1){t.remainingConfirmations-=1,this.confirmationReasked=!1;let s=this.messages.doubleConfirmationQuestion;this.confirmationMessage=s,this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:s}),this.emit(),await this.speakReply(s,null),this.pending&&this.beginConfirmationVoiceWindow();return}this.pending=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.phase==="confirming"&&this.setPhase("idle"),this.emit(),this.setActivity({kind:"executing",label:(i=this.actionLabel(t.intent))!=null?i:t.intent});let n=await this.executor.execute(t.action,t.context);this.telemetry.logEvent({eventType:n.success?"action_executed":"action_failed",intentDetected:t.intent,sessionId:this.sessionId,actionExecuted:{intent:t.intent,confirmed:!0}}),n.message&&(this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:n.message}),this.emit(),await this.speakReply(n.message,null));let o=this.chainState;o&&(this.chainState=null,n.success&&this.chaining.enabled?(this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:t.intent,sessionId:this.sessionId,chainStep:o.step}),o.pendingKey&&o.visitedKeys.add(o.pendingKey),await this.runChainLoop({userMessage:o.userMessage,step:o.step,lastStep:(r=o.pendingStep)!=null?r:o.lastStep,visitedKeys:o.visitedKeys})):n.success||this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainAbortReason:"error"})),this.pending||this.setActivity(null)}cancelPendingAction(){this.clearConfirmWindow();let t=this.pending;this.pending=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.setActivity(null),this.phase==="confirming"&&this.setPhase("idle"),this.emit();let n=this.chainState;this.chainState=null,n&&this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainAbortReason:"user_interrupt"}),t&&(this.telemetry.logEvent({eventType:"action_cancelled",intentDetected:t.intent,sessionId:this.sessionId}),this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:this.messages.cancelled}),this.emit(),this.speakReply(this.messages.cancelled,null))}async handleConfirmationTranscript(t){this.confirmationVoiceActive=!1,this.clearConfirmWindow();let n=this.pending;if(this.phase==="confirming"&&this.setPhase("idle"),!n||n.voiceMode==="disabled"||n.silent)return;let o=Si(t,n,this.lexicon,{silent:n.silent});if(o==="affirmative"){await this.confirmPendingAction();return}if(o==="negative"){this.cancelPendingAction();return}if(!this.confirmationReasked){this.confirmationReasked=!0;let i=`${this.messages.confirmationNotUnderstood} ${n.question}`.trim();this.confirmationMessage=i,this.emit(),await this.speakReply(i,null),this.pending&&this.beginConfirmationVoiceWindow()}}platformCapabilities(){var n;let t=!1;try{t=((n=this.credentialAutofill)==null?void 0:n.isSupported())===!0}catch{t=!1}return t?{credentialAutofill:!0}:void 0}sessionContext(){let{isAuthenticated:t,getSessionCapabilities:n}=this.config;if(!t&&!n)return;let o=null;try{let r=t==null?void 0:t();o=r==null?null:!!r}catch{o=null}let i;try{let r=n==null?void 0:n();if(r&&typeof r=="object"){let s={};for(let[a,l]of Object.entries(r))typeof l=="boolean"&&(s[a]=l);Object.keys(s).length>0&&(i=s)}}catch{i=void 0}return{authenticated:o,...i?{capabilities:i}:{}}}routeLabel(t){var n;return(n=this.config.manifest.routes.find(o=>o.intent===t))==null?void 0:n.label}actionLabel(t){var n;return(n=this.config.manifest.actions.find(o=>o.intent===t))==null?void 0:n.label}async applyOutcome(t,n,o,i){var x,T,v,S,I,E,g,C,A,N,Q;let r=t.reply,s=t.audioBase64;r&&(this.serverTtsUnavailable=!s);let a=await Ai({action:t.action,manifest:this.config.manifest,executor:this.executor,context:o,messages:this.messages,userMessage:i}),l=!1,c,u,p=!1,f=!1,m,h;if(a.kind==="executed"){let B=a.result;if(B.success&&((x=t.action)==null?void 0:x.type)==="navigate"?this.setActivity({kind:"navigating",label:(S=(v=this.routeLabel((T=t.action.intent)!=null?T:""))!=null?v:t.action.intent)!=null?S:""}):B.success&&!B.recoverable&&((I=t.action)==null?void 0:I.type)==="execute"&&this.setActivity({kind:"executing",label:(C=(g=this.actionLabel((E=t.action.intent)!=null?E:""))!=null?g:t.action.intent)!=null?C:""}),((A=t.action)==null?void 0:A.type)==="navigate"?this.telemetry.logEvent({eventType:B.success?"navigation_executed":"navigation_failed",intentDetected:t.action.intent,sessionId:this.sessionId,currentRoute:n!=null?n:void 0}):((N=t.action)==null?void 0:N.type)==="execute"&&this.telemetry.logEvent({eventType:B.recoverable?"action_needs_context":B.success?"action_executed":"action_failed",intentDetected:t.action.intent,sessionId:this.sessionId,actionExecuted:{intent:t.action.intent,confirmed:!1}}),B.recoverable||(B.message?(r=B.message,s=null):B.success||(r=this.messages.actionFailed,s=null)),t.action&&(t.action.type==="navigate"||t.action.type==="execute")&&B.success&&!B.recoverable){let Y=(Q=t.action.intent)!=null?Q:"",oe=Gt(B.data);c={type:t.action.type,intent:Y,label:t.action.type==="navigate"?this.routeLabel(Y):this.actionLabel(Y),success:!0,...oe?{data:oe}:{}},u=`${t.action.type}:${Y}`,l=t.taskStatus==="in_progress"}}else if(a.kind==="precheck-resolved")a.result.message&&!a.result.recoverable&&(r=a.result.message,s=null);else if(a.kind==="needs-confirmation"){this.pending={...a.pending,silent:this.silentTurn},this.confirmationReasked=!1,this.confirmationMessage=a.pending.question,this.confirmationVoiceHint=a.pending.voiceMode==="strict"&&a.pending.strictPhrase&&!this.silentTurn?ee(this.messages.strictConfirmationModalHint,{phrase:a.pending.strictPhrase}):null,this.emit(),this.telemetry.logEvent({eventType:"action_confirmation_requested",intentDetected:a.pending.intent,sessionId:this.sessionId}),this.setActivity({kind:"waiting_confirmation"}),p=!0,f=t.taskStatus==="in_progress";let B=a.pending.intent||"";m={type:"execute",intent:B,label:this.actionLabel(B),success:!0},h=`execute:${B}`}return{reply:r,audioBase64:s,hasPending:p,canContinue:l,lastStep:c,actionKey:u,pendingInProgress:f,pendingStep:m,pendingKey:h}}async runChainLoop(t){var r,s,a,l,c,u,p,f,m,h,x;let n=t.step,o=t.lastStep,i=t.visitedKeys;this.setChainActive(!0);try{for(;n<this.chaining.maxSteps;){if(n+=1,this.chaining.dwellMs>0&&await Da(this.chaining.dwellMs),this.pending!=null)return;let T=this.config.navigation.getCurrentRoute(),v=this.screenStore.getSnapshot(),S=nt((a=(s=(r=this.config).getUserContextText)==null?void 0:s.call(r))!=null?a:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),I=S?this.sanitizer(S).sanitized:void 0,E=rt(this.conversation,Date.now(),this.conversationOptions);this.setPhase("thinking"),this.setActivity({kind:"thinking"});let g=new AbortController;this.abort=g;let C;try{let A=await this.config.backend.sendTurn({message:t.userMessage,language:this.config.locale,voice:this.getTtsVoice(),screenContext:I,currentRoute:T!=null?T:void 0,conversationHistory:E.history,conversationSummary:(l=E.summary)!=null?l:void 0,sessionId:this.sessionId,isContinuation:!0,chainStep:n,lastStep:o,platformCapabilities:this.platformCapabilities(),sessionContext:this.sessionContext(),...bo(this.config.manifest,this.config.registries)},{signal:g.signal});C=await this.applyOutcome(A,T,(c=v==null?void 0:v.context)!=null?c:{},t.userMessage)}catch(A){this.abort=null;let N=A instanceof V&&A.code==="cancelled";if(N)this.phase==="thinking"&&this.setPhase("idle");else{A instanceof V&&A.code==="quota_exceeded"&&((p=(u=this.config).onQuotaExceeded)==null||p.call(u));let Q=yo(A,this.config.locale);this.lastExchange={userText:t.userMessage,replyText:Q},this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(Q)}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:N?"user_interrupt":"error"});return}if(this.abort=null,C.reply&&(this.lastExchange={userText:t.userMessage,replyText:C.reply},this.emit(),st(this.conversation,t.userMessage,C.reply,Date.now(),this.conversationOptions),this.persistConversation()),await this.speakReply(C.reply,C.audioBase64),this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:(x=(h=(f=C.lastStep)==null?void 0:f.intent)!=null?h:(m=C.pendingStep)==null?void 0:m.intent)!=null?x:null,sessionId:this.sessionId,chainStep:n}),C.hasPending){this.chainState=C.pendingInProgress?{userMessage:t.userMessage,step:n,lastStep:o,visitedKeys:i,pendingKey:C.pendingKey,pendingStep:C.pendingStep}:null,this.beginConfirmationVoiceWindow();return}if(this.phase!=="speaking"&&this.setPhase("idle"),C.actionKey&&i.has(C.actionKey)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(C.actionKey&&i.add(C.actionKey),!C.canContinue){this.telemetry.logEvent({eventType:"agent_chain_completed",sessionId:this.sessionId,chainStep:n});return}o=C.lastStep}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"max_steps"})}finally{this.setChainActive(!1)}}async handleTranscript(t){var f,m,h,x,T,v,S,I,E;let n=t.trim();if(!this.enabled||n.length<this.timings.minTranscriptChars){this.phase==="thinking"&&this.setPhase("idle");return}this.syncConversationIdentity(),this.setPhase("thinking"),this.setActivity({kind:"thinking"}),this.pendingTurnText=n,this.lastExchange={userText:n,replyText:""},this.emit(),this.clearWatchdog(),this.watchdog=setTimeout(()=>{var g;if(this.phase==="thinking"){this.telemetry.logEvent({eventType:"agent_watchdog_reset",sessionId:this.sessionId});let C=(g=this.pendingTurnText)!=null?g:n,A=this.config.locale.startsWith("es")?"La respuesta tard\xF3 demasiado. Int\xE9ntalo de nuevo.":"The response took too long. Please try again.";this.lastExchange={userText:C,replyText:A},this.pendingTurnText=null,this.setActivity(null),this.setPhase("idle"),this.emit()}},this.timings.thinkingWatchdogMs);let o=this.config.navigation.getCurrentRoute();this.sessionStarted||(this.sessionStarted=!0,this.telemetry.logEvent({eventType:"agent_session_started",sessionId:this.sessionId})),this.telemetry.logEvent({eventType:"agent_invoked",sessionId:this.sessionId,currentRoute:o});let i=this.screenStore.getSnapshot(),r=nt((h=(m=(f=this.config).getUserContextText)==null?void 0:m.call(f))!=null?h:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),s=r?this.sanitizer(r).sanitized:void 0,a=rt(this.conversation,Date.now(),this.conversationOptions),l=new AbortController;this.abort=l;let c=null;try{let g=await this.config.backend.sendTurn({message:n,language:this.config.locale,voice:this.getTtsVoice(),screenContext:s,currentRoute:o!=null?o:void 0,conversationHistory:a.history,conversationSummary:(x=a.summary)!=null?x:void 0,sessionId:this.sessionId,platformCapabilities:this.platformCapabilities(),sessionContext:this.sessionContext(),...bo(this.config.manifest,this.config.registries)},{signal:l.signal});c=await this.applyOutcome(g,o,(T=i==null?void 0:i.context)!=null?T:{},n)}catch(g){if(this.clearWatchdog(),this.abort=null,this.setActivity(null),g instanceof V&&g.code==="cancelled"){this.phase==="thinking"&&this.setPhase("idle"),this.pendingTurnText=null;return}g instanceof V&&g.code==="quota_exceeded"&&((S=(v=this.config).onQuotaExceeded)==null||S.call(v));let C=yo(g,this.config.locale);this.lastExchange={userText:n,replyText:C},this.pendingTurnText=null,this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(C);return}if(this.clearWatchdog(),this.abort=null,this.pendingTurnText=null,!c)return;let u=c.reply;if(u)this.lastExchange={userText:n,replyText:u},this.emit(),st(this.conversation,n,u,Date.now(),this.conversationOptions),this.persistConversation();else{let g=this.config.locale.startsWith("es")?"No recib\xED respuesta del servidor. Int\xE9ntalo de nuevo.":"No reply from the server. Please try again.";this.lastExchange={userText:n,replyText:g},this.emit()}let p=c.hasPending;if(await this.speakReply(u,c.audioBase64),p?(this.beginConfirmationVoiceWindow(),this.chaining.enabled&&c.pendingInProgress&&(this.telemetry.logEvent({eventType:"agent_chain_started",sessionId:this.sessionId,chainStep:1}),this.chainState={userMessage:n,step:1,lastStep:c.pendingStep,visitedKeys:new Set,pendingKey:c.pendingKey,pendingStep:c.pendingStep})):this.phase!=="speaking"&&this.setPhase("idle"),this.chaining.enabled&&c.canContinue&&!p){this.telemetry.logEvent({eventType:"agent_chain_started",sessionId:this.sessionId,chainStep:1});let g=new Set;c.actionKey&&g.add(c.actionKey),await this.runChainLoop({userMessage:n,step:1,lastStep:c.lastStep,visitedKeys:g})}this.pending||this.setActivity(null),(E=(I=this.config).onTurnCompleted)==null||E.call(I)}onTranscript(t){if(this.confirmationVoiceActive||this.pending){this.handleConfirmationTranscript(t);return}this.handleTranscript(t)}onSpeechError(t){this.telemetry.logEvent({eventType:"agent_stt_failed",sessionId:this.sessionId}),(this.phase==="listening"||this.phase==="confirming")&&this.setPhase("idle");let n=t instanceof Error?t.message:String(t),o=n.toLowerCase();if(o.includes("not-allowed")||o.includes("not allowed")||o.includes("service-not-allowed")||o.includes("audio-capture")||o.includes("permission")){this.markVoiceBlocked(!0);return}this.notifyError(n)}async beginListening(){var n,o;if(!this.enabled)return;if(!this.config.voice.isRecognitionAvailable()){this.telemetry.logEvent({eventType:"agent_stt_failed",sessionId:this.sessionId}),this.notifyError(this.ui.voiceUnavailable);return}let t=(o=(n=this.config).gateTurn)==null?void 0:o.call(n);if(t&&!t.ok){t.message&&this.notifyError(t.message);return}this.config.voice.stopPlayback(),this.silentTurn=!1,this.setPhase("listening"),await this.speech.start()}async toggleListening(){if(!this.enabled||this.phase==="confirming")return;if(this.phase==="listening"){this.speech.stop(),this.setPhase("thinking");return}if(this.phase==="speaking"){this.cancelAll();return}if(this.phase==="thinking")return;if(!await this.consent.hasConsented()){this.pendingConsentIntent="voice",this.consentModalVisible=!0,this.emit();return}await this.beginListening()}async submitTextTurn(t,n){var r,s;if(!this.enabled)return;let o=t.trim();if(!o)return;let i=(s=(r=this.config).gateTurn)==null?void 0:s.call(r);if(i&&!i.ok){i.message&&this.notifyError(i.message);return}if(this.pending&&!this.pending.silent){await this.handleConfirmationTranscript(o);return}this.silentTurn=(n==null?void 0:n.speak)!==!0,await this.handleTranscript(o)}async acceptConsent(){await this.consent.grant(),this.consentModalVisible=!1,this.emit(),this.telemetry.logEvent({eventType:"agent_consent_granted",sessionId:this.sessionId});let t=this.pendingConsentIntent;this.pendingConsentIntent=null,t==="voice"&&await this.beginListening()}declineConsent(){this.consentModalVisible=!1,this.pendingConsentIntent=null,this.emit(),this.telemetry.logEvent({eventType:"agent_consent_declined",sessionId:this.sessionId})}cancelAll(){var n;(n=this.abort)==null||n.abort(),this.abort=null,this.clearWatchdog(),this.clearConfirmWindow(),this.clearSpeakTimer(),this.speech.cancel(),this.config.voice.stopPlayback(),this.pending=null,this.chainState=null,this.confirmationMessage=null,this.confirmationVoiceHint=null,this.liveActivity=null,this.chainActive=!1;let t=this.pendingTurnText;return t&&(this.pendingTurnText=null,this.lastExchange=null),this.setPhase("idle"),this.emit(),t}warmUp(){var t,n;(n=(t=this.config.backend).warmUp)==null||n.call(t)}dispose(){var t,n;this.cancelAll(),(t=this.removeIdentityListeners)==null||t.call(this),this.removeIdentityListeners=null,this.loadOlderTimer&&(clearTimeout(this.loadOlderTimer),this.loadOlderTimer=null),(n=this.unsubscribeSpeech)==null||n.call(this),this.unsubscribeSpeech=null,this.speech.dispose(),this.listeners.clear()}};var Fa="http://www.w3.org/2000/svg",ce={accentColor:"#4f8cff",backgroundColor:"#1b2a4a",colorKey:"azul",glowIntensity:100,size:56};function ne(e,t){let n=document.createElementNS(Fa,e);for(let[o,i]of Object.entries(t))n.setAttribute(o,String(i));return n}function _i(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:i,fillRadius:r,midPx:s}=ft(e.fillDiameter,e.exteriorWidthSlider,e.interiorWidthSlider),a=typeof e.borderRadius=="number",l=a?`${r}px`:String(e.borderRadius),c=a?`${s/2}px`:String(e.borderRadius),u=a?`${i/2}px`:String(e.borderRadius),p=e.outerGlow!==!1,f=e.fillDepth!==!1,m=document.createElement("div");Object.assign(m.style,{boxSizing:"content-box",border:o>0?`${o}px solid ${e.exteriorColor}`:"",borderRadius:u,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:"0",boxShadow:p&&o>0?cn(i,e.exteriorColor):""});let h=document.createElement("div");Object.assign(h.style,{boxSizing:"content-box",border:n>0?`${n}px solid ${e.interiorColor}`:"",borderRadius:c,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});let x=document.createElement("div");return Object.assign(x.style,{width:`${t}px`,height:`${t}px`,borderRadius:l,background:e.fill,overflow:"hidden",position:"relative",flexShrink:"0",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:f&&t>0?ln(e.fillDiameter):""}),h.appendChild(x),m.appendChild(h),{root:m,fill:x}}function Wa(e,t){let{bars:n,color:o,radius:i}=dn(e,t),r=ne("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,"aria-hidden":"true"});r.style.display="block";let s=n.map(l=>{let c=ne("rect",{x:l.x,y:l.y,width:l.width,height:l.height,rx:i,ry:i,fill:o});return r.appendChild(c),c}),a=0;return{el:r,start(){let l=performance.now(),c=u=>{a=requestAnimationFrame(c);let p=(u-l)/1e3;n.forEach((f,m)=>{let h=pn(p,m,f.baseHalfHeight,f.maxHalfHeight);s[m].setAttribute("y",(f.centerY-h).toFixed(2)),s[m].setAttribute("height",(2*h).toFixed(2))})};a=requestAnimationFrame(c)},stop(){cancelAnimationFrame(a)}}}var Ua=9,Ha=[.25,.45,.65,.85,1,.85,.65,.45,.25],Oi=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],Va=26;function za(e,t){let n=t/Va,o=3*n,i=3*n,r=3*n,s=document.createElement("div");Object.assign(s.style,{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:`${i}px`,height:`${t}px`,width:"100%",maxWidth:"88%"});let a=[];for(let h=0;h<Ua;h++){let x=document.createElement("div");Object.assign(x.style,{width:`${o}px`,height:`${t}px`,borderRadius:`${Math.max(1,2*n)}px`,backgroundColor:e,transformOrigin:"center center",transform:`scaleY(${r/t})`,flexShrink:"0"}),a.push(x),s.appendChild(x)}let l=0,c=0,u=0,p=0,f=r/t,m=h=>{l=requestAnimationFrame(m),!(h-u<80)&&(u=h,c+=.22,a.forEach((x,T)=>{var S,I,E;let v;if(p<.05){let g=(Math.sin(c+((S=Oi[T])!=null?S:0))+1)/2;v=f+g*(.22-f)}else{let g=Math.sin(c*2.3+((I=Oi[T])!=null?I:0))*.18+.82+Math.random()*.18;v=f+p*((E=Ha[T])!=null?E:.5)*(1-f)*g}x.style.transform=`scaleY(${Math.min(1,Math.max(f,v))})`}))};return{el:s,start(){l||(u=typeof performance!="undefined"?performance.now():Date.now(),l=requestAnimationFrame(m))},stop(){l&&cancelAnimationFrame(l),l=0},setVolume(h){p=h}}}var ki=8,Pi=68,Ga=360-Pi,Ka=Pi/2,Ya=[.15,.25,.35,.5,.65,.78,.88,1];function ja(e,t){var a;let n=Math.max(28,e*.52),o=document.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"});let i=document.createElement("div");Object.assign(i.style,{width:`${n}px`,height:`${n}px`,animation:"fy-spin 0.92s linear infinite"}),i.setAttribute("role","progressbar"),i.setAttribute("aria-label","Loading");let r=ne("svg",{width:n,height:n,viewBox:"0 0 40 40","aria-hidden":"true"}),s=Ga/(ki-1);for(let l=0;l<ki;l++){let c=Ka+s*l;r.appendChild(ne("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(a=Ya[l])!=null?a:1,transform:`rotate(${c} 20 20)`}))}return i.appendChild(r),o.appendChild(i),o}var Xa=118/380,qa=30/380,Qa=2/380;function Ja(e,t){let n=document.createElement("div");Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"});let o=e*Xa,i=Math.max(1,e*Qa);for(let a of[0,.85]){let l=document.createElement("div");Object.assign(l.style,{position:"absolute",width:`${o}px`,height:`${o}px`,borderRadius:"50%",border:`${i}px solid ${t}`,opacity:"0.55",animation:`fy-voice 1.7s ease-out infinite ${a}s`}),n.appendChild(l)}let r=e*qa,s=document.createElement("div");return Object.assign(s.style,{width:`${r}px`,height:`${r}px`,borderRadius:"50%",background:t,opacity:"0.9",animation:"fy-opulse 1s ease-in-out infinite"}),n.appendChild(s),n}function Za(e,t,n){let o=Cn(e),i=1.8,{x:r,y:s}=An(o),a=ne("svg",{width:t,height:t,viewBox:o.viewBox,fill:"none","aria-hidden":"true"});a.style.display="block",a.style.pointerEvents="none";let l=ne("g",{transform:`translate(${r} ${s})`});if(o.keyboardFrame&&o.keyDots){let c=o.keyboardFrame;l.appendChild(ne("rect",{x:c.x,y:c.y,width:c.w,height:c.h,rx:c.rx,stroke:n,"stroke-width":i}));for(let[u,p]of o.keyDots)l.appendChild(ne("rect",{x:u-.6,y:p-.6,width:1.2,height:1.2,rx:.2,fill:n}))}else if(o.chatFrame&&o.chatLines){let c=o.chatFrame,u=c.x+c.w/2,p=c.y+c.h,f=Math.max(1.15,i*.65);if(l.appendChild(ne("rect",{x:c.x,y:c.y,width:c.w,height:c.h,rx:c.rx,stroke:n,"stroke-width":i})),o.chatTail){let m=o.chatTail;l.appendChild(ne("polygon",{points:`${m.left},${p} ${m.tipX},${m.tipY} ${m.right},${p}`,fill:n}))}for(let{y:m,w:h}of o.chatLines)l.appendChild(ne("line",{x1:u-h/2,y1:m,x2:u+h/2,y2:m,stroke:n,"stroke-width":f,"stroke-linecap":"round"}))}else for(let c of o.paths)l.appendChild(ne("path",{d:c.d,stroke:n,fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round"}));return a.appendChild(l),a}function Mi(e){var x,T,v,S,I,E,g;let{theme:t}=e,n=(x=t.size)!=null?x:30,o=(T=t.shape)!=null?T:"circle",i=o==="circle"?"50%":`${xn(o,n)}px`,r=(v=t.backgroundColor)!=null?v:e.backgroundColor,s=(S=t.borderColor)!=null?S:e.accentColor,a=vn(t.iconColor,r,e.accentColor),l=Ue(t.icon),c=yn((I=t.iconScale)!=null?I:1),u=Math.round(bn(n)*c),p=ft(n,(E=t.borderWidth)!=null?E:100,t.innerBorderWidth),f=document.createElement("button");f.type="button",f.setAttribute("aria-label",e.label),Object.assign(f.style,{border:"none",background:"transparent",padding:"0",cursor:"pointer",lineHeight:"0",flexShrink:"0",width:`${p.totalPx}px`,height:`${p.totalPx}px`,display:"flex",alignItems:"center",justifyContent:"center"}),f.onclick=e.onClick;let{root:m,fill:h}=_i({fillDiameter:n,borderRadius:i,exteriorColor:s,exteriorWidthSlider:(g=t.borderWidth)!=null?g:100,interiorColor:pt(t.innerBorderColor),interiorWidthSlider:t.innerBorderWidth,fill:r,outerGlow:!1,fillDepth:!1});if(t.iconImageDataUrl){let C=document.createElement("img");C.src=t.iconImageDataUrl,C.alt="",Object.assign(C.style,{width:`${u}px`,height:`${u}px`,objectFit:"contain",display:"block"}),h.appendChild(C)}else h.appendChild(Za(l,u,a));return f.appendChild(m),f}function Li(e){let t=document.createElement("div");t.style.display="inline-flex";let n=e,o="idle",i=0,r=null,s=null,a=null;function l(){var T,v,S,I;let u=(T=n.size)!=null?T:ce.size,p=Ct({colorKey:(v=n.colorKey)!=null?v:ce.colorKey,backgroundColor:n.backgroundColor,accentColor:n.accentColor}),f=(S=n.glowColor)!=null&&S.startsWith("#")?n.glowColor:n.accentColor,m=pt(n.innerBorderColor);s==null||s.stop(),s=null,a==null||a.stop(),a=null,t.replaceChildren();let{root:h,fill:x}=_i({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(I=n.glowIntensity)!=null?I:ce.glowIntensity,interiorColor:m,interiorWidthSlider:n.innerBorderWidth,fill:p});r=x,t.appendChild(h),c()}function c(){var f,m;if(!r)return;let u=(f=n.size)!=null?f:ce.size,p=(m=n.waveformColor)!=null?m:"#ffffff";if(s==null||s.stop(),s=null,a==null||a.stop(),a=null,r.replaceChildren(),t.style.animation="",o==="thinking"){r.appendChild(ja(u,p));return}if(o==="listening"){s=za(p,Math.round(u*.46)),s.setVolume(i),r.appendChild(s.el),s.start();return}if(n.logoDataUrl){let h=document.createElement("img");h.src=n.logoDataUrl,h.alt="",h.draggable=!1,h.addEventListener("dragstart",x=>x.preventDefault()),Object.assign(h.style,{width:"64%",height:"64%",objectFit:"contain",pointerEvents:"none",userSelect:"none",webkitUserSelect:"none",webkitUserDrag:"none",animation:o==="speaking"?"fy-opulse 1s ease-in-out infinite":""}),r.appendChild(h);return}if(o==="speaking"){r.appendChild(Ja(u,p));return}o==="idle"&&(a=Wa(u,n.waveformColor),r.appendChild(a.el),a.start())}return l(),{element:t,applyAppearance(u){n=u,l()},applyState(u,p){i=p,u!==o?(o=u,c()):o==="listening"&&(s==null||s.setVolume(i))}}}var xo="fyodos:published-config:v1";function ec(){try{if(typeof window=="undefined"||!window.localStorage)return null;let e=window.localStorage.getItem(xo);return e?JSON.parse(e):null}catch{return null}}function Bi(e){try{if(typeof window=="undefined"||!window.localStorage)return;e?window.localStorage.setItem(xo,JSON.stringify(e)):window.localStorage.removeItem(xo)}catch{}}function Ni(e,t){var r,s,a,l;let n=t.orbEnabled!==!1,o=e.theme;return{appearance:{accentColor:(r=o.accentColor)!=null?r:ce.accentColor,backgroundColor:(s=o.backgroundColor)!=null?s:ce.backgroundColor,glowColor:o.glowColor,colorKey:o.colorKey,glowIntensity:o.glowIntensity,hapticIntensity:o.hapticIntensity,innerBorderColor:o.innerBorderColor,innerBorderWidth:o.innerBorderWidth,size:(a=o.size)!=null?a:ce.size,waveformColor:o.waveformColor,logoDataUrl:e.logoDataUrl},keyboardChip:(l=o.keyboardChip)!=null?l:null,modalTheme:e.modalTheme,screenPosition:e.screenPosition,bubbleTheme:We(t.bubbleTheme),bubbleEnabled:t.bubbleEnabled!==!1,voiceInputEnabled:t.voiceInputEnabled!==!1,thinkingStepsEnabled:t.agentThinkingStepsEnabled===!0,enabled:n,conversationRetentionMinutes:typeof t.conversationRetentionMinutes=="number"?t.conversationRetentionMinutes:null,internalProfile:t.orbProfile==="internal"}}function $i(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,i=ec();i&&t.onChange(Ni(At(i),i));let r=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange(Ni(At(c.published),c.published)),Bi(c.published)):(t.onChange(null),Bi(null))}catch{}};r();let s=(l=t.pollMs)!=null?l:12e3,a=s>0?setInterval(()=>{r()},s):null;return()=>{o=!0,a&&clearInterval(a)}}function tc(){var t,n;if(typeof window=="undefined")return null;let e=window;return(n=(t=e.SpeechRecognition)!=null?t:e.webkitSpeechRecognition)!=null?n:null}function nc(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function St(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Di(e){let t=tc(),n=null,o=!1,i="",r=()=>{n==null||n.stop()};return{isSupported:()=>t!=null,isListening:()=>o,stop:r,dispose:()=>{r(),n=null,o=!1},toggle(a,l){if(!t)return;if(o){r();return}i=a();let c=new t;c.lang=nc(e),c.interimResults=!0,c.continuous=!0;let u="";c.onresult=p=>{var x,T;let f="";for(let v=p.resultIndex;v<p.results.length;v+=1){let S=p.results[v];if(!S)continue;let I=(T=(x=S[0])==null?void 0:x.transcript)!=null?T:"";S.isFinal?u+=I:f+=I}let m=`${u}${f}`.trimStart(),h=i?`${i}${i.endsWith(" ")?"":" "}${m}`:m;l(h)},c.onend=()=>{o=!1,n=null},c.onerror=()=>{o=!1,n=null},n=c,o=!0,c.start()}}}var Fi="fyodos-orb-styles",oc=`
4
4
  .fyodos-orb-root{position:fixed;display:inline-flex;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;touch-action:none;}
5
5
  .fyodos-orb-btn{appearance:none;border:none;background:transparent;padding:0;cursor:pointer;line-height:0;display:inline-flex;touch-action:none;user-select:none;-webkit-user-select:none;-webkit-user-drag:none;}
6
6
  .fyodos-orb-btn img{pointer-events:none;-webkit-user-drag:none;user-select:none;}
@@ -61,6 +61,6 @@
61
61
  .fyodos-modal-actions{display:flex;gap:10px;justify-content:flex-end;}
62
62
  .fyodos-btn-ghost{appearance:none;border:1px solid rgba(160,180,220,0.25);background:transparent;border-radius:999px;padding:10px 16px;font-size:13px;cursor:pointer;}
63
63
  .fyodos-btn-primary{appearance:none;border:none;border-radius:999px;padding:10px 18px;font-size:13px;font-weight:600;color:#fff;cursor:pointer;}
64
- `;function za(){if(typeof document=="undefined"||document.getElementById(Ri))return;let e=document.createElement("style");e.id=Ri,e.textContent=Ha,document.head.appendChild(e)}function Oi(){let e=typeof document!="undefined"?document.documentElement:null;return{width:(e==null?void 0:e.clientWidth)||window.innerWidth,height:(e==null?void 0:e.clientHeight)||window.innerHeight}}function Va(e){switch(e){case"bottom-left":return{x:0,y:1};case"top-right":return{x:1,y:0};case"top-left":return{x:0,y:0};default:return{x:1,y:1}}}var vt={cardBackgroundColor:"#0b0f1a",cardBorderColor:"rgba(160,180,220,0.2)",titleColor:"#e7ecf7",bodyColor:"#b9c4dd"};function Ct(e,t={}){var Ro,Oo,ko;if(typeof document=="undefined")return{unmount(){}};za();let n=(Ro=t.container)!=null?Ro:document.body,o=(Oo=t.zIndex)!=null?Oo:2147483e3,i=t.enableTextInput!==!1,r=t.usePublishedPosition!==!1,s=e.ui;if(e.config.voice.isRecognitionAvailable()){let d=navigator.permissions;(ko=d==null?void 0:d.query)==null||ko.call(d,{name:"microphone"}).then(C=>{e.markVoiceBlocked(C.state==="denied"),C.onchange=()=>e.markVoiceBlocked(C.state==="denied")}).catch(()=>{})}let a=Vn(()=>x().hapticIntensity),l=null,c=null,u,p=Fe(null),f=!0,m=!0,h=!1,y=null,w=t.corner?Va(t.corner):{...Ce};function x(){let d={...se,...l!=null?l:{}};return t.accent&&(d.accentColor=t.accent,d.colorKey="custom",d.backgroundColor=t.accent,d.glowColor=t.accent),t.size&&(d.size=t.size),d}let S=document.createElement("div");S.className="fyodos-orb-root",S.style.zIndex=String(o);let R=document.createElement("div");R.className="fyodos-orb-anchor";let T=Si(x()),g=document.createElement("button");g.className="fyodos-orb-btn",g.type="button",g.setAttribute("aria-label",s.orbLabel),g.appendChild(T.element),R.appendChild(g),S.appendChild(R);let v=null,A=document.createElement("div");A.className="fyodos-thought",A.setAttribute("role","button"),A.tabIndex=0,A.style.display="none",A.addEventListener("click",()=>{if(a.trigger("orbTap"),e.primeAudio(),i){let d=Co();Ke(d?Wt(d,{locale:e.config.locale,messages:e.messages}):void 0);return}e.toggleListening()}),A.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),A.click())}),R.appendChild(A),n.appendChild(S);let B=null;function q(){var d;return(d=x().size)!=null?d:se.size}function N(){return B!=null?B:w}function K(){let d=q(),C=Oi(),{left:I,top:k}=bn({viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,contentWidth:C.width,contentHeight:C.height,orbDiameter:d,position:N()});S.style.left=`${I}px`,S.style.top=`${k}px`,S.style.right="",S.style.bottom="",ue()}function ue(){let d=mt(N());v&&(v.style.position="absolute",v.style.top="50%",v.style.transform="translateY(-50%)",d.horizontal==="left"?(v.style.right="calc(100% + 10px)",v.style.left=""):(v.style.left="calc(100% + 10px)",v.style.right="")),A.style.display!=="none"&&So()}window.addEventListener("resize",K);let O;typeof ResizeObserver!="undefined"&&document.documentElement&&(O=new ResizeObserver(()=>K()),O.observe(document.documentElement));let b=window.visualViewport,E=()=>{J&&En()};b==null||b.addEventListener("resize",E),b==null||b.addEventListener("scroll",E);let $=6,L=!1,Y=!1,F=0,M=0,Q=0,j=0;function me(d){if(d.button!=null&&d.button!==0)return;let C=S.getBoundingClientRect();Q=C.left,j=C.top,F=d.clientX,M=d.clientY,L=!1;try{g.setPointerCapture(d.pointerId)}catch{}}function de(d){var re;if(!((re=g.hasPointerCapture)!=null&&re.call(g,d.pointerId)))return;let C=d.clientX-F,I=d.clientY-M;if(!L&&Math.hypot(C,I)<$)return;L=!0,d.preventDefault();let k=q(),_=Oi(),P=8,U=_.width-P-k,V=_.height-P-k,Z=Math.min(U,Math.max(P,Q+C)),G=Math.min(V,Math.max(P,j+I));S.style.left=`${Z}px`,S.style.top=`${G}px`,S.style.right="",S.style.bottom="",B=xn({centerX:Z+k/2,centerY:G+k/2,viewportWidth:_.width,viewportHeight:_.height,orbDiameter:k}),ue()}function ge(d){try{g.releasePointerCapture(d.pointerId)}catch{}L&&(Y=!0,L=!1,B=yn(B!=null?B:N()),S.style.transition="left 220ms cubic-bezier(0.22, 1, 0.36, 1), top 220ms cubic-bezier(0.22, 1, 0.36, 1)",K(),window.setTimeout(()=>{S.style.transition=""},260))}g.draggable=!1,g.addEventListener("dragstart",d=>d.preventDefault()),g.addEventListener("pointerdown",me),g.addEventListener("pointermove",de),g.addEventListener("pointerup",ge),g.addEventListener("pointercancel",ge),g.addEventListener("lostpointercapture",ge);let J=!1,Ae=!1,be=!1,z=document.createElement("div");z.className="fyodos-bubble",z.style.display="none";function Fi(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function En(){z.style.position="fixed",z.style.left="50%",z.style.right="",z.style.top="",z.style.transform="translateX(-50%)",z.style.bottom=`${Fi()+16}px`,z.style.zIndex=String(o+5)}let oe=document.createElement("div");oe.className="fyodos-bubble-scroll";let ye=document.createElement("button");ye.type="button",ye.className="fyodos-bubble-close",ye.textContent="\xD7",ye.setAttribute("aria-label","Close"),ye.addEventListener("click",()=>St(!1));let pe=document.createElement("button");pe.type="button",pe.className="fyodos-bubble-unexpand",pe.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"></path></svg>',pe.setAttribute("aria-label","Collapse"),pe.addEventListener("click",d=>{d.stopPropagation(),At(!1)});let He=document.createElement("div");He.className="fyodos-bubble-loader",He.append(document.createElement("span")),He.style.display="none";let Se=document.createElement("div");Se.className="fyodos-bubble-exchanges",oe.append(He,Se);let ze="";function Wi(d){let C=d.map(_=>`${_.userText}\0${_.replyText}`).join("");if(C===ze)return;let I=ze.length>0&&C.length>ze.length&&C.endsWith(ze),k=oe.scrollHeight-oe.scrollTop;ze=C,Se.replaceChildren();for(let _ of d){let P=document.createElement("div");P.className="fyodos-bubble-exchange";let U=document.createElement("div");if(U.className="fyodos-bubble-user",U.textContent=_.userText,P.append(U),_.replyText){let V=document.createElement("div");V.className="fyodos-bubble-reply",V.textContent=_.replyText,P.append(V)}Se.append(P)}oe.scrollTop=I?oe.scrollHeight-k:oe.scrollHeight}oe.addEventListener("scroll",()=>{if(!J||oe.scrollTop>12)return;let d=e.getState();d.hasOlderExchanges&&!d.loadingOlderExchanges&&e.loadOlderExchanges()});let we=document.createElement("div");we.className="fyodos-bubble-busy";let ie=document.createElement("em");ie.className="fyodos-busy-step",ie.style.display="none",we.appendChild(ie),we.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let go=null;function Ui(d){if(!h||!d.liveActivity)return null;let{kind:C,label:I}=d.liveActivity;switch(C){case"navigating":return s.activityNavigating.replace("{label}",I!=null?I:"");case"executing":return s.activityExecuting.replace("{label}",I!=null?I:"");case"waiting_confirmation":return s.activityWaitingConfirmation;default:return s.activityThinking}}function Hi(d,C){let I=d?Ui(C):null;if(I!==go){if(go=I,!I){ie.textContent="",ie.style.display="none";return}ie.style.display="",ie.textContent=I,ie.style.animation="none",ie.offsetWidth,ie.style.animation=""}}let In=document.createElement("div");In.className="fyodos-bubble-row";let W=document.createElement("input");W.type="text",W.placeholder=s.textPlaceholder;let D=document.createElement("button");D.type="button",D.className="fyodos-bubble-mic",D.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"></rect><path d="M5 11a7 7 0 0014 0 M12 18v3"></path></svg>',D.style.display="none";let ae=document.createElement("button");ae.textContent="\u2191",ae.setAttribute("aria-label",s.sendLabel),In.append(W,D,ae);let Te=Ii(e.config.locale);Te.isSupported()&&(D.style.display="flex",D.setAttribute("aria-label",s.micLabel),D.title=s.micLabel,D.addEventListener("click",()=>{e.getState().isBusy||(Te.toggle(()=>W.value,d=>{W.value=d,xt(W)}),Ve())}));function Ve(){var _,P;let d=(_=u==null?void 0:u.primaryButtonColor)!=null?_:x().accentColor,C=`${(P=u==null?void 0:u.sendButtonRadius)!=null?P:10}px`,I={...vt,...u!=null?u:{}}.bodyColor,k=Te.isListening();D.classList.toggle("is-listening",k),k?(D.style.background=d,D.style.border="none",D.style.color="#000",D.style.borderRadius=C):(D.style.background="rgba(255,255,255,0.06)",D.style.border="1px solid rgba(148,163,184,0.4)",D.style.color=I,D.style.borderRadius="999px"),D.setAttribute("aria-label",k?s.micStopLabel:s.micLabel),D.title=k?s.micStopLabel:s.micLabel}z.append(ye,pe,oe,we,In),R.appendChild(z);function At(d){Ae!==d&&(Ae=d,z.classList.toggle("fyodos-bubble--expanded",d),pe.style.display=d?"flex":"none",En())}let bo=0,yo=0,Ge=null,zi=8,xo=()=>{var C;let d=typeof window!="undefined"?(C=window.getSelection)==null?void 0:C.call(window):null;return!!d&&!d.isCollapsed&&d.toString().length>0},Rn=()=>{Ge!=null&&(window.clearTimeout(Ge),Ge=null)};z.addEventListener("pointerdown",d=>{bo=d.clientX,yo=d.clientY}),z.addEventListener("click",d=>{if(Ae)return;let C=d.target;if(C!=null&&C.closest(".fyodos-bubble-row, .fyodos-bubble-close, .fyodos-bubble-unexpand, button, input, a")||Math.hypot(d.clientX-bo,d.clientY-yo)>zi)return;if(d.detail>1){Rn();return}if(Rn(),!!!(C!=null&&C.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!xo()){At(!0);return}Ge=window.setTimeout(()=>{Ge=null,xo()||At(!0)},280)}),K();function vo(){var k,_,P;let d={...vt,...u!=null?u:{}},C=(k=u==null?void 0:u.primaryButtonColor)!=null?k:x().accentColor;z.style.background=d.cardBackgroundColor,z.style.borderColor=d.cardBorderColor,(u==null?void 0:u.borderRadius)!=null&&(z.style.borderRadius=`${u.borderRadius}px`),ye.style.color=d.bodyColor,pe.style.color=d.bodyColor,Se.querySelectorAll(".fyodos-bubble-user").forEach(U=>{U.style.color=d.bodyColor}),Se.querySelectorAll(".fyodos-bubble-reply").forEach(U=>{U.style.color=d.titleColor});let I=(_=u==null?void 0:u.inputBackgroundColor)!=null?_:"#ffffff";W.style.background=I,W.style.color=tn(I),W.style.setProperty("--fyodos-input-placeholder",nn(I)),ae.style.background=C,ae.style.borderRadius=`${(P=u==null?void 0:u.sendButtonRadius)!=null?P:10}px`,Ve(),we.querySelectorAll("span").forEach(U=>{U.style.background=C}),ie.style.color=d.titleColor}function St(d){J=d,z.style.display=d?"flex":"none",d?(vo(),En(),W.focus()):(Te.stop(),Ve(),e.resetBubbleWindow(),be=!1,Rn(),At(!1)),kn(e.getState())}function On(){if(e.getState().isBusy)return;let d=W.value.trim();d&&(Te.stop(),Ve(),a.trigger("send"),W.value="",e.submitTextTurn(d))}function Ke(d,C=!1){var P;let I=e.cancelAll(),k=(P=d==null?void 0:d.trim())!=null?P:"",_=k||I||"";W.value=_,St(!0),C&&k&&queueMicrotask(()=>On())}function kn(d){if(!(i&&!J&&(d.phase==="listening"||be))){v&&(v.remove(),v=null);return}if(v){ue();return}let I=x();v=Ai({theme:c!=null?c:{},accentColor:I.accentColor,backgroundColor:I.backgroundColor,label:s.keyboardChipLabel,onClick:()=>{a.trigger("keyboardChip"),Ke()}}),R.appendChild(v),ue()}function Co(){return Mt(Je(y,e.config.manifest.routes),e.messages,{locale:e.config.locale,actions:e.config.manifest.actions})}function Vi(d){let C=p,{padH:I}=ht(C);A.style.width="",A.textContent=d;let k=A.scrollWidth,_=typeof window!="undefined"?window.innerWidth:280,P=Math.min(280,_*.7);if(!(k>P-C.borderWidth*2)){A.style.width="";return}let V=Math.max(0,k-I*2),Z=Math.max(4,(V+48)/30);A.style.width=`${P}px`,A.textContent="";let G=document.createElement("div");G.className="fyodos-thought-track",G.style.animation=`fyodos-marquee ${Z}s linear infinite`;let re=document.createElement("span");re.textContent=d;let Ie=document.createElement("span");Ie.textContent=d,Ie.setAttribute("aria-hidden","true"),G.appendChild(re),G.appendChild(Ie),A.appendChild(G)}function Ao(d){let C=p,{fontPx:I,padH:k,approxHeight:_}=ht(C),P=ln(C,_,1,d);A.style.fontSize=`${I}px`,A.style.height=`${_}px`,A.style.padding=`0 ${k}px`,A.style.color=C.textColor,A.style.background=C.backgroundColor,A.style.border=`${C.borderWidth}px solid ${C.borderColor}`,un(A,P)}function So(){let d=mt(N());d.horizontal==="left"?(A.style.right="calc(100% + 10px)",A.style.left=""):(A.style.left="calc(100% + 10px)",A.style.right=""),d.vertical==="up"?(A.style.top="0",A.style.bottom="",A.style.transform=""):(A.style.bottom="0",A.style.top="",A.style.transform="")}function _n(d){let C=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!be,I=f&&!J&&C?Co():null;if(!I){A.style.display="none";return}if(A.setAttribute("aria-label",I),A.style.display="flex",Ao(),Vi(I),p.shape==="cloud"){let k=A.offsetWidth;k>0&&Ao(k)}So()}let Ye=null;function je(){Ye&&(Ye.remove(),Ye=null)}function wo(){let d={...vt,...u!=null?u:{}},C=document.createElement("div");C.className="fyodos-overlay",C.style.zIndex=String(o+10);let I=document.createElement("div");return I.className="fyodos-modal",I.style.background=d.cardBackgroundColor,I.style.border=`1px solid ${d.cardBorderColor}`,I.style.color=d.titleColor,I.setAttribute("role","dialog"),I.setAttribute("aria-modal","true"),C.appendChild(I),{overlay:C,modal:I}}function Gi(d,C){var Ie;je();let I={...vt,...u!=null?u:{}},k=(Ie=u==null?void 0:u.primaryButtonColor)!=null?Ie:x().accentColor,{overlay:_,modal:P}=wo(),U=document.createElement("h3");U.textContent=s.confirmTitle;let V=document.createElement("p");if(V.style.color=I.bodyColor,V.textContent=d,P.append(U,V),C){let Re=document.createElement("div");Re.className="fyodos-hint",Re.style.color=I.bodyColor,Re.textContent=C,P.append(Re)}let Z=document.createElement("div");Z.className="fyodos-modal-actions";let G=document.createElement("button");G.className="fyodos-btn-ghost",G.style.color=I.bodyColor,G.textContent=s.cancelLabel,G.onclick=()=>e.cancelPendingAction();let re=document.createElement("button");re.className="fyodos-btn-primary",re.style.background=k,re.textContent=s.confirmLabel,re.onclick=()=>{e.confirmPendingAction()},Z.append(G,re),P.append(Z),_.onclick=Re=>{Re.target===_&&e.cancelPendingAction()},n.appendChild(_),Ye=_}function Ki(){var G;je();let d={...vt,...u!=null?u:{}},C=(G=u==null?void 0:u.primaryButtonColor)!=null?G:x().accentColor,{overlay:I,modal:k}=wo(),_=document.createElement("h3");_.textContent=s.consentTitle;let P=document.createElement("p");P.style.color=d.bodyColor,P.textContent=s.consentBody;let U=document.createElement("div");U.className="fyodos-modal-actions";let V=document.createElement("button");V.className="fyodos-btn-ghost",V.style.color=d.bodyColor,V.textContent=s.consentDecline,V.onclick=()=>e.declineConsent();let Z=document.createElement("button");Z.className="fyodos-btn-primary",Z.style.background=C,Z.textContent=s.consentAccept,Z.onclick=()=>{e.acceptConsent()},U.append(V,Z),k.append(_,P,U),n.appendChild(I),Ye=I}g.onclick=()=>{if(Y){Y=!1;return}if(e.primeAudio(),e.getState().showThinking){a.trigger("orbTap");let C=e.cancelAll();C&&J&&(W.value=C,xt(W));return}if(a.trigger("orbTap"),J){St(!1);return}if(!m&&i){be=!1,Ke();return}if(e.voiceAvailable&&m){be=!1,e.toggleListening();return}if(i){be=!1,Ke();return}e.toggleListening()},ae.onclick=()=>{let d=e.getState();if(d.isBusy||d.chainActive){a.trigger("orbTap");let C=e.cancelAll();C&&(W.value=C,xt(W)),W.focus();return}On()},W.onkeydown=d=>{d.key==="Enter"&&On(),d.key==="Escape"&&St(!1)},W.addEventListener("input",()=>xt(W)),i||v&&(v.style.display="none");let To=null,Eo=!1,Pn=!1,wt=null;function Io(d){if(d.voiceBlocked&&!Pn){if(Pn=!0,i&&!J&&!d.isBusy){Ke();return}}else d.voiceBlocked||(Pn=!1);d.phase!==wt&&(d.phase==="listening"?a.trigger("listenStart"):wt==="listening"&&a.trigger("listenStop"),wt==="thinking"&&a.trigger("response"),wt=d.phase);let C=d.showThinking?"thinking":d.showWaveform||be?"listening":d.phase==="speaking"?"speaking":"idle";T.applyState(C,d.volumeLevel);let I=d.showThinking||d.chainActive;if(Hi(I,d),J){He.style.display=d.loadingOlderExchanges?"flex":"none",Wi(d.recentExchanges),oe.style.display="flex",we.style.display=I?"flex":"none";let k=d.isBusy||d.chainActive;ae.textContent=k?"\u25FC":"\u2191",ae.setAttribute("aria-label",k?s.cancelLabel:s.sendLabel),ae.style.opacity="1",ae.disabled=!1,D.style.opacity=k?"0.45":"1",D.disabled=k,Ve()}kn(d),_n(d),d.confirmationMessage!==To&&(To=d.confirmationMessage,d.confirmationMessage?Gi(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||je()),d.consentModalVisible!==Eo&&(Eo=d.consentModalVisible,d.consentModalVisible?Ki():d.confirmationMessage||je())}let Yi=e.subscribe(Io);Io(e.getState());let Ee=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}d!==y&&(y=d,_n(e.getState()))};Ee();let ji=window.setInterval(Ee,700);window.addEventListener("popstate",Ee),document.addEventListener("visibilitychange",Ee);let Xi=Ei(e,{pollMs:t.appearancePollMs,onChange:d=>{let C=d!=null&&Cn(d.internalProfile,t.allowInternalOrb===!0);S.style.display=d&&d.enabled===!1||C?"none":"",d&&(l=d.appearance,c=d.keyboardChip,u=d.modalTheme,p=d.bubbleTheme,f=d.bubbleEnabled,m=d.voiceInputEnabled,h=d.thinkingStepsEnabled,e.setConversationRetention(d.conversationRetentionMinutes,d.internalProfile),r&&d.screenPosition&&(w=d.screenPosition)),T.applyAppearance(x()),K(),v&&(v.remove(),v=null),kn(e.getState()),_n(e.getState()),J&&vo()}});return{unmount(){Te.dispose(),Yi(),Xi(),window.clearInterval(ji),window.removeEventListener("popstate",Ee),document.removeEventListener("visibilitychange",Ee),window.removeEventListener("resize",K),O==null||O.disconnect(),b==null||b.removeEventListener("resize",E),b==null||b.removeEventListener("scroll",E),je(),v==null||v.remove(),S.remove()}}}var ki="fiodos-dev-error-badge";function Ga(){try{return!1}catch{return!1}}function po(e,t){if(!Ga()||typeof document=="undefined"||!document.body)return;let n=Ka(e),o=document.getElementById(ki);if(o){let l=o.querySelector("[data-fiodos-badge-msg]");l&&(l.textContent=n);return}o=document.createElement("div"),o.id=ki,o.setAttribute("role","alert"),o.style.cssText=["position:fixed","bottom:20px","right:20px","z-index:2147483000","max-width:340px","padding:12px 14px","border-radius:12px","background:#1b1b1f","color:#fff","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","font-size:13px","line-height:1.45","box-shadow:0 8px 28px rgba(0,0,0,0.35)","border:1px solid rgba(255,255,255,0.12)"].join(";");let i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:6px;margin-bottom:6px;font-weight:600;color:#ffd166",i.textContent="\u25C9 Fiodos \xB7 el orbe no se mont\xF3 (solo desarrollo)";let r=document.createElement("button");r.textContent="\xD7",r.setAttribute("aria-label","Cerrar aviso de Fiodos"),r.style.cssText=["margin-left:auto","background:transparent","border:0","color:rgba(255,255,255,0.6)","font-size:18px","line-height:1","cursor:pointer","padding:0 2px"].join(";"),r.addEventListener("click",()=>o==null?void 0:o.remove()),i.appendChild(r);let s=document.createElement("div");s.setAttribute("data-fiodos-badge-msg",""),s.textContent=n;let a=document.createElement("div");a.style.cssText="margin-top:8px;color:rgba(255,255,255,0.55);font-size:11.5px",a.textContent="Comprueba que la API key y la URL de tu app son las del MISMO proyecto donde publicaste. Este aviso solo aparece en desarrollo.",o.appendChild(i),o.appendChild(s),o.appendChild(a),document.body.appendChild(o)}function Ka(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var wn="0.1.14",_i="@fiodos/web-core";var Pi="https://api.fyodos.com";function Mi(e){return e.replace(/\/$/,"")}async function Li(e){let t=Mi(e.baseUrl);if(!e.apiKey)throw new Error("[fyodos] A drop-in agent requires an apiKey. Set it to the project key from your Fiodos dashboard (e.g. VITE_FYODOS_API_KEY).");let n=await fetch(`${t}/v1/client/manifest`,{method:"GET",headers:{"x-api-key":e.apiKey}});if(!n.ok)throw n.status===401?new Error(`[fyodos] The orb did not load: the API key was rejected (HTTP 401) by ${t}. Check that your FYODOS API key matches the current project key in the dashboard (a deleted/recreated project gets a NEW key).`):new Error(`[fyodos] The orb did not load: could not fetch the manifest (HTTP ${n.status}) from ${t}.`);let o=await n.json();return o.manifest?{status:"ready",manifest:o.manifest}:{status:"no-manifest",manifest:null}}function Ya(){return typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)?"web-mobile":"web"}async function fo(e){var n;if(!e.apiKey)return;let t=Mi(e.baseUrl);try{await fetch(`${t}/v1/client/orb-seen`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey},body:JSON.stringify({platform:(n=e.platform)!=null?n:Ya(),sdkVersion:wn,sdkPackage:_i})})}catch{}}function ja(e){typeof window!="undefined"&&window.location&&window.location.assign(e)}function Ni(){let e=typeof navigator!="undefined"&&navigator.language?navigator.language:"en-US";return{locale:e.split("-")[0]||"en",sttLocale:e}}function Xa(e){var n,o,i,r,s;let t=(o=(n=e.getLocale)==null?void 0:n.call(e))==null?void 0:o.trim();if(t)return t;if((i=e.locale)!=null&&i.trim())return e.locale.trim();if(e.localeDetection==="browser")return Ni().locale;if(e.localeDetection==="document"){let a=typeof document!="undefined"?(s=(r=document.documentElement.lang)==null?void 0:r.split(/[-_]/)[0])==null?void 0:s.trim():"";if(a)return a}return"en"}function Bi(e,t,n){var u,p,f,m;let o=Ni(),i=Xa(e),r=(p=(u=e.sttLocale)!=null?u:e.locale)!=null?p:o.sttLocale,s=ei({baseUrl:n,apiKey:e.apiKey,getUserId:e.getUserId}),a=ti({baseUrl:n,apiKey:e.apiKey,getUserId:e.getUserId}),l={manifest:t,locale:i,sttLocale:r,navigation:ni({navigate:(f=e.navigate)!=null?f:ja,getCurrentRoute:e.getCurrentRoute}),registries:(m=e.registries)!=null?m:{handlers:{},idempotencyCheckers:{}},backend:s,voice:si(),storage:oi(),telemetry:a,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},c=new Ue(l);return c.warmUp(),c}function $i(e){var a,l;let t=((a=e.baseUrl)!=null?a:Pi).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=Bi(e,e.manifest,t),u=n?Ct(c,e.orb):null;return n&&e.apiKey&&fo({baseUrl:t,apiKey:e.apiKey}),(l=e.onReady)==null||l.call(e,c),{controller:c,orb:u,ready:Promise.resolve(c),resetConversation(){c.resetConversation()},setScreenContext(f){c.screenStore.set(o,f)},clearScreenContext(){c.screenStore.clear(o)},destroy(){u==null||u.unmount(),c.dispose()}}}let i,r={controller:null,orb:null,ready:Promise.resolve(null),resetConversation(){var c;(c=r.controller)==null||c.resetConversation()},setScreenContext(c){r.controller?r.controller.screenStore.set(o,c):i=c},clearScreenContext(){r.controller?r.controller.screenStore.clear(o):i=null},destroy(){var c,u;s=!0,(c=r.orb)==null||c.unmount(),(u=r.controller)==null||u.dispose()}},s=!1;return r.ready=(async()=>{var c,u;try{if(!e.apiKey)throw new Error("[fyodos] createFiodosAgent requires either a `manifest` or an `apiKey` (to self-fetch the published manifest).");let p=await Li({baseUrl:t,apiKey:e.apiKey});if(s)return null;if(p.status==="no-manifest"||!p.manifest){let h="[fyodos] No hay manifest publicado para esta API key todav\xEDa. Ejecuta `npx @fiodos/cli analyze . --publish` o publ\xEDcalo desde el dashboard, y recarga.";return console.warn(h),po(h,{baseUrl:t}),null}let f=he(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
64
+ `;function ic(){if(typeof document=="undefined"||document.getElementById(Fi))return;let e=document.createElement("style");e.id=Fi,e.textContent=oc,document.head.appendChild(e)}function Wi(){let e=typeof document!="undefined"?document.documentElement:null;return{width:(e==null?void 0:e.clientWidth)||window.innerWidth,height:(e==null?void 0:e.clientHeight)||window.innerHeight}}function rc(e){switch(e){case"bottom-left":return{x:0,y:1};case"top-right":return{x:1,y:0};case"top-left":return{x:0,y:0};default:return{x:1,y:1}}}var Ve={cardBackgroundColor:"#0b0f1a",cardBorderColor:"rgba(160,180,220,0.2)",titleColor:"#e7ecf7",bodyColor:"#b9c4dd"};function wt(e,t={}){var No,$o,Do;if(typeof document=="undefined")return{unmount(){}};ic();let n=(No=t.container)!=null?No:document.body,o=($o=t.zIndex)!=null?$o:2147483e3,i=t.enableTextInput!==!1,r=t.usePublishedPosition!==!1,s=e.ui;if(e.config.voice.isRecognitionAvailable()){let d=navigator.permissions;(Do=d==null?void 0:d.query)==null||Do.call(d,{name:"microphone"}).then(y=>{e.markVoiceBlocked(y.state==="denied"),y.onchange=()=>e.markVoiceBlocked(y.state==="denied")}).catch(()=>{})}let a=Jn(()=>v().hapticIntensity),l=null,c=null,u,p=We(null),f=!0,m=!0,h=!1,x=null,T=t.corner?rc(t.corner):{...Ce};function v(){let d={...ce,...l!=null?l:{}};return t.accent&&(d.accentColor=t.accent,d.colorKey="custom",d.backgroundColor=t.accent,d.glowColor=t.accent),t.size&&(d.size=t.size),d}let S=document.createElement("div");S.className="fyodos-orb-root",S.style.zIndex=String(o);let I=document.createElement("div");I.className="fyodos-orb-anchor";let E=Li(v()),g=document.createElement("button");g.className="fyodos-orb-btn",g.type="button",g.setAttribute("aria-label",s.orbLabel),g.appendChild(E.element),I.appendChild(g),S.appendChild(I);let C=null,A=document.createElement("div");A.className="fyodos-thought",A.setAttribute("role","button"),A.tabIndex=0,A.style.display="none",A.addEventListener("click",()=>{if(a.trigger("orbTap"),e.primeAudio(),i){let d=Oo();Xe(d?jt(d,{locale:Rt(),messages:e.messages}):void 0);return}Tt=!0,e.toggleListening()}),A.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),A.click())}),I.appendChild(A),n.appendChild(S);let N=null;function Q(){var d;return(d=v().size)!=null?d:ce.size}function B(){return N!=null?N:T}function Y(){let d=Q(),y=Wi(),{left:w,top:k}=Sn({viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,contentWidth:y.width,contentHeight:y.height,orbDiameter:d,position:B()});S.style.left=`${w}px`,S.style.top=`${k}px`,S.style.right="",S.style.bottom="",oe()}function oe(){let d=xt(B());C&&(C.style.position="absolute",C.style.top="50%",C.style.transform="translateY(-50%)",d.horizontal==="left"?(C.style.right="calc(100% + 10px)",C.style.left=""):(C.style.left="calc(100% + 10px)",C.style.right="")),A.style.display!=="none"&&_o()}window.addEventListener("resize",Y);let O;typeof ResizeObserver!="undefined"&&document.documentElement&&(O=new ResizeObserver(()=>Y()),O.observe(document.documentElement));let b=window.visualViewport,R=()=>{Z&&Pn()};b==null||b.addEventListener("resize",R),b==null||b.addEventListener("scroll",R);let $=6,L=!1,j=!1,F=0,P=0,J=0,X=0;function me(d){if(d.button!=null&&d.button!==0)return;let y=S.getBoundingClientRect();J=y.left,X=y.top,F=d.clientX,P=d.clientY,L=!1;try{g.setPointerCapture(d.pointerId)}catch{}}function de(d){var ae;if(!((ae=g.hasPointerCapture)!=null&&ae.call(g,d.pointerId)))return;let y=d.clientX-F,w=d.clientY-P;if(!L&&Math.hypot(y,w)<$)return;L=!0,d.preventDefault();let k=Q(),M=Wi(),_=8,U=M.width-_-k,G=M.height-_-k,H=Math.min(U,Math.max(_,J+y)),K=Math.min(G,Math.max(_,X+w));S.style.left=`${H}px`,S.style.top=`${K}px`,S.style.right="",S.style.bottom="",N=Tn({centerX:H+k/2,centerY:K+k/2,viewportWidth:M.width,viewportHeight:M.height,orbDiameter:k}),oe()}function ge(d){try{g.releasePointerCapture(d.pointerId)}catch{}L&&(j=!0,L=!1,N=wn(N!=null?N:B()),S.style.transition="left 220ms cubic-bezier(0.22, 1, 0.36, 1), top 220ms cubic-bezier(0.22, 1, 0.36, 1)",Y(),window.setTimeout(()=>{S.style.transition=""},260))}g.draggable=!1,g.addEventListener("dragstart",d=>d.preventDefault()),g.addEventListener("pointerdown",me),g.addEventListener("pointermove",de),g.addEventListener("pointerup",ge),g.addEventListener("pointercancel",ge),g.addEventListener("lostpointercapture",ge);let Z=!1,Ae=!1,be=!1,Tt=!1,z=document.createElement("div");z.className="fyodos-bubble",z.style.display="none";function Ji(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function Pn(){z.style.position="fixed",z.style.left="50%",z.style.right="",z.style.top="",z.style.transform="translateX(-50%)",z.style.bottom=`${Ji()+16}px`,z.style.zIndex=String(o+5)}let ie=document.createElement("div");ie.className="fyodos-bubble-scroll";let ye=document.createElement("button");ye.type="button",ye.className="fyodos-bubble-close",ye.textContent="\xD7",ye.setAttribute("aria-label","Close"),ye.addEventListener("click",()=>je(!1));let pe=document.createElement("button");pe.type="button",pe.className="fyodos-bubble-unexpand",pe.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"></path></svg>',pe.setAttribute("aria-label","Collapse"),pe.addEventListener("click",d=>{d.stopPropagation(),Et(!1)});let ze=document.createElement("div");ze.className="fyodos-bubble-loader",ze.append(document.createElement("span")),ze.style.display="none";let Se=document.createElement("div");Se.className="fyodos-bubble-exchanges",ie.append(ze,Se);let Ge="";function Zi(d){let y=d.map(_=>`${_.userText}\0${_.replyText}`).join("");if(y===Ge)return;let w=Ge.length>0&&y.length>Ge.length&&y.endsWith(Ge),k=ie.scrollHeight-ie.scrollTop;Ge=y;let M={...Ve,...u!=null?u:{}};Se.replaceChildren();for(let _ of d){let U=document.createElement("div");U.className="fyodos-bubble-exchange";let G=document.createElement("div");if(G.className="fyodos-bubble-user",G.textContent=_.userText,G.style.color=M.bodyColor,U.append(G),_.replyText){let H=document.createElement("div");H.className="fyodos-bubble-reply",H.textContent=_.replyText,H.style.color=M.titleColor,U.append(H)}Se.append(U)}ie.scrollTop=w?ie.scrollHeight-k:ie.scrollHeight}ie.addEventListener("scroll",()=>{if(!Z||ie.scrollTop>12)return;let d=e.getState();d.hasOlderExchanges&&!d.loadingOlderExchanges&&e.loadOlderExchanges()});let we=document.createElement("div");we.className="fyodos-bubble-busy";let re=document.createElement("em");re.className="fyodos-busy-step",re.style.display="none",we.appendChild(re),we.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let wo=null;function er(d){if(!h||!d.liveActivity)return null;let{kind:y,label:w}=d.liveActivity;switch(y){case"navigating":return s.activityNavigating.replace("{label}",w!=null?w:"");case"executing":return s.activityExecuting.replace("{label}",w!=null?w:"");case"waiting_confirmation":return s.activityWaitingConfirmation;default:return s.activityThinking}}function tr(d,y){let w=d?er(y):null;if(w!==wo){if(wo=w,!w){re.textContent="",re.style.display="none";return}re.style.display="",re.textContent=w,re.style.animation="none",re.offsetWidth,re.style.animation=""}}let Mn=document.createElement("div");Mn.className="fyodos-bubble-row";let W=document.createElement("input");W.type="text",W.placeholder=s.textPlaceholder;let D=document.createElement("button");D.type="button",D.className="fyodos-bubble-mic",D.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"></rect><path d="M5 11a7 7 0 0014 0 M12 18v3"></path></svg>',D.style.display="none";let se=document.createElement("button");se.textContent="\u2191",se.setAttribute("aria-label",s.sendLabel),Mn.append(W,D,se);let Te=Di(e.config.locale);Te.isSupported()&&(D.style.display="flex",D.setAttribute("aria-label",s.micLabel),D.title=s.micLabel,D.addEventListener("click",()=>{e.getState().isBusy||(Te.toggle(()=>W.value,d=>{W.value=d,St(W)}),Ke())}));function Ke(){var M,_;let d=(M=u==null?void 0:u.primaryButtonColor)!=null?M:v().accentColor,y=`${(_=u==null?void 0:u.sendButtonRadius)!=null?_:10}px`,w={...Ve,...u!=null?u:{}}.bodyColor,k=Te.isListening();D.classList.toggle("is-listening",k),k?(D.style.background=d,D.style.border="none",D.style.color=Fe(d),D.style.borderRadius=y):(D.style.background="rgba(255,255,255,0.06)",D.style.border="1px solid rgba(148,163,184,0.4)",D.style.color=w,D.style.borderRadius="999px"),D.setAttribute("aria-label",k?s.micStopLabel:s.micLabel),D.title=k?s.micStopLabel:s.micLabel}z.append(ye,pe,ie,we,Mn),I.appendChild(z);function Et(d){Ae!==d&&(Ae=d,z.classList.toggle("fyodos-bubble--expanded",d),pe.style.display=d?"flex":"none",Pn())}let To=0,Eo=0,Ye=null,nr=8,Ro=()=>{var y;let d=typeof window!="undefined"?(y=window.getSelection)==null?void 0:y.call(window):null;return!!d&&!d.isCollapsed&&d.toString().length>0},Ln=()=>{Ye!=null&&(window.clearTimeout(Ye),Ye=null)};z.addEventListener("pointerdown",d=>{To=d.clientX,Eo=d.clientY}),z.addEventListener("click",d=>{if(Ae)return;let y=d.target;if(y!=null&&y.closest(".fyodos-bubble-row, .fyodos-bubble-close, .fyodos-bubble-unexpand, button, input, a")||Math.hypot(d.clientX-To,d.clientY-Eo)>nr)return;if(d.detail>1){Ln();return}if(Ln(),!!!(y!=null&&y.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!Ro()){Et(!0);return}Ye=window.setTimeout(()=>{Ye=null,Ro()||Et(!0)},280)}),Y();function Io(){var k,M,_;let d={...Ve,...u!=null?u:{}},y=(k=u==null?void 0:u.primaryButtonColor)!=null?k:v().accentColor;z.style.background=d.cardBackgroundColor,z.style.borderColor=d.cardBorderColor,(u==null?void 0:u.borderRadius)!=null&&(z.style.borderRadius=`${u.borderRadius}px`),ye.style.color=d.bodyColor,pe.style.color=d.bodyColor,Se.querySelectorAll(".fyodos-bubble-user").forEach(U=>{U.style.color=d.bodyColor}),Se.querySelectorAll(".fyodos-bubble-reply").forEach(U=>{U.style.color=d.titleColor});let w=(M=u==null?void 0:u.inputBackgroundColor)!=null?M:"#ffffff";W.style.background=w,W.style.color=Fe(w),W.style.setProperty("--fyodos-input-placeholder",un(w)),se.style.background=y,se.style.color=Fe(y),se.style.borderRadius=`${(_=u==null?void 0:u.sendButtonRadius)!=null?_:10}px`,Ke(),we.querySelectorAll("span").forEach(U=>{U.style.background=y}),re.style.color=d.titleColor}let Bn=`fyodos:panel-open:${e.config.manifest.appId}`;function or(d){try{d?window.sessionStorage.setItem(Bn,"1"):window.sessionStorage.removeItem(Bn)}catch{}}function ir(){try{return window.sessionStorage.getItem(Bn)==="1"}catch{return!1}}function je(d){Z=d,z.style.display=d?"flex":"none",or(d),d?(Io(),Pn(),W.focus(),Fn(e.getState())):(Te.stop(),Ke(),e.resetBubbleWindow(),be=!1,Ln(),Et(!1)),$n(e.getState()),It(e.getState())}function Nn(){if(e.getState().isBusy)return;let d=W.value.trim();d&&(Te.stop(),Ke(),a.trigger("send"),W.value="",e.submitTextTurn(d))}function Xe(d,y=!1){var _;let w=e.cancelAll(),k=(_=d==null?void 0:d.trim())!=null?_:"",M=k||w||"";W.value=M,je(!0),y&&k&&queueMicrotask(()=>Nn())}function $n(d){if(!(i&&!Z&&(d.phase==="listening"||be))){C&&(C.remove(),C=null);return}if(C){oe();return}let w=v();C=Mi({theme:c!=null?c:{},accentColor:w.accentColor,backgroundColor:w.backgroundColor,label:s.keyboardChipLabel,onClick:()=>{a.trigger("keyboardChip"),Xe()}}),I.appendChild(C),oe()}function Rt(){var d,y;try{let w=(y=(d=e.config).getLocale)==null?void 0:y.call(d);if(typeof w=="string"&&w.trim())return w.trim()}catch{}return e.config.locale}function Oo(){return Dt(tt(x,e.config.manifest.routes),e.messages,{locale:Rt(),actions:e.config.manifest.actions})}function rr(d){let y=p,{padH:w}=yt(y);A.style.width="",A.textContent=d;let k=A.scrollWidth,M=typeof window!="undefined"?window.innerWidth:280,_=Math.min(280,M*.7);if(!(k>_-y.borderWidth*2)){A.style.width="";return}let G=Math.max(0,k-w*2),H=Math.max(4,(G+48)/30);A.style.width=`${_}px`,A.textContent="";let K=document.createElement("div");K.className="fyodos-thought-track",K.style.animation=`fyodos-marquee ${H}s linear infinite`;let ae=document.createElement("span");ae.textContent=d;let Re=document.createElement("span");Re.textContent=d,Re.setAttribute("aria-hidden","true"),K.appendChild(ae),K.appendChild(Re),A.appendChild(K)}function ko(d){let y=p,{fontPx:w,padH:k,approxHeight:M}=yt(y),_=mn(y,M,1,d);A.style.fontSize=`${w}px`,A.style.height=`${M}px`,A.style.padding=`0 ${k}px`,A.style.color=y.textColor,A.style.background=y.backgroundColor,A.style.border=`${y.borderWidth}px solid ${y.borderColor}`,gn(A,_)}function _o(){let d=xt(B());d.horizontal==="left"?(A.style.right="calc(100% + 10px)",A.style.left=""):(A.style.left="calc(100% + 10px)",A.style.right=""),d.vertical==="up"?(A.style.top="0",A.style.bottom="",A.style.transform=""):(A.style.bottom="0",A.style.top="",A.style.transform="")}function It(d){let y=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!be,w=f&&!Z&&y?Oo():null;if(!w){A.style.display="none";return}if(A.setAttribute("aria-label",w),A.style.display="flex",ko(),rr(w),p.shape==="cloud"){let k=A.offsetWidth;k>0&&ko(k)}_o()}let qe=null;function Qe(){qe&&(qe.remove(),qe=null)}function Po(){let d={...Ve,...u!=null?u:{}},y=document.createElement("div");y.className="fyodos-overlay",y.style.zIndex=String(o+10);let w=document.createElement("div");return w.className="fyodos-modal",w.style.background=d.cardBackgroundColor,w.style.border=`1px solid ${d.cardBorderColor}`,w.style.color=d.titleColor,w.setAttribute("role","dialog"),w.setAttribute("aria-modal","true"),y.appendChild(w),{overlay:y,modal:w}}function sr(d,y){var Re;Qe();let w={...Ve,...u!=null?u:{}},k=(Re=u==null?void 0:u.primaryButtonColor)!=null?Re:v().accentColor,{overlay:M,modal:_}=Po(),U=document.createElement("h3");U.textContent=s.confirmTitle;let G=document.createElement("p");if(G.style.color=w.bodyColor,G.textContent=d,_.append(U,G),y){let Ie=document.createElement("div");Ie.className="fyodos-hint",Ie.style.color=w.bodyColor,Ie.textContent=y,_.append(Ie)}let H=document.createElement("div");H.className="fyodos-modal-actions";let K=document.createElement("button");K.className="fyodos-btn-ghost",K.style.color=w.bodyColor,K.textContent=s.cancelLabel,K.onclick=()=>e.cancelPendingAction();let ae=document.createElement("button");ae.className="fyodos-btn-primary",ae.style.background=k,ae.textContent=s.confirmLabel,ae.onclick=()=>{e.confirmPendingAction()},H.append(K,ae),_.append(H),M.onclick=Ie=>{Ie.target===M&&e.cancelPendingAction()},n.appendChild(M),qe=M}function ar(){var K;Qe();let d={...Ve,...u!=null?u:{}},y=(K=u==null?void 0:u.primaryButtonColor)!=null?K:v().accentColor,{overlay:w,modal:k}=Po(),M=document.createElement("h3");M.textContent=s.consentTitle;let _=document.createElement("p");_.style.color=d.bodyColor,_.textContent=s.consentBody;let U=document.createElement("div");U.className="fyodos-modal-actions";let G=document.createElement("button");G.className="fyodos-btn-ghost",G.style.color=d.bodyColor,G.textContent=s.consentDecline,G.onclick=()=>e.declineConsent();let H=document.createElement("button");H.className="fyodos-btn-primary",H.style.background=y,H.textContent=s.consentAccept,H.onclick=()=>{e.acceptConsent()},U.append(G,H),k.append(M,_,U),n.appendChild(w),qe=w}g.onclick=()=>{if(j){j=!1;return}if(e.primeAudio(),e.getState().showThinking){a.trigger("orbTap");let y=e.cancelAll();y&&Z&&(W.value=y,St(W));return}if(a.trigger("orbTap"),Z){je(!1);return}if(!m&&i){be=!1,Xe();return}if(e.voiceAvailable&&m){be=!1,Tt=!0,e.toggleListening();return}if(i){be=!1,Xe();return}Tt=!0,e.toggleListening()},se.onclick=()=>{let d=e.getState();if(d.isBusy||d.chainActive){a.trigger("orbTap");let y=e.cancelAll();y&&(W.value=y,St(W)),W.focus();return}Nn()},W.onkeydown=d=>{d.key==="Enter"&&Nn(),d.key==="Escape"&&je(!1)},W.addEventListener("input",()=>St(W)),i||C&&(C.style.display="none");let Mo=null,Lo=!1,Dn=!1,Ot=null;function Fn(d){if(d.voiceBlocked&&!Dn){if(Dn=!0,Tt&&i&&!Z&&!d.isBusy){Xe();return}}else d.voiceBlocked||(Dn=!1);d.phase!==Ot&&(d.phase==="listening"?a.trigger("listenStart"):Ot==="listening"&&a.trigger("listenStop"),Ot==="thinking"&&a.trigger("response"),Ot=d.phase);let y=d.showThinking?"thinking":d.showWaveform||be?"listening":d.phase==="speaking"?"speaking":"idle";E.applyState(y,d.volumeLevel);let w=d.showThinking||d.chainActive;if(tr(w,d),Z){ze.style.display=d.loadingOlderExchanges?"flex":"none",Zi(d.recentExchanges),ie.style.display="flex",we.style.display=w?"flex":"none";let k=d.isBusy||d.chainActive;se.textContent=k?"\u25FC":"\u2191",se.setAttribute("aria-label",k?s.cancelLabel:s.sendLabel),se.style.opacity="1",se.disabled=!1,D.style.opacity=k?"0.45":"1",D.disabled=k,Ke()}$n(d),It(d),d.confirmationMessage!==Mo&&(Mo=d.confirmationMessage,d.confirmationMessage?sr(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||Qe()),d.consentModalVisible!==Lo&&(Lo=d.consentModalVisible,d.consentModalVisible?ar():d.confirmationMessage||Qe())}let cr=e.subscribe(Fn);Fn(e.getState()),i&&ir()&&je(!0);let Bo=Rt(),Ee=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}let y=Rt();(d!==x||y!==Bo)&&(x=d,Bo=y,It(e.getState()))};Ee();let lr=window.setInterval(Ee,700);window.addEventListener("popstate",Ee),document.addEventListener("visibilitychange",Ee);let ur=$i(e,{pollMs:t.appearancePollMs,onChange:d=>{let y=d!=null&&Rn(d.internalProfile,t.allowInternalOrb===!0);S.style.display=d&&d.enabled===!1||y?"none":"",d&&(l=d.appearance,c=d.keyboardChip,u=d.modalTheme,p=d.bubbleTheme,f=d.bubbleEnabled,m=d.voiceInputEnabled,h=d.thinkingStepsEnabled,e.setConversationRetention(d.conversationRetentionMinutes,d.internalProfile),r&&d.screenPosition&&(T=d.screenPosition)),E.applyAppearance(v()),Y(),C&&(C.remove(),C=null),$n(e.getState()),It(e.getState()),Z&&Io()}});return{unmount(){Te.dispose(),cr(),ur(),window.clearInterval(lr),window.removeEventListener("popstate",Ee),document.removeEventListener("visibilitychange",Ee),window.removeEventListener("resize",Y),O==null||O.disconnect(),b==null||b.removeEventListener("resize",R),b==null||b.removeEventListener("scroll",R),Qe(),C==null||C.remove(),S.remove()}}}var Ui="fiodos-dev-error-badge";function sc(){try{return!1}catch{return!1}}function vo(e,t){if(!sc()||typeof document=="undefined"||!document.body)return;let n=ac(e),o=document.getElementById(Ui);if(o){let l=o.querySelector("[data-fiodos-badge-msg]");l&&(l.textContent=n);return}o=document.createElement("div"),o.id=Ui,o.setAttribute("role","alert"),o.style.cssText=["position:fixed","bottom:20px","right:20px","z-index:2147483000","max-width:340px","padding:12px 14px","border-radius:12px","background:#1b1b1f","color:#fff","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","font-size:13px","line-height:1.45","box-shadow:0 8px 28px rgba(0,0,0,0.35)","border:1px solid rgba(255,255,255,0.12)"].join(";");let i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:6px;margin-bottom:6px;font-weight:600;color:#ffd166",i.textContent="\u25C9 Fiodos \xB7 el orbe no se mont\xF3 (solo desarrollo)";let r=document.createElement("button");r.textContent="\xD7",r.setAttribute("aria-label","Cerrar aviso de Fiodos"),r.style.cssText=["margin-left:auto","background:transparent","border:0","color:rgba(255,255,255,0.6)","font-size:18px","line-height:1","cursor:pointer","padding:0 2px"].join(";"),r.addEventListener("click",()=>o==null?void 0:o.remove()),i.appendChild(r);let s=document.createElement("div");s.setAttribute("data-fiodos-badge-msg",""),s.textContent=n;let a=document.createElement("div");a.style.cssText="margin-top:8px;color:rgba(255,255,255,0.55);font-size:11.5px",a.textContent="Comprueba que la API key y la URL de tu app son las del MISMO proyecto donde publicaste. Este aviso solo aparece en desarrollo.",o.appendChild(i),o.appendChild(s),o.appendChild(a),document.body.appendChild(o)}function ac(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var kn="0.1.17",Hi="@fiodos/web-core";var Vi="https://api.fyodos.com";function zi(e){return e.replace(/\/$/,"")}async function Gi(e){let t=zi(e.baseUrl);if(!e.apiKey)throw new Error("[fyodos] A drop-in agent requires an apiKey. Set it to the project key from your Fiodos dashboard (e.g. VITE_FYODOS_API_KEY).");let n=await fetch(`${t}/v1/client/manifest`,{method:"GET",headers:{"x-api-key":e.apiKey}});if(!n.ok)throw n.status===401?new Error(`[fyodos] The orb did not load: the API key was rejected (HTTP 401) by ${t}. Check that your FYODOS API key matches the current project key in the dashboard (a deleted/recreated project gets a NEW key).`):new Error(`[fyodos] The orb did not load: could not fetch the manifest (HTTP ${n.status}) from ${t}.`);let o=await n.json();return o.manifest?{status:"ready",manifest:o.manifest}:{status:"no-manifest",manifest:null}}function cc(){return typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)?"web-mobile":"web"}async function Co(e){var n;if(!e.apiKey)return;let t=zi(e.baseUrl);try{await fetch(`${t}/v1/client/orb-seen`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey},body:JSON.stringify({platform:(n=e.platform)!=null?n:cc(),sdkVersion:kn,sdkPackage:Hi})})}catch{}}function lc(e){typeof window!="undefined"&&window.location&&window.location.assign(e)}function Xi(){let e=typeof navigator!="undefined"&&navigator.language?navigator.language:"en-US";return{locale:e.split("-")[0]||"en",sttLocale:e}}function Ki(){var e,t;return typeof document!="undefined"&&((t=(e=document.documentElement.lang)==null?void 0:e.split(/[-_]/)[0])==null?void 0:t.trim())||""}function Yi(e){var o,i,r;let t=(i=(o=e.getLocale)==null?void 0:o.call(e))==null?void 0:i.trim();if(t)return t;if((r=e.locale)!=null&&r.trim())return e.locale.trim();if(e.localeDetection==="browser")return Xi().locale;if(e.localeDetection==="document"){let s=Ki();if(s)return s}let n=Ki();return n||"en"}function ji(e,t,n){var u,p,f,m;let o=Xi(),i=Yi(e),r=(p=(u=e.sttLocale)!=null?u:e.locale)!=null?p:o.sttLocale,s=di({baseUrl:n,apiKey:e.apiKey,getUserId:e.getUserId}),a=pi({baseUrl:n,apiKey:e.apiKey,getUserId:e.getUserId}),l={manifest:t,locale:i,getLocale:()=>Yi(e),sttLocale:r,navigation:fi({navigate:(f=e.navigate)!=null?f:lc,getCurrentRoute:e.getCurrentRoute}),registries:(m=e.registries)!=null?m:{handlers:{},idempotencyCheckers:{}},backend:s,voice:bi(),storage:hi(),telemetry:a,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},c=new He(l);return c.warmUp(),c}function qi(e){var a,l;let t=((a=e.baseUrl)!=null?a:Vi).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=ji(e,e.manifest,t),u=n?wt(c,e.orb):null;return n&&e.apiKey&&Co({baseUrl:t,apiKey:e.apiKey}),(l=e.onReady)==null||l.call(e,c),{controller:c,orb:u,ready:Promise.resolve(c),resetConversation(){c.resetConversation()},setScreenContext(f){c.screenStore.set(o,f)},clearScreenContext(){c.screenStore.clear(o)},destroy(){u==null||u.unmount(),c.dispose()}}}let i,r={controller:null,orb:null,ready:Promise.resolve(null),resetConversation(){var c;(c=r.controller)==null||c.resetConversation()},setScreenContext(c){r.controller?r.controller.screenStore.set(o,c):i=c},clearScreenContext(){r.controller?r.controller.screenStore.clear(o):i=null},destroy(){var c,u;s=!0,(c=r.orb)==null||c.unmount(),(u=r.controller)==null||u.dispose()}},s=!1;return r.ready=(async()=>{var c,u;try{if(!e.apiKey)throw new Error("[fyodos] createFiodosAgent requires either a `manifest` or an `apiKey` (to self-fetch the published manifest).");let p=await Gi({baseUrl:t,apiKey:e.apiKey});if(s)return null;if(p.status==="no-manifest"||!p.manifest){let h="[fyodos] No hay manifest publicado para esta API key todav\xEDa. Ejecuta `npx @fiodos/cli analyze . --publish` o publ\xEDcalo desde el dashboard, y recarga.";return console.warn(h),vo(h,{baseUrl:t}),null}let f=he(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
65
65
  - ${f.errors.join(`
66
- - `)}`);let m=Bi(e,p.manifest,t);return s?(m.dispose(),null):(r.controller=m,i&&m.screenStore.set(o,i),i=void 0,r.orb=n?Ct(m,e.orb):null,n&&e.apiKey&&fo({baseUrl:t,apiKey:e.apiKey}),(c=e.onReady)==null||c.call(e,m),m)}catch(p){let f=p instanceof Error?p:new Error(String(p));return console.error(f.message),po(f.message,{baseUrl:t}),(u=e.onError)==null||u.call(e,f),null}})(),r}function Tn(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function qa(e){let t=e.map(n=>n&&typeof n=="object"&&typeof n.name=="string"?n.name:null).filter(n=>!!n);return t.length?t.join(", "):null}function Qa(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return Tn(o);if(Array.isArray(o)&&o.length)return Tn(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?Tn(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=qa(t);return o?Tn(o):null}return null}function ho(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function mo(e,t={}){var h,y,w,x,S,R,T,g;let n=(h=e.data)==null?void 0:h.entity;if(!n)return null;let o=n.getEntityName(),i=ho((y=n.getId())!=null?y:""),r=(w=t.attributes)!=null&&w.length?new Set(t.attributes.map(v=>v.trim().toLowerCase()).filter(Boolean)):null,s=(x=t.maxAttributes)!=null?x:12,a={},l=0;(S=n.attributes)==null||S.forEach(v=>{let A;try{A=v.getName()}catch{return}if(!A)return;if(r){if(!r.has(A.toLowerCase()))return}else if(l>=s)return;let B=Qa(v);B!=null&&(a[A]=B,l+=1)});let c;try{c=(T=(R=n.getPrimaryAttributeValue)==null?void 0:R.call(n))!=null?T:void 0}catch{c=void 0}let u=i?{id:i,kind:o,title:c,metadata:a}:null,p=Object.entries(a).map(([v,A])=>`${v}: ${A}`).join("; "),f=[`Dynamics 365 form \u2014 entity "${o}"`,i?`record "${c!=null?c:i}" (id ${i})`:"new record (not saved yet)"];p&&f.push(`Fields: ${p}`);let m={...u?{visibleContent:{items:[u],focusedIndex:0}}:{},custom:{platform:"dynamics365",entityName:o,...i?{recordId:i}:{},...typeof((g=e.ui)==null?void 0:g.getFormType)=="function"?{formType:e.ui.getFormType()}:{}}};return{kind:`dynamics-form:${o}`,text:f.join(". "),context:m}}function Di(e,t,n={}){var s;let o=!1,i=()=>{if(o)return;let a=mo(t,n);a?e.setScreenContext(a):e.clearScreenContext()};i();let r=(s=t.data)==null?void 0:s.entity;if(r!=null&&r.addOnPostSave)try{r.addOnPostSave(i)}catch{}return{refresh:i,disconnect(){var a;if(!o){o=!0;try{(a=r==null?void 0:r.removeOnPostSave)==null||a.call(r,i)}catch{}e.clearScreenContext()}}}}var Ja={version:wn,createFiodosAgent:$i,mountOrb:Ct,AgentController:Ue,createScreenContextStore:Sn,buildApiActionRegistries:kt,validateManifest:he,connectDynamicsFormContext:Di,dynamicsFormSnapshot:mo,normalizeDynamicsId:ho};globalThis.Fiodos=Ja;})();
66
+ - `)}`);let m=ji(e,p.manifest,t);return s?(m.dispose(),null):(r.controller=m,i&&m.screenStore.set(o,i),i=void 0,r.orb=n?wt(m,e.orb):null,n&&e.apiKey&&Co({baseUrl:t,apiKey:e.apiKey}),(c=e.onReady)==null||c.call(e,m),m)}catch(p){let f=p instanceof Error?p:new Error(String(p));return console.error(f.message),vo(f.message,{baseUrl:t}),(u=e.onError)==null||u.call(e,f),null}})(),r}function _n(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function uc(e){let t=e.map(n=>n&&typeof n=="object"&&typeof n.name=="string"?n.name:null).filter(n=>!!n);return t.length?t.join(", "):null}function dc(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return _n(o);if(Array.isArray(o)&&o.length)return _n(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?_n(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=uc(t);return o?_n(o):null}return null}function Ao(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function So(e,t={}){var h,x,T,v,S,I,E,g;let n=(h=e.data)==null?void 0:h.entity;if(!n)return null;let o=n.getEntityName(),i=Ao((x=n.getId())!=null?x:""),r=(T=t.attributes)!=null&&T.length?new Set(t.attributes.map(C=>C.trim().toLowerCase()).filter(Boolean)):null,s=(v=t.maxAttributes)!=null?v:12,a={},l=0;(S=n.attributes)==null||S.forEach(C=>{let A;try{A=C.getName()}catch{return}if(!A)return;if(r){if(!r.has(A.toLowerCase()))return}else if(l>=s)return;let N=dc(C);N!=null&&(a[A]=N,l+=1)});let c;try{c=(E=(I=n.getPrimaryAttributeValue)==null?void 0:I.call(n))!=null?E:void 0}catch{c=void 0}let u=i?{id:i,kind:o,title:c,metadata:a}:null,p=Object.entries(a).map(([C,A])=>`${C}: ${A}`).join("; "),f=[`Dynamics 365 form \u2014 entity "${o}"`,i?`record "${c!=null?c:i}" (id ${i})`:"new record (not saved yet)"];p&&f.push(`Fields: ${p}`);let m={...u?{visibleContent:{items:[u],focusedIndex:0}}:{},custom:{platform:"dynamics365",entityName:o,...i?{recordId:i}:{},...typeof((g=e.ui)==null?void 0:g.getFormType)=="function"?{formType:e.ui.getFormType()}:{}}};return{kind:`dynamics-form:${o}`,text:f.join(". "),context:m}}function Qi(e,t,n={}){var s;let o=!1,i=()=>{if(o)return;let a=So(t,n);a?e.setScreenContext(a):e.clearScreenContext()};i();let r=(s=t.data)==null?void 0:s.entity;if(r!=null&&r.addOnPostSave)try{r.addOnPostSave(i)}catch{}return{refresh:i,disconnect(){var a;if(!o){o=!0;try{(a=r==null?void 0:r.removeOnPostSave)==null||a.call(r,i)}catch{}e.clearScreenContext()}}}}var pc={version:kn,createFiodosAgent:qi,mountOrb:wt,AgentController:He,createScreenContextStore:On,buildApiActionRegistries:Bt,validateManifest:he,connectDynamicsFormContext:Qi,dynamicsFormSnapshot:So,normalizeDynamicsId:Ao};globalThis.Fiodos=pc;})();