@fiodos/web-core 0.1.18 → 0.1.19

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 yr=new Set(["navigate","execute","none"]);function _t(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!yr.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 le="BACK";function Pt(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 Mt(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 Hn=/\{([a-zA-Z0-9_]+)\}/g,xr="baseUrl";function Lt(e){let t=[];for(let n of e.matchAll(Hn)){let o=n[1];o&&!t.includes(o)&&t.push(o)}return t}function Bt(e){let t=new Set(Lt(e.url)),n=o=>{if(typeof o=="string")for(let i of Lt(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 ke=class extends Error{};function vr(e,t,n){return e.replace(Hn,(o,i)=>{if(i===xr){if(!n)throw new ke("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let r=t[i];if(r==null)throw new ke(`Missing parameter '${i}' for URL template`);return encodeURIComponent(String(r))})}function Un(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 ke(`Missing parameter '${o}' for body template`);return i}return e.replace(Hn,(o,i)=>{let r=t[i];if(r==null)throw new ke(`Missing parameter '${i}' for body template`);return String(r)})}return Array.isArray(e)?e.map(n=>Un(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Un(o,t)])):e}function Cr(){let e=globalThis.fetch;return typeof e=="function"?e:null}function Ar(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 Sr(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,h,m,x,T;let a={...(f=e.headers)!=null?f:{}};if(e.authRef){let v=(h=t.authProviders)==null?void 0:h[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=vr(e.url,s,n),e.body&&(a["Content-Type"]=(m=a["Content-Type"])!=null?m:"application/json",c=JSON.stringify(Un(e.body,s)))}catch(v){return{success:!1,error:v instanceof Error?v.message:"Template resolution failed"}}let u=(x=t.fetchFn)!=null?x:Cr();if(!u)return{success:!1,error:"No fetch implementation available"};let p=Ar(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 Nt(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]=Sr(r.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var wr=new Set(["string","number","boolean"]),Tr=new Set(["standard","strict","disabled"]),Er=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)}'`),Er.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 Bt(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,h,m,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`):(h=E.handler)!=null&&h.trim()||t.push(`action '${g}' has empty handler`),(m=E.examples)!=null&&m.length||t.push(`action '${g}' has no examples`),E.doubleConfirmation&&!E.requireConfirmation&&t.push(`action '${g}' declares doubleConfirmation without requireConfirmation`),E.voiceConfirmation!==void 0&&(Tr.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:{}))wr.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`);Rr(E,g,t)}return{valid:t.length===0,errors:t}}function Vn(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 h=o.isAuthenticated?o.isAuthenticated():null;if(h==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(!h)return{ok:!1,reason:"User not authenticated",userMessage:o.messages.needsAuth,recoverable:!1}}for(let h of(u=i.custom)!=null?u:[]){let m=(p=n.contextValidators)==null?void 0:p[h];if(!m)return{ok:!1,reason:`Context validator not registered: ${h}`,userMessage:o.messages.actionUnavailable,recoverable:!1};let x;try{x=m(t)}catch(T){return{ok:!1,reason:`Context validator '${h}' 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 Ze(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=Vn(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 et(e,t,n,o,i){var l;let r=await Ze(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 Wo={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 Uo={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 tt={en:Wo,es:Uo};function Or(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:tt[e],i=Or(e),r=(l=o!=null?o:n[i])!=null?l:tt[i];if(!r){let c=[...new Set([...Object.keys(tt),...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 ve(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var Ho=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function kr(e){let t=ve(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||Ho.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&Ho.test(n[0]))}function _r(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function zn(e){return _r(e)==="es"}var Vo=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function Pr(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function Mr(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 Lr(e,t){var c;let n=zn(t),o=ve(e.label),i=ve(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 ve(e.intent).replace(/_/g," ")}function Br(e,t,n){let o=Lr(e,n);return ee(t.bubblePromptFromAction,{action:o})}function Nr(e,t){let n=e.toLowerCase(),o=zn(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 $r(e,t){let n=zn(t),o=Pr(e.intent),i=ve(e.label).toLowerCase();if(Vo.has(o)||Vo.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 Dr(e,t,n){var r;let o=((r=e.examples)!=null?r:[]).map(ve).find(s=>s.length>0&&kr(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 Dt(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=Mr(e,i);if(r)return Br(r,t,o);let s=ve(e.description);if(s){let c=Nr(s,o);if(c)return c}let a=$r(e,o);return a||Dr(e,t,o)}function K(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 zo(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}function nt(e,t){if(e==null||!t||t.length===0)return null;let n=String(e).trim();if(!n)return null;let o=K(n),i=t.filter(s=>s&&s.route&&s.route!==le);if(i.length===0)return null;for(let s of i)if(K(s.route)===o)return s;if(o){let s=null;for(let a of i){let l=K(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=zo(o)||o;if(r){for(let s of i)if(K(s.intent)===r||K(s.label)===r||zo(K(s.route))===r)return s;for(let s of i)if(K(s.intent)===o||K(s.label)===o)return s}return null}function Gn(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 h=new Map(i.map(T=>[T.intent,T])),m=[],x=new Set;for(let T of a){let v=h.get(T),S=(f=v==null?void 0:v.label)==null?void 0:f.trim();S&&!x.has(S)&&(x.add(S),m.push(S))}m.length>0&&r.push(ee(o.currentScreenActions,{actions:m.join(", ")}))}return r.join(" \u2014 ")}function Yo(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Go(e){return String(e!=null?e:"").split(/[-_]/)[0].trim().toLowerCase()}function Fr(e,t){let n=e.bubblePrompts;if(!n||typeof n!="object")return null;let o=Go(t);if(!o)return null;for(let[i,r]of Object.entries(n))if(Go(i)===o){let s=Yo(r);if(s)return s}return null}function Ft(e,t,n){if(!e)return null;let o=Fr(e,n==null?void 0:n.locale);if(o)return o;let i=Yo(e.bubblePrompt);if(i)return i;let r=Dt(e,t,{locale:n==null?void 0:n.locale,actions:n==null?void 0:n.actions});return r||null}function Wt(e,t,n){let o=nt(e,t.routes);return Gn(o,{messages:n,actions:t.actions})}var Wr=/(^|[\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,Ur=/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,Hr=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,Vr=/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(Ur.test(t)||!Wr.test(t))return!1;let n=Ut(e);return n.usernameParam!==null&&n.passwordParam!==null}function Ut(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&&Vr.test(i)){n=i;continue}t===null&&Hr.test(i)&&(t=i)}return{usernameParam:t,passwordParam:n}}function Yn(e){return typeof e=="string"?e.trim().length>0:e!=null}async function Ht(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}=Ut(t);if(!r||!s)return{kind:"not-applicable"};let a=(c=e.parameters)!=null?c:{};if(Yn(a[r])&&Yn(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]:Yn(a[r])?a[r]:l.username,[s]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}var Ko=/FYODOS_HANDLER_UNREADY|is not a function/i,zr=12,Gr=300;function Yr(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}function Vt(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(r){var l,c;let s=(l=r.intent)==null?void 0:l.trim();if(!s)return{success:!1,error:"No intent specified"};let a=e.manifest.routes.find(u=>u.intent===s);if(!a)return{success:!1,error:`Unknown intent: ${s}`};if(a.route!==le&&e.messages.alreadyOnScreen)try{let u=e.navigation.getCurrentRoute();if(u!=null&&String(u).trim()!==""&&K(u)===K(a.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return a.route===le?e.navigation.back():e.navigation.navigate(a.route),{success:!0}}catch(u){return{success:!1,error:`Navigation failed: ${u instanceof Error?u.message:"unknown"}`,message:(c=e.messages.navigationFailed)!=null?c:e.messages.actionFailed}}}async function o(r,s){var p,f,h;let a=await et(r,e.manifest.actions,s,e.registries,t);if(a.success||!Ko.test((p=a.error)!=null?p:""))return a;let l=(f=r.intent)==null?void 0:f.trim(),c=e.manifest.routes.find(m=>m.route!==le&&Array.isArray(m.actionIntents)&&l!=null&&m.actionIntents.includes(l));if(!c)return a;try{let m=e.navigation.getCurrentRoute();m!=null&&String(m).trim()!==""&&K(m)===K(c.route)||e.navigation.navigate(c.route)}catch{return a}let u=a;for(let m=0;m<zr;m+=1)if(await Yr(Gr),u=await et(r,e.manifest.actions,s,e.registries,t),u.success||!Ko.test((h=u.error)!=null?h:""))return u;return u}function i(r,s){if(!(r!=null&&r.showcaseRoute)||!s.success||s.recoverable)return;let a=e.manifest.routes.find(l=>l.intent===r.showcaseRoute);if(!(!a||a.route===le))try{let l=e.navigation.getCurrentRoute();if(l!=null&&String(l).trim()!==""&&K(l)===K(a.route))return;e.navigation.navigate(a.route)}catch{}}return{async execute(r,s={}){var a,l;if(!r||r.type==="none")return{success:!0};if(r.type==="navigate")return n(r);if(r.type==="execute"){let c=e.manifest.actions.find(p=>{var f;return p.intent===((f=r.intent)==null?void 0:f.trim())});if(c){let p=await Ht(r,c,e.credentialAutofill,e.isAuthenticated);if(p.kind==="proceed"){let f=await o(p.action,s);return i(c,f),f}if(p.kind==="dismissed"||p.kind==="unavailable"){let f=p.kind==="dismissed"?(a=e.messages.signInAutofillDismissed)!=null?a:e.messages.cancelled:(l=e.messages.signInAutofillUnavailable)!=null?l:e.messages.actionUnavailable;return{success:!1,error:`sign_in_autofill_${p.kind}`,message:f}}}let u=await o(r,s);return i(c,u),u}return{success:!1,error:`Action type not implemented: ${r.type}`}},async precheck(r,s={}){return Ze(r,e.manifest.actions,s,e.registries,t)}}}function zt(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 jo=new Set;function Gt(e,t){var s,a,l;if(!t)return e;let n=(s=e.actions)!=null?s:[],o=n.filter(c=>zt(c,t));if(o.length===n.length)return e;let i=n.filter(c=>!zt(c,t)).map(c=>c.intent).sort(),r=i.join(",");return jo.has(r)||(jo.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 jn(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=>jn(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,jn(o,t+1)]))}function Yt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return;let t;try{t=jn(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 _e(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 ot(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 _e(i,{...n,maxChars:o});if(!i)return _e(r,{...n,maxChars:o});let s=`
1
+ "use strict";(()=>{var yi=new Set(["navigate","execute","none"]);function _t(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!yi.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 le="BACK";function Pt(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 Mt(e){return e.actions.map(t=>{var r,i,s,a;let n=Object.entries((r=t.parameters)!=null?r:{}),o=(i=t.contextRequirements)==null?void 0:i.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 Hn=/\{([a-zA-Z0-9_]+)\}/g,xi="baseUrl";function Lt(e){let t=[];for(let n of e.matchAll(Hn)){let o=n[1];o&&!t.includes(o)&&t.push(o)}return t}function Bt(e){let t=new Set(Lt(e.url)),n=o=>{if(typeof o=="string")for(let r of Lt(o))t.add(r);else Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return e.body&&n(e.body),[...t]}var ke=class extends Error{};function vi(e,t,n){return e.replace(Hn,(o,r)=>{if(r===xi){if(!n)throw new ke("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let i=t[r];if(i==null)throw new ke(`Missing parameter '${r}' for URL template`);return encodeURIComponent(String(i))})}function Un(e,t){if(typeof e=="string"){let n=/^\{([a-zA-Z0-9_]+)\}$/.exec(e);if(n){let o=n[1],r=t[o];if(r==null)throw new ke(`Missing parameter '${o}' for body template`);return r}return e.replace(Hn,(o,r)=>{let i=t[r];if(i==null)throw new ke(`Missing parameter '${r}' for body template`);return String(i)})}return Array.isArray(e)?e.map(n=>Un(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Un(o,t)])):e}function Ci(){let e=globalThis.fetch;return typeof e=="function"?e:null}function Ai(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 r;return(r=t.clearTimeout)==null?void 0:r.call(t,o)}}}function Si(e,t){var r,i;let n=(r=t.baseUrl)==null?void 0:r.replace(/\/$/,""),o=(i=t.timeoutMs)!=null?i:15e3;return async s=>{var f,m,h,g,R;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(A){return{success:!1,error:`Auth provider '${e.authRef}' failed: ${A instanceof Error?A.message:"unknown"}`}}}let l,c;try{l=vi(e.url,s,n),e.body&&(a["Content-Type"]=(h=a["Content-Type"])!=null?h:"application/json",c=JSON.stringify(Un(e.body,s)))}catch(v){return{success:!1,error:v instanceof Error?v.message:"Template resolution failed"}}let u=(g=t.fetchFn)!=null?g:Ci();if(!u)return{success:!1,error:"No fetch implementation available"};let p=Ai(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 A;try{if(((R=v.headers.get("content-type"))!=null?R:"").includes("json")){let T=await v.text();if(T){let b=JSON.parse(T);b&&typeof b=="object"&&!Array.isArray(b)&&(A=b)}}}catch{}return{success:!0,...A?{data:A}:{}}}catch(v){return{success:!1,error:`Request failed: ${v instanceof Error?v.message:"unknown"}`}}finally{p.cancel()}}}function Nt(e,t={}){var o,r;let n={};for(let i of(o=e.actions)!=null?o:[]){if(!i.execution||i.kind==="link")continue;let s=(r=i.handler)==null?void 0:r.trim();s&&(n[s]=Si(i.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var wi=new Set(["string","number","boolean"]),Ti=new Set(["standard","strict","disabled"]),Ei=new Set(["GET","POST","PUT","PATCH","DELETE"]);function Ri(e,t,n){var i,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)}'`),Ei.has(o.method)||n.push(`action '${t}' has invalid execution method '${String(o.method)}'`),!((i=o.url)!=null&&i.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 r=new Set(Object.keys((s=e.parameters)!=null?s:{}));for(let a of Bt(o))a!=="baseUrl"&&!r.has(a)&&n.push(`action '${t}' execution references undeclared parameter '{${a}}'`)}function me(e){var o,r,i,s,a,l,c,u,p,f,m,h,g,R,v,A,I;let t=[];(o=e.appId)!=null&&o.trim()||t.push("appId is required"),(r=e.appName)!=null&&r.trim()||t.push("appName is required"),(i=e.version)!=null&&i.trim()||t.push("version is required");let n=new Set;for(let T of(s=e.routes)!=null?s:[]){let b=(a=T.intent)==null?void 0:a.trim();if(!b){t.push("route with empty intent");continue}n.has(b)&&t.push(`duplicate intent: ${b}`),n.add(b),(l=T.route)!=null&&l.trim()||t.push(`route intent '${b}' has empty route`),(c=T.examples)!=null&&c.length||t.push(`route intent '${b}' has no examples`)}for(let T of(u=e.actions)!=null?u:[]){let b=(p=T.intent)==null?void 0:p.trim();if(!b){t.push("action with empty intent");continue}n.has(b)&&t.push(`duplicate intent: ${b}`),n.add(b),T.kind==="link"?(f=T.navTarget)!=null&&f.trim()||t.push(`link action '${b}' has empty navTarget`):(m=T.handler)!=null&&m.trim()||t.push(`action '${b}' has empty handler`),(h=T.examples)!=null&&h.length||t.push(`action '${b}' has no examples`),T.doubleConfirmation&&!T.requireConfirmation&&t.push(`action '${b}' declares doubleConfirmation without requireConfirmation`),T.voiceConfirmation!==void 0&&(Ti.has(T.voiceConfirmation)||t.push(`action '${b}' has invalid voiceConfirmation '${T.voiceConfirmation}'`),T.requireConfirmation||t.push(`action '${b}' declares voiceConfirmation without requireConfirmation`)),T.confirmationPhrase!==void 0&&!T.confirmationPhrase.trim()&&t.push(`action '${b}' has an empty confirmationPhrase`),T.requireConfirmation&&!((g=T.confirmationMessageTemplate)!=null&&g.trim())&&t.push(`action '${b}' requires confirmation but has no confirmationMessageTemplate`);for(let[C,S]of Object.entries((R=T.parameters)!=null?R:{}))wi.has(S.type)||t.push(`action '${b}' parameter '${C}' has invalid type '${S.type}'`),(v=S.description)!=null&&v.trim()||t.push(`action '${b}' parameter '${C}' has empty description`);for(let C of(I=(A=T.contextRequirements)==null?void 0:A.custom)!=null?I:[])C.trim()||t.push(`action '${b}' has an empty custom requirement name`);Ri(T,b,t)}return{valid:t.length===0,errors:t}}function Vn(e,t,n,o){var i,s,a,l,c,u,p,f;let r=e.contextRequirements;if(!r)return{ok:!0};if(r.requiresVisibleContent&&!(((s=(i=t.visibleContent)==null?void 0:i.items.length)!=null?s:0)>0))return{ok:!1,reason:"No visible content in context",userMessage:o.messages.needsVisibleContent,recoverable:!0};if(r.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=r.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 g;try{g=h(t)}catch(R){return{ok:!1,reason:`Context validator '${m}' threw: ${R instanceof Error?R.message:"unknown"}`,userMessage:o.messages.actionUnavailable,recoverable:!1}}if(!g.ok)return{ok:!1,reason:g.reason,userMessage:(f=g.userMessage)!=null?f:o.messages.actionUnavailable,recoverable:!0}}return{ok:!0}}async function Ze(e,t,n,o,r){var l;let i=(l=e.intent)==null?void 0:l.trim();if(!i)return{kind:"done",result:{success:!1,error:"No intent specified"}};let s=t.find(c=>c.intent===i);if(!s)return{kind:"done",result:{success:!1,error:`Unknown action intent: ${i}`}};let a=Vn(s,n,o,r);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 et(e,t,n,o,r){var l;let i=await Ze(e,t,n,o,r);if(i.kind==="done")return i.result;let{actionConfig:s}=i,a=o.handlers[s.handler];if(!a)return{success:!1,error:`Handler not found: ${s.handler}`,message:r.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:r.messages.actionFailed}}}var Wo={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 Uo={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 tt={en:Wo,es:Uo};function Oi(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Dt(e,t={}){var s,a,l;let n=(s=t.catalogs)!=null?s:{},o=(a=n[e])!=null?a:tt[e],r=Oi(e),i=(l=o!=null?o:n[r])!=null?l:tt[r];if(!i){let c=[...new Set([...Object.keys(tt),...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?{...i,...t.overrides}:i}function ee(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n)}function ve(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var Ho=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function ki(e){let t=ve(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||Ho.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&Ho.test(n[0]))}function _i(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function zn(e){return _i(e)==="es"}var Vo=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function Pi(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function Mi(e,t){var r;let n=(r=e.actionIntents)!=null?r:[];if(n.length===0||!(t!=null&&t.length))return null;let o=new Map(t.map(i=>[i.intent,i]));for(let i of n){let s=o.get(i);if(s)return s}return null}function Li(e,t){var c;let n=zn(t),o=ve(e.label),r=ve(e.description),i=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[i])return l[i];if(r){let u=r.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 ve(e.intent).replace(/_/g," ")}function Bi(e,t,n){let o=Li(e,n);return ee(t.bubblePromptFromAction,{action:o})}function Ni(e,t){let n=e.toLowerCase(),o=zn(t),r=e.match(/from here (?:you|the user|users?) (?:can|may|could)\s+(.+?)(?:[.;]|$)/i);if(r!=null&&r[1]){let i=r[1].trim().replace(/[.;]+$/,"");if(i.length>=4&&i.length<=56)return o?`\xBFQuieres ${i.toLowerCase()}?`:`Want to ${i.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 Di(e,t){let n=zn(t),o=Pi(e.intent),r=ve(e.label).toLowerCase();if(Vo.has(o)||Vo.has(r.replace(/\s+/g,"_")))return null;let i=`${o} ${r}`;return/login|sign_in|signin|auth/.test(i)?n?"\xBFQuieres iniciar sesi\xF3n?":"Want to sign in?":/register|signup|sign_up|sign-up/.test(i)?n?"\xBFQuieres registrarte?":"Want to create an account?":/cart|checkout|basket/.test(i)?n?"\xBFFinalizar tu compra?":"Ready to checkout?":/user|users|account|people|member/.test(i)?n?"\xBFBuscar un usuario?":"Looking for a user?":/product|catalog|shop|store|item/.test(i)?n?"\xBFBuscar un producto?":"Browse products?":/todo|task/.test(i)?n?"\xBFA\xF1adir una tarea?":"Want to add a task?":/setting|preference|config/.test(i)?n?"\xBFCambiar alg\xFAn ajuste?":"Need to change a setting?":/profile|account_overview/.test(i)?n?"\xBFActualizar tu perfil?":"Update your profile?":/bill|invoice|payment|subscription|pricing/.test(i)?n?"\xBFVer tu facturaci\xF3n?":"Check your billing?":/search|find|lookup/.test(i)?n?"\xBFQu\xE9 buscas?":"What are you looking for?":/chat|message|inbox|conversation/.test(i)?n?"\xBFEnviar un mensaje?":"Send a message?":/password|security/.test(i)?n?"\xBFCambiar tu contrase\xF1a?":"Change your password?":/order|transaction|history/.test(i)?n?"\xBFVer tu historial?":"Review your history?":/wallet|budget|saving|finance|balance/.test(i)?n?"\xBFRevisar tus finanzas?":"Review your finances?":/note|editor|write|compose|new_chat/.test(i)?n?"\xBFEscribir algo nuevo?":"Write something new?":null}function $i(e,t,n){var i;let o=((i=e.examples)!=null?i:[]).map(ve).find(s=>s.length>0&&ki(s));if(!o)return null;let r=o.replace(/\?+$/,"").trim();return/^(take me|go to|open|show me|navigate|ir a|abrir|mostrar|llévame)/i.test(r)?null:ee(t.bubblePromptFromExample,{phrase:r})}function $t(e,t,n){var l;let o=(l=n==null?void 0:n.locale)!=null?l:"en",r=n==null?void 0:n.actions,i=Mi(e,r);if(i)return Bi(i,t,o);let s=ve(e.description);if(s){let c=Ni(s,o);if(c)return c}let a=Di(e,o);return a||$i(e,t,o)}function K(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 zo(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}function nt(e,t){if(e==null||!t||t.length===0)return null;let n=String(e).trim();if(!n)return null;let o=K(n),r=t.filter(s=>s&&s.route&&s.route!==le);if(r.length===0)return null;for(let s of r)if(K(s.route)===o)return s;if(o){let s=null;for(let a of r){let l=K(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 i=zo(o)||o;if(i){for(let s of r)if(K(s.intent)===i||K(s.label)===i||zo(K(s.route))===i)return s;for(let s of r)if(K(s.intent)===o||K(s.label)===o)return s}return null}function Gn(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:r}=t,i=[ee(o.currentScreenLabel,{label:n})],s=(u=e.description)==null?void 0:u.trim();s&&i.push(s);let a=(p=e.actionIntents)!=null?p:[];if(a.length>0&&r&&r.length>0){let m=new Map(r.map(R=>[R.intent,R])),h=[],g=new Set;for(let R of a){let v=m.get(R),A=(f=v==null?void 0:v.label)==null?void 0:f.trim();A&&!g.has(A)&&(g.add(A),h.push(A))}h.length>0&&i.push(ee(o.currentScreenActions,{actions:h.join(", ")}))}return i.join(" \u2014 ")}function Yo(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Go(e){return String(e!=null?e:"").split(/[-_]/)[0].trim().toLowerCase()}function Fi(e,t){let n=e.bubblePrompts;if(!n||typeof n!="object")return null;let o=Go(t);if(!o)return null;for(let[r,i]of Object.entries(n))if(Go(r)===o){let s=Yo(i);if(s)return s}return null}function Ft(e,t,n){if(!e)return null;let o=Fi(e,n==null?void 0:n.locale);if(o)return o;let r=Yo(e.bubblePrompt);if(r)return r;let i=$t(e,t,{locale:n==null?void 0:n.locale,actions:n==null?void 0:n.actions});return i||null}function Wt(e,t,n){let o=nt(e,t.routes);return Gn(o,{messages:n,actions:t.actions})}var Wi=/(^|[\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,Ui=/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,Hi=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,Vi=/pass(word)?|contrase|clave|pwd/i;function Kn(e){var o,r;if(e.kind==="link"||(o=e.contextRequirements)!=null&&o.requiresAuth)return!1;let t=`${e.intent} ${e.label} ${(r=e.handler)!=null?r:""}`;if(Ui.test(t)||!Wi.test(t))return!1;let n=Ut(e);return n.usernameParam!==null&&n.passwordParam!==null}function Ut(e){var o;let t=null,n=null;for(let[r,i]of Object.entries((o=e.parameters)!=null?o:{}))if(i.type==="string"){if(n===null&&Vi.test(r)){n=r;continue}t===null&&Hi.test(r)&&(t=r)}return{usernameParam:t,passwordParam:n}}function Yn(e){return typeof e=="string"?e.trim().length>0:e!=null}async function Ht(e,t,n,o){var c;if(!n)return{kind:"not-applicable"};let r=!1;try{r=n.isSupported()===!0}catch{r=!1}if(!r)return{kind:"not-applicable"};if(!Kn(t))return{kind:"not-applicable"};if((o==null?void 0:o())===!0)return{kind:"not-applicable"};let{usernameParam:i,passwordParam:s}=Ut(t);if(!i||!s)return{kind:"not-applicable"};let a=(c=e.parameters)!=null?c:{};if(Yn(a[i])&&Yn(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,[i]:Yn(a[i])?a[i]:l.username,[s]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}var Ko=/FYODOS_HANDLER_UNREADY|is not a function/i,zi=12,Gi=300;function Yi(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}function Vt(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(i){var l,c;let s=(l=i.intent)==null?void 0:l.trim();if(!s)return{success:!1,error:"No intent specified"};let a=e.manifest.routes.find(u=>u.intent===s);if(!a)return{success:!1,error:`Unknown intent: ${s}`};if(a.route!==le&&e.messages.alreadyOnScreen)try{let u=e.navigation.getCurrentRoute();if(u!=null&&String(u).trim()!==""&&K(u)===K(a.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return a.route===le?e.navigation.back():e.navigation.navigate(a.route),{success:!0}}catch(u){return{success:!1,error:`Navigation failed: ${u instanceof Error?u.message:"unknown"}`,message:(c=e.messages.navigationFailed)!=null?c:e.messages.actionFailed}}}async function o(i,s){var p,f,m;let a=await et(i,e.manifest.actions,s,e.registries,t);if(a.success||!Ko.test((p=a.error)!=null?p:""))return a;let l=(f=i.intent)==null?void 0:f.trim(),c=e.manifest.routes.find(h=>h.route!==le&&Array.isArray(h.actionIntents)&&l!=null&&h.actionIntents.includes(l));if(!c)return a;try{let h=e.navigation.getCurrentRoute();h!=null&&String(h).trim()!==""&&K(h)===K(c.route)||e.navigation.navigate(c.route)}catch{return a}let u=a;for(let h=0;h<zi;h+=1)if(await Yi(Gi),u=await et(i,e.manifest.actions,s,e.registries,t),u.success||!Ko.test((m=u.error)!=null?m:""))return u;return u}function r(i,s,a){if(a||!(i!=null&&i.showcaseRoute)||!s.success||s.recoverable)return;let l=e.manifest.routes.find(c=>c.intent===i.showcaseRoute);if(!(!l||l.route===le))try{let c=e.navigation.getCurrentRoute();if(c!=null&&String(c).trim()!==""&&K(c)===K(l.route))return;e.navigation.navigate(l.route)}catch{}}return{async execute(i,s={},a={}){var l,c;if(!i||i.type==="none")return{success:!0};if(i.type==="navigate")return n(i);if(i.type==="execute"){let u=e.manifest.actions.find(f=>{var m;return f.intent===((m=i.intent)==null?void 0:m.trim())});if(u){let f=await Ht(i,u,e.credentialAutofill,e.isAuthenticated);if(f.kind==="proceed"){let m=await o(f.action,s);return r(u,m,a.suppressEscort),m}if(f.kind==="dismissed"||f.kind==="unavailable"){let m=f.kind==="dismissed"?(l=e.messages.signInAutofillDismissed)!=null?l:e.messages.cancelled:(c=e.messages.signInAutofillUnavailable)!=null?c:e.messages.actionUnavailable;return{success:!1,error:`sign_in_autofill_${f.kind}`,message:m}}}let p=await o(i,s);return r(u,p,a.suppressEscort),p}return{success:!1,error:`Action type not implemented: ${i.type}`}},async precheck(i,s={}){return Ze(i,e.manifest.actions,s,e.registries,t)},escortForIntent(i){let s=e.manifest.actions.find(a=>a.intent===(i==null?void 0:i.trim()));r(s,{success:!0})}}}function zt(e,t){var o,r;if(e.kind==="link"||e.execution)return!0;let n=((o=e.handler)!=null?o:"").trim();return n?typeof((r=t.handlers)==null?void 0:r[n])=="function":!1}var jo=new Set;function Gt(e,t){var s,a,l;if(!t)return e;let n=(s=e.actions)!=null?s:[],o=n.filter(c=>zt(c,t));if(o.length===n.length)return e;let r=n.filter(c=>!zt(c,t)).map(c=>c.intent).sort(),i=r.join(",");return jo.has(i)||(jo.add(i),(l=(a=globalThis.console)==null?void 0:a.warn)==null||l.call(a,`[fyodos] ${r.length} manifest action(s) have no live handler in this app and were hidden from the agent so it never promises them: ${r.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 jn(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=>jn(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,jn(o,t+1)]))}function Yt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return;let t;try{t=jn(e,0);let n=JSON.stringify(t);if(n.length>6e3){let o=Object.entries(t).sort((r,i)=>JSON.stringify(i[1]).length-JSON.stringify(r[1]).length);for(;n.length>6e3&&o.length>1;){let[r]=o.shift();delete t[r],t[r]="\u2026(omitted)",n=JSON.stringify(t)}if(n.length>6e3)return}}catch{return}return t}function _e(e,t){var r;let n=(r=t.maxChars)!=null?r:1500;if(e.length<=n)return e;let o=Math.max(0,n-t.truncationSuffix.length);return e.slice(0,o)+t.truncationSuffix}function ot(e,t,n){var l;let o=(l=n.maxChars)!=null?l:1500,r=(e==null?void 0:e.trim())||null,i=(t==null?void 0:t.trim())||null;if(!r&&!i)return null;if(!i)return _e(r,{...n,maxChars:o});if(!r)return _e(i,{...n,maxChars:o});let s=`
2
2
 
3
- `,a=o-i.length-s.length;return a<=n.truncationSuffix.length?_e(i,{...n,maxChars:o}):i+s+_e(r,{...n,maxChars:a})}var Xn=[{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 qn(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]=Xn;return[n,...(r=e.customPatterns)!=null?r:[],...t,...o]}function jt(e={}){let t=qn(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 jr(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Xr(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function qr(e){return Xr(e)==="es"}function Qn(e){return e.replace(/^[¿¡]+/,"").replace(/[?!.…]+$/,"").trim()}function Qr(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 Jr=[[/^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"]],Zr=[[/^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 Xt(e,t){var c;let n=jr(e);if(!n)return"";let o=(c=t==null?void 0:t.locale)!=null?c:"en",i=qr(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 h=Qr(n,p,f);if(h)return h}}let a=i?Zr:Jr;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 Jn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function qt(e){var o;let t=Jn(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 Jt(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 Zt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var Xo=40;function en(e){return typeof e!="number"||Number.isNaN(e)?Xo:Math.max(0,Math.min(100,Math.round(e)))}function qo(e,t){let n=en(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 Zn(e){let t=()=>typeof e=="function"?e():e;return{trigger(n){try{let i=globalThis.navigator,r=qo(n,t());!(r===0||Array.isArray(r)&&r.every(a=>a===0))&&i&&typeof i.vibrate=="function"&&i.vibrate(r)}catch{}}}}var it={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 tn(e){var o,i,r;let t=(i=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?i:e.toLowerCase(),n=(r=it[e])!=null?r:it[t];if(!n)throw new Error(`[fyodos] No confirmation lexicon for locale "${e}". Built-in locales: ${Object.keys(it).join(", ")}. Pass a custom ConfirmationLexicon for your locale.`);return n}function Pe(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Qo(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function eo(e,t){let n=Pe(e);return n?t.affirmative.some(o=>Qo(n,Pe(o))):!1}function nn(e,t){let n=Pe(e);return n?t.negative.some(o=>Qo(n,Pe(o))):!1}function on(e,t){let n=nn(e,t),o=eo(e,t);return n?"negative":o?"affirmative":"ambiguous"}function xs(e,t){return t?` ${e} `.includes(` ${t} `):!1}function rn(e,t,n){let o=Pe(e);return o?nn(e,n)?"negative":xs(o,Pe(t))?"affirmative":"ambiguous":"ambiguous"}var to={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},rt={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Le(e,t=!1){let n=t?rt: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 Ce=5,Me=200;function Jo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Zo(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function ei(e,t,n){let o=t.map(i=>i.role==="user"?`User: ${Jo(i.content,120)}`:`Assistant: ${Jo(i.content,120)}`).join(" | ");return Zo(e?`${e} | ${o}`:o,n)}function no(e){return{...to,...e}}function Be(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function Ne(e,t=Date.now(),n){var i;let{sessionIdleMs:o}=no(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 oo(e,t=null,n){let{maxRecentTurns:o}=no(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 st(e,t=Date.now(),n){return Ne(e,t,n),e.lastActivityAt=t,oo(e.turns,e.summary,n)}function vs(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=ei(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=ei(e.summary,s,i),e.turns=e.turns.slice(-n)}}function at(e,t,n,o=Date.now(),i){var l;let r=no(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>Me&&(e.uiArchive=e.uiArchive.slice(-Me)),e.lastActivityAt=o,vs(e,r))}function Cs(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 ct(e,t,n=Ce,o){Ne(e,Date.now(),o);let i=Cs(e,t),r=Math.max(1,n);return{exchanges:i.slice(-r),hasOlder:i.length>r,totalCount:i.length}}var ue="anon";function lt(e){let t=(e!=null?e:"").trim();if(!t)return ue;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 ut(e,t="public",n=ue){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===ue?o:`${o}/${n}`}function As(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-rt.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 Ss(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Me)){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 sn(e,t,n,o=null,i="public",r=ue){var a,l;let s=ut(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 an(e,t,n=Date.now(),o="public",i=ue){var s;let r=ut(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:ue)!==i)return null;let u={turns:As(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:Ss(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return Ne(u,n,Le(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 cn(e,t,n="public",o=ue){try{await e.removeItem(ut(t,n,o))}catch{}}function $e(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function io(e,t){let n=$e(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function ro(e,t){return io(e,t)}var De=35,dt="rgba(255,255,255,0.1)",pt="#ffffff";function Fe(e){return e==null||Number.isNaN(Number(e))?De:Math.max(0,Math.min(100,Number(e)))}function so(e,t){let n=Fe(t)/100;return n<=0?0:e*(.002+n*.012)}function ft(e){let t=e==null?void 0:e.trim();if(!t)return dt;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))?dt:`rgba(${o},${i},${r},0.12)`}return dt}function mt(e,t,n){let o=e,i=so(e,n),r=ro(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 ln(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function un(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"},ti={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:pt,innerBorderWidth:De,borderWidth:1.5,waveformHeight:26,size:52},ni={size:30,shape:"circle",backgroundColor:te.background,borderColor:te.accent,iconColor:te.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:pt,innerBorderWidth:De,borderWidth:100},gt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},oi={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 We(e){let t=ii(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function dn(e){let t=ii(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function ii(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 ao(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((h,m)=>{let x=Math.max(a,c*h);return{x:p+m*(a+l),y:(e-x)/2,width:a,height:x}}),color:s,radius:a/2}}function pn(e,t){let{bars:n,color:o,radius:i}=ao(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 fn(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 Is=["pill","rounded","square","cloud"];function ri(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 Os(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 ks(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 mn(e,t,n){n&&t.shift(),e.push(...t)}var _s=1.28,Ps=38;function ai(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function lo(e){if(!Number.isFinite(e)||e<=0)return 5;let t=e*.88;return ai(t/Ps,3,7)}function ci(e=5){let l=ai(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];mn(f,ri(6,50,u,p,Math.PI/2,Math.PI*3/2,10),!1);for(let m=0;m<l;m++){let x=6+c+2*c*m;mn(f,Os(x,18,c,14,8),!0)}mn(f,ri(94,50,u,p,-Math.PI/2,Math.PI/2,10),!0);for(let m=l-1;m>=0;m--){let x=6+c+2*c*m;mn(f,ks(x,83,c,12,8),!0)}return`polygon(${f.map(([m,x])=>`${m.toFixed(2)}% ${x.toFixed(2)}%`).join(", ")})`}var uo=ci(5);function po(e){return ci(lo(e))}function bt(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function co(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":Is.includes(t)?t:gt.shape}function yt(e,t){if(e!=null)return`${Math.round(e*t)}px`}function Ue(e){let t=e!=null?e:{},n=gt,o=bt(t.textSize,bt(t.size,n.textSize));return{backgroundColor:co(t.backgroundColor,n.backgroundColor),textColor:co(t.textColor,n.textColor),borderColor:co(t.borderColor,n.borderColor),borderWidth:bt(t.borderWidth,n.borderWidth),shape:hn(t.shape),borderRadius:bt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:bt(t.bubbleScale,n.bubbleScale)}}var fo=38,mo=14,si=4;function xt(e){let t=e.textSize,n=e.bubbleScale,o=Math.round(mo*n),i=Math.round(t*1.25),r=Math.max(Math.round(fo*n),i+si*2);hn(e.shape)==="cloud"&&(r=Math.round(r*_s));let s=Math.max(si,Math.round((r-i)/2));return{fontPx:t,padV:s,padH:o,approxHeight:r}}function Ms(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var li=999;function ho(e,t,n){switch(hn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:li};case"cloud":{let i=Ms(t),r=typeof n=="number"&&n>0?po(n):uo;return{...i,clipPath:r}}default:return{borderRadius:Math.min(e.borderRadius,Math.round(t/2))}}}function gn(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(li*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:yt(r.borderRadius,n),borderTopLeftRadius:yt(r.borderTopLeftRadius,n),borderTopRightRadius:yt(r.borderTopRightRadius,n),borderBottomLeftRadius:yt(r.borderBottomLeftRadius,n),borderBottomRightRadius:yt(r.borderBottomRightRadius,n),clipPath:(s=r.clipPath)!=null?s:"none"}}function bn(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 yn(e){return Math.round(e*.5)}function xn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function vn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function Cn(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]],ui={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 An(e="keyboard"){var t;return(t=ui[e])!=null?t:ui.keyboard}function Sn(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 Bs=["keyboard","pen","chat"];function He(e){return Bs.includes(e)?e:"keyboard"}var Ae={x:1,y:1};function de(e){if(e==null)return{...Ae};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Ae.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Ae.y}}function go(e){var f,h,m,x,T;let t=de(e.position),n=(f=e.safeAreaTop)!=null?f:0,o=(h=e.safeAreaBottom)!=null?h:0,i=(m=e.safeAreaLeft)!=null?m: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 wn(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=go({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 vt(e){let t=de(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function Tn(e){let t=de(e);return{x:t.x>=.5?1:0,y:t.y}}function En(e){var h,m,x,T,v;let t=(h=e.safeAreaTop)!=null?h:0,n=(m=e.safeAreaBottom)!=null?m: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 de({x:p,y:f})}var di={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},Ct="rgba(0,0,0,0.72)";function At(e){var o,i,r;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&di[t])return di[t];let n=(i=e.backgroundColor)==null?void 0:i.trim();return n&&n!==Ct?n:(r=e.accentColor)!=null&&r.trim()?e.accentColor.trim():n||Ct}function Rn(e){var s,a,l,c,u,p,f,h;let t=At(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:He(n.icon),backgroundColor:!o||o===Ct?t:o,borderColor:(l=n.borderColor)!=null?l:i,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:Fe(n.innerBorderWidth),borderWidth:$e(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:$e(e.glowIntensity),hapticIntensity:en(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:Fe(e.innerBorderWidth),size:e.size,borderWidth:(p=e.borderWidth)!=null?p:2,waveformHeight:(f=e.waveformHeight)!=null?f:26,waveformColor:(h=e.waveformColor)!=null?h:e.accentColor,keyboardChip:r}}function St(e){var n,o;return{theme:Rn(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:de(e.orbTheme.screenPosition)}}var Ns=/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|0\.0\.0\.0$)/;function bo(e){let t=(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"");return t?t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="::"||t.endsWith(".local")?!0:Ns.test(t):!1}function In(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:!bo(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 Na=15e3,$a=12e3;async function On(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 pi(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 fi(e){var r,s;let t=e.baseUrl.replace(/\/$/,""),n=(r=e.turnTimeoutMs)!=null?r:Na,o=(s=e.ttsTimeoutMs)!=null?s:$a;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 m,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};(m=a.appType)!=null&&m.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 On(`${t}/assistant/chat`,{method:"POST",headers:i(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await pi(u);let p;try{p=await u.json()}catch{throw new V("invalid_response")}let f=typeof p.task_status=="string"?p.task_status:"",h=f==="in_progress"||f==="blocked"?f:"complete";return{reply:((A=p.reply)!=null?A:"").trim(),audioBase64:(N=p.audio_base64)!=null?N:null,action:_t(p.action),wasTruncated:p.was_truncated===!0,taskStatus:h}},async previewTts(a,l){var c;try{let u=await On(`${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 On(`${t}/health`,{method:"GET",headers:i()},5e3)}catch{}},async fetchPublishedConfig(){let a=await On(`${t}/v1/client/config`,{method:"GET",headers:i()},8e3);if(!a.ok)throw await pi(a);return await a.json()}}}function yo(e,t){let n=Gt(e,t);return{manifestVersion:n.version,manifestRoutes:Pt(n),manifestActions:Mt(n),appName:n.appName,appDescription:n.appDescription,...n.appType?{appType:n.appType}:{},...n.appFlow?{appFlow:n.appFlow}:{}}}function Da(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 mi(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,h;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}:{},...(h=e.headers)!=null?h:{}}}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=Da(p);if(f.length!==0){for(let h of f)i.push(h);i.length>=o?a():l()}}}}var Fa="BACK";function Wa(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function hi(e){let t=null,n=!1;return{navigate(o){if(!o||o===Fa){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():Wa()},setCurrentRoute(o){t=o}}}function Ua(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 gi(e={}){let t=Ua(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 Ha(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 Va(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 bi(){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 yi(){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 xi(e={}){let t=bi(),n=null,o="",i=null,r=!1,s=!1,a=null,l=null,c=null,u=!1,p=!1,f=[],h="",m=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=bi();if(!O||!u||p)return;if(typeof document!="undefined"&&document.hidden){S();return}let b=new O;c=b,b.lang=h,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 q=J[0];$=`${$} ${(F=q==null?void 0:q.transcript)!=null?F:""}`.trim()}let L=Jt($,f);if(!L.matched)return;p=!0;let X=m;v(),X==null||X.onDetected(L.command)},b.onerror=R=>{var $;R.error==="aborted"||R.error==="no-speech"||!u||p||($=m==null?void 0:m.onError)==null||$.call(m,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 j(){i&&(clearTimeout(i),i=null)}function oe(){j(),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,X;if(!t){($=b.onError)==null||$.call(b,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,m=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 q,ge;let P="";for(let fe=F.resultIndex;fe<F.results.length;fe+=1){let be=F.results[fe];if(!be)continue;let Z=be[0],Se=(q=Z==null?void 0:Z.transcript)!=null?q:"";be.isFinal?o=`${o} ${Se}`.trim():P=`${P} ${Se}`.trim()}let J=`${o} ${P}`.trim();J&&((ge=b.onInterim)==null||ge.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,q,ge,fe;j();let F=r,P=o.trim();if(oe(),s){(J=b.onEnd)==null||J.call(b);return}if(F){(q=b.onEnd)==null||q.call(b);return}P?(ge=b.onFinal)==null||ge.call(b,P):(fe=b.onEnd)==null||fe.call(b)};try{R.start()}catch(F){oe(),(X=b.onError)==null||X.call(b,F);return}O.maxSeconds&&O.maxSeconds>0&&(i=setTimeout(()=>{try{R.stop()}catch{}},O.maxSeconds*1e3))},stopListening(){if(j(),n)try{n.stop()}catch{}},cancelListening(){if(j(),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 Ha(R);return new Promise(L=>{let X=null,F=()=>{X&&(clearInterval(X),X=null)};try{R.cancel();let P=new SpeechSynthesisUtterance(O);P.lang=b.locale;let J=Va($,b.locale);J&&(P.voice=J),P.volume=1,P.rate=1,P.pitch=1,l=P;let q=()=>{F(),P.onstart=null,P.onend=null,P.onerror=null,l===P&&(l=null),L()};P.onend=q,P.onerror=q,R.speak(P),R.resume(),X=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&&!yi()},isWakeWordListening(){return u},async startWakeWordDetection(O,b){var R;if(!t||yi()){(R=b.onError)==null||R.call(b,new Error("wake_word_unsupported"));return}f=O.phrases,h=O.locale,m=b,u=!0,p=!1,I()},stopWakeWordDetection(){u=!1,p=!1,m=null,v()}}}function vi(){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 Ai(){return{isSupported(){return vi()!==null&&Ci()},async requestCredentials(){let e=vi();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 xo(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 kn(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 Si(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 za(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function wi(e){var a,l,c,u,p,f,h;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 m=za(n,t.intent);if(!((m==null?void 0:m.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=m==null?void 0:m.voiceConfirmation)!=null?a:"standard",S=v==="strict"?(u=m==null?void 0:m.confirmationPhrase)!=null?u:ee(r.strictConfirmationPhraseTemplate,{label:((c=(l=m==null?void 0:m.label)!=null?l:t.intent)!=null?c:"").toLowerCase()}):null;return{kind:"needs-confirmation",pending:{action:t,context:i,question:(f=(p=m==null?void 0:m.confirmationMessageTemplate)!=null?p:t.confirmationMessage)!=null?f:r.confirmationFallbackQuestion,voiceMode:v,strictPhrase:S,remainingConfirmations:(m==null?void 0:m.doubleConfirmation)===!0?2:1,userMessage:s,intent:(h=t.intent)!=null?h:""}}}return{kind:"noop"}}function Ti(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?rn(i,t.strictPhrase,n):on(i,n)}var Ei={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},Ri={enabled:!1,maxSteps:6,dwellMs:450};var Oi={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"},Ga={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"},Ii={en:Oi,es:Ga};function Ya(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function ki(e,t={}){var r,s,a,l,c;let n=(r=t.catalogs)!=null?r:{},o=Ya(e),i=(c=(l=(a=(s=n[e])!=null?s:Ii[e])!=null?a:n[o])!=null?l:Ii[o])!=null?c:Oi;return t.overrides?{...i,...t.overrides}:i}function Ka(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var ja=e=>new Promise(t=>setTimeout(t,e)),Ve=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=Ka();this.sessionStarted=!1;this.conversation=Be();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=Ce;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=ki(t.locale,t.uiMessages),this.lexicon=(r=t.confirmationLexicon)!=null?r:tn(t.locale),this.sanitizer=(s=t.sanitizer)!=null?s:jt(),this.telemetry=Zt(t.telemetry),this.consent=qt({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?Ai():t.credentialAutofill,this.executor=Vt({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...Ei,...t.timings};let n={...Ri,...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=kn({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Wt(f,t.manifest,this.messages))}),this.speech=Si({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=lt((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 an(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(){sn(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=lt((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=Be(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=Be(),this.lastExchange=null,cn(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=ct(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||!ct(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=Ce,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Le(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=Ce}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=Ti(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 wi({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,h,m;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 j=(Q=t.action.intent)!=null?Q:"",oe=Yt(B.data);c={type:t.action.type,intent:j,label:t.action.type==="navigate"?this.routeLabel(j):this.actionLabel(j),success:!0,...oe?{data:oe}:{}},u=`${t.action.type}:${j}`,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||"";h={type:"execute",intent:B,label:this.actionLabel(B),success:!0},m=`execute:${B}`}return{reply:r,audioBase64:s,hasPending:p,canContinue:l,lastStep:c,actionKey:u,pendingInProgress:f,pendingStep:h,pendingKey:m}}async runChainLoop(t){var r,s,a,l,c,u,p,f,h,m,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 ja(this.chaining.dwellMs),this.pending!=null)return;let T=this.config.navigation.getCurrentRoute(),v=this.screenStore.getSnapshot(),S=ot((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=st(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(),...yo(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=xo(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(),at(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=(m=(f=C.lastStep)==null?void 0:f.intent)!=null?m:(h=C.pendingStep)==null?void 0:h.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,h,m,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=ot((m=(h=(f=this.config).getUserContextText)==null?void 0:h.call(f))!=null?m:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),s=r?this.sanitizer(r).sanitized:void 0,a=st(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(),...yo(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=xo(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(),at(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 Xa="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(Xa,e);for(let[o,i]of Object.entries(t))n.setAttribute(o,String(i));return n}function Mi(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:i,fillRadius:r,midPx:s}=mt(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,h=document.createElement("div");Object.assign(h.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?ln(i,e.exteriorColor):""});let m=document.createElement("div");Object.assign(m.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?un(e.fillDiameter):""}),m.appendChild(x),h.appendChild(m),{root:h,fill:x}}function qa(e,t){let{bars:n,color:o,radius:i}=pn(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,h)=>{let m=fn(p,h,f.baseHalfHeight,f.maxHalfHeight);s[h].setAttribute("y",(f.centerY-m).toFixed(2)),s[h].setAttribute("height",(2*m).toFixed(2))})};a=requestAnimationFrame(c)},stop(){cancelAnimationFrame(a)}}}var Qa=9,Ja=[.25,.45,.65,.85,1,.85,.65,.45,.25],_i=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],Za=26;function ec(e,t){let n=t/Za,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 m=0;m<Qa;m++){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,h=m=>{l=requestAnimationFrame(h),!(m-u<80)&&(u=m,c+=.22,a.forEach((x,T)=>{var S,I,E;let v;if(p<.05){let g=(Math.sin(c+((S=_i[T])!=null?S:0))+1)/2;v=f+g*(.22-f)}else{let g=Math.sin(c*2.3+((I=_i[T])!=null?I:0))*.18+.82+Math.random()*.18;v=f+p*((E=Ja[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(h))},stop(){l&&cancelAnimationFrame(l),l=0},setVolume(m){p=m}}}var Pi=8,Li=68,tc=360-Li,nc=Li/2,oc=[.15,.25,.35,.5,.65,.78,.88,1];function ic(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=tc/(Pi-1);for(let l=0;l<Pi;l++){let c=nc+s*l;r.appendChild(ne("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(a=oc[l])!=null?a:1,transform:`rotate(${c} 20 20)`}))}return i.appendChild(r),o.appendChild(i),o}var rc=118/380,sc=30/380,ac=2/380;function cc(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*rc,i=Math.max(1,e*ac);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*sc,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 lc(e,t,n){let o=An(e),i=1.8,{x:r,y:s}=Sn(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 h=o.chatTail;l.appendChild(ne("polygon",{points:`${h.left},${p} ${h.tipX},${h.tipY} ${h.right},${p}`,fill:n}))}for(let{y:h,w:m}of o.chatLines)l.appendChild(ne("line",{x1:u-m/2,y1:h,x2:u+m/2,y2:h,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 Bi(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%":`${vn(o,n)}px`,r=(v=t.backgroundColor)!=null?v:e.backgroundColor,s=(S=t.borderColor)!=null?S:e.accentColor,a=Cn(t.iconColor,r,e.accentColor),l=He(t.icon),c=xn((I=t.iconScale)!=null?I:1),u=Math.round(yn(n)*c),p=mt(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:h,fill:m}=Mi({fillDiameter:n,borderRadius:i,exteriorColor:s,exteriorWidthSlider:(g=t.borderWidth)!=null?g:100,interiorColor:ft(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"}),m.appendChild(C)}else m.appendChild(lc(l,u,a));return f.appendChild(h),f}function Ni(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=At({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,h=ft(n.innerBorderColor);s==null||s.stop(),s=null,a==null||a.stop(),a=null,t.replaceChildren();let{root:m,fill:x}=Mi({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(I=n.glowIntensity)!=null?I:ce.glowIntensity,interiorColor:h,interiorWidthSlider:n.innerBorderWidth,fill:p});r=x,t.appendChild(m),c()}function c(){var f,h;if(!r)return;let u=(f=n.size)!=null?f:ce.size,p=(h=n.waveformColor)!=null?h:"#ffffff";if(s==null||s.stop(),s=null,a==null||a.stop(),a=null,r.replaceChildren(),t.style.animation="",o==="thinking"){r.appendChild(ic(u,p));return}if(o==="listening"){s=ec(p,Math.round(u*.46)),s.setVolume(i),r.appendChild(s.el),s.start();return}if(n.logoDataUrl){let m=document.createElement("img");m.src=n.logoDataUrl,m.alt="",m.draggable=!1,m.addEventListener("dragstart",x=>x.preventDefault()),Object.assign(m.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(m);return}if(o==="speaking"){r.appendChild(cc(u,p));return}o==="idle"&&(a=qa(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 vo="fyodos:published-config:v1";function uc(){try{if(typeof window=="undefined"||!window.localStorage)return null;let e=window.localStorage.getItem(vo);return e?JSON.parse(e):null}catch{return null}}function $i(e){try{if(typeof window=="undefined"||!window.localStorage)return;e?window.localStorage.setItem(vo,JSON.stringify(e)):window.localStorage.removeItem(vo)}catch{}}function Di(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:Ue(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 Fi(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,i=uc();i&&t.onChange(Di(St(i),i));let r=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange(Di(St(c.published),c.published)),$i(c.published)):(t.onChange(null),$i(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 dc(){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 pc(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function wt(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Wi(e){let t=dc(),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=pc(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 h=`${u}${f}`.trimStart(),m=i?`${i}${i.endsWith(" ")?"":" "}${h}`:h;l(m)},c.onend=()=>{o=!1,n=null},c.onerror=()=>{o=!1,n=null},n=c,o=!0,c.start()}}}var Ui="fyodos-orb-styles",fc=`
3
+ `,a=o-r.length-s.length;return a<=n.truncationSuffix.length?_e(r,{...n,maxChars:o}):r+s+_e(i,{...n,maxChars:a})}var Xn=[{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 qn(e={}){var r,i;let t=((r=e.countryPacks)!=null?r:[]).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]=Xn;return[n,...(i=e.customPatterns)!=null?i:[],...t,...o]}function jt(e={}){let t=qn(e);return n=>{let o=n,r=[];for(let{type:i,regex:s,replacement:a}of t)s.test(o)&&(r.push(i),o=o.replace(s,a)),s.lastIndex=0;return o=o.replace(/\+\s?\[REDACTED:PHONE\]/g,"[REDACTED:PHONE]"),{sanitized:o,redactions:r}}}function ji(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Xi(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function qi(e){return Xi(e)==="es"}function Qn(e){return e.replace(/^[¿¡]+/,"").replace(/[?!.…]+$/,"").trim()}function Qi(e,t,n){var f;let o=Qn(e),r=Qn(t),i=r.match(/\{(\w+)\}/);if(!i||i.index==null)return null;let s=i[1],a=r.slice(0,i.index).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=r.slice(i.index+i[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 Ji=[[/^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"]],Zi=[[/^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 Xt(e,t){var c;let n=ji(e);if(!n)return"";let o=(c=t==null?void 0:t.locale)!=null?c:"en",r=qi(o),i=t==null?void 0:t.messages,s=Qn(n);if(i){let u=r?[[i.bubblePromptFromExample,"Quiero {phrase}"],[i.bubblePromptFromAction,"Quiero {action}"],[i.bubblePromptFromLabel,"Quiero ir a {label}"]]:[[i.bubblePromptFromExample,"I want to {phrase}"],[i.bubblePromptFromAction,"I want to {action}"],[i.bubblePromptFromLabel,"I want to open {label}"]];for(let[p,f]of u){let m=Qi(n,p,f);if(m)return m}}let a=r?Zi:Ji;for(let[u,p]of a)if(u.test(s))return s.replace(u,p);return r?`Quiero ${s.charAt(0).toLowerCase()+s.slice(1)}`:`I want to ${s.charAt(0).toLowerCase()+s.slice(1)}`}function Jn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function qt(e){var o;let t=Jn(e.appId,(o=e.version)!=null?o:1),{storage:n}=e;return{storageKey:t,async hasConsented(){try{let r=await n.getItem(t);return r?JSON.parse(r).granted===!0:!1}catch{return!1}},async grant(){let r=JSON.stringify({granted:!0,grantedAt:new Date().toISOString()});await n.setItem(t,r)},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 Jt(e,t){let n=Qt(e);if(!n)return{matched:!1,command:""};for(let o of t){let r=Qt(o);if(!r)continue;let i=n.indexOf(r);if(i===-1)continue;return{matched:!0,command:n.slice(i+r.length).trim(),phrase:r}}return{matched:!1,command:""}}function Zt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var Xo=40;function en(e){return typeof e!="number"||Number.isNaN(e)?Xo:Math.max(0,Math.min(100,Math.round(e)))}function qo(e,t){let n=en(t);if(n<=0)return 0;let o=n/100,r=i=>Math.max(1,Math.round(i*o));switch(e){case"response":return[0,r(12),40,r(12)];case"orbTap":return r(18);case"listenStart":return r(14);case"listenStop":return r(8);default:return r(10)}}function Zn(e){let t=()=>typeof e=="function"?e():e;return{trigger(n){try{let r=globalThis.navigator,i=qo(n,t());!(i===0||Array.isArray(i)&&i.every(a=>a===0))&&r&&typeof r.vibrate=="function"&&r.vibrate(i)}catch{}}}}var rt={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 tn(e){var o,r,i;let t=(r=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?r:e.toLowerCase(),n=(i=rt[e])!=null?i:rt[t];if(!n)throw new Error(`[fyodos] No confirmation lexicon for locale "${e}". Built-in locales: ${Object.keys(rt).join(", ")}. Pass a custom ConfirmationLexicon for your locale.`);return n}function Pe(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Qo(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function eo(e,t){let n=Pe(e);return n?t.affirmative.some(o=>Qo(n,Pe(o))):!1}function nn(e,t){let n=Pe(e);return n?t.negative.some(o=>Qo(n,Pe(o))):!1}function on(e,t){let n=nn(e,t),o=eo(e,t);return n?"negative":o?"affirmative":"ambiguous"}function xs(e,t){return t?` ${e} `.includes(` ${t} `):!1}function rn(e,t,n){let o=Pe(e);return o?nn(e,n)?"negative":xs(o,Pe(t))?"affirmative":"ambiguous":"ambiguous"}var to={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},it={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Le(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 Ce=5,Me=200;function Jo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Zo(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function er(e,t,n){let o=t.map(r=>r.role==="user"?`User: ${Jo(r.content,120)}`:`Assistant: ${Jo(r.content,120)}`).join(" | ");return Zo(e?`${e} | ${o}`:o,n)}function no(e){return{...to,...e}}function Be(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function Ne(e,t=Date.now(),n){var r;let{sessionIdleMs:o}=no(n);return e.turns.length===0&&!e.summary&&!((r=e.uiArchive)!=null&&r.length)?(e.lastActivityAt=t,!1):t-e.lastActivityAt<=o?!1:(e.turns=[],e.summary=null,e.uiArchive=[],e.lastActivityAt=t,!0)}function oo(e,t=null,n){let{maxRecentTurns:o}=no(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 st(e,t=Date.now(),n){return Ne(e,t,n),e.lastActivityAt=t,oo(e.turns,e.summary,n)}function vs(e,t){let{maxRecentTurns:n,summarizeAfterTurns:o,maxSummaryChars:r,maxStoredTurns:i}=t;if(e.turns.length>o){let s=e.turns.length-n,a=e.turns.slice(0,s);e.summary=er(e.summary,a,r),e.turns=e.turns.slice(s)}if(e.turns.length>i){let s=e.turns.slice(0,e.turns.length-n);e.summary=er(e.summary,s,r),e.turns=e.turns.slice(-n)}}function at(e,t,n,o=Date.now(),r){var l;let i=no(r),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>Me&&(e.uiArchive=e.uiArchive.slice(-Me)),e.lastActivityAt=o,vs(e,i))}function Cs(e,t){var i,s,a,l;let n;if((i=e.uiArchive)!=null&&i.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 ct(e,t,n=Ce,o){Ne(e,Date.now(),o);let r=Cs(e,t),i=Math.max(1,n);return{exchanges:r.slice(-i),hasOlder:r.length>i,totalCount:r.length}}var ue="anon";function lt(e){let t=(e!=null?e:"").trim();if(!t)return ue;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 ut(e,t="public",n=ue){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===ue?o:`${o}/${n}`}function As(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-it.maxStoredTurns)){let o=n==null?void 0:n.role,r=n==null?void 0:n.content;(o==="user"||o==="assistant")&&typeof r=="string"&&r&&t.push({role:o,content:r})}return t}function Ss(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Me)){let o=n==null?void 0:n.userText,r=n==null?void 0:n.replyText;typeof o=="string"&&o&&typeof r=="string"&&t.push({userText:o,replyText:r})}return t}async function sn(e,t,n,o=null,r="public",i=ue){var a,l;let s=ut(t,r,i);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:i};await e.setItem(s,JSON.stringify(u))}catch{}}async function an(e,t,n=Date.now(),o="public",r=ue){var s;let i=ut(t,o,r);try{let a=await e.getItem(i);if(!a)return null;let l=JSON.parse(a);if((l==null?void 0:l.v)!==1)return await e.removeItem(i),null;if((typeof l.owner=="string"?l.owner:ue)!==r)return null;let u={turns:As(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:Ss(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return Ne(u,n,Le(p))||u.turns.length===0&&!u.summary&&!((s=u.uiArchive)!=null&&s.length)?(await e.removeItem(i),null):(u.lastActivityAt=n,u)}catch{return null}}async function cn(e,t,n="public",o=ue){try{await e.removeItem(ut(t,n,o))}catch{}}function De(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function ro(e,t){let n=De(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function io(e,t){return ro(e,t)}var $e=35,dt="rgba(255,255,255,0.1)",pt="#ffffff";function Fe(e){return e==null||Number.isNaN(Number(e))?$e:Math.max(0,Math.min(100,Number(e)))}function so(e,t){let n=Fe(t)/100;return n<=0?0:e*(.002+n*.012)}function ft(e){let t=e==null?void 0:e.trim();if(!t)return dt;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),r=parseInt(n.slice(3,5),16),i=parseInt(n.slice(5,7),16);return[o,r,i].some(s=>Number.isNaN(s))?dt:`rgba(${o},${r},${i},0.12)`}return dt}function ht(e,t,n){let o=e,r=so(e,n),i=io(e,t),s=o+2*r,a=o+2*r+2*i;return{fillPx:o,interiorPx:r,exteriorPx:i,totalPx:a,fillRadius:o/2,midPx:s}}function ln(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function un(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"},tr={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:pt,innerBorderWidth:$e,borderWidth:1.5,waveformHeight:26,size:52},nr={size:30,shape:"circle",backgroundColor:te.background,borderColor:te.accent,iconColor:te.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:pt,innerBorderWidth:$e,borderWidth:100},gt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},or={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 We(e){let t=rr(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function dn(e){let t=rr(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function rr(e){if(!e)return null;let t=e.trim().toLowerCase(),n,o,r,i=t.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/);if(i){let s=i[1];s.length===3?(n=parseInt(s[0]+s[0],16),o=parseInt(s[1]+s[1],16),r=parseInt(s[2]+s[2],16)):(n=parseInt(s.slice(0,2),16),o=parseInt(s.slice(2,4),16),r=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]),r=Number(s[3])}return(.299*n+.587*o+.114*r)/255}var mt={bars:[.42,.72,1,.72,.42],color:"#eaf1ff",barWidthRatio:.06,gapRatio:.05,heightRatio:.4};function ao(e,t){let{bars:n,barWidthRatio:o,gapRatio:r,heightRatio:i}=mt,s=(t!=null?t:"").trim()||mt.color,a=e*o,l=e*r,c=e*i,u=n.length*a+(n.length-1)*l,p=(e-u)/2;return{bars:n.map((m,h)=>{let g=Math.max(a,c*m);return{x:p+h*(a+l),y:(e-g)/2,width:a,height:g}}),color:s,radius:a/2}}function pn(e,t){let{bars:n,color:o,radius:r}=ao(e,t),i=e/2,s=e*mt.heightRatio/2;return{color:o,radius:r,bars:n.map(a=>({...a,baseHalfHeight:a.height/2,centerY:i,maxHalfHeight:s}))}}function fn(e,t,n,o){let r=.5+.5*((.5+.5*Math.sin(e*1.6))*.6+(.5+.5*Math.sin(e*.9+1.1))*.4),i=.35+.65*(.5+.5*Math.sin(e*7+t*.95))*(.55+.45*Math.sin(e*3.1+t*.6)),s=n*(.5+i*r);return Math.max(n*.35,Math.min(s,o))}var Is=["pill","rounded","square","cloud"];function ir(e,t,n,o,r,i,s){let a=[];for(let l=0;l<=s;l++){let c=r+(i-r)*l/s;a.push([e+n*Math.cos(c),t+o*Math.sin(c)])}return a}function Os(e,t,n,o,r){let i=[];for(let s=0;s<=r;s++){let a=Math.PI-Math.PI*s/r;i.push([e+n*Math.cos(a),t-o*Math.sin(a)])}return i}function ks(e,t,n,o,r){let i=[];for(let s=0;s<=r;s++){let a=Math.PI*s/r;i.push([e+n*Math.cos(a),t+o*Math.sin(a)])}return i}function hn(e,t,n){n&&t.shift(),e.push(...t)}var _s=1.28,Ps=38;function ar(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function lo(e){if(!Number.isFinite(e)||e<=0)return 5;let t=e*.88;return ar(t/Ps,3,7)}function cr(e=5){let l=ar(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];hn(f,ir(6,50,u,p,Math.PI/2,Math.PI*3/2,10),!1);for(let h=0;h<l;h++){let g=6+c+2*c*h;hn(f,Os(g,18,c,14,8),!0)}hn(f,ir(94,50,u,p,-Math.PI/2,Math.PI/2,10),!0);for(let h=l-1;h>=0;h--){let g=6+c+2*c*h;hn(f,ks(g,83,c,12,8),!0)}return`polygon(${f.map(([h,g])=>`${h.toFixed(2)}% ${g.toFixed(2)}%`).join(", ")})`}var uo=cr(5);function po(e){return cr(lo(e))}function bt(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function co(e,t){return typeof e=="string"&&e.trim()?e:t}function mn(e){let t=String(e!=null?e:"").toLowerCase();return t==="circle"||t==="round"?"cloud":Is.includes(t)?t:gt.shape}function yt(e,t){if(e!=null)return`${Math.round(e*t)}px`}function Ue(e){let t=e!=null?e:{},n=gt,o=bt(t.textSize,bt(t.size,n.textSize));return{backgroundColor:co(t.backgroundColor,n.backgroundColor),textColor:co(t.textColor,n.textColor),borderColor:co(t.borderColor,n.borderColor),borderWidth:bt(t.borderWidth,n.borderWidth),shape:mn(t.shape),borderRadius:bt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:bt(t.bubbleScale,n.bubbleScale)}}var fo=38,ho=14,sr=4;function xt(e){let t=e.textSize,n=e.bubbleScale,o=Math.round(ho*n),r=Math.round(t*1.25),i=Math.max(Math.round(fo*n),r+sr*2);mn(e.shape)==="cloud"&&(i=Math.round(i*_s));let s=Math.max(sr,Math.round((i-r)/2));return{fontPx:t,padV:s,padH:o,approxHeight:i}}function Ms(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var lr=999;function mo(e,t,n){switch(mn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:lr};case"cloud":{let r=Ms(t),i=typeof n=="number"&&n>0?po(n):uo;return{...r,clipPath:i}}default:return{borderRadius:Math.min(e.borderRadius,Math.round(t/2))}}}function gn(e,t,n=1,o){var s;let r=mn(e.shape),i=mo({...e,shape:r},t,o);if(r==="pill"){let a=`${Math.round(lr*n)}px`;return{borderRadius:a,borderTopLeftRadius:a,borderTopRightRadius:a,borderBottomLeftRadius:a,borderBottomRightRadius:a,clipPath:"none"}}return r==="square"?{borderRadius:"0px",borderTopLeftRadius:"0px",borderTopRightRadius:"0px",borderBottomLeftRadius:"0px",borderBottomRightRadius:"0px",clipPath:"none"}:{borderRadius:yt(i.borderRadius,n),borderTopLeftRadius:yt(i.borderTopLeftRadius,n),borderTopRightRadius:yt(i.borderTopRightRadius,n),borderBottomLeftRadius:yt(i.borderBottomLeftRadius,n),borderBottomRightRadius:yt(i.borderBottomRightRadius,n),clipPath:(s=i.clipPath)!=null?s:"none"}}function bn(e,t){if(!e)return;let n=(o,r)=>{if(!r){e.style.removeProperty(o);return}e.style.setProperty(o,r,"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 yn(e){return Math.round(e*.5)}function xn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function vn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function Cn(e,t,n="#ffffff"){let o=(e!=null?e:n).trim(),r=t.trim();if(!o)return n;let i=s=>{let a=s.toLowerCase();return a.startsWith("#")&&a.length>=7?a.slice(0,7):a};return i(o)===i(r)?n:o}var Ls=[[8,11],[11,11],[14,11],[17,11],[8,14],[11,14],[14,14],[17,14]],ur={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 An(e="keyboard"){var t;return(t=ur[e])!=null?t:ur.keyboard}function Sn(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:r,minY:i,maxX:s,maxY:a}=e.contentBBox;return{x:n/2-(r+s)/2,y:o/2-(i+a)/2}}var Bs=["keyboard","pen","chat"];function He(e){return Bs.includes(e)?e:"keyboard"}var Ae={x:1,y:1};function de(e){if(e==null)return{...Ae};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Ae.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Ae.y}}function go(e){var f,m,h,g,R;let t=de(e.position),n=(f=e.safeAreaTop)!=null?f:0,o=(m=e.safeAreaBottom)!=null?m:0,r=(h=e.safeAreaLeft)!=null?h:0,i=(g=e.safeAreaRight)!=null?g:0,s=(R=e.margin)!=null?R:16,a=e.orbDiameter,l=Math.max(0,e.viewportWidth-r-i-2*s-a),c=Math.max(0,e.viewportHeight-n-o-2*s-a),u=r+s+t.x*l,p=n+s+t.y*c;return{right:e.viewportWidth-u-a,bottom:e.viewportHeight-p-a}}function wn(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,r=(f=e.edgeGap)!=null?f:8,i=go({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-i.right-o,a=n-i.bottom-o,l=Math.max(r,t-o-r),c=Math.max(r,n-o-r);return{left:Math.min(l,Math.max(r,s)),top:Math.min(c,Math.max(r,a))}}function vt(e){let t=de(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function Tn(e){let t=de(e);return{x:t.x>=.5?1:0,y:t.y}}function En(e){var m,h,g,R,v;let t=(m=e.safeAreaTop)!=null?m:0,n=(h=e.safeAreaBottom)!=null?h:0,o=(g=e.safeAreaLeft)!=null?g:0,r=(R=e.safeAreaRight)!=null?R:0,i=(v=e.margin)!=null?v:16,s=e.orbDiameter,a=Math.max(0,e.viewportWidth-o-r-2*i-s),l=Math.max(0,e.viewportHeight-t-n-2*i-s),c=e.centerX-s/2,u=e.centerY-s/2,p=a>0?(c-o-i)/a:0,f=l>0?(u-t-i)/l:0;return de({x:p,y:f})}var dr={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},Ct="rgba(0,0,0,0.72)";function At(e){var o,r,i;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&dr[t])return dr[t];let n=(r=e.backgroundColor)==null?void 0:r.trim();return n&&n!==Ct?n:(i=e.accentColor)!=null&&i.trim()?e.accentColor.trim():n||Ct}function Rn(e){var s,a,l,c,u,p,f,m;let t=At(e),n=e.keyboardChip,o=(s=n==null?void 0:n.backgroundColor)==null?void 0:s.trim(),r=(a=e.glowColor)!=null?a:e.accentColor,i=n?{...n,icon:He(n.icon),backgroundColor:!o||o===Ct?t:o,borderColor:(l=n.borderColor)!=null?l:r,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:Fe(n.innerBorderWidth),borderWidth:De(n.borderWidth)}:void 0;return{accentColor:e.accentColor,backgroundColor:t,glowColor:r,colorKey:e.colorKey,glowKey:e.glowKey,speed:(u=e.speed)!=null?u:42,glowIntensity:De(e.glowIntensity),hapticIntensity:en(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:Fe(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:i}}function St(e){var n,o;return{theme:Rn(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:de(e.orbTheme.screenPosition)}}var Ns=/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|0\.0\.0\.0$)/;function bo(e){let t=(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"");return t?t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="::"||t.endsWith(".local")?!0:Ns.test(t):!1}function In(e,t=!1,n){var i;if(!e||t)return!1;let o=globalThis.location,r=n!=null?n:o?(i=o.hostname)!=null?i:"":null;return r==null?!1:!bo(r)}var V=class extends Error{constructor(t,n,o){super(n!=null?n:t),this.name="AgentApiError",this.code=t,this.status=o}};var Na=15e3,Da=12e3;async function On(e,t,n,o){let r=new AbortController,i=!1,s=setTimeout(()=>{i=!0,r.abort()},n);o&&(o.aborted?r.abort():o.addEventListener("abort",()=>r.abort()));try{return await fetch(e,{...t,signal:r.signal})}catch(a){if(i)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 pr(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=t.error==="quota_exceeded"||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 fr(e){var i,s;let t=e.baseUrl.replace(/\/$/,""),n=(i=e.turnTimeoutMs)!=null?i:Na,o=(s=e.ttsTimeoutMs)!=null?s:Da;function r(){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,g,R,v,A,I,T,b,C,S,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()),(g=a.appFlow)!=null&&g.trim()&&(c.app_flow=a.appFlow.trim()),a.voice&&(c.voice=a.voice),(R=a.screenContext)!=null&&R.trim()&&(c.screen_context=a.screenContext.trim()),(v=a.currentRoute)!=null&&v.trim()&&(c.current_route=a.currentRoute.trim()),(A=a.conversationHistory)!=null&&A.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()),(T=a.llmModel)!=null&&T.trim()&&(c.llm_model=a.llmModel.trim()),(b=a.sessionId)!=null&&b.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 On(`${t}/assistant/chat`,{method:"POST",headers:r(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await pr(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:((S=p.reply)!=null?S:"").trim(),audioBase64:(N=p.audio_base64)!=null?N:null,action:_t(p.action),wasTruncated:p.was_truncated===!0,taskStatus:m}},async previewTts(a,l){var c;try{let u=await On(`${t}/assistant/preview-tts`,{method:"POST",headers:r(),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 On(`${t}/health`,{method:"GET",headers:r()},5e3)}catch{}},async fetchPublishedConfig(){let a=await On(`${t}/v1/client/config`,{method:"GET",headers:r()},8e3);if(!a.ok)throw await pr(a);return await a.json()}}}function yo(e,t){let n=Gt(e,t);return{manifestVersion:n.version,manifestRoutes:Pt(n),manifestActions:Mt(n),appName:n.appName,appDescription:n.appDescription,...n.appType?{appType:n.appType}:{},...n.appFlow?{appFlow:n.appFlow}:{}}}function $a(e){var o,r;let t=(o=e.intentDetected)!=null?o:null,n=(r=e.sessionId)!=null?r:null;switch(e.eventType){case"agent_session_started":return[{type:"session",session_id:n}];case"action_executed":{let i=[{type:"action",intent:t,session_id:n}];return e.actionExecuted!=null&&e.actionExecuted.confirmed===!0&&i.push({type:"confirmation_completed",intent:t,session_id:n}),i}case"action_confirmation_requested":return[{type:"confirmation_requested",intent:t,session_id:n}];default:return[]}}function hr(e){var c,u;let t=e.baseUrl.replace(/\/$/,""),n=(c=e.flushIntervalMs)!=null?c:4e3,o=(u=e.maxBatch)!=null?u:20,r=[],i=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(i&&(clearTimeout(i),i=null),r.length===0)return;let p=r;r=[],(async()=>{try{await fetch(`${t}/v1/agent/events`,{method:"POST",headers:s(),body:JSON.stringify({events:p})})}catch{}})()}function l(){i||(i=setTimeout(a,n))}return{logEvent(p){let f=$a(p);if(f.length!==0){for(let m of f)r.push(m);r.length>=o?a():l()}}}}var Fa="BACK";function Wa(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function mr(e){let t=null,n=!1;return{navigate(o){if(!o||o===Fa){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():Wa()},setCurrentRoute(o){t=o}}}function Ua(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 gr(e={}){let t=Ua(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 Ha(e){let t=e.getVoices();return t.length?Promise.resolve(t):new Promise(n=>{let o=!1,r=()=>{o||(o=!0,n(e.getVoices()))};try{e.addEventListener("voiceschanged",r,{once:!0})}catch{}setTimeout(r,600)})}function Va(e,t){var r,i,s,a,l;if(!e.length)return;let n=t.toLowerCase(),o=(r=n.split("-")[0])!=null?r:n;return(l=(a=(s=(i=e.find(c=>{var u;return((u=c.lang)==null?void 0:u.toLowerCase())===n}))!=null?i: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 br(){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 yr(){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 xr(e={}){let t=br(),n=null,o="",r=null,i=!1,s=!1,a=null,l=null,c=null,u=!1,p=!1,f=[],m="",h=null,g=null;function R(){g&&(clearTimeout(g),g=null)}function v(){if(R(),c){c.onresult=null,c.onerror=null,c.onend=null,c.onstart=null;try{c.abort()}catch{}}c=null}function A(){R(),!(!u||p)&&(g=setTimeout(()=>{g=null,u&&!p&&I()},600))}function I(){let O=br();if(!O||!u||p)return;if(typeof document!="undefined"&&document.hidden){A();return}let y=new O;c=y,y.lang=m,y.continuous=!0,y.interimResults=!0,y.maxAlternatives=1,y.onresult=E=>{var F;if(!u||p)return;let D="";for(let P=0;P<E.results.length;P+=1){let J=E.results[P];if(!J)continue;let X=J[0];D=`${D} ${(F=X==null?void 0:X.transcript)!=null?F:""}`.trim()}let L=Jt(D,f);if(!L.matched)return;p=!0;let j=h;v(),j==null||j.onDetected(L.command)},y.onerror=E=>{var D;E.error==="aborted"||E.error==="no-speech"||!u||p||(D=h==null?void 0:h.onError)==null||D.call(h,new Error(E.error||"wake recognition error"))},y.onend=()=>{!u||p||A()};try{y.start()}catch{A()}}let T=null,b=null;function C(){var y,E;if(typeof window=="undefined")return null;let O=window;return(E=(y=O.AudioContext)!=null?y:O.webkitAudioContext)!=null?E:null}function S(){if(T)return T;let O=C();if(!O)return null;try{T=new O}catch{T=null}return T}function N(O){let y=atob(O),E=y.length,D=new Uint8Array(E);for(let L=0;L<E;L+=1)D[L]=y.charCodeAt(L);return D.buffer}function q(){if(b){try{b.onended=null,b.stop()}catch{}b=null}}async function ce(O){let y=S();if(!y)return!1;try{y.state==="suspended"&&await y.resume();let E=await y.decodeAudioData(N(O));return await new Promise(D=>{q();let L=y.createBufferSource();b=L,L.buffer=E,L.connect(y.destination),L.onended=()=>{L.onended=null,b===L&&(b=null),D(!0)},L.start()})}catch{return!1}}function Q(){r&&(clearTimeout(r),r=null)}function B(){Q(),n&&(n.onresult=null,n.onerror=null,n.onend=null,n.onstart=null),n=null}return{isRecognitionAvailable(){return t!=null},async startListening(O,y){var D,L,j;if(!t){(D=y.onError)==null||D.call(y,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,h=null,v()),n){i=!0;try{n.abort()}catch{}B()}o="",i=!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 X,ge;let P="";for(let fe=F.resultIndex;fe<F.results.length;fe+=1){let be=F.results[fe];if(!be)continue;let Z=be[0],Se=(X=Z==null?void 0:Z.transcript)!=null?X:"";be.isFinal?o=`${o} ${Se}`.trim():P=`${P} ${Se}`.trim()}let J=`${o} ${P}`.trim();J&&((ge=y.onInterim)==null||ge.call(y,J))},E.onerror=F=>{var P;F.error==="aborted"||i||F.error!=="no-speech"&&(s=!0,(P=y.onError)==null||P.call(y,new Error(F.error||"speech recognition error")))},E.onend=()=>{var J,X,ge,fe;Q();let F=i,P=o.trim();if(B(),s){(J=y.onEnd)==null||J.call(y);return}if(F){(X=y.onEnd)==null||X.call(y);return}P?(ge=y.onFinal)==null||ge.call(y,P):(fe=y.onEnd)==null||fe.call(y)};try{E.start()}catch(F){B(),(j=y.onError)==null||j.call(y,F);return}O.maxSeconds&&O.maxSeconds>0&&(r=setTimeout(()=>{try{E.stop()}catch{}},O.maxSeconds*1e3))},stopListening(){if(Q(),n)try{n.stop()}catch{}},cancelListening(){if(Q(),i=!0,n)try{n.abort()}catch{}},primePlayback(){let O=S();if(O)try{O.state==="suspended"&&O.resume();let y=O.createBuffer(1,1,O.sampleRate),E=O.createBufferSource();E.buffer=y,E.connect(O.destination),E.start(0)}catch{}if(!e.disableDeviceTtsFallback&&typeof window!="undefined"&&window.speechSynthesis)try{let y=window.speechSynthesis;y.getVoices(),y.paused&&y.resume();let E=new SpeechSynthesisUtterance(" ");E.volume=0,y.speak(E)}catch{}},async playAudioBase64Mp3(O){if(typeof window!="undefined"&&(this.stopPlayback(),!await ce(O)&&typeof Audio!="undefined"))return new Promise(y=>{try{let E=new Audio(`data:audio/mp3;base64,${O}`);a=E;let D=()=>{E.onended=null,E.onerror=null,a===E&&(a=null),y()};E.onended=D,E.onerror=D,E.play().catch(()=>D())}catch{y()}})},async speakWithDeviceTts(O,y){if(e.disableDeviceTtsFallback||typeof window=="undefined"||!window.speechSynthesis)return;let E=window.speechSynthesis,D=await Ha(E);return new Promise(L=>{let j=null,F=()=>{j&&(clearInterval(j),j=null)};try{E.cancel();let P=new SpeechSynthesisUtterance(O);P.lang=y.locale;let J=Va(D,y.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,E.speak(P),E.resume(),j=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&&!yr()},isWakeWordListening(){return u},async startWakeWordDetection(O,y){var E;if(!t||yr()){(E=y.onError)==null||E.call(y,new Error("wake_word_unsupported"));return}f=O.phrases,m=O.locale,h=y,u=!0,p=!1,I()},stopWakeWordDetection(){u=!1,p=!1,h=null,v()}}}function vr(){if(typeof navigator=="undefined")return null;let e=navigator;return e.credentials&&typeof e.credentials.get=="function"?e.credentials:null}function Cr(){if(typeof window=="undefined")return!1;let e=window;return typeof e.PasswordCredential=="function"&&e.isSecureContext!==!1}function Ar(){return{isSupported(){return vr()!==null&&Cr()},async requestCredentials(){let e=vr();if(!e||!Cr())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 xo(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 kn(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 r,i,s;let n=(r=t==null?void 0:t.snapshot.text)==null?void 0:r.trim();return n||((s=(i=e.routeFallback)==null?void 0:i.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 Sr(e){let{adapter:t,locale:n,maxSeconds:o}=e,r={state:"idle",interimText:"",volumeLevel:0},i=new Set;function s(l){r={...r,...l};for(let c of i)c(r)}function a(){s({state:"idle",interimText:"",volumeLevel:0})}return{getSnapshot(){return r},subscribe(l){return i.add(l),()=>i.delete(l)},async start(){r.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:()=>{r.state!=="idle"&&a()},onError:l=>{var c;a(),(c=e.onError)==null||c.call(e,l)}}))},stop(){r.state==="recording"&&(s({state:"transcribing",volumeLevel:0}),t.stopListening())},cancel(){t.cancelListening(),a()},dispose(){t.cancelListening(),i.clear()}}}function za(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function wr(e){var l,c,u,p,f,m,h;let{action:t,manifest:n,executor:o,context:r,messages:i,userMessage:s,suppressEscort:a}=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 g=za(n,t.intent);if(!((g==null?void 0:g.requireConfirmation)===!0))return{kind:"executed",result:await o.execute(t,r,{suppressEscort:a})};let v=await o.precheck(t,r);if(v.kind==="done")return{kind:"precheck-resolved",result:v.result};let A=(l=g==null?void 0:g.voiceConfirmation)!=null?l:"standard",I=A==="strict"?(p=g==null?void 0:g.confirmationPhrase)!=null?p:ee(i.strictConfirmationPhraseTemplate,{label:((u=(c=g==null?void 0:g.label)!=null?c:t.intent)!=null?u:"").toLowerCase()}):null;return{kind:"needs-confirmation",pending:{action:t,context:r,question:(m=(f=g==null?void 0:g.confirmationMessageTemplate)!=null?f:t.confirmationMessage)!=null?m:i.confirmationFallbackQuestion,voiceMode:A,strictPhrase:I,remainingConfirmations:(g==null?void 0:g.doubleConfirmation)===!0?2:1,userMessage:s,intent:(h=t.intent)!=null?h:""}}}return{kind:"noop"}}function Tr(e,t,n,o={}){if(t.voiceMode==="disabled"||o.silent)return"ambiguous";let r=e.trim();return r.length<2?"ambiguous":t.voiceMode==="strict"&&t.strictPhrase!=null?rn(r,t.strictPhrase,n):on(r,n)}var Er={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},Rr={enabled:!0,maxSteps:6,dwellMs:450};var Or={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"},Ga={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"},Ir={en:Or,es:Ga};function Ya(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function kr(e,t={}){var i,s,a,l,c;let n=(i=t.catalogs)!=null?i:{},o=Ya(e),r=(c=(l=(a=(s=n[e])!=null?s:Ir[e])!=null?a:n[o])!=null?l:Ir[o])!=null?c:Or;return t.overrides?{...r,...t.overrides}:r}function Ka(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var ja=e=>new Promise(t=>setTimeout(t,e)),Ve=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=Ka();this.sessionStarted=!1;this.conversation=Be();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.deferredEscortIntent=null;this.liveActivity=null;this.chainActive=!1;this.bubbleWindowSize=Ce;this.conversationRetentionMinutes=null;this.conversationScope="public";this.removeIdentityListeners=null;this.loadingOlderExchanges=!1;this.loadOlderTimer=null;this.listeners=new Set;this.unsubscribeSpeech=null;var o,r,i,s,a,l,c,u,p;me(t.manifest),this.config=t,this.messages=Dt(t.locale,{catalogs:(o=t.messages)==null?void 0:o.catalogs,overrides:(r=t.messages)==null?void 0:r.overrides}),this.ui=kr(t.locale,t.uiMessages),this.lexicon=(i=t.confirmationLexicon)!=null?i:tn(t.locale),this.sanitizer=(s=t.sanitizer)!=null?s:jt(),this.telemetry=Zt(t.telemetry),this.consent=qt({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?Ar():t.credentialAutofill,this.executor=Vt({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...Er,...t.timings};let n={...Rr,...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=kn({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Wt(f,t.manifest,this.messages))}),this.speech=Sr({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=lt((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 an(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(){sn(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=lt((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=Be(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=Be(),this.lastExchange=null,cn(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",r=ct(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:r.exchanges,hasOlderExchanges:r.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||!ct(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=Ce,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Le(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=Ce}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,r;let n=this.phase;n!==t&&(this.phase=t,(r=(o=this.config).onPhaseChange)==null||r.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 r=n;if(r&&(this.serverTtsUnavailable=!1),!r&&t&&!this.serverTtsUnavailable)try{r=await this.config.backend.previewTts((o=this.getTtsVoice())!=null?o:"",t),r||(this.serverTtsUnavailable=!0)}catch{r=null,this.serverTtsUnavailable=!0}let i=r?this.config.voice.playAudioBase64Mp3(r):t?this.config.voice.speakWithDeviceTts(t,{locale:this.ttsLocale}):Promise.resolve();await this.raceSpeakingWatchdog(i,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(r=>{let i=!1,s=()=>{i||(i=!0,this.clearSpeakTimer(),r())};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 r,i;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:(r=this.actionLabel(t.intent))!=null?r: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:(i=o.pendingStep)!=null?i: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,this.deferredEscortIntent=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=Tr(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 r=`${this.messages.confirmationNotUnderstood} ${n.question}`.trim();this.confirmationMessage=r,this.emit(),await this.speakReply(r,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 i=t==null?void 0:t();o=i==null?null:!!i}catch{o=null}let r;try{let i=n==null?void 0:n();if(i&&typeof i=="object"){let s={};for(let[a,l]of Object.entries(i))typeof l=="boolean"&&(s[a]=l);Object.keys(s).length>0&&(r=s)}}catch{r=void 0}return{authenticated:o,...r?{capabilities:r}:{}}}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,r){var R,v,A,I,T,b,C,S,N,q,ce,Q;let i=t.reply,s=t.audioBase64;i&&(this.serverTtsUnavailable=!s);let a=this.chaining.enabled&&t.taskStatus==="in_progress",l=await wr({action:t.action,manifest:this.config.manifest,executor:this.executor,context:o,messages:this.messages,userMessage:r,suppressEscort:a}),c=!1,u,p,f=!1,m=!1,h,g;if(l.kind==="executed"){let B=l.result;if(B.success&&((R=t.action)==null?void 0:R.type)==="navigate"?this.setActivity({kind:"navigating",label:(I=(A=this.routeLabel((v=t.action.intent)!=null?v:""))!=null?A:t.action.intent)!=null?I:""}):B.success&&!B.recoverable&&((T=t.action)==null?void 0:T.type)==="execute"&&this.setActivity({kind:"executing",label:(S=(C=this.actionLabel((b=t.action.intent)!=null?b:""))!=null?C:t.action.intent)!=null?S:""}),((N=t.action)==null?void 0:N.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}):((q=t.action)==null?void 0:q.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?(i=B.message,s=null):B.success||(i=this.messages.actionFailed,s=null)),t.action&&(t.action.type==="navigate"||t.action.type==="execute")&&B.success&&!B.recoverable){t.action.type==="execute"?this.deferredEscortIntent=a&&(ce=t.action.intent)!=null?ce:null:this.deferredEscortIntent=null;let O=(Q=t.action.intent)!=null?Q:"",y=Yt(B.data);u={type:t.action.type,intent:O,label:t.action.type==="navigate"?this.routeLabel(O):this.actionLabel(O),success:!0,...y?{data:y}:{}},p=`${t.action.type}:${O}`,c=t.taskStatus==="in_progress"}}else if(l.kind==="precheck-resolved")l.result.message&&!l.result.recoverable&&(i=l.result.message,s=null);else if(l.kind==="needs-confirmation"){this.pending={...l.pending,silent:this.silentTurn},this.confirmationReasked=!1,this.confirmationMessage=l.pending.question,this.confirmationVoiceHint=l.pending.voiceMode==="strict"&&l.pending.strictPhrase&&!this.silentTurn?ee(this.messages.strictConfirmationModalHint,{phrase:l.pending.strictPhrase}):null,this.emit(),this.telemetry.logEvent({eventType:"action_confirmation_requested",intentDetected:l.pending.intent,sessionId:this.sessionId}),this.setActivity({kind:"waiting_confirmation"}),f=!0,m=t.taskStatus==="in_progress";let B=l.pending.intent||"";h={type:"execute",intent:B,label:this.actionLabel(B),success:!0},g=`execute:${B}`}return{reply:i,audioBase64:s,hasPending:f,canContinue:c,lastStep:u,actionKey:p,pendingInProgress:m,pendingStep:h,pendingKey:g}}async runChainLoop(t){var i,s,a,l,c,u,p,f,m,h,g;let n=t.step,o=t.lastStep,r=t.visitedKeys;this.setChainActive(!0);try{for(;n<this.chaining.maxSteps;){if(n+=1,this.chaining.dwellMs>0&&await ja(this.chaining.dwellMs),this.pending!=null)return;let R=this.config.navigation.getCurrentRoute(),v=this.screenStore.getSnapshot(),A=ot((a=(s=(i=this.config).getUserContextText)==null?void 0:s.call(i))!=null?a:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),I=A?this.sanitizer(A).sanitized:void 0,T=st(this.conversation,Date.now(),this.conversationOptions);this.setPhase("thinking"),this.setActivity({kind:"thinking"});let b=new AbortController;this.abort=b;let C;try{let S=await this.config.backend.sendTurn({message:t.userMessage,language:this.config.locale,voice:this.getTtsVoice(),screenContext:I,currentRoute:R!=null?R: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(),...yo(this.config.manifest,this.config.registries)},{signal:b.signal});C=await this.applyOutcome(S,R,(c=v==null?void 0:v.context)!=null?c:{},t.userMessage)}catch(S){this.abort=null;let N=S instanceof V&&S.code==="cancelled";if(N)this.phase==="thinking"&&this.setPhase("idle");else{S instanceof V&&S.code==="quota_exceeded"&&((p=(u=this.config).onQuotaExceeded)==null||p.call(u));let q=xo(S,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(),at(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:(g=(h=(f=C.lastStep)==null?void 0:f.intent)!=null?h:(m=C.pendingStep)==null?void 0:m.intent)!=null?g:null,sessionId:this.sessionId,chainStep:n}),C.hasPending){this.chainState=C.pendingInProgress?{userMessage:t.userMessage,step:n,lastStep:o,visitedKeys:r,pendingKey:C.pendingKey,pendingStep:C.pendingStep}:null,this.beginConfirmationVoiceWindow();return}if(this.phase!=="speaking"&&this.setPhase("idle"),C.actionKey&&r.has(C.actionKey)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(C.actionKey&&r.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),this.flushDeferredEscort()}}flushDeferredEscort(){if(this.pending!=null)return;let t=this.deferredEscortIntent;this.deferredEscortIntent=null,t&&this.executor.escortForIntent(t)}async handleTranscript(t){var f,m,h,g,R,v,A,I,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 b;if(this.phase==="thinking"){this.telemetry.logEvent({eventType:"agent_watchdog_reset",sessionId:this.sessionId});let C=(b=this.pendingTurnText)!=null?b:n,S=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:S},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 r=this.screenStore.getSnapshot(),i=ot((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=i?this.sanitizer(i).sanitized:void 0,a=st(this.conversation,Date.now(),this.conversationOptions),l=new AbortController;this.abort=l;let c=null;try{let b=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:(g=a.summary)!=null?g:void 0,sessionId:this.sessionId,platformCapabilities:this.platformCapabilities(),sessionContext:this.sessionContext(),...yo(this.config.manifest,this.config.registries)},{signal:l.signal});c=await this.applyOutcome(b,o,(R=r==null?void 0:r.context)!=null?R:{},n)}catch(b){if(this.clearWatchdog(),this.abort=null,this.setActivity(null),b instanceof V&&b.code==="cancelled"){this.phase==="thinking"&&this.setPhase("idle"),this.pendingTurnText=null;return}b instanceof V&&b.code==="quota_exceeded"&&((A=(v=this.config).onQuotaExceeded)==null||A.call(v));let C=xo(b,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(),at(this.conversation,n,u,Date.now(),this.conversationOptions),this.persistConversation();else{let b=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:b},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 b=new Set;c.actionKey&&b.add(c.actionKey),await this.runChainLoop({userMessage:n,step:1,lastStep:c.lastStep,visitedKeys:b})}this.pending||this.setActivity(null),(T=(I=this.config).onTurnCompleted)==null||T.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 i,s;if(!this.enabled)return;let o=t.trim();if(!o)return;let r=(s=(i=this.config).gateTurn)==null?void 0:s.call(i);if(r&&!r.ok){r.message&&this.notifyError(r.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.deferredEscortIntent=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 Xa="http://www.w3.org/2000/svg",ae={accentColor:"#4f8cff",backgroundColor:"#1b2a4a",colorKey:"azul",glowIntensity:100,size:56};function ne(e,t){let n=document.createElementNS(Xa,e);for(let[o,r]of Object.entries(t))n.setAttribute(o,String(r));return n}function Mr(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:r,fillRadius:i,midPx:s}=ht(e.fillDiameter,e.exteriorWidthSlider,e.interiorWidthSlider),a=typeof e.borderRadius=="number",l=a?`${i}px`:String(e.borderRadius),c=a?`${s/2}px`:String(e.borderRadius),u=a?`${r/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?ln(r,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 g=document.createElement("div");return Object.assign(g.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?un(e.fillDiameter):""}),h.appendChild(g),m.appendChild(h),{root:m,fill:g}}function qa(e,t){let{bars:n,color:o,radius:r}=pn(e,t),i=ne("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,"aria-hidden":"true"});i.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:r,ry:r,fill:o});return i.appendChild(c),c}),a=0;return{el:i,start(){let l=performance.now(),c=u=>{a=requestAnimationFrame(c);let p=(u-l)/1e3;n.forEach((f,m)=>{let h=fn(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 Qa=9,Ja=[.25,.45,.65,.85,1,.85,.65,.45,.25],_r=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],Za=26;function ec(e,t){let n=t/Za,o=3*n,r=3*n,i=3*n,s=document.createElement("div");Object.assign(s.style,{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:`${r}px`,height:`${t}px`,width:"100%",maxWidth:"88%"});let a=[];for(let h=0;h<Qa;h++){let g=document.createElement("div");Object.assign(g.style,{width:`${o}px`,height:`${t}px`,borderRadius:`${Math.max(1,2*n)}px`,backgroundColor:e,transformOrigin:"center center",transform:`scaleY(${i/t})`,flexShrink:"0"}),a.push(g),s.appendChild(g)}let l=0,c=0,u=0,p=0,f=i/t,m=h=>{l=requestAnimationFrame(m),!(h-u<80)&&(u=h,c+=.22,a.forEach((g,R)=>{var A,I,T;let v;if(p<.05){let b=(Math.sin(c+((A=_r[R])!=null?A:0))+1)/2;v=f+b*(.22-f)}else{let b=Math.sin(c*2.3+((I=_r[R])!=null?I:0))*.18+.82+Math.random()*.18;v=f+p*((T=Ja[R])!=null?T:.5)*(1-f)*b}g.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 Pr=8,Lr=68,tc=360-Lr,nc=Lr/2,oc=[.15,.25,.35,.5,.65,.78,.88,1];function rc(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 r=document.createElement("div");Object.assign(r.style,{width:`${n}px`,height:`${n}px`,animation:"fy-spin 0.92s linear infinite"}),r.setAttribute("role","progressbar"),r.setAttribute("aria-label","Loading");let i=ne("svg",{width:n,height:n,viewBox:"0 0 40 40","aria-hidden":"true"}),s=tc/(Pr-1);for(let l=0;l<Pr;l++){let c=nc+s*l;i.appendChild(ne("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(a=oc[l])!=null?a:1,transform:`rotate(${c} 20 20)`}))}return r.appendChild(i),o.appendChild(r),o}var ic=118/380,sc=30/380,ac=2/380;function cc(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*ic,r=Math.max(1,e*ac);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:`${r}px solid ${t}`,opacity:"0.55",animation:`fy-voice 1.7s ease-out infinite ${a}s`}),n.appendChild(l)}let i=e*sc,s=document.createElement("div");return Object.assign(s.style,{width:`${i}px`,height:`${i}px`,borderRadius:"50%",background:t,opacity:"0.9",animation:"fy-opulse 1s ease-in-out infinite"}),n.appendChild(s),n}function lc(e,t,n){let o=An(e),r=1.8,{x:i,y:s}=Sn(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(${i} ${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":r}));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,r*.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":r})),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":r,"stroke-linecap":"round","stroke-linejoin":"round"}));return a.appendChild(l),a}function Br(e){var g,R,v,A,I,T,b;let{theme:t}=e,n=(g=t.size)!=null?g:30,o=(R=t.shape)!=null?R:"circle",r=o==="circle"?"50%":`${vn(o,n)}px`,i=(v=t.backgroundColor)!=null?v:e.backgroundColor,s=(A=t.borderColor)!=null?A:e.accentColor,a=Cn(t.iconColor,i,e.accentColor),l=He(t.icon),c=xn((I=t.iconScale)!=null?I:1),u=Math.round(yn(n)*c),p=ht(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}=Mr({fillDiameter:n,borderRadius:r,exteriorColor:s,exteriorWidthSlider:(b=t.borderWidth)!=null?b:100,interiorColor:ft(t.innerBorderColor),interiorWidthSlider:t.innerBorderWidth,fill:i,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(lc(l,u,a));return f.appendChild(m),f}function Nr(e){let t=document.createElement("div");t.style.display="inline-flex";let n=e,o="idle",r=0,i=null,s=null,a=null;function l(){var R,v,A,I;let u=(R=n.size)!=null?R:ae.size,p=At({colorKey:(v=n.colorKey)!=null?v:ae.colorKey,backgroundColor:n.backgroundColor,accentColor:n.accentColor}),f=(A=n.glowColor)!=null&&A.startsWith("#")?n.glowColor:n.accentColor,m=ft(n.innerBorderColor);s==null||s.stop(),s=null,a==null||a.stop(),a=null,t.replaceChildren();let{root:h,fill:g}=Mr({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(I=n.glowIntensity)!=null?I:ae.glowIntensity,interiorColor:m,interiorWidthSlider:n.innerBorderWidth,fill:p});i=g,t.appendChild(h),c()}function c(){var f,m;if(!i)return;let u=(f=n.size)!=null?f:ae.size,p=(m=n.waveformColor)!=null?m:"#ffffff";if(s==null||s.stop(),s=null,a==null||a.stop(),a=null,i.replaceChildren(),t.style.animation="",o==="thinking"){i.appendChild(rc(u,p));return}if(o==="listening"){s=ec(p,Math.round(u*.46)),s.setVolume(r),i.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",g=>g.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":""}),i.appendChild(h);return}if(o==="speaking"){i.appendChild(cc(u,p));return}o==="idle"&&(a=qa(u,n.waveformColor),i.appendChild(a.el),a.start())}return l(),{element:t,applyAppearance(u){n=u,l()},applyState(u,p){r=p,u!==o?(o=u,c()):o==="listening"&&(s==null||s.setVolume(r))}}}var vo="fyodos:published-config:v1";function uc(){try{if(typeof window=="undefined"||!window.localStorage)return null;let e=window.localStorage.getItem(vo);return e?JSON.parse(e):null}catch{return null}}function Dr(e){try{if(typeof window=="undefined"||!window.localStorage)return;e?window.localStorage.setItem(vo,JSON.stringify(e)):window.localStorage.removeItem(vo)}catch{}}function $r(e,t){var i,s,a,l;let n=t.orbEnabled!==!1,o=e.theme;return{appearance:{accentColor:(i=o.accentColor)!=null?i:ae.accentColor,backgroundColor:(s=o.backgroundColor)!=null?s:ae.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:ae.size,waveformColor:o.waveformColor,logoDataUrl:e.logoDataUrl},keyboardChip:(l=o.keyboardChip)!=null?l:null,modalTheme:e.modalTheme,screenPosition:e.screenPosition,bubbleTheme:Ue(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 Fr(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,r=uc();r&&t.onChange($r(St(r),r));let i=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange($r(St(c.published),c.published)),Dr(c.published)):(t.onChange(null),Dr(null))}catch{}};i();let s=(l=t.pollMs)!=null?l:12e3,a=s>0?setInterval(()=>{i()},s):null;return()=>{o=!0,a&&clearInterval(a)}}function dc(){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 pc(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function wt(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Wr(e){let t=dc(),n=null,o=!1,r="",i=()=>{let a=n;if(a){a.onresult=null,n=null,o=!1;try{typeof a.abort=="function"?a.abort():a.stop()}catch{}}};return{isSupported:()=>t!=null,isListening:()=>o,stop:i,dispose:()=>{i()},toggle(a,l){if(!t)return;if(o){i();return}r=a();let c=new t;c.lang=pc(e),c.interimResults=!0,c.continuous=!0;let u="";c.onresult=p=>{var g,R;let f="";for(let v=p.resultIndex;v<p.results.length;v+=1){let A=p.results[v];if(!A)continue;let I=(R=(g=A[0])==null?void 0:g.transcript)!=null?R:"";A.isFinal?u+=I:f+=I}let m=`${u}${f}`.trimStart(),h=r?`${r}${r.endsWith(" ")?"":" "}${m}`:m;l(h)},c.onend=()=>{n===c&&(o=!1,n=null)},c.onerror=()=>{n===c&&(o=!1,n=null)},n=c,o=!0,c.start()}}}var Ur="fyodos-orb-styles",fc=`
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 mc(){if(typeof document=="undefined"||document.getElementById(Ui))return;let e=document.createElement("style");e.id=Ui,e.textContent=fc,document.head.appendChild(e)}function Hi(){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 hc(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 ze={cardBackgroundColor:"#0b0f1a",cardBorderColor:"rgba(160,180,220,0.2)",titleColor:"#e7ecf7",bodyColor:"#b9c4dd"};function Tt(e,t={}){var $o,Do,Fo;if(typeof document=="undefined")return{unmount(){}};mc();let n=($o=t.container)!=null?$o:document.body,o=(Do=t.zIndex)!=null?Do:2147483e3,i=t.enableTextInput!==!1,r=t.usePublishedPosition!==!1,s=e.ui;if(e.config.voice.isRecognitionAvailable()){let d=navigator.permissions;(Fo=d==null?void 0:d.query)==null||Fo.call(d,{name:"microphone"}).then(y=>{e.markVoiceBlocked(y.state==="denied"),y.onchange=()=>e.markVoiceBlocked(y.state==="denied")}).catch(()=>{})}let a=Zn(()=>v().hapticIntensity),l=null,c=null,u,p=Ue(null),f=!0,h=!0,m=!1,x=null,T=t.corner?hc(t.corner):{...Ae};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=Ni(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=ko();qe(d?Xt(d,{locale:It(),messages:e.messages}):void 0);return}Et=!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 j(){let d=Q(),y=Hi(),{left:w,top:k}=wn({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=vt(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"&&Po()}window.addEventListener("resize",j);let O;typeof ResizeObserver!="undefined"&&document.documentElement&&(O=new ResizeObserver(()=>j()),O.observe(document.documentElement));let b=window.visualViewport,R=()=>{Z&&Mn()};b==null||b.addEventListener("resize",R),b==null||b.addEventListener("scroll",R);let $=6,L=!1,X=!1,F=0,P=0,J=0,q=0;function ge(d){if(d.button!=null&&d.button!==0)return;let y=S.getBoundingClientRect();J=y.left,q=y.top,F=d.clientX,P=d.clientY,L=!1;try{g.setPointerCapture(d.pointerId)}catch{}}function fe(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=Hi(),_=8,U=M.width-_-k,G=M.height-_-k,H=Math.min(U,Math.max(_,J+y)),Y=Math.min(G,Math.max(_,q+w));S.style.left=`${H}px`,S.style.top=`${Y}px`,S.style.right="",S.style.bottom="",N=En({centerX:H+k/2,centerY:Y+k/2,viewportWidth:M.width,viewportHeight:M.height,orbDiameter:k}),oe()}function be(d){try{g.releasePointerCapture(d.pointerId)}catch{}L&&(X=!0,L=!1,N=Tn(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)",j(),window.setTimeout(()=>{S.style.transition=""},260))}g.draggable=!1,g.addEventListener("dragstart",d=>d.preventDefault()),g.addEventListener("pointerdown",ge),g.addEventListener("pointermove",fe),g.addEventListener("pointerup",be),g.addEventListener("pointercancel",be),g.addEventListener("lostpointercapture",be);let Z=!1,Se=!1,ye=!1,Et=!1,z=document.createElement("div");z.className="fyodos-bubble",z.style.display="none";function rr(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function Mn(){z.style.position="fixed",z.style.left="50%",z.style.right="",z.style.top="",z.style.transform="translateX(-50%)",z.style.bottom=`${rr()+16}px`,z.style.zIndex=String(o+5)}let ie=document.createElement("div");ie.className="fyodos-bubble-scroll";let xe=document.createElement("button");xe.type="button",xe.className="fyodos-bubble-close",xe.textContent="\xD7",xe.setAttribute("aria-label","Close"),xe.addEventListener("click",()=>Xe(!1));let me=document.createElement("button");me.type="button",me.className="fyodos-bubble-unexpand",me.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>',me.setAttribute("aria-label","Collapse"),me.addEventListener("click",d=>{d.stopPropagation(),Rt(!1)});let Ge=document.createElement("div");Ge.className="fyodos-bubble-loader",Ge.append(document.createElement("span")),Ge.style.display="none";let we=document.createElement("div");we.className="fyodos-bubble-exchanges",ie.append(Ge,we);let Ye="";function sr(d){let y=d.map(_=>`${_.userText}\0${_.replyText}`).join("");if(y===Ye)return;let w=Ye.length>0&&y.length>Ye.length&&y.endsWith(Ye),k=ie.scrollHeight-ie.scrollTop;Ye=y;let M={...ze,...u!=null?u:{}};we.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)}we.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 Te=document.createElement("div");Te.className="fyodos-bubble-busy";let re=document.createElement("em");re.className="fyodos-busy-step",re.style.display="none",Te.appendChild(re),Te.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let To=null;function ar(d){if(!m||!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 cr(d,y){let w=d?ar(y):null;if(w!==To){if(To=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 Ln=document.createElement("div");Ln.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),Ln.append(W,D,se);let Ee=Wi(e.config.locale);Ee.isSupported()&&(D.style.display="flex",D.setAttribute("aria-label",s.micLabel),D.title=s.micLabel,D.addEventListener("click",()=>{e.getState().isBusy||(Ee.toggle(()=>W.value,d=>{W.value=d,wt(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={...ze,...u!=null?u:{}}.bodyColor,k=Ee.isListening();D.classList.toggle("is-listening",k),k?(D.style.background=d,D.style.border="none",D.style.color=We(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(xe,me,ie,Te,Ln),I.appendChild(z);function Rt(d){Se!==d&&(Se=d,z.classList.toggle("fyodos-bubble--expanded",d),me.style.display=d?"flex":"none",Mn())}let Eo=0,Ro=0,je=null,lr=8,Io=()=>{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},Bn=()=>{je!=null&&(window.clearTimeout(je),je=null)};z.addEventListener("pointerdown",d=>{Eo=d.clientX,Ro=d.clientY}),z.addEventListener("click",d=>{if(Se)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-Eo,d.clientY-Ro)>lr)return;if(d.detail>1){Bn();return}if(Bn(),!!!(y!=null&&y.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!Io()){Rt(!0);return}je=window.setTimeout(()=>{je=null,Io()||Rt(!0)},280)}),j();function Oo(){var k,M,_;let d={...ze,...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`),xe.style.color=d.bodyColor,me.style.color=d.bodyColor,we.querySelectorAll(".fyodos-bubble-user").forEach(U=>{U.style.color=d.bodyColor}),we.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=We(w),W.style.setProperty("--fyodos-input-placeholder",dn(w)),se.style.background=y,se.style.color=We(y),se.style.borderRadius=`${(_=u==null?void 0:u.sendButtonRadius)!=null?_:10}px`,Ke(),Te.querySelectorAll("span").forEach(U=>{U.style.background=y}),re.style.color=d.titleColor}let Nn=`fyodos:panel-open:${e.config.manifest.appId}`;function ur(d){try{d?window.sessionStorage.setItem(Nn,"1"):window.sessionStorage.removeItem(Nn)}catch{}}function dr(){try{return window.sessionStorage.getItem(Nn)==="1"}catch{return!1}}function Xe(d){Z=d,z.style.display=d?"flex":"none",ur(d),d?(Oo(),Mn(),W.focus(),Wn(e.getState())):(Ee.stop(),Ke(),e.resetBubbleWindow(),ye=!1,Bn(),Rt(!1)),Dn(e.getState()),Ot(e.getState())}function $n(){if(e.getState().isBusy)return;let d=W.value.trim();d&&(Ee.stop(),Ke(),a.trigger("send"),W.value="",e.submitTextTurn(d))}function qe(d,y=!1){var _;let w=e.cancelAll(),k=(_=d==null?void 0:d.trim())!=null?_:"",M=k||w||"";W.value=M,Xe(!0),y&&k&&queueMicrotask(()=>$n())}function Dn(d){if(!(i&&!Z&&(d.phase==="listening"||ye))){C&&(C.remove(),C=null);return}if(C){oe();return}let w=v();C=Bi({theme:c!=null?c:{},accentColor:w.accentColor,backgroundColor:w.backgroundColor,label:s.keyboardChipLabel,onClick:()=>{a.trigger("keyboardChip"),qe()}}),I.appendChild(C),oe()}function It(){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 ko(){return Ft(nt(x,e.config.manifest.routes),e.messages,{locale:It(),actions:e.config.manifest.actions})}function pr(d){let y=p,{padH:w}=xt(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 Y=document.createElement("div");Y.className="fyodos-thought-track",Y.style.animation=`fyodos-marquee ${H}s linear infinite`;let ae=document.createElement("span");ae.textContent=d;let Ie=document.createElement("span");Ie.textContent=d,Ie.setAttribute("aria-hidden","true"),Y.appendChild(ae),Y.appendChild(Ie),A.appendChild(Y)}function _o(d){let y=p,{fontPx:w,padH:k,approxHeight:M}=xt(y),_=gn(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}`,bn(A,_)}function Po(){let d=vt(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 Ot(d){let y=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!ye,w=f&&!Z&&y?ko():null;if(!w){A.style.display="none";return}if(A.setAttribute("aria-label",w),A.style.display="flex",_o(),pr(w),p.shape==="cloud"){let k=A.offsetWidth;k>0&&_o(k)}Po()}let Qe=null;function Je(){Qe&&(Qe.remove(),Qe=null)}function Mo(){let d={...ze,...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 fr(d,y){var Ie;Je();let w={...ze,...u!=null?u:{}},k=(Ie=u==null?void 0:u.primaryButtonColor)!=null?Ie:v().accentColor,{overlay:M,modal:_}=Mo(),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 Oe=document.createElement("div");Oe.className="fyodos-hint",Oe.style.color=w.bodyColor,Oe.textContent=y,_.append(Oe)}let H=document.createElement("div");H.className="fyodos-modal-actions";let Y=document.createElement("button");Y.className="fyodos-btn-ghost",Y.style.color=w.bodyColor,Y.textContent=s.cancelLabel,Y.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(Y,ae),_.append(H),M.onclick=Oe=>{Oe.target===M&&e.cancelPendingAction()},n.appendChild(M),Qe=M}function mr(){var Y;Je();let d={...ze,...u!=null?u:{}},y=(Y=u==null?void 0:u.primaryButtonColor)!=null?Y:v().accentColor,{overlay:w,modal:k}=Mo(),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(X){X=!1;return}if(e.primeAudio(),e.getState().showThinking){a.trigger("orbTap");let y=e.cancelAll();y&&Z&&(W.value=y,wt(W));return}if(a.trigger("orbTap"),Z){Xe(!1);return}if(!h&&i){ye=!1,qe();return}if(e.voiceAvailable&&h){ye=!1,Et=!0,e.toggleListening();return}if(i){ye=!1,qe();return}Et=!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,wt(W)),W.focus();return}$n()},W.onkeydown=d=>{d.key==="Enter"&&$n(),d.key==="Escape"&&Xe(!1)},W.addEventListener("input",()=>wt(W)),i||C&&(C.style.display="none");let Lo=null,Bo=!1,Fn=!1,kt=null;function Wn(d){if(d.voiceBlocked&&!Fn){if(Fn=!0,Et&&i&&!Z&&!d.isBusy){qe();return}}else d.voiceBlocked||(Fn=!1);d.phase!==kt&&(d.phase==="listening"?a.trigger("listenStart"):kt==="listening"&&a.trigger("listenStop"),kt==="thinking"&&a.trigger("response"),kt=d.phase);let y=d.showThinking?"thinking":d.showWaveform||ye?"listening":d.phase==="speaking"?"speaking":"idle";E.applyState(y,d.volumeLevel);let w=d.showThinking||d.chainActive;if(cr(w,d),Z){Ge.style.display=d.loadingOlderExchanges?"flex":"none",sr(d.recentExchanges),ie.style.display="flex",Te.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()}Dn(d),Ot(d),d.confirmationMessage!==Lo&&(Lo=d.confirmationMessage,d.confirmationMessage?fr(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||Je()),d.consentModalVisible!==Bo&&(Bo=d.consentModalVisible,d.consentModalVisible?mr():d.confirmationMessage||Je())}let hr=e.subscribe(Wn);Wn(e.getState()),i&&dr()&&Xe(!0);let No=It(),Re=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}let y=It();(d!==x||y!==No)&&(x=d,No=y,Ot(e.getState()))};Re();let gr=window.setInterval(Re,700);window.addEventListener("popstate",Re),document.addEventListener("visibilitychange",Re);let br=Fi(e,{pollMs:t.appearancePollMs,onChange:d=>{let y=d!=null&&In(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,h=d.voiceInputEnabled,m=d.thinkingStepsEnabled,e.setConversationRetention(d.conversationRetentionMinutes,d.internalProfile),r&&d.screenPosition&&(T=d.screenPosition)),E.applyAppearance(v()),j(),C&&(C.remove(),C=null),Dn(e.getState()),Ot(e.getState()),Z&&Oo()}});return{unmount(){Ee.dispose(),hr(),br(),window.clearInterval(gr),window.removeEventListener("popstate",Re),document.removeEventListener("visibilitychange",Re),window.removeEventListener("resize",j),O==null||O.disconnect(),b==null||b.removeEventListener("resize",R),b==null||b.removeEventListener("scroll",R),Je(),C==null||C.remove(),S.remove()}}}var Vi="fiodos-dev-error-badge";function gc(){try{return!1}catch{return!1}}function Co(e,t){if(!gc()||typeof document=="undefined"||!document.body)return;let n=bc(e),o=document.getElementById(Vi);if(o){let l=o.querySelector("[data-fiodos-badge-msg]");l&&(l.textContent=n);return}o=document.createElement("div"),o.id=Vi,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 bc(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var _n="0.1.18",zi="@fiodos/web-core";var Gi="https://api.fyodos.com";function Yi(e){return e.replace(/\/$/,"")}async function Ki(e){let t=Yi(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}}var ji=!1;function Xi(){ji=!0}function yc(){let e=typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);return ji?e?"web-embed-mobile":"web-embed":e?"web-mobile":"web"}async function Ao(e){var n;if(!e.apiKey)return;let t=Yi(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:yc(),sdkVersion:_n,sdkPackage:zi})})}catch{}}var qi="fyodos:anon-caller:v1",pe=null;function Qi(){try{let e=globalThis.crypto;if(e!=null&&e.randomUUID)return`anon-${e.randomUUID()}`}catch{}return`anon-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function xc(){if(pe)return pe;try{let e=window.localStorage.getItem(qi);if(e)return pe=e,e;let t=Qi();return window.localStorage.setItem(qi,t),pe=t,t}catch{return pe=pe!=null?pe:Qi(),pe}}function Ji(e){return()=>{let t=e==null?void 0:e();return t||xc()}}function vc(e){typeof window!="undefined"&&window.location&&window.location.assign(e)}function nr(){let e=typeof navigator!="undefined"&&navigator.language?navigator.language:"en-US";return{locale:e.split("-")[0]||"en",sttLocale:e}}function Zi(){var e,t;return typeof document!="undefined"&&((t=(e=document.documentElement.lang)==null?void 0:e.split(/[-_]/)[0])==null?void 0:t.trim())||""}function er(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 nr().locale;if(e.localeDetection==="document"){let s=Zi();if(s)return s}let n=Zi();return n||"en"}function tr(e,t,n){var p,f,h,m;let o=nr(),i=er(e),r=(f=(p=e.sttLocale)!=null?p:e.locale)!=null?f:o.sttLocale,s=Ji(e.getUserId),a=fi({baseUrl:n,apiKey:e.apiKey,getUserId:s}),l=mi({baseUrl:n,apiKey:e.apiKey,getUserId:s}),c={manifest:t,locale:i,getLocale:()=>er(e),sttLocale:r,navigation:hi({navigate:(h=e.navigate)!=null?h:vc,getCurrentRoute:e.getCurrentRoute}),registries:(m=e.registries)!=null?m:{handlers:{},idempotencyCheckers:{}},backend:a,voice:xi(),storage:gi(),telemetry:l,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},u=new Ve(c);return u.warmUp(),u}function or(e){var a,l;let t=((a=e.baseUrl)!=null?a:Gi).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=tr(e,e.manifest,t),u=n?Tt(c,e.orb):null;return n&&e.apiKey&&Ao({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 Ki({baseUrl:t,apiKey:e.apiKey});if(s)return null;if(p.status==="no-manifest"||!p.manifest){let m="[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(m),Co(m,{baseUrl:t}),null}let f=he(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
64
+ `;function hc(){if(typeof document=="undefined"||document.getElementById(Ur))return;let e=document.createElement("style");e.id=Ur,e.textContent=fc,document.head.appendChild(e)}function Hr(){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 mc(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 ze={cardBackgroundColor:"#0b0f1a",cardBorderColor:"rgba(160,180,220,0.2)",titleColor:"#e7ecf7",bodyColor:"#b9c4dd"};function Tt(e,t={}){var Do,$o,Fo;if(typeof document=="undefined")return{unmount(){}};hc();let n=(Do=t.container)!=null?Do:document.body,o=($o=t.zIndex)!=null?$o:2147483e3,r=t.enableTextInput!==!1,i=t.usePublishedPosition!==!1,s=e.ui;if(e.config.voice.isRecognitionAvailable()){let d=navigator.permissions;(Fo=d==null?void 0:d.query)==null||Fo.call(d,{name:"microphone"}).then(x=>{e.markVoiceBlocked(x.state==="denied"),x.onchange=()=>e.markVoiceBlocked(x.state==="denied")}).catch(()=>{})}let a=Zn(()=>v().hapticIntensity),l=null,c=null,u,p=Ue(null),f=!0,m=!0,h=!1,g=null,R=t.corner?mc(t.corner):{...Ae};function v(){let d={...ae,...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 A=document.createElement("div");A.className="fyodos-orb-root",A.style.zIndex=String(o);let I=document.createElement("div");I.className="fyodos-orb-anchor";let T=Nr(v()),b=document.createElement("button");b.className="fyodos-orb-btn",b.type="button",b.setAttribute("aria-label",s.orbLabel),b.appendChild(T.element),I.appendChild(b),A.appendChild(I);let C=null,S=document.createElement("div");S.className="fyodos-thought",S.setAttribute("role","button"),S.tabIndex=0,S.style.display="none",S.addEventListener("click",()=>{if(a.trigger("orbTap"),e.primeAudio(),r){let d=ko();qe(d?Xt(d,{locale:It(),messages:e.messages}):void 0);return}Et=!0,e.toggleListening()}),S.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),S.click())}),I.appendChild(S),n.appendChild(A);let N=null;function q(){var d;return(d=v().size)!=null?d:ae.size}function ce(){return N!=null?N:R}function Q(){let d=q(),x=Hr(),{left:w,top:k}=wn({viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,contentWidth:x.width,contentHeight:x.height,orbDiameter:d,position:ce()});A.style.left=`${w}px`,A.style.top=`${k}px`,A.style.right="",A.style.bottom="",B()}function B(){let d=vt(ce());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="")),S.style.display!=="none"&&Po()}window.addEventListener("resize",Q);let O;typeof ResizeObserver!="undefined"&&document.documentElement&&(O=new ResizeObserver(()=>Q()),O.observe(document.documentElement));let y=window.visualViewport,E=()=>{Z&&Mn()};y==null||y.addEventListener("resize",E),y==null||y.addEventListener("scroll",E);let D=6,L=!1,j=!1,F=0,P=0,J=0,X=0;function ge(d){if(d.button!=null&&d.button!==0)return;let x=A.getBoundingClientRect();J=x.left,X=x.top,F=d.clientX,P=d.clientY,L=!1;try{b.setPointerCapture(d.pointerId)}catch{}}function fe(d){var se;if(!((se=b.hasPointerCapture)!=null&&se.call(b,d.pointerId)))return;let x=d.clientX-F,w=d.clientY-P;if(!L&&Math.hypot(x,w)<D)return;L=!0,d.preventDefault();let k=q(),M=Hr(),_=8,U=M.width-_-k,G=M.height-_-k,H=Math.min(U,Math.max(_,J+x)),Y=Math.min(G,Math.max(_,X+w));A.style.left=`${H}px`,A.style.top=`${Y}px`,A.style.right="",A.style.bottom="",N=En({centerX:H+k/2,centerY:Y+k/2,viewportWidth:M.width,viewportHeight:M.height,orbDiameter:k}),B()}function be(d){try{b.releasePointerCapture(d.pointerId)}catch{}L&&(j=!0,L=!1,N=Tn(N!=null?N:ce()),A.style.transition="left 220ms cubic-bezier(0.22, 1, 0.36, 1), top 220ms cubic-bezier(0.22, 1, 0.36, 1)",Q(),window.setTimeout(()=>{A.style.transition=""},260))}b.draggable=!1,b.addEventListener("dragstart",d=>d.preventDefault()),b.addEventListener("pointerdown",ge),b.addEventListener("pointermove",fe),b.addEventListener("pointerup",be),b.addEventListener("pointercancel",be),b.addEventListener("lostpointercapture",be);let Z=!1,Se=!1,ye=!1,Et=!1,z=document.createElement("div");z.className="fyodos-bubble",z.style.display="none";function ii(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function Mn(){z.style.position="fixed",z.style.left="50%",z.style.right="",z.style.top="",z.style.transform="translateX(-50%)",z.style.bottom=`${ii()+16}px`,z.style.zIndex=String(o+5)}let oe=document.createElement("div");oe.className="fyodos-bubble-scroll";let xe=document.createElement("button");xe.type="button",xe.className="fyodos-bubble-close",xe.textContent="\xD7",xe.setAttribute("aria-label","Close"),xe.addEventListener("click",()=>Xe(!1));let he=document.createElement("button");he.type="button",he.className="fyodos-bubble-unexpand",he.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>',he.setAttribute("aria-label","Collapse"),he.addEventListener("click",d=>{d.stopPropagation(),Rt(!1)});let Ge=document.createElement("div");Ge.className="fyodos-bubble-loader",Ge.append(document.createElement("span")),Ge.style.display="none";let we=document.createElement("div");we.className="fyodos-bubble-exchanges",oe.append(Ge,we);let Ye="";function si(d){let x=d.map(_=>`${_.userText}\0${_.replyText}`).join("");if(x===Ye)return;let w=Ye.length>0&&x.length>Ye.length&&x.endsWith(Ye),k=oe.scrollHeight-oe.scrollTop;Ye=x;let M={...ze,...u!=null?u:{}};we.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)}we.append(U)}oe.scrollTop=w?oe.scrollHeight-k:oe.scrollHeight}oe.addEventListener("scroll",()=>{if(!Z||oe.scrollTop>12)return;let d=e.getState();d.hasOlderExchanges&&!d.loadingOlderExchanges&&e.loadOlderExchanges()});let Te=document.createElement("div");Te.className="fyodos-bubble-busy";let re=document.createElement("em");re.className="fyodos-busy-step",re.style.display="none",Te.appendChild(re),Te.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let To=null;function ai(d){if(!h||!d.liveActivity)return null;let{kind:x,label:w}=d.liveActivity;switch(x){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 ci(d,x){let w=d?ai(x):null;if(w!==To){if(To=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 Ln=document.createElement("div");Ln.className="fyodos-bubble-row";let W=document.createElement("input");W.type="text",W.placeholder=s.textPlaceholder;let $=document.createElement("button");$.type="button",$.className="fyodos-bubble-mic",$.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>',$.style.display="none";let ie=document.createElement("button");ie.textContent="\u2191",ie.setAttribute("aria-label",s.sendLabel),Ln.append(W,$,ie);let Ee=Wr(e.config.locale);Ee.isSupported()&&($.style.display="flex",$.setAttribute("aria-label",s.micLabel),$.title=s.micLabel,$.addEventListener("click",()=>{e.getState().isBusy||(Ee.toggle(()=>W.value,d=>{W.value=d,wt(W)}),Ke())}));function Ke(){var M,_;let d=(M=u==null?void 0:u.primaryButtonColor)!=null?M:v().accentColor,x=`${(_=u==null?void 0:u.sendButtonRadius)!=null?_:10}px`,w={...ze,...u!=null?u:{}}.bodyColor,k=Ee.isListening();$.classList.toggle("is-listening",k),k?($.style.background=d,$.style.border="none",$.style.color=We(d),$.style.borderRadius=x):($.style.background="rgba(255,255,255,0.06)",$.style.border="1px solid rgba(148,163,184,0.4)",$.style.color=w,$.style.borderRadius="999px"),$.setAttribute("aria-label",k?s.micStopLabel:s.micLabel),$.title=k?s.micStopLabel:s.micLabel}z.append(xe,he,oe,Te,Ln),I.appendChild(z);function Rt(d){Se!==d&&(Se=d,z.classList.toggle("fyodos-bubble--expanded",d),he.style.display=d?"flex":"none",Mn())}let Eo=0,Ro=0,je=null,li=8,Io=()=>{var x;let d=typeof window!="undefined"?(x=window.getSelection)==null?void 0:x.call(window):null;return!!d&&!d.isCollapsed&&d.toString().length>0},Bn=()=>{je!=null&&(window.clearTimeout(je),je=null)};z.addEventListener("pointerdown",d=>{Eo=d.clientX,Ro=d.clientY}),z.addEventListener("click",d=>{if(Se)return;let x=d.target;if(x!=null&&x.closest(".fyodos-bubble-row, .fyodos-bubble-close, .fyodos-bubble-unexpand, button, input, a")||Math.hypot(d.clientX-Eo,d.clientY-Ro)>li)return;if(d.detail>1){Bn();return}if(Bn(),!!!(x!=null&&x.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!Io()){Rt(!0);return}je=window.setTimeout(()=>{je=null,Io()||Rt(!0)},280)}),Q();function Oo(){var k,M,_;let d={...ze,...u!=null?u:{}},x=(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`),xe.style.color=d.bodyColor,he.style.color=d.bodyColor,we.querySelectorAll(".fyodos-bubble-user").forEach(U=>{U.style.color=d.bodyColor}),we.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=We(w),W.style.setProperty("--fyodos-input-placeholder",dn(w)),ie.style.background=x,ie.style.color=We(x),ie.style.borderRadius=`${(_=u==null?void 0:u.sendButtonRadius)!=null?_:10}px`,Ke(),Te.querySelectorAll("span").forEach(U=>{U.style.background=x}),re.style.color=d.titleColor}let Nn=`fyodos:panel-open:${e.config.manifest.appId}`;function ui(d){try{d?window.sessionStorage.setItem(Nn,"1"):window.sessionStorage.removeItem(Nn)}catch{}}function di(){try{return window.sessionStorage.getItem(Nn)==="1"}catch{return!1}}function Xe(d){Z=d,z.style.display=d?"flex":"none",ui(d),d?(Oo(),Mn(),W.focus(),Wn(e.getState())):(Ee.stop(),Ke(),e.resetBubbleWindow(),ye=!1,Bn(),Rt(!1)),$n(e.getState()),Ot(e.getState())}function Dn(){if(e.getState().isBusy)return;let d=W.value.trim();d&&(Ee.stop(),Ke(),a.trigger("send"),W.value="",e.submitTextTurn(d))}function qe(d,x=!1){var _;let w=e.cancelAll(),k=(_=d==null?void 0:d.trim())!=null?_:"",M=k||w||"";W.value=M,Xe(!0),x&&k&&queueMicrotask(()=>Dn())}function $n(d){if(!(r&&!Z&&(d.phase==="listening"||ye))){C&&(C.remove(),C=null);return}if(C){B();return}let w=v();C=Br({theme:c!=null?c:{},accentColor:w.accentColor,backgroundColor:w.backgroundColor,label:s.keyboardChipLabel,onClick:()=>{a.trigger("keyboardChip"),qe()}}),I.appendChild(C),B()}function It(){var d,x;try{let w=(x=(d=e.config).getLocale)==null?void 0:x.call(d);if(typeof w=="string"&&w.trim())return w.trim()}catch{}return e.config.locale}function ko(){return Ft(nt(g,e.config.manifest.routes),e.messages,{locale:It(),actions:e.config.manifest.actions})}function pi(d){let x=p,{padH:w}=xt(x);S.style.width="",S.textContent=d;let k=S.scrollWidth,M=typeof window!="undefined"?window.innerWidth:280,_=Math.min(280,M*.7);if(!(k>_-x.borderWidth*2)){S.style.width="";return}let G=Math.max(0,k-w*2),H=Math.max(4,(G+48)/30);S.style.width=`${_}px`,S.textContent="";let Y=document.createElement("div");Y.className="fyodos-thought-track",Y.style.animation=`fyodos-marquee ${H}s linear infinite`;let se=document.createElement("span");se.textContent=d;let Ie=document.createElement("span");Ie.textContent=d,Ie.setAttribute("aria-hidden","true"),Y.appendChild(se),Y.appendChild(Ie),S.appendChild(Y)}function _o(d){let x=p,{fontPx:w,padH:k,approxHeight:M}=xt(x),_=gn(x,M,1,d);S.style.fontSize=`${w}px`,S.style.height=`${M}px`,S.style.padding=`0 ${k}px`,S.style.color=x.textColor,S.style.background=x.backgroundColor,S.style.border=`${x.borderWidth}px solid ${x.borderColor}`,bn(S,_)}function Po(){let d=vt(ce());d.horizontal==="left"?(S.style.right="calc(100% + 10px)",S.style.left=""):(S.style.left="calc(100% + 10px)",S.style.right=""),d.vertical==="up"?(S.style.top="0",S.style.bottom="",S.style.transform=""):(S.style.bottom="0",S.style.top="",S.style.transform="")}function Ot(d){let x=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!ye,w=f&&!Z&&x?ko():null;if(!w){S.style.display="none";return}if(S.setAttribute("aria-label",w),S.style.display="flex",_o(),pi(w),p.shape==="cloud"){let k=S.offsetWidth;k>0&&_o(k)}Po()}let Qe=null;function Je(){Qe&&(Qe.remove(),Qe=null)}function Mo(){let d={...ze,...u!=null?u:{}},x=document.createElement("div");x.className="fyodos-overlay",x.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"),x.appendChild(w),{overlay:x,modal:w}}function fi(d,x){var Ie;Je();let w={...ze,...u!=null?u:{}},k=(Ie=u==null?void 0:u.primaryButtonColor)!=null?Ie:v().accentColor,{overlay:M,modal:_}=Mo(),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),x){let Oe=document.createElement("div");Oe.className="fyodos-hint",Oe.style.color=w.bodyColor,Oe.textContent=x,_.append(Oe)}let H=document.createElement("div");H.className="fyodos-modal-actions";let Y=document.createElement("button");Y.className="fyodos-btn-ghost",Y.style.color=w.bodyColor,Y.textContent=s.cancelLabel,Y.onclick=()=>e.cancelPendingAction();let se=document.createElement("button");se.className="fyodos-btn-primary",se.style.background=k,se.textContent=s.confirmLabel,se.onclick=()=>{e.confirmPendingAction()},H.append(Y,se),_.append(H),M.onclick=Oe=>{Oe.target===M&&e.cancelPendingAction()},n.appendChild(M),Qe=M}function hi(){var Y;Je();let d={...ze,...u!=null?u:{}},x=(Y=u==null?void 0:u.primaryButtonColor)!=null?Y:v().accentColor,{overlay:w,modal:k}=Mo(),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=x,H.textContent=s.consentAccept,H.onclick=()=>{e.acceptConsent()},U.append(G,H),k.append(M,_,U),n.appendChild(w),Qe=w}b.onclick=()=>{if(j){j=!1;return}if(e.primeAudio(),e.getState().showThinking){a.trigger("orbTap");let x=e.cancelAll();x&&Z&&(W.value=x,wt(W));return}if(a.trigger("orbTap"),Z){Xe(!1);return}if(!m&&r){ye=!1,qe();return}if(e.voiceAvailable&&m){ye=!1,Et=!0,e.toggleListening();return}if(r){ye=!1,qe();return}Et=!0,e.toggleListening()},ie.onclick=()=>{let d=e.getState();if(d.isBusy||d.chainActive){a.trigger("orbTap");let x=e.cancelAll();x&&(W.value=x,wt(W)),W.focus();return}Dn()},W.onkeydown=d=>{d.key==="Enter"&&Dn(),d.key==="Escape"&&Xe(!1)},W.addEventListener("input",()=>wt(W)),r||C&&(C.style.display="none");let Lo=null,Bo=!1,Fn=!1,kt=null;function Wn(d){if(d.voiceBlocked&&!Fn){if(Fn=!0,Et&&r&&!Z&&!d.isBusy){qe();return}}else d.voiceBlocked||(Fn=!1);d.phase!==kt&&(d.phase==="listening"?a.trigger("listenStart"):kt==="listening"&&a.trigger("listenStop"),kt==="thinking"&&a.trigger("response"),kt=d.phase);let x=d.showThinking?"thinking":d.showWaveform||ye?"listening":d.phase==="speaking"?"speaking":"idle";T.applyState(x,d.volumeLevel);let w=d.showThinking||d.chainActive;if(ci(w,d),Z){Ge.style.display=d.loadingOlderExchanges?"flex":"none",si(d.recentExchanges),oe.style.display="flex",Te.style.display=w?"flex":"none";let k=d.isBusy||d.chainActive;ie.textContent=k?"\u25FC":"\u2191",ie.setAttribute("aria-label",k?s.cancelLabel:s.sendLabel),ie.style.opacity="1",ie.disabled=!1,$.style.opacity=k?"0.45":"1",$.disabled=k,Ke()}$n(d),Ot(d),d.confirmationMessage!==Lo&&(Lo=d.confirmationMessage,d.confirmationMessage?fi(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||Je()),d.consentModalVisible!==Bo&&(Bo=d.consentModalVisible,d.consentModalVisible?hi():d.confirmationMessage||Je())}let mi=e.subscribe(Wn);Wn(e.getState()),r&&di()&&Xe(!0);let No=It(),Re=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}let x=It();(d!==g||x!==No)&&(g=d,No=x,Ot(e.getState()))};Re();let gi=window.setInterval(Re,700);window.addEventListener("popstate",Re),document.addEventListener("visibilitychange",Re);let bi=Fr(e,{pollMs:t.appearancePollMs,onChange:d=>{let x=d!=null&&In(d.internalProfile,t.allowInternalOrb===!0);A.style.display=d&&d.enabled===!1||x?"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),i&&d.screenPosition&&(R=d.screenPosition)),T.applyAppearance(v()),Q(),C&&(C.remove(),C=null),$n(e.getState()),Ot(e.getState()),Z&&Oo()}});return{unmount(){Ee.dispose(),mi(),bi(),window.clearInterval(gi),window.removeEventListener("popstate",Re),document.removeEventListener("visibilitychange",Re),window.removeEventListener("resize",Q),O==null||O.disconnect(),y==null||y.removeEventListener("resize",E),y==null||y.removeEventListener("scroll",E),Je(),C==null||C.remove(),A.remove()}}}var Vr="fiodos-dev-error-badge";function gc(){try{return!1}catch{return!1}}function Co(e,t){if(!gc()||typeof document=="undefined"||!document.body)return;let n=bc(e),o=document.getElementById(Vr);if(o){let l=o.querySelector("[data-fiodos-badge-msg]");l&&(l.textContent=n);return}o=document.createElement("div"),o.id=Vr,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 r=document.createElement("div");r.style.cssText="display:flex;align-items:center;gap:6px;margin-bottom:6px;font-weight:600;color:#ffd166",r.textContent="\u25C9 Fiodos \xB7 el orbe no se mont\xF3 (solo desarrollo)";let i=document.createElement("button");i.textContent="\xD7",i.setAttribute("aria-label","Cerrar aviso de Fiodos"),i.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(";"),i.addEventListener("click",()=>o==null?void 0:o.remove()),r.appendChild(i);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(r),o.appendChild(s),o.appendChild(a),document.body.appendChild(o)}function bc(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var _n="0.1.19",zr="@fiodos/web-core";var Gr="https://api.fyodos.com";function Yr(e){return e.replace(/\/$/,"")}async function Kr(e){let t=Yr(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}}var jr=!1;function Xr(){jr=!0}function yc(){let e=typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);return jr?e?"web-embed-mobile":"web-embed":e?"web-mobile":"web"}async function Ao(e){var n;if(!e.apiKey)return;let t=Yr(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:yc(),sdkVersion:_n,sdkPackage:zr})})}catch{}}var qr="fyodos:anon-caller:v1",pe=null;function Qr(){try{let e=globalThis.crypto;if(e!=null&&e.randomUUID)return`anon-${e.randomUUID()}`}catch{}return`anon-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function xc(){if(pe)return pe;try{let e=window.localStorage.getItem(qr);if(e)return pe=e,e;let t=Qr();return window.localStorage.setItem(qr,t),pe=t,t}catch{return pe=pe!=null?pe:Qr(),pe}}function Jr(e){return()=>{let t=e==null?void 0:e();return t||xc()}}function vc(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 Zr(){var e,t;return typeof document!="undefined"&&((t=(e=document.documentElement.lang)==null?void 0:e.split(/[-_]/)[0])==null?void 0:t.trim())||""}function ei(e){var o,r,i;let t=(r=(o=e.getLocale)==null?void 0:o.call(e))==null?void 0:r.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 s=Zr();if(s)return s}let n=Zr();return n||"en"}function ti(e,t,n){var p,f,m,h;let o=ni(),r=ei(e),i=(f=(p=e.sttLocale)!=null?p:e.locale)!=null?f:o.sttLocale,s=Jr(e.getUserId),a=fr({baseUrl:n,apiKey:e.apiKey,getUserId:s}),l=hr({baseUrl:n,apiKey:e.apiKey,getUserId:s}),c={manifest:t,locale:r,getLocale:()=>ei(e),sttLocale:i,navigation:mr({navigate:(m=e.navigate)!=null?m:vc,getCurrentRoute:e.getCurrentRoute}),registries:(h=e.registries)!=null?h:{handlers:{},idempotencyCheckers:{}},backend:a,voice:xr(),storage:gr(),telemetry:l,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},u=new Ve(c);return u.warmUp(),u}function oi(e){var a,l;let t=((a=e.baseUrl)!=null?a:Gr).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=ti(e,e.manifest,t),u=n?Tt(c,e.orb):null;return n&&e.apiKey&&Ao({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 r,i={controller:null,orb:null,ready:Promise.resolve(null),resetConversation(){var c;(c=i.controller)==null||c.resetConversation()},setScreenContext(c){i.controller?i.controller.screenStore.set(o,c):r=c},clearScreenContext(){i.controller?i.controller.screenStore.clear(o):r=null},destroy(){var c,u;s=!0,(c=i.orb)==null||c.unmount(),(u=i.controller)==null||u.dispose()}},s=!1;return i.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 Kr({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),Co(h,{baseUrl:t}),null}let f=me(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
65
65
  - ${f.errors.join(`
66
- - `)}`);let h=tr(e,p.manifest,t);return s?(h.dispose(),null):(r.controller=h,i&&h.screenStore.set(o,i),i=void 0,r.orb=n?Tt(h,e.orb):null,n&&e.apiKey&&Ao({baseUrl:t,apiKey:e.apiKey}),(c=e.onReady)==null||c.call(e,h),h)}catch(p){let f=p instanceof Error?p:new Error(String(p));return console.error(f.message),Co(f.message,{baseUrl:t}),(u=e.onError)==null||u.call(e,f),null}})(),r}function Pn(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function Cc(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 Ac(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return Pn(o);if(Array.isArray(o)&&o.length)return Pn(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?Pn(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=Cc(t);return o?Pn(o):null}return null}function So(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function wo(e,t={}){var m,x,T,v,S,I,E,g;let n=(m=e.data)==null?void 0:m.entity;if(!n)return null;let o=n.getEntityName(),i=So((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=Ac(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 h={...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:h}}function ir(e,t,n={}){var s;let o=!1,i=()=>{if(o)return;let a=wo(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()}}}}Xi();var Sc={version:_n,createFiodosAgent:or,mountOrb:Tt,AgentController:Ve,createScreenContextStore:kn,buildApiActionRegistries:Nt,validateManifest:he,connectDynamicsFormContext:ir,dynamicsFormSnapshot:wo,normalizeDynamicsId:So};globalThis.Fiodos=Sc;})();
66
+ - `)}`);let m=ti(e,p.manifest,t);return s?(m.dispose(),null):(i.controller=m,r&&m.screenStore.set(o,r),r=void 0,i.orb=n?Tt(m,e.orb):null,n&&e.apiKey&&Ao({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),Co(f.message,{baseUrl:t}),(u=e.onError)==null||u.call(e,f),null}})(),i}function Pn(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function Cc(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 Ac(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return Pn(o);if(Array.isArray(o)&&o.length)return Pn(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?Pn(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=Cc(t);return o?Pn(o):null}return null}function So(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function wo(e,t={}){var h,g,R,v,A,I,T,b;let n=(h=e.data)==null?void 0:h.entity;if(!n)return null;let o=n.getEntityName(),r=So((g=n.getId())!=null?g:""),i=(R=t.attributes)!=null&&R.length?new Set(t.attributes.map(C=>C.trim().toLowerCase()).filter(Boolean)):null,s=(v=t.maxAttributes)!=null?v:12,a={},l=0;(A=n.attributes)==null||A.forEach(C=>{let S;try{S=C.getName()}catch{return}if(!S)return;if(i){if(!i.has(S.toLowerCase()))return}else if(l>=s)return;let N=Ac(C);N!=null&&(a[S]=N,l+=1)});let c;try{c=(T=(I=n.getPrimaryAttributeValue)==null?void 0:I.call(n))!=null?T:void 0}catch{c=void 0}let u=r?{id:r,kind:o,title:c,metadata:a}:null,p=Object.entries(a).map(([C,S])=>`${C}: ${S}`).join("; "),f=[`Dynamics 365 form \u2014 entity "${o}"`,r?`record "${c!=null?c:r}" (id ${r})`:"new record (not saved yet)"];p&&f.push(`Fields: ${p}`);let m={...u?{visibleContent:{items:[u],focusedIndex:0}}:{},custom:{platform:"dynamics365",entityName:o,...r?{recordId:r}:{},...typeof((b=e.ui)==null?void 0:b.getFormType)=="function"?{formType:e.ui.getFormType()}:{}}};return{kind:`dynamics-form:${o}`,text:f.join(". "),context:m}}function ri(e,t,n={}){var s;let o=!1,r=()=>{if(o)return;let a=wo(t,n);a?e.setScreenContext(a):e.clearScreenContext()};r();let i=(s=t.data)==null?void 0:s.entity;if(i!=null&&i.addOnPostSave)try{i.addOnPostSave(r)}catch{}return{refresh:r,disconnect(){var a;if(!o){o=!0;try{(a=i==null?void 0:i.removeOnPostSave)==null||a.call(i,r)}catch{}e.clearScreenContext()}}}}Xr();var Sc={version:_n,createFiodosAgent:oi,mountOrb:Tt,AgentController:Ve,createScreenContextStore:kn,buildApiActionRegistries:Nt,validateManifest:me,connectDynamicsFormContext:ri,dynamicsFormSnapshot:wo,normalizeDynamicsId:So};globalThis.Fiodos=Sc;})();