@fiodos/web-core 0.1.20 → 0.1.22

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.
@@ -151,6 +151,9 @@ function createFiodosBackendClient(options) {
151
151
  intent: request.lastStep.intent,
152
152
  ...(request.lastStep.label ? { label: request.lastStep.label } : {}),
153
153
  success: request.lastStep.success,
154
+ // Technical error of a FAILED step: the backend renders it in the
155
+ // RECOVERY block so the model can diagnose and change path.
156
+ ...(request.lastStep.error ? { error: request.lastStep.error } : {}),
154
157
  // Bounded result payload of the executed step (product search
155
158
  // results…): the backend renders it so the model can read real
156
159
  // ids for the NEXT step's parameters.
@@ -28,6 +28,13 @@ const speechSession_1 = require("../speech/speechSession");
28
28
  const turnEngine_1 = require("../core/turnEngine");
29
29
  const types_1 = require("../config/types");
30
30
  const messages_1 = require("../ui/messages");
31
+ /**
32
+ * How many FAILED-step recovery turns one chain may consume. A failed action
33
+ * (invented handle → 404, wrong id kind → 422, transient 5xx) no longer kills
34
+ * the task: the model gets the technical error back and picks a different
35
+ * path — bounded so a persistently failing action can never loop.
36
+ */
37
+ const MAX_CHAIN_RECOVERIES = 2;
31
38
  function randomSessionId() {
32
39
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
33
40
  }
@@ -525,6 +532,28 @@ class AgentController {
525
532
  step: chainState.step,
526
533
  lastStep: chainState.pendingStep ?? chainState.lastStep,
527
534
  visitedKeys: chainState.visitedKeys,
535
+ recoveries: chainState.recoveries,
536
+ });
537
+ }
538
+ else if (!result.success && this.chaining.enabled) {
539
+ // The CONFIRMED action failed: same recovery contract as any other
540
+ // failed step — the model reads the technical error and takes a
541
+ // different path (bounded by the recovery budget). The user's
542
+ // confirmation covered THIS intent; a recovery that re-attempts it
543
+ // stages a NEW confirmation, so the human gate is never bypassed.
544
+ const failedStep = {
545
+ type: 'execute',
546
+ intent: pending.intent,
547
+ label: this.actionLabel(pending.intent),
548
+ success: false,
549
+ ...(result.error ? { error: String(result.error).slice(0, 300) } : {}),
550
+ };
551
+ await this.runChainLoop({
552
+ userMessage: chainState.userMessage,
553
+ step: chainState.step,
554
+ lastStep: failedStep,
555
+ visitedKeys: chainState.visitedKeys,
556
+ recoveries: (chainState.recoveries ?? 0) + 1,
528
557
  });
529
558
  }
530
559
  else if (!result.success) {
@@ -692,6 +721,7 @@ class AgentController {
692
721
  let pendingInProgress = false;
693
722
  let pendingStep;
694
723
  let pendingKey;
724
+ let stepFailed = false;
695
725
  if (decision.kind === 'executed') {
696
726
  const r = decision.result;
697
727
  // REAL activity for the panel: this action actually just ran — the
@@ -732,6 +762,15 @@ class AgentController {
732
762
  if (r.recoverable) {
733
763
  /* keep the assistant's guiding reply; never speak a refusal. */
734
764
  }
765
+ else if (turn.action?.type === 'navigate' &&
766
+ r.success &&
767
+ turn.taskStatus === 'in_progress') {
768
+ // Mid-chain navigate housekeeping (e.g. the no-op "you're already on
769
+ // that screen"): the task CONTINUES with the next step, so replacing
770
+ // the reply here would speak an irrelevant aside ("Ya estás en esa
771
+ // pantalla") instead of the model's narration of what it is doing.
772
+ // Keep the LLM reply; the chain's final step sets the real outcome.
773
+ }
735
774
  else if (r.message) {
736
775
  // FEEDBACK GUARANTEE: the handler's outcome message (success,
737
776
  // idempotent or failure) is the ground truth that the action ran;
@@ -755,6 +794,24 @@ class AgentController {
755
794
  // be findable in the console or every field report is undebuggable.
756
795
  console.warn(`[fyodos] action "${turn.action?.intent ?? '?'}" failed: ${r.error ?? 'unknown error'}`);
757
796
  }
797
+ // RECOVERY signal: the step RAN and FAILED (not a recoverable guidance
798
+ // case). Feed the technical error back as a failed lastStep so the model
799
+ // can diagnose (invented handle → 404, wrong id kind → 422…) and take a
800
+ // DIFFERENT path, exactly like a human agent. The chain loop bounds how
801
+ // many of these turns run (MAX_CHAIN_RECOVERIES); task_status is
802
+ // irrelevant here — the model believed the step would succeed.
803
+ if (turn.action?.type === 'execute' && !r.success && !r.recoverable) {
804
+ const intent = turn.action.intent ?? '';
805
+ lastStep = {
806
+ type: 'execute',
807
+ intent,
808
+ label: this.actionLabel(intent),
809
+ success: false,
810
+ ...(r.error ? { error: String(r.error).slice(0, 300) } : {}),
811
+ };
812
+ stepFailed = true;
813
+ canContinue = this.chaining.enabled;
814
+ }
758
815
  // Chain signal: only a cleanly EXECUTED, non-recoverable step may advance,
759
816
  // and only when the backend asked to continue (task_status=in_progress).
760
817
  if (turn.action &&
@@ -830,6 +887,7 @@ class AgentController {
830
887
  pendingInProgress,
831
888
  pendingStep,
832
889
  pendingKey,
890
+ stepFailed,
833
891
  };
834
892
  }
835
893
  /**
@@ -840,6 +898,7 @@ class AgentController {
840
898
  async runChainLoop(state) {
841
899
  let step = state.step;
842
900
  let lastStep = state.lastStep;
901
+ let recoveries = state.recoveries ?? 0;
843
902
  const visitedKeys = state.visitedKeys;
844
903
  // Keep the panel's live row visible for the WHOLE chain (including the
845
904
  // dwell between steps), so the real narration never flickers away.
@@ -936,6 +995,7 @@ class AgentController {
936
995
  visitedKeys,
937
996
  pendingKey: oc.pendingKey,
938
997
  pendingStep: oc.pendingStep,
998
+ recoveries,
939
999
  }
940
1000
  : null;
941
1001
  this.beginConfirmationVoiceWindow();
@@ -943,6 +1003,21 @@ class AgentController {
943
1003
  }
944
1004
  if (this.phase !== 'speaking')
945
1005
  this.setPhase('idle');
1006
+ // Failed step: consume one recovery slot. The budget is what keeps a
1007
+ // persistently failing action from looping; a chain that exhausts it
1008
+ // ends with the (honest) failure reply already on screen.
1009
+ if (oc.stepFailed) {
1010
+ recoveries += 1;
1011
+ if (recoveries > MAX_CHAIN_RECOVERIES) {
1012
+ this.telemetry.logEvent({
1013
+ eventType: 'agent_chain_aborted',
1014
+ sessionId: this.sessionId,
1015
+ chainStep: step,
1016
+ chainAbortReason: 'no_progress',
1017
+ });
1018
+ return;
1019
+ }
1020
+ }
946
1021
  if (oc.actionKey && visitedKeys.has(oc.actionKey)) {
947
1022
  this.telemetry.logEvent({
948
1023
  eventType: 'agent_chain_aborted',
@@ -1125,7 +1200,8 @@ class AgentController {
1125
1200
  this.setPhase('idle');
1126
1201
  }
1127
1202
  // Kick off the autonomous chain when the first step executed cleanly and
1128
- // the backend asked to continue (no sensitive confirmation pending).
1203
+ // the backend asked to continue (no sensitive confirmation pending) — or
1204
+ // when the first step FAILED and a recovery turn should diagnose it.
1129
1205
  if (this.chaining.enabled && outcome.canContinue && !hasPending) {
1130
1206
  this.telemetry.logEvent({
1131
1207
  eventType: 'agent_chain_started',
@@ -1140,6 +1216,7 @@ class AgentController {
1140
1216
  step: 1,
1141
1217
  lastStep: outcome.lastStep,
1142
1218
  visitedKeys,
1219
+ recoveries: outcome.stepFailed ? 1 : 0,
1143
1220
  });
1144
1221
  }
1145
1222
  // Final reply is on screen: the live narrative disappears (unless the
@@ -27,7 +27,7 @@ import { createScreenContextStore } from '../context/screenContextStore';
27
27
  import { connectDynamicsFormContext, dynamicsFormSnapshot, normalizeDynamicsId } from './dynamics';
28
28
  import { buildApiActionRegistries, validateManifest } from '@fiodos/core';
29
29
  declare const api: {
30
- readonly version: "0.1.20";
30
+ readonly version: "0.1.22";
31
31
  readonly createFiodosAgent: typeof createFiodosAgent;
32
32
  readonly mountOrb: typeof mountOrb;
33
33
  readonly AgentController: typeof AgentController;
@@ -5,5 +5,5 @@
5
5
  * Auto-generated by scripts/sync-sdk-version.mjs from package.json. Do not edit
6
6
  * by hand — change package.json `version` and re-run the sync/release script.
7
7
  */
8
- export declare const SDK_VERSION = "0.1.20";
8
+ export declare const SDK_VERSION = "0.1.22";
9
9
  export declare const SDK_PACKAGE = "@fiodos/web-core";
@@ -8,5 +8,5 @@ exports.SDK_PACKAGE = exports.SDK_VERSION = void 0;
8
8
  * Auto-generated by scripts/sync-sdk-version.mjs from package.json. Do not edit
9
9
  * by hand — change package.json `version` and re-run the sync/release script.
10
10
  */
11
- exports.SDK_VERSION = '0.1.20';
11
+ exports.SDK_VERSION = '0.1.22';
12
12
  exports.SDK_PACKAGE = '@fiodos/web-core';
@@ -1,6 +1,6 @@
1
- "use strict";(()=>{var vi=new Set(["navigate","execute","none"]);function kt(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!vi.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 ue="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,a,s;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:((a=t.contextRequirements)==null?void 0:a.requiresVisibleContent)===!0,requires_auth:((s=t.contextRequirements)==null?void 0:s.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 zn=/\{([a-zA-Z0-9_]+)\}/g,Ci="baseUrl";var Ai=new Set([429,502,503,504]),Si=1200;function Lt(e){let t=[];for(let n of e.matchAll(zn)){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 Pe=class extends Error{};function wi(e,t,n){return e.replace(zn,(o,r)=>{if(r===Ci){if(!n)throw new Pe("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let i=t[r];if(i==null)throw new Pe(`Missing parameter '${r}' for URL template`);return encodeURIComponent(String(i))})}function Hn(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 Pe(`Missing parameter '${o}' for body template`);return r}return e.replace(zn,(o,r)=>{let i=t[r];if(i==null)throw new Pe(`Missing parameter '${r}' for body template`);return String(i)})}return Array.isArray(e)?e.map(n=>Hn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Hn(o,t)])):e}function Ei(){let e=globalThis.fetch;return typeof e=="function"?e:null}function Ti(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 Ri(e,t){var r,i;let n=(r=t.baseUrl)==null?void 0:r.replace(/\/$/,""),o=(i=t.timeoutMs)!=null?i:15e3;return async a=>{var p,f,m,h,g;let s={...(p=e.headers)!=null?p:{}};if(e.authRef){let w=(f=t.authProviders)==null?void 0:f[e.authRef];if(!w)return{success:!1,error:`Auth provider not registered: ${e.authRef}`};try{Object.assign(s,await w())}catch(S){return{success:!1,error:`Auth provider '${e.authRef}' failed: ${S instanceof Error?S.message:"unknown"}`}}}let l,c;try{l=wi(e.url,a,n),e.body&&(s["Content-Type"]=(m=s["Content-Type"])!=null?m:"application/json",c=JSON.stringify(Hn(e.body,a)))}catch(w){return{success:!1,error:w instanceof Error?w.message:"Template resolution failed"}}let u=(h=t.fetchFn)!=null?h:Ei();if(!u)return{success:!1,error:"No fetch implementation available"};for(let w=0;;w+=1){let S=Ti(o);try{let C=await u(l,{method:e.method,headers:s,...c!==void 0?{body:c}:{},...S.signal?{signal:S.signal}:{}});if(!C.ok){if(w===0&&Ai.has(C.status)){S.cancel(),await Ii(Si);continue}let R="";try{R=(await C.text()).slice(0,200)}catch{}return{success:!1,error:`HTTP ${C.status} (${e.method} ${Wo(l)})${R?`: ${R}`:""}`}}let O;try{if(((g=C.headers.get("content-type"))!=null?g:"").includes("json")){let b=await C.text();if(b){let v=JSON.parse(b);v&&typeof v=="object"&&!Array.isArray(v)&&(O=v)}}}catch{}return{success:!0,...O?{data:O}:{}}}catch(C){return{success:!1,error:`Request failed (${e.method} ${Wo(l)}): ${C instanceof Error?C.message:"unknown"}`}}finally{S.cancel()}}}}function Wo(e){var n,o;let t=/^[a-z]+:\/\/[^/]+(\/[^?#]*)/i.exec(e);return(o=(n=t==null?void 0:t[1])!=null?n:e.split("?")[0])!=null?o:e}function Ii(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}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 a=(r=i.handler)==null?void 0:r.trim();a&&(n[a]=Ri(i.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var Oi=new Set(["string","number","boolean"]),_i=new Set(["standard","strict","disabled"]),ki=new Set(["GET","POST","PUT","PATCH","DELETE"]);function Pi(e,t,n){var i,a;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)}'`),ki.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((a=e.parameters)!=null?a:{}));for(let s of Bt(o))s!=="baseUrl"&&!r.has(s)&&n.push(`action '${t}' execution references undeclared parameter '{${s}}'`)}function ge(e){var o,r,i,a,s,l,c,u,p,f,m,h,g,w,S,C,O;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 R of(a=e.routes)!=null?a:[]){let b=(s=R.intent)==null?void 0:s.trim();if(!b){t.push("route with empty intent");continue}n.has(b)&&t.push(`duplicate intent: ${b}`),n.add(b),(l=R.route)!=null&&l.trim()||t.push(`route intent '${b}' has empty route`),(c=R.examples)!=null&&c.length||t.push(`route intent '${b}' has no examples`)}for(let R of(u=e.actions)!=null?u:[]){let b=(p=R.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),R.kind==="link"?(f=R.navTarget)!=null&&f.trim()||t.push(`link action '${b}' has empty navTarget`):(m=R.handler)!=null&&m.trim()||t.push(`action '${b}' has empty handler`),(h=R.examples)!=null&&h.length||t.push(`action '${b}' has no examples`),R.doubleConfirmation&&!R.requireConfirmation&&t.push(`action '${b}' declares doubleConfirmation without requireConfirmation`),R.voiceConfirmation!==void 0&&(_i.has(R.voiceConfirmation)||t.push(`action '${b}' has invalid voiceConfirmation '${R.voiceConfirmation}'`),R.requireConfirmation||t.push(`action '${b}' declares voiceConfirmation without requireConfirmation`)),R.confirmationPhrase!==void 0&&!R.confirmationPhrase.trim()&&t.push(`action '${b}' has an empty confirmationPhrase`),R.requireConfirmation&&!((g=R.confirmationMessageTemplate)!=null&&g.trim())&&t.push(`action '${b}' requires confirmation but has no confirmationMessageTemplate`);for(let[v,A]of Object.entries((w=R.parameters)!=null?w:{}))Oi.has(A.type)||t.push(`action '${b}' parameter '${v}' has invalid type '${A.type}'`),(S=A.description)!=null&&S.trim()||t.push(`action '${b}' parameter '${v}' has empty description`);for(let v of(O=(C=R.contextRequirements)==null?void 0:C.custom)!=null?O:[])v.trim()||t.push(`action '${b}' has an empty custom requirement name`);Pi(R,b,t)}return{valid:t.length===0,errors:t}}function Vn(e,t,n,o){var i,a,s,l,c,u,p,f;let r=e.contextRequirements;if(!r)return{ok:!0};if(r.requiresVisibleContent&&!(((a=(i=t.visibleContent)==null?void 0:i.items.length)!=null?a: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=(s=globalThis.console)==null?void 0:s.warn)==null||l.call(s,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(w){return{ok:!1,reason:`Context validator '${m}' threw: ${w instanceof Error?w.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 et(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 a=t.find(c=>c.intent===i);if(!a)return{kind:"done",result:{success:!1,error:`Unknown action intent: ${i}`}};let s=Vn(a,n,o,r);if(!s.ok)return{kind:"done",result:{success:!1,error:s.reason,message:s.userMessage,recoverable:s.recoverable}};if(a.idempotencyCheck){let c=o.idempotencyCheckers[a.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:a}}async function tt(e,t,n,o,r){var l;let i=await et(e,t,n,o,r);if(i.kind==="done")return i.result;let{actionConfig:a}=i,s=o.handlers[a.handler];if(!s)return{success:!1,error:`Handler not found: ${a.handler}`,message:r.messages.actionUnavailable};try{return await s((l=e.parameters)!=null?l:{},n,a.intent)}catch(c){return{success:!1,error:`Handler failed: ${c instanceof Error?c.message:"unknown"}`,message:r.messages.actionFailed}}}var Uo={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 Ho={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 nt={en:Uo,es:Ho};function Li(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function $t(e,t={}){var a,s,l;let n=(a=t.catalogs)!=null?a:{},o=(s=n[e])!=null?s:nt[e],r=Li(e),i=(l=o!=null?o:n[r])!=null?l:nt[r];if(!i){let c=[...new Set([...Object.keys(nt),...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 Ce(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var zo=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function Bi(e){let t=Ce(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||zo.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&zo.test(n[0]))}function Ni(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Gn(e){return Ni(e)==="es"}var Vo=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function $i(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function Di(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 a=o.get(i);if(a)return a}return null}function Fi(e,t){var c;let n=Gn(t),o=Ce(e.label),r=Ce(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 Ce(e.intent).replace(/_/g," ")}function Wi(e,t,n){let o=Fi(e,n);return ee(t.bubblePromptFromAction,{action:o})}function Ui(e,t){let n=e.toLowerCase(),o=Gn(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 Hi(e,t){let n=Gn(t),o=$i(e.intent),r=Ce(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 zi(e,t,n){var i;let o=((i=e.examples)!=null?i:[]).map(Ce).find(a=>a.length>0&&Bi(a));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 Dt(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=Di(e,r);if(i)return Wi(i,t,o);let a=Ce(e.description);if(a){let c=Ui(a,o);if(c)return c}let s=Hi(e,o);return s||zi(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 Go(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}var Vi=/^[a-z]{2}(-[a-z0-9]{2,4})?$/;function Gi(e){if(!e)return null;let t=e.indexOf("/"),n=t===-1?e:e.slice(0,t);return Vi.test(n)?t===-1?"":e.slice(t+1):null}function ot(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(l=>l&&l.route&&l.route!==ue);if(r.length===0)return null;function i(l){for(let u of r)if(K(u.route)===l)return u;if(l){let u=null;for(let p of r){let f=K(p.route);if(!f)continue;(l===f||l.startsWith(`${f}/`)||f.startsWith(`${l}/`)||l.endsWith(`/${f}`)||f.endsWith(`/${l}`))&&(!u||f.length>u.len)&&(u={route:p,len:f.length})}if(u)return u.route}let c=Go(l)||l;if(c){for(let u of r)if(K(u.intent)===c||K(u.label)===c||Go(K(u.route))===c)return u;for(let u of r)if(K(u.intent)===l||K(u.label)===l)return u}return null}let a=i(o);if(a)return a;let s=Gi(o);return s!=null&&s!==o?i(s):null}function Yn(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})],a=(u=e.description)==null?void 0:u.trim();a&&i.push(a);let s=(p=e.actionIntents)!=null?p:[];if(s.length>0&&r&&r.length>0){let m=new Map(r.map(w=>[w.intent,w])),h=[],g=new Set;for(let w of s){let S=m.get(w),C=(f=S==null?void 0:S.label)==null?void 0:f.trim();C&&!g.has(C)&&(g.add(C),h.push(C))}h.length>0&&i.push(ee(o.currentScreenActions,{actions:h.join(", ")}))}return i.join(" \u2014 ")}function Ko(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Yo(e){return String(e!=null?e:"").split(/[-_]/)[0].trim().toLowerCase()}function Yi(e,t){let n=e.bubblePrompts;if(!n||typeof n!="object")return null;let o=Yo(t);if(!o)return null;for(let[r,i]of Object.entries(n))if(Yo(r)===o){let a=Ko(i);if(a)return a}return null}function Ft(e,t,n){if(!e)return null;let o=Yi(e,n==null?void 0:n.locale);if(o)return o;let r=Ko(e.bubblePrompt);if(r)return r;let i=Dt(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=ot(e,t.routes);return Yn(o,{messages:n,actions:t.actions})}var Ki=/(^|[\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,ji=/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,Xi=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,qi=/pass(word)?|contrase|clave|pwd/i;function jn(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(ji.test(t)||!Ki.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&&qi.test(r)){n=r;continue}t===null&&Xi.test(r)&&(t=r)}return{usernameParam:t,passwordParam:n}}function Kn(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(!jn(t))return{kind:"not-applicable"};if((o==null?void 0:o())===!0)return{kind:"not-applicable"};let{usernameParam:i,passwordParam:a}=Ut(t);if(!i||!a)return{kind:"not-applicable"};let s=(c=e.parameters)!=null?c:{};if(Kn(s[i])&&Kn(s[a]))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:{...s,[i]:Kn(s[i])?s[i]:l.username,[a]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}var jo=/FYODOS_HANDLER_UNREADY|is not a function/i,Qi=12,Ji=300;function Zi(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}function zt(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(i){var l,c;let a=(l=i.intent)==null?void 0:l.trim();if(!a)return{success:!1,error:"No intent specified"};let s=e.manifest.routes.find(u=>u.intent===a);if(!s)return{success:!1,error:`Unknown intent: ${a}`};if(s.route!==ue&&e.messages.alreadyOnScreen)try{let u=e.navigation.getCurrentRoute();if(u!=null&&String(u).trim()!==""&&K(u)===K(s.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return s.route===ue?e.navigation.back():e.navigation.navigate(s.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,a){var p,f,m;let s=await tt(i,e.manifest.actions,a,e.registries,t);if(s.success||!jo.test((p=s.error)!=null?p:""))return s;let l=(f=i.intent)==null?void 0:f.trim(),c=e.manifest.routes.find(h=>h.route!==ue&&Array.isArray(h.actionIntents)&&l!=null&&h.actionIntents.includes(l));if(!c)return s;try{let h=e.navigation.getCurrentRoute();h!=null&&String(h).trim()!==""&&K(h)===K(c.route)||e.navigation.navigate(c.route)}catch{return s}let u=s;for(let h=0;h<Qi;h+=1)if(await Zi(Ji),u=await tt(i,e.manifest.actions,a,e.registries,t),u.success||!jo.test((m=u.error)!=null?m:""))return u;return u}function r(i,a,s){if(s||!(i!=null&&i.showcaseRoute)||!a.success||a.recoverable)return;let l=e.manifest.routes.find(c=>c.intent===i.showcaseRoute);if(!(!l||l.route===ue))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,a={},s={}){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,a);return r(u,m,s.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,a);return r(u,p,s.suppressEscort),p}return{success:!1,error:`Action type not implemented: ${i.type}`}},async precheck(i,a={}){return et(i,e.manifest.actions,a,e.registries,t)},escortForIntent(i){let a=e.manifest.actions.find(s=>s.intent===(i==null?void 0:i.trim()));r(a,{success:!0})}}}function Vt(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 Xo=new Set;function Gt(e,t){var a,s,l;if(!t)return e;let n=(a=e.actions)!=null?a:[],o=n.filter(c=>Vt(c,t));if(o.length===n.length)return e;let r=n.filter(c=>!Vt(c,t)).map(c=>c.intent).sort(),i=r.join(",");return Xo.has(i)||(Xo.add(i),(l=(s=globalThis.console)==null?void 0:s.warn)==null||l.call(s,`[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 Xn(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=>Xn(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,Xn(o,t+1)]))}function Yt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return;let t;try{t=Xn(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 Me(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 rt(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 Me(r,{...n,maxChars:o});if(!r)return Me(i,{...n,maxChars:o});let a=`
1
+ "use strict";(()=>{var vi=new Set(["navigate","execute","none"]);function kt(e){if(!e||typeof e!="object")return null;let t=e,n=t.type;if(typeof n!="string"||!vi.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 ue="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,a,s;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:((a=t.contextRequirements)==null?void 0:a.requiresVisibleContent)===!0,requires_auth:((s=t.contextRequirements)==null?void 0:s.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 zn=/\{([a-zA-Z0-9_]+)\}/g,Ci="baseUrl";var Ai=new Set([429,502,503,504]),Si=1200;function Lt(e){let t=[];for(let n of e.matchAll(zn)){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 Pe=class extends Error{};function wi(e,t,n){return e.replace(zn,(o,r)=>{if(r===Ci){if(!n)throw new Pe("URL template uses {baseUrl} but no baseUrl was provided to buildApiActionRegistries");return n}let i=t[r];if(i==null)throw new Pe(`Missing parameter '${r}' for URL template`);return encodeURIComponent(String(i))})}function Hn(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 Pe(`Missing parameter '${o}' for body template`);return r}return e.replace(zn,(o,r)=>{let i=t[r];if(i==null)throw new Pe(`Missing parameter '${r}' for body template`);return String(i)})}return Array.isArray(e)?e.map(n=>Hn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Hn(o,t)])):e}function Ei(){let e=globalThis.fetch;return typeof e=="function"?e:null}function Ti(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 Ri(e,t){var r,i;let n=(r=t.baseUrl)==null?void 0:r.replace(/\/$/,""),o=(i=t.timeoutMs)!=null?i:15e3;return async a=>{var p,f,m,h,g;let s={...(p=e.headers)!=null?p:{}};if(e.authRef){let w=(f=t.authProviders)==null?void 0:f[e.authRef];if(!w)return{success:!1,error:`Auth provider not registered: ${e.authRef}`};try{Object.assign(s,await w())}catch(C){return{success:!1,error:`Auth provider '${e.authRef}' failed: ${C instanceof Error?C.message:"unknown"}`}}}let l,c;try{l=wi(e.url,a,n),e.body&&(s["Content-Type"]=(m=s["Content-Type"])!=null?m:"application/json",c=JSON.stringify(Hn(e.body,a)))}catch(w){return{success:!1,error:w instanceof Error?w.message:"Template resolution failed"}}let u=(h=t.fetchFn)!=null?h:Ei();if(!u)return{success:!1,error:"No fetch implementation available"};for(let w=0;;w+=1){let C=Ti(o);try{let v=await u(l,{method:e.method,headers:s,...c!==void 0?{body:c}:{},...C.signal?{signal:C.signal}:{}});if(!v.ok){if(w===0&&Ai.has(v.status)){C.cancel(),await Ii(Si);continue}let R="";try{R=(await v.text()).slice(0,200)}catch{}return{success:!1,error:`HTTP ${v.status} (${e.method} ${Wo(l)})${R?`: ${R}`:""}`}}let O;try{if(((g=v.headers.get("content-type"))!=null?g:"").includes("json")){let b=await v.text();if(b){let E=JSON.parse(b);E&&typeof E=="object"&&!Array.isArray(E)&&(O=E)}}}catch{}return{success:!0,...O?{data:O}:{}}}catch(v){return{success:!1,error:`Request failed (${e.method} ${Wo(l)}): ${v instanceof Error?v.message:"unknown"}`}}finally{C.cancel()}}}}function Wo(e){var n,o;let t=/^[a-z]+:\/\/[^/]+(\/[^?#]*)/i.exec(e);return(o=(n=t==null?void 0:t[1])!=null?n:e.split("?")[0])!=null?o:e}function Ii(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}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 a=(r=i.handler)==null?void 0:r.trim();a&&(n[a]=Ri(i.execution,t))}return{handlers:n,idempotencyCheckers:{},contextValidators:{}}}var Oi=new Set(["string","number","boolean"]),_i=new Set(["standard","strict","disabled"]),ki=new Set(["GET","POST","PUT","PATCH","DELETE"]);function Pi(e,t,n){var i,a;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)}'`),ki.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((a=e.parameters)!=null?a:{}));for(let s of Bt(o))s!=="baseUrl"&&!r.has(s)&&n.push(`action '${t}' execution references undeclared parameter '{${s}}'`)}function ge(e){var o,r,i,a,s,l,c,u,p,f,m,h,g,w,C,v,O;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 R of(a=e.routes)!=null?a:[]){let b=(s=R.intent)==null?void 0:s.trim();if(!b){t.push("route with empty intent");continue}n.has(b)&&t.push(`duplicate intent: ${b}`),n.add(b),(l=R.route)!=null&&l.trim()||t.push(`route intent '${b}' has empty route`),(c=R.examples)!=null&&c.length||t.push(`route intent '${b}' has no examples`)}for(let R of(u=e.actions)!=null?u:[]){let b=(p=R.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),R.kind==="link"?(f=R.navTarget)!=null&&f.trim()||t.push(`link action '${b}' has empty navTarget`):(m=R.handler)!=null&&m.trim()||t.push(`action '${b}' has empty handler`),(h=R.examples)!=null&&h.length||t.push(`action '${b}' has no examples`),R.doubleConfirmation&&!R.requireConfirmation&&t.push(`action '${b}' declares doubleConfirmation without requireConfirmation`),R.voiceConfirmation!==void 0&&(_i.has(R.voiceConfirmation)||t.push(`action '${b}' has invalid voiceConfirmation '${R.voiceConfirmation}'`),R.requireConfirmation||t.push(`action '${b}' declares voiceConfirmation without requireConfirmation`)),R.confirmationPhrase!==void 0&&!R.confirmationPhrase.trim()&&t.push(`action '${b}' has an empty confirmationPhrase`),R.requireConfirmation&&!((g=R.confirmationMessageTemplate)!=null&&g.trim())&&t.push(`action '${b}' requires confirmation but has no confirmationMessageTemplate`);for(let[E,A]of Object.entries((w=R.parameters)!=null?w:{}))Oi.has(A.type)||t.push(`action '${b}' parameter '${E}' has invalid type '${A.type}'`),(C=A.description)!=null&&C.trim()||t.push(`action '${b}' parameter '${E}' has empty description`);for(let E of(O=(v=R.contextRequirements)==null?void 0:v.custom)!=null?O:[])E.trim()||t.push(`action '${b}' has an empty custom requirement name`);Pi(R,b,t)}return{valid:t.length===0,errors:t}}function Vn(e,t,n,o){var i,a,s,l,c,u,p,f;let r=e.contextRequirements;if(!r)return{ok:!0};if(r.requiresVisibleContent&&!(((a=(i=t.visibleContent)==null?void 0:i.items.length)!=null?a: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=(s=globalThis.console)==null?void 0:s.warn)==null||l.call(s,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(w){return{ok:!1,reason:`Context validator '${m}' threw: ${w instanceof Error?w.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 et(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 a=t.find(c=>c.intent===i);if(!a)return{kind:"done",result:{success:!1,error:`Unknown action intent: ${i}`}};let s=Vn(a,n,o,r);if(!s.ok)return{kind:"done",result:{success:!1,error:s.reason,message:s.userMessage,recoverable:s.recoverable}};if(a.idempotencyCheck){let c=o.idempotencyCheckers[a.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:a}}async function tt(e,t,n,o,r){var l;let i=await et(e,t,n,o,r);if(i.kind==="done")return i.result;let{actionConfig:a}=i,s=o.handlers[a.handler];if(!s)return{success:!1,error:`Handler not found: ${a.handler}`,message:r.messages.actionUnavailable};try{return await s((l=e.parameters)!=null?l:{},n,a.intent)}catch(c){return{success:!1,error:`Handler failed: ${c instanceof Error?c.message:"unknown"}`,message:r.messages.actionFailed}}}var Uo={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 Ho={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 nt={en:Uo,es:Ho};function Li(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function $t(e,t={}){var a,s,l;let n=(a=t.catalogs)!=null?a:{},o=(s=n[e])!=null?s:nt[e],r=Li(e),i=(l=o!=null?o:n[r])!=null?l:nt[r];if(!i){let c=[...new Set([...Object.keys(nt),...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 Ce(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}var zo=/^(open|go to|navigate|show|view|launch|access|enter|get|take me|ir a|abrir|mostrar|ver|llévame)\b/i;function Bi(e){let t=Ce(e);if(!t||t.length>72)return!1;if(t.includes("?")||t.includes("\xBF")||/[áéíóúñüÁÉÍÓÚÑÜ]/.test(t))return!0;if(/[_-]/.test(t)||zo.test(t)||!/\s/.test(t)&&t===t.toLowerCase())return!1;let n=t.split(/\s+/);return!(n.length===2&&zo.test(n[0]))}function Ni(e){var t,n;return(n=(t=e.split(/[-_]/)[0])==null?void 0:t.toLowerCase())!=null?n:e.toLowerCase()}function Gn(e){return Ni(e)==="es"}var Vo=new Set(["home","landing","index","main","feed","dashboard","root","start"]);function $i(e){return e.toLowerCase().replace(/[\s-]+/g,"_")}function Di(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 a=o.get(i);if(a)return a}return null}function Fi(e,t){var c;let n=Gn(t),o=Ce(e.label),r=Ce(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 Ce(e.intent).replace(/_/g," ")}function Wi(e,t,n){let o=Fi(e,n);return ee(t.bubblePromptFromAction,{action:o})}function Ui(e,t){let n=e.toLowerCase(),o=Gn(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 Hi(e,t){let n=Gn(t),o=$i(e.intent),r=Ce(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 zi(e,t,n){var i;let o=((i=e.examples)!=null?i:[]).map(Ce).find(a=>a.length>0&&Bi(a));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 Dt(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=Di(e,r);if(i)return Wi(i,t,o);let a=Ce(e.description);if(a){let c=Ui(a,o);if(c)return c}let s=Hi(e,o);return s||zi(e,t,o)}function Q(e){let t=String(e!=null?e:"").trim();return t?(t=t.split("?")[0].split("#")[0],t=t.replace(/\([^)]*\)/g,""),t=t.replace(/\/{2,}/g,"/").replace(/^\/+|\/+$/g,""),t=t.replace(/(^|\/)index$/i,""),t=t.replace(/^\/+|\/+$/g,""),t.toLowerCase()):""}function Go(e){var n;if(!e)return"";let t=e.split("/");return(n=t[t.length-1])!=null?n:""}var Vi=/^[a-z]{2}(-[a-z0-9]{2,4})?$/;function Gi(e){if(!e)return null;let t=e.indexOf("/"),n=t===-1?e:e.slice(0,t);return Vi.test(n)?t===-1?"":e.slice(t+1):null}function ot(e,t){if(e==null||!t||t.length===0)return null;let n=String(e).trim();if(!n)return null;let o=Q(n),r=t.filter(l=>l&&l.route&&l.route!==ue);if(r.length===0)return null;function i(l){for(let u of r)if(Q(u.route)===l)return u;if(l){let u=null;for(let p of r){let f=Q(p.route);if(!f)continue;(l===f||l.startsWith(`${f}/`)||f.startsWith(`${l}/`)||l.endsWith(`/${f}`)||f.endsWith(`/${l}`))&&(!u||f.length>u.len)&&(u={route:p,len:f.length})}if(u)return u.route}let c=Go(l)||l;if(c){for(let u of r)if(Q(u.intent)===c||Q(u.label)===c||Go(Q(u.route))===c)return u;for(let u of r)if(Q(u.intent)===l||Q(u.label)===l)return u}return null}let a=i(o);if(a)return a;let s=Gi(o);return s!=null&&s!==o?i(s):null}function Yn(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})],a=(u=e.description)==null?void 0:u.trim();a&&i.push(a);let s=(p=e.actionIntents)!=null?p:[];if(s.length>0&&r&&r.length>0){let m=new Map(r.map(w=>[w.intent,w])),h=[],g=new Set;for(let w of s){let C=m.get(w),v=(f=C==null?void 0:C.label)==null?void 0:f.trim();v&&!g.has(v)&&(g.add(v),h.push(v))}h.length>0&&i.push(ee(o.currentScreenActions,{actions:h.join(", ")}))}return i.join(" \u2014 ")}function Ko(e){return String(e!=null?e:"").replace(/\s+/g," ").trim()}function Yo(e){return String(e!=null?e:"").split(/[-_]/)[0].trim().toLowerCase()}function Yi(e,t){let n=e.bubblePrompts;if(!n||typeof n!="object")return null;let o=Yo(t);if(!o)return null;for(let[r,i]of Object.entries(n))if(Yo(r)===o){let a=Ko(i);if(a)return a}return null}function Ft(e,t,n){if(!e)return null;let o=Yi(e,n==null?void 0:n.locale);if(o)return o;let r=Ko(e.bubblePrompt);if(r)return r;let i=Dt(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=ot(e,t.routes);return Yn(o,{messages:n,actions:t.actions})}var Ki=/(^|[\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,ji=/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,Xi=/^(e-?mail|correo|username|user|usuario|login|identifier|account)$|email|user/i,qi=/pass(word)?|contrase|clave|pwd/i;function jn(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(ji.test(t)||!Ki.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&&qi.test(r)){n=r;continue}t===null&&Xi.test(r)&&(t=r)}return{usernameParam:t,passwordParam:n}}function Kn(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(!jn(t))return{kind:"not-applicable"};if((o==null?void 0:o())===!0)return{kind:"not-applicable"};let{usernameParam:i,passwordParam:a}=Ut(t);if(!i||!a)return{kind:"not-applicable"};let s=(c=e.parameters)!=null?c:{};if(Kn(s[i])&&Kn(s[a]))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:{...s,[i]:Kn(s[i])?s[i]:l.username,[a]:l.password}}}:l.status==="dismissed"?{kind:"dismissed"}:{kind:"unavailable"}}var jo=/FYODOS_HANDLER_UNREADY|is not a function/i,Qi=12,Ji=300;function Zi(e){let t=globalThis;return new Promise(n=>{t.setTimeout?t.setTimeout(n,e):n()})}function zt(e){let t={messages:e.messages,isAuthenticated:e.isAuthenticated};function n(i){var l,c;let a=(l=i.intent)==null?void 0:l.trim();if(!a)return{success:!1,error:"No intent specified"};let s=e.manifest.routes.find(u=>u.intent===a);if(!s)return{success:!1,error:`Unknown intent: ${a}`};if(s.route!==ue&&e.messages.alreadyOnScreen)try{let u=e.navigation.getCurrentRoute();if(u!=null&&String(u).trim()!==""&&Q(u)===Q(s.route))return{success:!0,message:e.messages.alreadyOnScreen}}catch{}try{return s.route===ue?e.navigation.back():e.navigation.navigate(s.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,a){var p,f,m;let s=await tt(i,e.manifest.actions,a,e.registries,t);if(s.success||!jo.test((p=s.error)!=null?p:""))return s;let l=(f=i.intent)==null?void 0:f.trim(),c=e.manifest.routes.find(h=>h.route!==ue&&Array.isArray(h.actionIntents)&&l!=null&&h.actionIntents.includes(l));if(!c)return s;try{let h=e.navigation.getCurrentRoute();h!=null&&String(h).trim()!==""&&Q(h)===Q(c.route)||e.navigation.navigate(c.route)}catch{return s}let u=s;for(let h=0;h<Qi;h+=1)if(await Zi(Ji),u=await tt(i,e.manifest.actions,a,e.registries,t),u.success||!jo.test((m=u.error)!=null?m:""))return u;return u}function r(i,a,s){if(s||!(i!=null&&i.showcaseRoute)||!a.success||a.recoverable)return;let l=e.manifest.routes.find(c=>c.intent===i.showcaseRoute);if(!(!l||l.route===ue))try{let c=e.navigation.getCurrentRoute();if(c!=null&&String(c).trim()!==""&&Q(c)===Q(l.route))return;e.navigation.navigate(l.route)}catch{}}return{async execute(i,a={},s={}){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,a);return r(u,m,s.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,a);return r(u,p,s.suppressEscort),p}return{success:!1,error:`Action type not implemented: ${i.type}`}},async precheck(i,a={}){return et(i,e.manifest.actions,a,e.registries,t)},escortForIntent(i){let a=e.manifest.actions.find(s=>s.intent===(i==null?void 0:i.trim()));r(a,{success:!0})}}}function Vt(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 Xo=new Set;function Gt(e,t){var a,s,l;if(!t)return e;let n=(a=e.actions)!=null?a:[],o=n.filter(c=>Vt(c,t));if(o.length===n.length)return e;let r=n.filter(c=>!Vt(c,t)).map(c=>c.intent).sort(),i=r.join(",");return Xo.has(i)||(Xo.add(i),(l=(s=globalThis.console)==null?void 0:s.warn)==null||l.call(s,`[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 Xn(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=>Xn(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,Xn(o,t+1)]))}function Yt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return;let t;try{t=Xn(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 Me(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 rt(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 Me(r,{...n,maxChars:o});if(!r)return Me(i,{...n,maxChars:o});let a=`
2
2
 
3
- `,s=o-r.length-a.length;return s<=n.truncationSuffix.length?Me(r,{...n,maxChars:o}):r+a+Me(i,{...n,maxChars:s})}var qn=[{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(a=>{let s=Kt[a.toUpperCase()];if(!s)throw new Error(`[fyodos] Unknown PII country pack "${a}". Available packs: ${Object.keys(Kt).join(", ")}. Use customPatterns to add your own.`);return s}),[n,...o]=qn;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:a,replacement:s}of t)a.test(o)&&(r.push(i),o=o.replace(a,s)),a.lastIndex=0;return o=o.replace(/\+\s?\[REDACTED:PHONE\]/g,"[REDACTED:PHONE]"),{sanitized:o,redactions:r}}}function Jn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function Xt(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 Qt(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 Jt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var qo=40;function Zt(e){return typeof e!="number"||Number.isNaN(e)?qo:Math.max(0,Math.min(100,Math.round(e)))}function Qo(e,t){let n=Zt(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(s=>s===0))&&r&&typeof r.vibrate=="function"&&r.vibrate(i)}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 en(e){var o,r,i;let t=(r=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?r:e.toLowerCase(),n=(i=it[e])!=null?i: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 Le(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Jo(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function eo(e,t){let n=Le(e);return n?t.affirmative.some(o=>Jo(n,Le(o))):!1}function tn(e,t){let n=Le(e);return n?t.negative.some(o=>Jo(n,Le(o))):!1}function nn(e,t){let n=tn(e,t),o=eo(e,t);return n?"negative":o?"affirmative":"ambiguous"}function Cs(e,t){return t?` ${e} `.includes(` ${t} `):!1}function on(e,t,n){let o=Le(e);return o?tn(e,n)?"negative":Cs(o,Le(t))?"affirmative":"ambiguous":"ambiguous"}var to={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},st={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Ne(e,t=!1){let n=t?st: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 Ae=5,Be=200;function Zo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function er(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function tr(e,t,n){let o=t.map(r=>r.role==="user"?`User: ${Zo(r.content,120)}`:`Assistant: ${Zo(r.content,120)}`).join(" | ");return er(e?`${e} | ${o}`:o,n)}function no(e){return{...to,...e}}function $e(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function De(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 at(e,t=Date.now(),n){return De(e,t,n),e.lastActivityAt=t,oo(e.turns,e.summary,n)}function As(e,t){let{maxRecentTurns:n,summarizeAfterTurns:o,maxSummaryChars:r,maxStoredTurns:i}=t;if(e.turns.length>o){let a=e.turns.length-n,s=e.turns.slice(0,a);e.summary=tr(e.summary,s,r),e.turns=e.turns.slice(a)}if(e.turns.length>i){let a=e.turns.slice(0,e.turns.length-n);e.summary=tr(e.summary,a,r),e.turns=e.turns.slice(-n)}}function ct(e,t,n,o=Date.now(),r){var l;let i=no(r),a=t.trim(),s=n.trim();!a||!s||(e.turns.push({role:"user",content:a},{role:"assistant",content:s}),e.uiArchive=(l=e.uiArchive)!=null?l:[],e.uiArchive.push({userText:a,replyText:s}),e.uiArchive.length>Be&&(e.uiArchive=e.uiArchive.slice(-Be)),e.lastActivityAt=o,As(e,i))}function Ss(e,t){var i,a,s,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(!((a=t==null?void 0:t.userText)!=null&&a.trim()))return n;let o=n[n.length-1];return o!=null&&o.userText===t.userText&&o.replyText===((s=t.replyText)!=null?s:"")?t.replyText&&o.replyText!==t.replyText?[...n.slice(0,-1),t]:n:[...n,{userText:t.userText,replyText:(l=t.replyText)!=null?l:""}]}function lt(e,t,n=Ae,o){De(e,Date.now(),o);let r=Ss(e,t),i=Math.max(1,n);return{exchanges:r.slice(-i),hasOlder:r.length>i,totalCount:r.length}}var de="anon";function ut(e){let t=(e!=null?e:"").trim();if(!t)return de;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 dt(e,t="public",n=de){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===de?o:`${o}/${n}`}function ws(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-st.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 Es(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Be)){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 rn(e,t,n,o=null,r="public",i=de){var s,l;let a=dt(t,r,i);try{if(n.turns.length===0&&!n.summary&&!((s=n.uiArchive)!=null&&s.length)){await e.removeItem(a);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(a,JSON.stringify(u))}catch{}}async function sn(e,t,n=Date.now(),o="public",r=de){var a;let i=dt(t,o,r);try{let s=await e.getItem(i);if(!s)return null;let l=JSON.parse(s);if((l==null?void 0:l.v)!==1)return await e.removeItem(i),null;if((typeof l.owner=="string"?l.owner:de)!==r)return null;let u={turns:ws(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:Es(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return De(u,n,Ne(p))||u.turns.length===0&&!u.summary&&!((a=u.uiArchive)!=null&&a.length)?(await e.removeItem(i),null):(u.lastActivityAt=n,u)}catch{return null}}async function an(e,t,n="public",o=de){try{await e.removeItem(dt(t,n,o))}catch{}}function Fe(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function ro(e,t){let n=Fe(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function io(e,t){return ro(e,t)}var We=35,pt="rgba(255,255,255,0.1)",ft="#ffffff";function Ue(e){return e==null||Number.isNaN(Number(e))?We:Math.max(0,Math.min(100,Number(e)))}function so(e,t){let n=Ue(t)/100;return n<=0?0:e*(.002+n*.012)}function ht(e){let t=e==null?void 0:e.trim();if(!t)return pt;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(a=>Number.isNaN(a))?pt:`rgba(${o},${r},${i},0.12)`}return pt}function mt(e,t,n){let o=e,r=so(e,n),i=io(e,t),a=o+2*r,s=o+2*r+2*i;return{fillPx:o,interiorPx:r,exteriorPx:i,totalPx:s,fillRadius:o/2,midPx:a}}function cn(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function ln(e){let t=e/150;return[`inset -${Math.round(8*t)}px -${Math.round(12*t)}px ${Math.round(28*t)}px rgba(0,0,0,0.36)`,`inset ${Math.round(6*t)}px ${Math.round(8*t)}px ${Math.round(20*t)}px rgba(255,255,255,0.07)`].join(", ")}var te={accent:"#2f6bff",glow:"#5aa2ff",background:"rgba(0,0,0,0.72)",waveform:"#ffffff",colorKey:"azul"},nr={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:ft,innerBorderWidth:We,borderWidth:1.5,waveformHeight:26,size:52},or={size:30,shape:"circle",backgroundColor:te.background,borderColor:te.accent,iconColor:te.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:ft,innerBorderWidth:We,borderWidth:100},bt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},rr={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 He(e){let t=ir(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function un(e){let t=ir(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function ir(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 a=i[1];a.length===3?(n=parseInt(a[0]+a[0],16),o=parseInt(a[1]+a[1],16),r=parseInt(a[2]+a[2],16)):(n=parseInt(a.slice(0,2),16),o=parseInt(a.slice(2,4),16),r=parseInt(a.slice(4,6),16))}else{let a=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(!a)return null;n=Number(a[1]),o=Number(a[2]),r=Number(a[3])}return(.299*n+.587*o+.114*r)/255}var gt={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}=gt,a=(t!=null?t:"").trim()||gt.color,s=e*o,l=e*r,c=e*i,u=n.length*s+(n.length-1)*l,p=(e-u)/2;return{bars:n.map((m,h)=>{let g=Math.max(s,c*m);return{x:p+h*(s+l),y:(e-g)/2,width:s,height:g}}),color:a,radius:s/2}}function dn(e,t){let{bars:n,color:o,radius:r}=ao(e,t),i=e/2,a=e*gt.heightRatio/2;return{color:o,radius:r,bars:n.map(s=>({...s,baseHalfHeight:s.height/2,centerY:i,maxHalfHeight:a}))}}function pn(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)),a=n*(.5+i*r);return Math.max(n*.35,Math.min(a,o))}var _s=["pill","rounded","square","cloud"];function sr(e,t,n,o,r,i,a){let s=[];for(let l=0;l<=a;l++){let c=r+(i-r)*l/a;s.push([e+n*Math.cos(c),t+o*Math.sin(c)])}return s}function ks(e,t,n,o,r){let i=[];for(let a=0;a<=r;a++){let s=Math.PI-Math.PI*a/r;i.push([e+n*Math.cos(s),t-o*Math.sin(s)])}return i}function Ps(e,t,n,o,r){let i=[];for(let a=0;a<=r;a++){let s=Math.PI*a/r;i.push([e+n*Math.cos(s),t+o*Math.sin(s)])}return i}function fn(e,t,n){n&&t.shift(),e.push(...t)}var Ms=1.28,Ls=38;function cr(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 cr(t/Ls,3,7)}function lr(e=5){let l=cr(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];fn(f,sr(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;fn(f,ks(g,18,c,14,8),!0)}fn(f,sr(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;fn(f,Ps(g,83,c,12,8),!0)}return`polygon(${f.map(([h,g])=>`${h.toFixed(2)}% ${g.toFixed(2)}%`).join(", ")})`}var uo=lr(5);function po(e){return lr(lo(e))}function yt(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":_s.includes(t)?t:bt.shape}function xt(e,t){if(e!=null)return`${Math.round(e*t)}px`}function ze(e){let t=e!=null?e:{},n=bt,o=yt(t.textSize,yt(t.size,n.textSize));return{backgroundColor:co(t.backgroundColor,n.backgroundColor),textColor:co(t.textColor,n.textColor),borderColor:co(t.borderColor,n.borderColor),borderWidth:yt(t.borderWidth,n.borderWidth),shape:hn(t.shape),borderRadius:yt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:yt(t.bubbleScale,n.bubbleScale)}}var fo=38,ho=14,ar=4;function vt(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+ar*2);hn(e.shape)==="cloud"&&(i=Math.round(i*Ms));let a=Math.max(ar,Math.round((i-r)/2));return{fontPx:t,padV:a,padH:o,approxHeight:i}}function Bs(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var ur=999;function mo(e,t,n){switch(hn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:ur};case"cloud":{let r=Bs(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 mn(e,t,n=1,o){var a;let r=hn(e.shape),i=mo({...e,shape:r},t,o);if(r==="pill"){let s=`${Math.round(ur*n)}px`;return{borderRadius:s,borderTopLeftRadius:s,borderTopRightRadius:s,borderBottomLeftRadius:s,borderBottomRightRadius:s,clipPath:"none"}}return r==="square"?{borderRadius:"0px",borderTopLeftRadius:"0px",borderTopRightRadius:"0px",borderBottomLeftRadius:"0px",borderBottomRightRadius:"0px",clipPath:"none"}:{borderRadius:xt(i.borderRadius,n),borderTopLeftRadius:xt(i.borderTopLeftRadius,n),borderTopRightRadius:xt(i.borderTopRightRadius,n),borderBottomLeftRadius:xt(i.borderBottomLeftRadius,n),borderBottomRightRadius:xt(i.borderBottomRightRadius,n),clipPath:(a=i.clipPath)!=null?a:"none"}}function gn(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 bn(e){return Math.round(e*.5)}function yn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function xn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function vn(e,t,n="#ffffff"){let o=(e!=null?e:n).trim(),r=t.trim();if(!o)return n;let i=a=>{let s=a.toLowerCase();return s.startsWith("#")&&s.length>=7?s.slice(0,7):s};return i(o)===i(r)?n:o}var Ns=[[8,11],[11,11],[14,11],[17,11],[8,14],[11,14],[14,14],[17,14]],dr={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:Ns},pen:{viewBox:"0 0 24 24",paths:[{d:"M4 20h4l10.5-10.5a1.5 1.5 0 0 0 0-2.12l-2.38-2.38a1.5 1.5 0 0 0-2.12 0L4 15.5V20z",fill:!1},{d:"M13.5 6.5l4 4",fill:!1}],contentBBox:{minX:4,minY:6.5,maxX:17.5,maxY:20}},chat:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:5,minY:4,maxX:19,maxY:18.5},chatFrame:{x:5,y:4,w:14,h:10,rx:2.5},chatTail:{left:7.5,right:10.5,tipX:5,tipY:18.5},chatLines:[{y:8,w:6},{y:10,w:6}]}};function Cn(e="keyboard"){var t;return(t=dr[e])!=null?t:dr.keyboard}function An(e){var l,c;let t=e.viewBox.split(/\s+/).map(Number),n=(l=t[2])!=null?l:24,o=(c=t[3])!=null?c:24,{minX:r,minY:i,maxX:a,maxY:s}=e.contentBBox;return{x:n/2-(r+a)/2,y:o/2-(i+s)/2}}var $s=["keyboard","pen","chat"];function Ve(e){return $s.includes(e)?e:"keyboard"}var Se={x:1,y:1};function pe(e){if(e==null)return{...Se};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Se.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Se.y}}function go(e){var f,m,h,g,w;let t=pe(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,a=(w=e.margin)!=null?w:16,s=e.orbDiameter,l=Math.max(0,e.viewportWidth-r-i-2*a-s),c=Math.max(0,e.viewportHeight-n-o-2*a-s),u=r+a+t.x*l,p=n+a+t.y*c;return{right:e.viewportWidth-u-s,bottom:e.viewportHeight-p-s}}function Sn(e){var u,p,f;let t=(u=e.contentWidth)!=null?u:e.viewportWidth,n=(p=e.contentHeight)!=null?p:e.viewportHeight,o=e.orbDiameter,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}),a=t-i.right-o,s=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,a)),top:Math.min(c,Math.max(r,s))}}function Ct(e){let t=pe(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function wn(e){let t=pe(e);return{x:t.x>=.5?1:0,y:t.y}}function En(e){var m,h,g,w,S;let t=(m=e.safeAreaTop)!=null?m:0,n=(h=e.safeAreaBottom)!=null?h:0,o=(g=e.safeAreaLeft)!=null?g:0,r=(w=e.safeAreaRight)!=null?w:0,i=(S=e.margin)!=null?S:16,a=e.orbDiameter,s=Math.max(0,e.viewportWidth-o-r-2*i-a),l=Math.max(0,e.viewportHeight-t-n-2*i-a),c=e.centerX-a/2,u=e.centerY-a/2,p=s>0?(c-o-i)/s:0,f=l>0?(u-t-i)/l:0;return pe({x:p,y:f})}var pr={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},At="rgba(0,0,0,0.72)";function St(e){var o,r,i;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&pr[t])return pr[t];let n=(r=e.backgroundColor)==null?void 0:r.trim();return n&&n!==At?n:(i=e.accentColor)!=null&&i.trim()?e.accentColor.trim():n||At}function Tn(e){var a,s,l,c,u,p,f,m;let t=St(e),n=e.keyboardChip,o=(a=n==null?void 0:n.backgroundColor)==null?void 0:a.trim(),r=(s=e.glowColor)!=null?s:e.accentColor,i=n?{...n,icon:Ve(n.icon),backgroundColor:!o||o===At?t:o,borderColor:(l=n.borderColor)!=null?l:r,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:Ue(n.innerBorderWidth),borderWidth:Fe(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:Fe(e.glowIntensity),hapticIntensity:Zt(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:Ue(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 wt(e){var n,o;return{theme:Tn(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:pe(e.orbTheme.screenPosition)}}var Ds=/^(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:Ds.test(t):!1}function Rn(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 H=class extends Error{constructor(t,n,o){super(n!=null?n:t),this.name="AgentApiError",this.code=t,this.status=o}};var Da=15e3,Fa=12e3;async function In(e,t,n,o){let r=new AbortController,i=!1,a=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(s){if(i)throw new H("timeout");if(o!=null&&o.aborted)throw new H("cancelled");let l=s instanceof Error?s.message:String(s);throw new H("network",l)}finally{clearTimeout(a)}}async function fr(e){let t={};try{let o=await e.text();o&&(t=JSON.parse(o))}catch{}let n=typeof t.detail=="string"?t.detail:typeof t.error=="string"?t.error:t.message;if(e.status===401||e.status===403)return new H("unauthorized",n,e.status);if(e.status===429){let o=t.error==="quota_exceeded"||typeof t.remaining=="number"||(n!=null?n:"").toLowerCase().includes("quota");return new H(o?"quota_exceeded":"rate_limited",n,e.status)}return e.status===404?new H("not_found",n,e.status):e.status>=500?new H("server_error",n,e.status):new H("unknown",n!=null?n:e.statusText,e.status)}function hr(e){var i,a;let t=e.baseUrl.replace(/\/$/,""),n=(i=e.turnTimeoutMs)!=null?i:Da,o=(a=e.ttsTimeoutMs)!=null?a:Fa;function r(){var l,c;let s=(l=e.getUserId)==null?void 0:l.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...s?{"x-user-id":s}:{},...(c=e.headers)!=null?c:{}}}return{async sendTurn(s,l){var h,g,w,S,C,O,R,b,v,A,N;let c={message:s.message.trim(),language:s.language,manifest_version:s.manifestVersion,manifest_routes:s.manifestRoutes,manifest_actions:s.manifestActions,app_name:s.appName,app_description:s.appDescription};(h=s.appType)!=null&&h.trim()&&(c.app_type=s.appType.trim()),(g=s.appFlow)!=null&&g.trim()&&(c.app_flow=s.appFlow.trim()),s.voice&&(c.voice=s.voice),(w=s.screenContext)!=null&&w.trim()&&(c.screen_context=s.screenContext.trim()),(S=s.currentRoute)!=null&&S.trim()&&(c.current_route=s.currentRoute.trim()),(C=s.conversationHistory)!=null&&C.length&&(c.conversation_history=s.conversationHistory.map(X=>({role:X.role,content:X.content.trim()}))),(O=s.conversationSummary)!=null&&O.trim()&&(c.conversation_summary=s.conversationSummary.trim()),(R=s.llmModel)!=null&&R.trim()&&(c.llm_model=s.llmModel.trim()),(b=s.sessionId)!=null&&b.trim()&&(c.session_id=s.sessionId.trim()),(v=s.platformCapabilities)!=null&&v.credentialAutofill&&(c.platform_capabilities={credential_autofill:!0}),s.sessionContext&&(c.session_context={authenticated:s.sessionContext.authenticated,...s.sessionContext.capabilities?{capabilities:s.sessionContext.capabilities}:{}}),s.isContinuation&&(c.is_continuation=!0,typeof s.chainStep=="number"&&(c.chain_step=s.chainStep),s.lastStep&&(c.last_step={type:s.lastStep.type,intent:s.lastStep.intent,...s.lastStep.label?{label:s.lastStep.label}:{},success:s.lastStep.success,...s.lastStep.data?{data:s.lastStep.data}:{}}));let u=await In(`${t}/assistant/chat`,{method:"POST",headers:r(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await fr(u);let p;try{p=await u.json()}catch{throw new H("invalid_response")}let f=typeof p.task_status=="string"?p.task_status:"",m=f==="in_progress"||f==="blocked"?f:"complete";return{reply:((A=p.reply)!=null?A:"").trim(),audioBase64:(N=p.audio_base64)!=null?N:null,action:kt(p.action),wasTruncated:p.was_truncated===!0,taskStatus:m}},async previewTts(s,l){var c;try{let u=await In(`${t}/assistant/preview-tts`,{method:"POST",headers:r(),body:JSON.stringify({voice:s,text:l})},o);if(!u.ok)return null;let p=await u.json();return(c=p.audio_base64)!=null&&c.length?p.audio_base64:null}catch{return null}},async warmUp(){try{await In(`${t}/health`,{method:"GET",headers:r()},5e3)}catch{}},async fetchPublishedConfig(){let s=await In(`${t}/v1/client/config`,{method:"GET",headers:r()},8e3);if(!s.ok)throw await fr(s);return await s.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 Wa(e){var o,r,i;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 a=[{type:"action",intent:t,session_id:n}];return e.actionExecuted!=null&&e.actionExecuted.confirmed===!0&&a.push({type:"confirmation_completed",intent:t,session_id:n}),a}case"action_failed":return[{type:"action_failed",intent:t,session_id:n,error:((i=e.errorDetail)!=null?i:"").slice(0,200)||null}];case"action_confirmation_requested":return[{type:"confirmation_requested",intent:t,session_id:n}];default:return[]}}function mr(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 a(){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 s(){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:a(),body:JSON.stringify({events:p})})}catch{}})()}function l(){i||(i=setTimeout(s,n))}return{logEvent(p){let f=Wa(p);if(f.length!==0){for(let m of f)r.push(m);r.length>=o?s():l()}}}}var Ua="BACK";function Ha(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function gr(e){let t=null,n=!1;return{navigate(o){if(!o||o===Ua){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():Ha()},setCurrentRoute(o){t=o}}}function za(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 br(e={}){let t=za(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 Va(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 Ga(e,t){var r,i,a,s,l;if(!e.length)return;let n=t.toLowerCase(),o=(r=n.split("-")[0])!=null?r:n;return(l=(s=(a=(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?a:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(o)}))!=null?s:e.find(c=>c.default))!=null?l:e[0]}function yr(){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 xr(){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 vr(e={}){let t=yr(),n=null,o="",r=null,i=!1,a=!1,s=null,l=null,c=null,u=!1,p=!1,f=[],m="",h=null,g=null;function w(){g&&(clearTimeout(g),g=null)}function S(){if(w(),c){c.onresult=null,c.onerror=null,c.onend=null,c.onstart=null;try{c.abort()}catch{}}c=null}function C(){w(),!(!u||p)&&(g=setTimeout(()=>{g=null,u&&!p&&O()},600))}function O(){let _=yr();if(!_||!u||p)return;if(typeof document!="undefined"&&document.hidden){C();return}let y=new _;c=y,y.lang=m,y.continuous=!0,y.interimResults=!0,y.maxAlternatives=1,y.onresult=T=>{var D;if(!u||p)return;let I="";for(let L=0;L<T.results.length;L+=1){let Q=T.results[L];if(!Q)continue;let j=Q[0];I=`${I} ${(D=j==null?void 0:j.transcript)!=null?D:""}`.trim()}let M=Qt(I,f);if(!M.matched)return;p=!0;let z=h;S(),z==null||z.onDetected(M.command)},y.onerror=T=>{var I;T.error==="aborted"||T.error==="no-speech"||!u||p||(I=h==null?void 0:h.onError)==null||I.call(h,new Error(T.error||"wake recognition error"))},y.onend=()=>{!u||p||C()};try{y.start()}catch{C()}}let R=null,b=null;function v(){var y,T;if(typeof window=="undefined")return null;let _=window;return(T=(y=_.AudioContext)!=null?y:_.webkitAudioContext)!=null?T:null}function A(){if(R)return R;let _=v();if(!_)return null;try{R=new _}catch{R=null}return R}function N(_){let y=atob(_),T=y.length,I=new Uint8Array(T);for(let M=0;M<T;M+=1)I[M]=y.charCodeAt(M);return I.buffer}function X(){if(b){try{b.onended=null,b.stop()}catch{}b=null}}async function ce(_){let y=A();if(!y)return!1;try{y.state==="suspended"&&await y.resume();let T=await y.decodeAudioData(N(_));return await new Promise(I=>{X();let M=y.createBufferSource();b=M,M.buffer=T,M.connect(y.destination),M.onended=()=>{M.onended=null,b===M&&(b=null),I(!0)},M.start()})}catch{return!1}}function q(){r&&(clearTimeout(r),r=null)}function oe(){q(),n&&(n.onresult=null,n.onerror=null,n.onend=null,n.onstart=null),n=null}return{isRecognitionAvailable(){return t!=null},async startListening(_,y){var I,M,z;if(!t){(I=y.onError)==null||I.call(y,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,h=null,S()),n){i=!0;try{n.abort()}catch{}oe()}o="",i=!1,a=!1;let T=new t;n=T,T.lang=_.locale,T.continuous=(M=_.continuous)!=null?M:!0,T.interimResults=!0,T.maxAlternatives=1,T.onresult=D=>{var j,be;let L="";for(let he=D.resultIndex;he<D.results.length;he+=1){let ye=D.results[he];if(!ye)continue;let J=ye[0],Ee=(j=J==null?void 0:J.transcript)!=null?j:"";ye.isFinal?o=`${o} ${Ee}`.trim():L=`${L} ${Ee}`.trim()}let Q=`${o} ${L}`.trim();Q&&((be=y.onInterim)==null||be.call(y,Q))},T.onerror=D=>{var L;D.error==="aborted"||i||D.error!=="no-speech"&&(a=!0,(L=y.onError)==null||L.call(y,new Error(D.error||"speech recognition error")))},T.onend=()=>{var Q,j,be,he;q();let D=i,L=o.trim();if(oe(),a){(Q=y.onEnd)==null||Q.call(y);return}if(D){(j=y.onEnd)==null||j.call(y);return}L?(be=y.onFinal)==null||be.call(y,L):(he=y.onEnd)==null||he.call(y)};try{T.start()}catch(D){oe(),(z=y.onError)==null||z.call(y,D);return}_.maxSeconds&&_.maxSeconds>0&&(r=setTimeout(()=>{try{T.stop()}catch{}},_.maxSeconds*1e3))},stopListening(){if(q(),n)try{n.stop()}catch{}},cancelListening(){if(q(),i=!0,n)try{n.abort()}catch{}},primePlayback(){let _=A();if(_)try{_.state==="suspended"&&_.resume();let y=_.createBuffer(1,1,_.sampleRate),T=_.createBufferSource();T.buffer=y,T.connect(_.destination),T.start(0)}catch{}if(!e.disableDeviceTtsFallback&&typeof window!="undefined"&&window.speechSynthesis)try{let y=window.speechSynthesis;y.getVoices(),y.paused&&y.resume();let T=new SpeechSynthesisUtterance(" ");T.volume=0,y.speak(T)}catch{}},async playAudioBase64Mp3(_){if(typeof window!="undefined"&&(this.stopPlayback(),!await ce(_)&&typeof Audio!="undefined"))return new Promise(y=>{try{let T=new Audio(`data:audio/mp3;base64,${_}`);s=T;let I=()=>{T.onended=null,T.onerror=null,s===T&&(s=null),y()};T.onended=I,T.onerror=I,T.play().catch(()=>I())}catch{y()}})},async speakWithDeviceTts(_,y){if(e.disableDeviceTtsFallback||typeof window=="undefined"||!window.speechSynthesis)return;let T=window.speechSynthesis,I=await Va(T);return new Promise(M=>{let z=null,D=()=>{z&&(clearInterval(z),z=null)};try{T.cancel();let L=new SpeechSynthesisUtterance(_);L.lang=y.locale;let Q=Ga(I,y.locale);Q&&(L.voice=Q),L.volume=1,L.rate=1,L.pitch=1,l=L;let j=()=>{D(),L.onstart=null,L.onend=null,L.onerror=null,l===L&&(l=null),M()};L.onend=j,L.onerror=j,T.speak(L),T.resume(),z=setInterval(()=>{if(!T.speaking&&!T.pending){D();return}T.pause(),T.resume()},9e3)}catch{D(),M()}})},stopPlayback(){if(X(),s){try{s.pause()}catch{}s=null}if(typeof window!="undefined"&&window.speechSynthesis)try{window.speechSynthesis.cancel()}catch{}},supportsWakeWordDetection(){return t!=null&&!xr()},isWakeWordListening(){return u},async startWakeWordDetection(_,y){var T;if(!t||xr()){(T=y.onError)==null||T.call(y,new Error("wake_word_unsupported"));return}f=_.phrases,m=_.locale,h=y,u=!0,p=!1,O()},stopWakeWordDetection(){u=!1,p=!1,h=null,S()}}}function Cr(){if(typeof navigator=="undefined")return null;let e=navigator;return e.credentials&&typeof e.credentials.get=="function"?e.credentials:null}function Ar(){if(typeof window=="undefined")return!1;let e=window;return typeof e.PasswordCredential=="function"&&e.isSecureContext!==!1}function Sr(){return{isSupported(){return Cr()!==null&&Ar()},async requestCredentials(){let e=Cr();if(!e||!Ar())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 H){switch(e.code){case"timeout":return n?"La respuesta tard\xF3 demasiado. Comprueba tu conexi\xF3n e int\xE9ntalo de nuevo.":"The response took too long. Check your connection and try again.";case"network":return n?"No pude conectar con el servidor de Fiodos. \xBFEst\xE1 el backend en marcha y la URL correcta?":"Could not reach the Fiodos server. Is the backend running and the URL correct?";case"unauthorized":return n?"La API key fue rechazada. Comprueba que coincide con la del proyecto en el dashboard.":"The API key was rejected. Check it matches the project key in your dashboard.";case"quota_exceeded":return n?"Has alcanzado el l\xEDmite de uso de IA de tu plan. Mej\xF3ralo en el dashboard para seguir.":"You reached your plan\u2019s AI usage limit. Upgrade in the dashboard to continue.";case"rate_limited":return n?"Demasiadas peticiones seguidas. Espera un momento e int\xE9ntalo de nuevo.":"Too many requests. Wait a moment and try again.";case"server_error":return n?"El servidor no pudo responder. Revisa que la IA est\xE9 configurada en el backend.":"The server could not respond. Check that the AI is configured on the backend.";case"cancelled":return n?"Cancelado.":"Cancelled.";default:break}if(e.message&&e.message!==e.code)return e.message}return e instanceof Error&&e.message?e.message:n?"No pude responder. Int\xE9ntalo de nuevo.":"I could not reply. Please try again."}function On(e){let t=null;return{set(n,o){t={ownerId:n,snapshot:o}},clear(n){(t==null?void 0:t.ownerId)===n&&(t=null)},getText(){var r,i,a;let n=(r=t==null?void 0:t.snapshot.text)==null?void 0:r.trim();return n||((a=(i=e.routeFallback)==null?void 0:i.call(e,e.getCurrentRoute()))==null?void 0:a.trim())||null},getSnapshot(){var n;return(n=t==null?void 0:t.snapshot)!=null?n:null}}}function wr(e){let{adapter:t,locale:n,maxSeconds:o}=e,r={state:"idle",interimText:"",volumeLevel:0},i=new Set;function a(l){r={...r,...l};for(let c of i)c(r)}function s(){a({state:"idle",interimText:"",volumeLevel:0})}return{getSnapshot(){return r},subscribe(l){return i.add(l),()=>i.delete(l)},async start(){r.state==="idle"&&(a({state:"recording",interimText:"",volumeLevel:.85}),await t.startListening({locale:n,continuous:!0,maxSeconds:o},{onInterim:l=>a({interimText:l}),onFinal:l=>{s(),l.trim()&&e.onTranscript(l)},onEnd:()=>{r.state!=="idle"&&s()},onError:l=>{var c;s(),(c=e.onError)==null||c.call(e,l)}}))},stop(){r.state==="recording"&&(a({state:"transcribing",volumeLevel:0}),t.stopListening())},cancel(){t.cancelListening(),s()},dispose(){t.cancelListening(),i.clear()}}}function Ya(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function Er(e){var l,c,u,p,f,m,h;let{action:t,manifest:n,executor:o,context:r,messages:i,userMessage:a,suppressEscort: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 g=Ya(n,t.intent);if(!((g==null?void 0:g.requireConfirmation)===!0))return{kind:"executed",result:await o.execute(t,r,{suppressEscort:s})};let S=await o.precheck(t,r);if(S.kind==="done")return{kind:"precheck-resolved",result:S.result};let C=(l=g==null?void 0:g.voiceConfirmation)!=null?l:"standard",O=C==="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:C,strictPhrase:O,remainingConfirmations:(g==null?void 0:g.doubleConfirmation)===!0?2:1,userMessage:a,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?on(r,t.strictPhrase,n):nn(r,n)}var Rr={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},Ir={enabled:!0,maxSteps:6,dwellMs:450};var _r={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"},Ka={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"},Or={en:_r,es:Ka};function ja(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,a,s,l,c;let n=(i=t.catalogs)!=null?i:{},o=ja(e),r=(c=(l=(s=(a=n[e])!=null?a:Or[e])!=null?s:n[o])!=null?l:Or[o])!=null?c:_r;return t.overrides?{...r,...t.overrides}:r}function Xa(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var qa=e=>new Promise(t=>setTimeout(t,e)),Ge=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=Xa();this.sessionStarted=!1;this.conversation=$e();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=Ae;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,a,s,l,c,u,p;ge(t.manifest),this.config=t,this.messages=$t(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:en(t.locale),this.sanitizer=(a=t.sanitizer)!=null?a:jt(),this.telemetry=Jt(t.telemetry),this.consent=Xt({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?Sr():t.credentialAutofill,this.executor=zt({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...Rr,...t.timings};let n={...Ir,...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((s=n.dwellMs)!=null?s:450)))},this.ttsLocale=(l=t.ttsLocale)!=null?l:t.sttLocale,this.notifyError=(c=t.notifyError)!=null?c:(f=>{console.error(`[fyodos] ${f}`)}),this.screenStore=On({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Wt(f,t.manifest,this.messages))}),this.speech=wr({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=ut((p=t.getUserId)==null?void 0:p.call(t)),this.restorePersistedConversation(),typeof window!="undefined"){let f=()=>{this.syncConversationIdentity()};window.addEventListener("focus",f),document.addEventListener("visibilitychange",f),this.removeIdentityListeners=()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",f)}}}async restorePersistedConversation(){var o;let t=this.conversationIdentity,n=await sn(this.config.storage,this.config.manifest.appId,Date.now(),this.conversationScope,t);!n||this.conversationIdentity!==t||this.conversation.turns.length>0||(o=this.conversation.uiArchive)!=null&&o.length||(this.conversation.turns=n.turns,this.conversation.summary=n.summary,this.conversation.uiArchive=n.uiArchive,this.conversation.lastActivityAt=n.lastActivityAt,this.emit())}persistConversation(){rn(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=ut((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=$e(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=$e(),this.lastExchange=null,an(this.config.storage,this.config.manifest.appId,this.conversationScope,this.conversationIdentity),this.emit()}getState(){let t=this.speech.getSnapshot(),n=(this.phase==="listening"||this.phase==="confirming")&&t.state==="recording",o=this.phase==="thinking"||this.phase==="listening"&&t.state==="transcribing",r=lt(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||!lt(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=Ae,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Ne(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=Ae}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,a=()=>{i||(i=!0,this.clearSpeakTimer(),r())};this.clearSpeakTimer(),this.speakTimer=setTimeout(()=>{this.config.voice.stopPlayback(),a()},o),t.then(a,a)})}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,a,s;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 l=this.messages.doubleConfirmationQuestion;this.confirmationMessage=l,this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:l}),this.emit(),await this.speakReply(l,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.success?{}:{errorDetail:(i=n.error)!=null?i:null}}),n.success||console.warn(`[fyodos] action "${t.intent}" failed: ${(a=n.error)!=null?a:"unknown error"}`),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:(s=o.pendingStep)!=null?s: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 a={};for(let[s,l]of Object.entries(i))typeof l=="boolean"&&(a[s]=l);Object.keys(a).length>0&&(r=a)}}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 w,S,C,O,R,b,v,A,N,X,ce,q,oe,_,y,T;let i=t.reply,a=t.audioBase64;i&&(this.serverTtsUnavailable=!a);let s=this.chaining.enabled&&t.taskStatus==="in_progress",l=await Er({action:t.action,manifest:this.config.manifest,executor:this.executor,context:o,messages:this.messages,userMessage:r,suppressEscort:s}),c=!1,u,p,f=!1,m=!1,h,g;if(l.kind==="executed"){let I=l.result;if(I.success&&((w=t.action)==null?void 0:w.type)==="navigate"?this.setActivity({kind:"navigating",label:(O=(C=this.routeLabel((S=t.action.intent)!=null?S:""))!=null?C:t.action.intent)!=null?O:""}):I.success&&!I.recoverable&&((R=t.action)==null?void 0:R.type)==="execute"&&this.setActivity({kind:"executing",label:(A=(v=this.actionLabel((b=t.action.intent)!=null?b:""))!=null?v:t.action.intent)!=null?A:""}),((N=t.action)==null?void 0:N.type)==="navigate"?this.telemetry.logEvent({eventType:I.success?"navigation_executed":"navigation_failed",intentDetected:t.action.intent,sessionId:this.sessionId,currentRoute:n!=null?n:void 0}):((X=t.action)==null?void 0:X.type)==="execute"&&this.telemetry.logEvent({eventType:I.recoverable?"action_needs_context":I.success?"action_executed":"action_failed",intentDetected:t.action.intent,sessionId:this.sessionId,actionExecuted:{intent:t.action.intent,confirmed:!1},...!I.success&&!I.recoverable?{errorDetail:(ce=I.error)!=null?ce:null}:{}}),I.recoverable||(I.message?(i=I.message,a=null):I.success||(i=this.messages.actionFailed,a=null)),I.success||console.warn(`[fyodos] action "${(oe=(q=t.action)==null?void 0:q.intent)!=null?oe:"?"}" failed: ${(_=I.error)!=null?_:"unknown error"}`),t.action&&(t.action.type==="navigate"||t.action.type==="execute")&&I.success&&!I.recoverable){t.action.type==="execute"?this.deferredEscortIntent=s&&(y=t.action.intent)!=null?y:null:this.deferredEscortIntent=null;let M=(T=t.action.intent)!=null?T:"",z=Yt(I.data);u={type:t.action.type,intent:M,label:t.action.type==="navigate"?this.routeLabel(M):this.actionLabel(M),success:!0,...z?{data:z}:{}},p=`${t.action.type}:${M}`,c=t.taskStatus==="in_progress"}}else if(l.kind==="precheck-resolved")l.result.message&&!l.result.recoverable&&(i=l.result.message,a=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 I=l.pending.intent||"";h={type:"execute",intent:I,label:this.actionLabel(I),success:!0},g=`execute:${I}`}return{reply:i,audioBase64:a,hasPending:f,canContinue:c,lastStep:u,actionKey:p,pendingInProgress:m,pendingStep:h,pendingKey:g}}async runChainLoop(t){var i,a,s,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 qa(this.chaining.dwellMs),this.pending!=null)return;let w=this.config.navigation.getCurrentRoute(),S=this.screenStore.getSnapshot(),C=rt((s=(a=(i=this.config).getUserContextText)==null?void 0:a.call(i))!=null?s:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),O=C?this.sanitizer(C).sanitized:void 0,R=at(this.conversation,Date.now(),this.conversationOptions);this.setPhase("thinking"),this.setActivity({kind:"thinking"});let b=new AbortController;this.abort=b;let v;try{let A=await this.config.backend.sendTurn({message:t.userMessage,language:this.config.locale,voice:this.getTtsVoice(),screenContext:O,currentRoute:w!=null?w:void 0,conversationHistory:R.history,conversationSummary:(l=R.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});v=await this.applyOutcome(A,w,(c=S==null?void 0:S.context)!=null?c:{},t.userMessage)}catch(A){this.abort=null;let N=A instanceof H&&A.code==="cancelled";if(N)this.phase==="thinking"&&this.setPhase("idle");else{A instanceof H&&A.code==="quota_exceeded"&&((p=(u=this.config).onQuotaExceeded)==null||p.call(u));let X=xo(A,this.config.locale);this.lastExchange={userText:t.userMessage,replyText:X},this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(X)}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:N?"user_interrupt":"error"});return}if(this.abort=null,v.reply&&(this.lastExchange={userText:t.userMessage,replyText:v.reply},this.emit(),ct(this.conversation,t.userMessage,v.reply,Date.now(),this.conversationOptions),this.persistConversation()),await this.speakReply(v.reply,v.audioBase64),this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:(g=(h=(f=v.lastStep)==null?void 0:f.intent)!=null?h:(m=v.pendingStep)==null?void 0:m.intent)!=null?g:null,sessionId:this.sessionId,chainStep:n}),v.hasPending){this.chainState=v.pendingInProgress?{userMessage:t.userMessage,step:n,lastStep:o,visitedKeys:r,pendingKey:v.pendingKey,pendingStep:v.pendingStep}:null,this.beginConfirmationVoiceWindow();return}if(this.phase!=="speaking"&&this.setPhase("idle"),v.actionKey&&r.has(v.actionKey)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(v.actionKey&&r.add(v.actionKey),!v.canContinue){this.telemetry.logEvent({eventType:"agent_chain_completed",sessionId:this.sessionId,chainStep:n});return}o=v.lastStep}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"max_steps"})}finally{this.setChainActive(!1),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,w,S,C,O,R;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 v=(b=this.pendingTurnText)!=null?b:n,A=this.config.locale.startsWith("es")?"La respuesta tard\xF3 demasiado. Int\xE9ntalo de nuevo.":"The response took too long. Please try again.";this.lastExchange={userText:v,replyText:A},this.pendingTurnText=null,this.setActivity(null),this.setPhase("idle"),this.emit()}},this.timings.thinkingWatchdogMs);let o=this.config.navigation.getCurrentRoute();this.sessionStarted||(this.sessionStarted=!0,this.telemetry.logEvent({eventType:"agent_session_started",sessionId:this.sessionId})),this.telemetry.logEvent({eventType:"agent_invoked",sessionId:this.sessionId,currentRoute:o});let r=this.screenStore.getSnapshot(),i=rt((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}),a=i?this.sanitizer(i).sanitized:void 0,s=at(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:a,currentRoute:o!=null?o:void 0,conversationHistory:s.history,conversationSummary:(g=s.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,(w=r==null?void 0:r.context)!=null?w:{},n)}catch(b){if(this.clearWatchdog(),this.abort=null,this.setActivity(null),b instanceof H&&b.code==="cancelled"){this.phase==="thinking"&&this.setPhase("idle"),this.pendingTurnText=null;return}b instanceof H&&b.code==="quota_exceeded"&&((C=(S=this.config).onQuotaExceeded)==null||C.call(S));let v=xo(b,this.config.locale);this.lastExchange={userText:n,replyText:v},this.pendingTurnText=null,this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(v);return}if(this.clearWatchdog(),this.abort=null,this.pendingTurnText=null,!c)return;let u=c.reply;if(u)this.lastExchange={userText:n,replyText:u},this.emit(),ct(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),(R=(O=this.config).onTurnCompleted)==null||R.call(O)}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,a;if(!this.enabled)return;let o=t.trim();if(!o)return;let r=(a=(i=this.config).gateTurn)==null?void 0:a.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 Qa="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(Qa,e);for(let[o,r]of Object.entries(t))n.setAttribute(o,String(r));return n}function Lr(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:r,fillRadius:i,midPx:a}=mt(e.fillDiameter,e.exteriorWidthSlider,e.interiorWidthSlider),s=typeof e.borderRadius=="number",l=s?`${i}px`:String(e.borderRadius),c=s?`${a/2}px`:String(e.borderRadius),u=s?`${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?cn(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?ln(e.fillDiameter):""}),h.appendChild(g),m.appendChild(h),{root:m,fill:g}}function Ja(e,t){let{bars:n,color:o,radius:r}=dn(e,t),i=ne("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,"aria-hidden":"true"});i.style.display="block";let a=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}),s=0;return{el:i,start(){let l=performance.now(),c=u=>{s=requestAnimationFrame(c);let p=(u-l)/1e3;n.forEach((f,m)=>{let h=pn(p,m,f.baseHalfHeight,f.maxHalfHeight);a[m].setAttribute("y",(f.centerY-h).toFixed(2)),a[m].setAttribute("height",(2*h).toFixed(2))})};s=requestAnimationFrame(c)},stop(){cancelAnimationFrame(s)}}}var Za=9,ec=[.25,.45,.65,.85,1,.85,.65,.45,.25],Pr=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],tc=26;function nc(e,t){let n=t/tc,o=3*n,r=3*n,i=3*n,a=document.createElement("div");Object.assign(a.style,{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:`${r}px`,height:`${t}px`,width:"100%",maxWidth:"88%"});let s=[];for(let h=0;h<Za;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"}),s.push(g),a.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,s.forEach((g,w)=>{var C,O,R;let S;if(p<.05){let b=(Math.sin(c+((C=Pr[w])!=null?C:0))+1)/2;S=f+b*(.22-f)}else{let b=Math.sin(c*2.3+((O=Pr[w])!=null?O:0))*.18+.82+Math.random()*.18;S=f+p*((R=ec[w])!=null?R:.5)*(1-f)*b}g.style.transform=`scaleY(${Math.min(1,Math.max(f,S))})`}))};return{el:a,start(){l||(u=typeof performance!="undefined"?performance.now():Date.now(),l=requestAnimationFrame(m))},stop(){l&&cancelAnimationFrame(l),l=0},setVolume(h){p=h}}}var Mr=8,Br=68,oc=360-Br,rc=Br/2,ic=[.15,.25,.35,.5,.65,.78,.88,1];function sc(e,t){var s;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"}),a=oc/(Mr-1);for(let l=0;l<Mr;l++){let c=rc+a*l;i.appendChild(ne("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(s=ic[l])!=null?s:1,transform:`rotate(${c} 20 20)`}))}return r.appendChild(i),o.appendChild(r),o}var ac=118/380,cc=30/380,lc=2/380;function uc(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*ac,r=Math.max(1,e*lc);for(let s 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 ${s}s`}),n.appendChild(l)}let i=e*cc,a=document.createElement("div");return Object.assign(a.style,{width:`${i}px`,height:`${i}px`,borderRadius:"50%",background:t,opacity:"0.9",animation:"fy-opulse 1s ease-in-out infinite"}),n.appendChild(a),n}function dc(e,t,n){let o=Cn(e),r=1.8,{x:i,y:a}=An(o),s=ne("svg",{width:t,height:t,viewBox:o.viewBox,fill:"none","aria-hidden":"true"});s.style.display="block",s.style.pointerEvents="none";let l=ne("g",{transform:`translate(${i} ${a})`});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 s.appendChild(l),s}function Nr(e){var g,w,S,C,O,R,b;let{theme:t}=e,n=(g=t.size)!=null?g:30,o=(w=t.shape)!=null?w:"circle",r=o==="circle"?"50%":`${xn(o,n)}px`,i=(S=t.backgroundColor)!=null?S:e.backgroundColor,a=(C=t.borderColor)!=null?C:e.accentColor,s=vn(t.iconColor,i,e.accentColor),l=Ve(t.icon),c=yn((O=t.iconScale)!=null?O:1),u=Math.round(bn(n)*c),p=mt(n,(R=t.borderWidth)!=null?R: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}=Lr({fillDiameter:n,borderRadius:r,exteriorColor:a,exteriorWidthSlider:(b=t.borderWidth)!=null?b:100,interiorColor:ht(t.innerBorderColor),interiorWidthSlider:t.innerBorderWidth,fill:i,outerGlow:!1,fillDepth:!1});if(t.iconImageDataUrl){let v=document.createElement("img");v.src=t.iconImageDataUrl,v.alt="",Object.assign(v.style,{width:`${u}px`,height:`${u}px`,objectFit:"contain",display:"block"}),h.appendChild(v)}else h.appendChild(dc(l,u,s));return f.appendChild(m),f}function $r(e){let t=document.createElement("div");t.style.display="inline-flex";let n=e,o="idle",r=0,i=null,a=null,s=null;function l(){var w,S,C,O;let u=(w=n.size)!=null?w:ae.size,p=St({colorKey:(S=n.colorKey)!=null?S:ae.colorKey,backgroundColor:n.backgroundColor,accentColor:n.accentColor}),f=(C=n.glowColor)!=null&&C.startsWith("#")?n.glowColor:n.accentColor,m=ht(n.innerBorderColor);a==null||a.stop(),a=null,s==null||s.stop(),s=null,t.replaceChildren();let{root:h,fill:g}=Lr({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(O=n.glowIntensity)!=null?O: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(a==null||a.stop(),a=null,s==null||s.stop(),s=null,i.replaceChildren(),t.style.animation="",o==="thinking"){i.appendChild(sc(u,p));return}if(o==="listening"){a=nc(p,Math.round(u*.46)),a.setVolume(r),i.appendChild(a.el),a.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(uc(u,p));return}o==="idle"&&(s=Ja(u,n.waveformColor),i.appendChild(s.el),s.start())}return l(),{element:t,applyAppearance(u){n=u,l()},applyState(u,p){r=p,u!==o?(o=u,c()):o==="listening"&&(a==null||a.setVolume(r))}}}var vo="fyodos:published-config:v1";function pc(){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 Fr(e,t){var i,a,s,l;let n=t.orbEnabled!==!1,o=e.theme;return{appearance:{accentColor:(i=o.accentColor)!=null?i:ae.accentColor,backgroundColor:(a=o.backgroundColor)!=null?a:ae.backgroundColor,glowColor:o.glowColor,colorKey:o.colorKey,glowIntensity:o.glowIntensity,hapticIntensity:o.hapticIntensity,innerBorderColor:o.innerBorderColor,innerBorderWidth:o.innerBorderWidth,size:(s=o.size)!=null?s:ae.size,waveformColor:o.waveformColor,logoDataUrl:e.logoDataUrl},keyboardChip:(l=o.keyboardChip)!=null?l:null,modalTheme:e.modalTheme,screenPosition:e.screenPosition,bubbleTheme:ze(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 Wr(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,r=pc();r&&t.onChange(Fr(wt(r),r));let i=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange(Fr(wt(c.published),c.published)),Dr(c.published)):(t.onChange(null),Dr(null))}catch{}};i();let a=(l=t.pollMs)!=null?l:12e3,s=a>0?setInterval(()=>{i()},a):null;return()=>{o=!0,s&&clearInterval(s)}}function fc(){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 hc(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function Et(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Ur(e){let t=fc(),n=null,o=!1,r="",i=()=>{let s=n;if(s){s.onresult=null,n=null,o=!1;try{typeof s.abort=="function"?s.abort():s.stop()}catch{}}};return{isSupported:()=>t!=null,isListening:()=>o,stop:i,dispose:()=>{i()},toggle(s,l){if(!t)return;if(o){i();return}r=s();let c=new t;c.lang=hc(e),c.interimResults=!0,c.continuous=!0;let u="";c.onresult=p=>{var g,w;let f="";for(let S=p.resultIndex;S<p.results.length;S+=1){let C=p.results[S];if(!C)continue;let O=(w=(g=C[0])==null?void 0:g.transcript)!=null?w:"";C.isFinal?u+=O:f+=O}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 Hr="fyodos-orb-styles",mc=`
3
+ `,s=o-r.length-a.length;return s<=n.truncationSuffix.length?Me(r,{...n,maxChars:o}):r+a+Me(i,{...n,maxChars:s})}var qn=[{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(a=>{let s=Kt[a.toUpperCase()];if(!s)throw new Error(`[fyodos] Unknown PII country pack "${a}". Available packs: ${Object.keys(Kt).join(", ")}. Use customPatterns to add your own.`);return s}),[n,...o]=qn;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:a,replacement:s}of t)a.test(o)&&(r.push(i),o=o.replace(a,s)),a.lastIndex=0;return o=o.replace(/\+\s?\[REDACTED:PHONE\]/g,"[REDACTED:PHONE]"),{sanitized:o,redactions:r}}}function Jn(e,t=1){return`@fiodos/${e}/assistant_consent_v${t}`}function Xt(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 Qt(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 Jt(e){return{logEvent(t){if(e)try{let n=e.logEvent(t);n&&typeof n.catch=="function"&&n.catch(()=>{})}catch{}}}}var qo=40;function Zt(e){return typeof e!="number"||Number.isNaN(e)?qo:Math.max(0,Math.min(100,Math.round(e)))}function Qo(e,t){let n=Zt(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(s=>s===0))&&r&&typeof r.vibrate=="function"&&r.vibrate(i)}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 en(e){var o,r,i;let t=(r=(o=e.split(/[-_]/)[0])==null?void 0:o.toLowerCase())!=null?r:e.toLowerCase(),n=(i=it[e])!=null?i: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 Le(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[.,;:!?¡¿"'«»()]/g," ").replace(/\s+/g," ").trim()}function Jo(e,t){return e===t||e.startsWith(`${t} `)||e.endsWith(` ${t}`)||e.includes(` ${t} `)}function eo(e,t){let n=Le(e);return n?t.affirmative.some(o=>Jo(n,Le(o))):!1}function tn(e,t){let n=Le(e);return n?t.negative.some(o=>Jo(n,Le(o))):!1}function nn(e,t){let n=tn(e,t),o=eo(e,t);return n?"negative":o?"affirmative":"ambiguous"}function Cs(e,t){return t?` ${e} `.includes(` ${t} `):!1}function on(e,t,n){let o=Le(e);return o?tn(e,n)?"negative":Cs(o,Le(t))?"affirmative":"ambiguous":"ambiguous"}var to={maxRecentTurns:10,summarizeAfterTurns:14,maxSummaryChars:800,sessionIdleMs:18e5,maxStoredTurns:40},st={maxRecentTurns:16,summarizeAfterTurns:22,maxSummaryChars:1600,maxStoredTurns:80};function Ne(e,t=!1){let n=t?st: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 Ae=5,Be=200;function Zo(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function er(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function tr(e,t,n){let o=t.map(r=>r.role==="user"?`User: ${Zo(r.content,120)}`:`Assistant: ${Zo(r.content,120)}`).join(" | ");return er(e?`${e} | ${o}`:o,n)}function no(e){return{...to,...e}}function $e(e){return{turns:[],summary:null,lastActivityAt:Date.now()}}function De(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 at(e,t=Date.now(),n){return De(e,t,n),e.lastActivityAt=t,oo(e.turns,e.summary,n)}function As(e,t){let{maxRecentTurns:n,summarizeAfterTurns:o,maxSummaryChars:r,maxStoredTurns:i}=t;if(e.turns.length>o){let a=e.turns.length-n,s=e.turns.slice(0,a);e.summary=tr(e.summary,s,r),e.turns=e.turns.slice(a)}if(e.turns.length>i){let a=e.turns.slice(0,e.turns.length-n);e.summary=tr(e.summary,a,r),e.turns=e.turns.slice(-n)}}function ct(e,t,n,o=Date.now(),r){var l;let i=no(r),a=t.trim(),s=n.trim();!a||!s||(e.turns.push({role:"user",content:a},{role:"assistant",content:s}),e.uiArchive=(l=e.uiArchive)!=null?l:[],e.uiArchive.push({userText:a,replyText:s}),e.uiArchive.length>Be&&(e.uiArchive=e.uiArchive.slice(-Be)),e.lastActivityAt=o,As(e,i))}function Ss(e,t){var i,a,s,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(!((a=t==null?void 0:t.userText)!=null&&a.trim()))return n;let o=n[n.length-1];return o!=null&&o.userText===t.userText&&o.replyText===((s=t.replyText)!=null?s:"")?t.replyText&&o.replyText!==t.replyText?[...n.slice(0,-1),t]:n:[...n,{userText:t.userText,replyText:(l=t.replyText)!=null?l:""}]}function lt(e,t,n=Ae,o){De(e,Date.now(),o);let r=Ss(e,t),i=Math.max(1,n);return{exchanges:r.slice(-i),hasOlder:r.length>i,totalCount:r.length}}var de="anon";function ut(e){let t=(e!=null?e:"").trim();if(!t)return de;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 dt(e,t="public",n=de){let o=t==="internal"?`@fiodos/${e}/conversation_internal_v1`:`@fiodos/${e}/conversation_v1`;return n===de?o:`${o}/${n}`}function ws(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-st.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 Es(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-Be)){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 rn(e,t,n,o=null,r="public",i=de){var s,l;let a=dt(t,r,i);try{if(n.turns.length===0&&!n.summary&&!((s=n.uiArchive)!=null&&s.length)){await e.removeItem(a);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(a,JSON.stringify(u))}catch{}}async function sn(e,t,n=Date.now(),o="public",r=de){var a;let i=dt(t,o,r);try{let s=await e.getItem(i);if(!s)return null;let l=JSON.parse(s);if((l==null?void 0:l.v)!==1)return await e.removeItem(i),null;if((typeof l.owner=="string"?l.owner:de)!==r)return null;let u={turns:ws(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:Es(l.uiArchive)},p=typeof l.retentionMinutes=="number"?l.retentionMinutes:null;return De(u,n,Ne(p))||u.turns.length===0&&!u.summary&&!((a=u.uiArchive)!=null&&a.length)?(await e.removeItem(i),null):(u.lastActivityAt=n,u)}catch{return null}}async function an(e,t,n="public",o=de){try{await e.removeItem(dt(t,n,o))}catch{}}function Fe(e){return e==null||Number.isNaN(Number(e))?100:Math.max(0,Math.min(100,Number(e)))}function ro(e,t){let n=Fe(t);if(n<=0)return 0;let o=n/100;return e*(.008+o*.035)}function io(e,t){return ro(e,t)}var We=35,pt="rgba(255,255,255,0.1)",ft="#ffffff";function Ue(e){return e==null||Number.isNaN(Number(e))?We:Math.max(0,Math.min(100,Number(e)))}function so(e,t){let n=Ue(t)/100;return n<=0?0:e*(.002+n*.012)}function ht(e){let t=e==null?void 0:e.trim();if(!t)return pt;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(a=>Number.isNaN(a))?pt:`rgba(${o},${r},${i},0.12)`}return pt}function mt(e,t,n){let o=e,r=so(e,n),i=io(e,t),a=o+2*r,s=o+2*r+2*i;return{fillPx:o,interiorPx:r,exteriorPx:i,totalPx:s,fillRadius:o/2,midPx:a}}function cn(e,t){let n=e/150;return`0 0 ${Math.round(48*n)}px ${t}33`}function ln(e){let t=e/150;return[`inset -${Math.round(8*t)}px -${Math.round(12*t)}px ${Math.round(28*t)}px rgba(0,0,0,0.36)`,`inset ${Math.round(6*t)}px ${Math.round(8*t)}px ${Math.round(20*t)}px rgba(255,255,255,0.07)`].join(", ")}var ne={accent:"#2f6bff",glow:"#5aa2ff",background:"rgba(0,0,0,0.72)",waveform:"#ffffff",colorKey:"azul"},nr={colorKey:ne.colorKey,glowKey:ne.colorKey,accentColor:ne.accent,glowColor:ne.glow,backgroundColor:ne.background,waveformColor:ne.waveform,waveformColorKey:"custom",speed:42,glowIntensity:100,innerBorderColor:ft,innerBorderWidth:We,borderWidth:1.5,waveformHeight:26,size:52},or={size:30,shape:"circle",backgroundColor:ne.background,borderColor:ne.accent,iconColor:ne.accent,icon:"keyboard",iconImageDataUrl:null,iconScale:1,innerBorderColor:ft,innerBorderWidth:We,borderWidth:100},bt={backgroundColor:"#ffffff",textColor:"#16181d",borderColor:"rgba(0,0,0,0.08)",borderWidth:1,shape:"pill",borderRadius:14,textSize:13,bubbleScale:1,size:13},rr={cardBackgroundColor:"#16181d",cardBorderColor:"rgba(255,255,255,0.14)",userTextColor:"rgba(255,255,255,0.75)",replyTextColor:"#ffffff",accentColor:ne.accent,inputBackgroundColor:"#ffffff",borderRadius:18,sendButtonRadius:16};function He(e){let t=ir(e);return t===null||t>.55?"#0f172a":"#f4f6fb"}function un(e){let t=ir(e);return t===null||t>.55?"#64748b":"rgba(244,246,251,0.65)"}function ir(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 a=i[1];a.length===3?(n=parseInt(a[0]+a[0],16),o=parseInt(a[1]+a[1],16),r=parseInt(a[2]+a[2],16)):(n=parseInt(a.slice(0,2),16),o=parseInt(a.slice(2,4),16),r=parseInt(a.slice(4,6),16))}else{let a=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(!a)return null;n=Number(a[1]),o=Number(a[2]),r=Number(a[3])}return(.299*n+.587*o+.114*r)/255}var gt={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}=gt,a=(t!=null?t:"").trim()||gt.color,s=e*o,l=e*r,c=e*i,u=n.length*s+(n.length-1)*l,p=(e-u)/2;return{bars:n.map((m,h)=>{let g=Math.max(s,c*m);return{x:p+h*(s+l),y:(e-g)/2,width:s,height:g}}),color:a,radius:s/2}}function dn(e,t){let{bars:n,color:o,radius:r}=ao(e,t),i=e/2,a=e*gt.heightRatio/2;return{color:o,radius:r,bars:n.map(s=>({...s,baseHalfHeight:s.height/2,centerY:i,maxHalfHeight:a}))}}function pn(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)),a=n*(.5+i*r);return Math.max(n*.35,Math.min(a,o))}var _s=["pill","rounded","square","cloud"];function sr(e,t,n,o,r,i,a){let s=[];for(let l=0;l<=a;l++){let c=r+(i-r)*l/a;s.push([e+n*Math.cos(c),t+o*Math.sin(c)])}return s}function ks(e,t,n,o,r){let i=[];for(let a=0;a<=r;a++){let s=Math.PI-Math.PI*a/r;i.push([e+n*Math.cos(s),t-o*Math.sin(s)])}return i}function Ps(e,t,n,o,r){let i=[];for(let a=0;a<=r;a++){let s=Math.PI*a/r;i.push([e+n*Math.cos(s),t+o*Math.sin(s)])}return i}function fn(e,t,n){n&&t.shift(),e.push(...t)}var Ms=1.28,Ls=38;function cr(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 cr(t/Ls,3,7)}function lr(e=5){let l=cr(e,3,7),c=88/(2*l),u=5,p=65/2,f=[];fn(f,sr(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;fn(f,ks(g,18,c,14,8),!0)}fn(f,sr(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;fn(f,Ps(g,83,c,12,8),!0)}return`polygon(${f.map(([h,g])=>`${h.toFixed(2)}% ${g.toFixed(2)}%`).join(", ")})`}var uo=lr(5);function po(e){return lr(lo(e))}function yt(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":_s.includes(t)?t:bt.shape}function xt(e,t){if(e!=null)return`${Math.round(e*t)}px`}function ze(e){let t=e!=null?e:{},n=bt,o=yt(t.textSize,yt(t.size,n.textSize));return{backgroundColor:co(t.backgroundColor,n.backgroundColor),textColor:co(t.textColor,n.textColor),borderColor:co(t.borderColor,n.borderColor),borderWidth:yt(t.borderWidth,n.borderWidth),shape:hn(t.shape),borderRadius:yt(t.borderRadius,n.borderRadius),textSize:o,bubbleScale:yt(t.bubbleScale,n.bubbleScale)}}var fo=38,ho=14,ar=4;function vt(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+ar*2);hn(e.shape)==="cloud"&&(i=Math.round(i*Ms));let a=Math.max(ar,Math.round((i-r)/2));return{fontPx:t,padV:a,padH:o,approxHeight:i}}function Bs(e){let t=Math.round(e*.45);return{borderTopLeftRadius:t,borderTopRightRadius:t,borderBottomLeftRadius:t,borderBottomRightRadius:t}}var ur=999;function mo(e,t,n){switch(hn(e.shape)){case"square":return{borderRadius:0};case"pill":return{borderRadius:ur};case"cloud":{let r=Bs(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 mn(e,t,n=1,o){var a;let r=hn(e.shape),i=mo({...e,shape:r},t,o);if(r==="pill"){let s=`${Math.round(ur*n)}px`;return{borderRadius:s,borderTopLeftRadius:s,borderTopRightRadius:s,borderBottomLeftRadius:s,borderBottomRightRadius:s,clipPath:"none"}}return r==="square"?{borderRadius:"0px",borderTopLeftRadius:"0px",borderTopRightRadius:"0px",borderBottomLeftRadius:"0px",borderBottomRightRadius:"0px",clipPath:"none"}:{borderRadius:xt(i.borderRadius,n),borderTopLeftRadius:xt(i.borderTopLeftRadius,n),borderTopRightRadius:xt(i.borderTopRightRadius,n),borderBottomLeftRadius:xt(i.borderBottomLeftRadius,n),borderBottomRightRadius:xt(i.borderBottomRightRadius,n),clipPath:(a=i.clipPath)!=null?a:"none"}}function gn(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 bn(e){return Math.round(e*.5)}function yn(e=1){return!Number.isFinite(e)||e<=0?1:Math.max(.35,Math.min(1.75,e))}function xn(e,t){return e==="circle"?t/2:e==="rounded"?Math.max(6,Math.round(t*.28)):6}function vn(e,t,n="#ffffff"){let o=(e!=null?e:n).trim(),r=t.trim();if(!o)return n;let i=a=>{let s=a.toLowerCase();return s.startsWith("#")&&s.length>=7?s.slice(0,7):s};return i(o)===i(r)?n:o}var Ns=[[8,11],[11,11],[14,11],[17,11],[8,14],[11,14],[14,14],[17,14]],dr={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:Ns},pen:{viewBox:"0 0 24 24",paths:[{d:"M4 20h4l10.5-10.5a1.5 1.5 0 0 0 0-2.12l-2.38-2.38a1.5 1.5 0 0 0-2.12 0L4 15.5V20z",fill:!1},{d:"M13.5 6.5l4 4",fill:!1}],contentBBox:{minX:4,minY:6.5,maxX:17.5,maxY:20}},chat:{viewBox:"0 0 24 24",paths:[],contentBBox:{minX:5,minY:4,maxX:19,maxY:18.5},chatFrame:{x:5,y:4,w:14,h:10,rx:2.5},chatTail:{left:7.5,right:10.5,tipX:5,tipY:18.5},chatLines:[{y:8,w:6},{y:10,w:6}]}};function Cn(e="keyboard"){var t;return(t=dr[e])!=null?t:dr.keyboard}function An(e){var l,c;let t=e.viewBox.split(/\s+/).map(Number),n=(l=t[2])!=null?l:24,o=(c=t[3])!=null?c:24,{minX:r,minY:i,maxX:a,maxY:s}=e.contentBBox;return{x:n/2-(r+a)/2,y:o/2-(i+s)/2}}var $s=["keyboard","pen","chat"];function Ve(e){return $s.includes(e)?e:"keyboard"}var Se={x:1,y:1};function pe(e){if(e==null)return{...Se};let t=Number(e.x),n=Number(e.y);return{x:Number.isFinite(t)?Math.min(1,Math.max(0,t)):Se.x,y:Number.isFinite(n)?Math.min(1,Math.max(0,n)):Se.y}}function go(e){var f,m,h,g,w;let t=pe(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,a=(w=e.margin)!=null?w:16,s=e.orbDiameter,l=Math.max(0,e.viewportWidth-r-i-2*a-s),c=Math.max(0,e.viewportHeight-n-o-2*a-s),u=r+a+t.x*l,p=n+a+t.y*c;return{right:e.viewportWidth-u-s,bottom:e.viewportHeight-p-s}}function Sn(e){var u,p,f;let t=(u=e.contentWidth)!=null?u:e.viewportWidth,n=(p=e.contentHeight)!=null?p:e.viewportHeight,o=e.orbDiameter,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}),a=t-i.right-o,s=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,a)),top:Math.min(c,Math.max(r,s))}}function Ct(e){let t=pe(e);return{horizontal:t.x>=.5?"left":"right",vertical:t.y>=.5?"up":"down"}}function wn(e){let t=pe(e);return{x:t.x>=.5?1:0,y:t.y}}function En(e){var m,h,g,w,C;let t=(m=e.safeAreaTop)!=null?m:0,n=(h=e.safeAreaBottom)!=null?h:0,o=(g=e.safeAreaLeft)!=null?g:0,r=(w=e.safeAreaRight)!=null?w:0,i=(C=e.margin)!=null?C:16,a=e.orbDiameter,s=Math.max(0,e.viewportWidth-o-r-2*i-a),l=Math.max(0,e.viewportHeight-t-n-2*i-a),c=e.centerX-a/2,u=e.centerY-a/2,p=s>0?(c-o-i)/s:0,f=l>0?(u-t-i)/l:0;return pe({x:p,y:f})}var pr={azul:"#2f6bff",cian:"#16b8d4",agua:"#19c39b",violeta:"#7a4dff",magenta:"#e0489e",ambar:"#f0820f",verde:"#46c24a",blanco:"#ffffff"},At="rgba(0,0,0,0.72)";function St(e){var o,r,i;let t=(o=e.colorKey)==null?void 0:o.trim();if(t&&t!=="custom"&&pr[t])return pr[t];let n=(r=e.backgroundColor)==null?void 0:r.trim();return n&&n!==At?n:(i=e.accentColor)!=null&&i.trim()?e.accentColor.trim():n||At}function Tn(e){var a,s,l,c,u,p,f,m;let t=St(e),n=e.keyboardChip,o=(a=n==null?void 0:n.backgroundColor)==null?void 0:a.trim(),r=(s=e.glowColor)!=null?s:e.accentColor,i=n?{...n,icon:Ve(n.icon),backgroundColor:!o||o===At?t:o,borderColor:(l=n.borderColor)!=null?l:r,iconColor:(c=n.iconColor)!=null?c:e.accentColor,innerBorderColor:n.innerBorderColor,innerBorderWidth:Ue(n.innerBorderWidth),borderWidth:Fe(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:Fe(e.glowIntensity),hapticIntensity:Zt(e.hapticIntensity),innerBorderColor:e.innerBorderColor,innerBorderWidth:Ue(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 wt(e){var n,o;return{theme:Tn(e.orbTheme),modalTheme:e.modalTheme,logoDataUrl:(n=e.logoDataUrl)!=null?n:null,logoTransform:(o=e.logoTransform)!=null?o:null,screenPosition:pe(e.orbTheme.screenPosition)}}var Ds=/^(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:Ds.test(t):!1}function Rn(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 Da=15e3,Fa=12e3;async function In(e,t,n,o){let r=new AbortController,i=!1,a=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(s){if(i)throw new V("timeout");if(o!=null&&o.aborted)throw new V("cancelled");let l=s instanceof Error?s.message:String(s);throw new V("network",l)}finally{clearTimeout(a)}}async function fr(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 hr(e){var i,a;let t=e.baseUrl.replace(/\/$/,""),n=(i=e.turnTimeoutMs)!=null?i:Da,o=(a=e.ttsTimeoutMs)!=null?a:Fa;function r(){var l,c;let s=(l=e.getUserId)==null?void 0:l.call(e);return{"Content-Type":"application/json",...e.apiKey?{"x-api-key":e.apiKey}:{},...s?{"x-user-id":s}:{},...(c=e.headers)!=null?c:{}}}return{async sendTurn(s,l){var h,g,w,C,v,O,R,b,E,A,k;let c={message:s.message.trim(),language:s.language,manifest_version:s.manifestVersion,manifest_routes:s.manifestRoutes,manifest_actions:s.manifestActions,app_name:s.appName,app_description:s.appDescription};(h=s.appType)!=null&&h.trim()&&(c.app_type=s.appType.trim()),(g=s.appFlow)!=null&&g.trim()&&(c.app_flow=s.appFlow.trim()),s.voice&&(c.voice=s.voice),(w=s.screenContext)!=null&&w.trim()&&(c.screen_context=s.screenContext.trim()),(C=s.currentRoute)!=null&&C.trim()&&(c.current_route=s.currentRoute.trim()),(v=s.conversationHistory)!=null&&v.length&&(c.conversation_history=s.conversationHistory.map(H=>({role:H.role,content:H.content.trim()}))),(O=s.conversationSummary)!=null&&O.trim()&&(c.conversation_summary=s.conversationSummary.trim()),(R=s.llmModel)!=null&&R.trim()&&(c.llm_model=s.llmModel.trim()),(b=s.sessionId)!=null&&b.trim()&&(c.session_id=s.sessionId.trim()),(E=s.platformCapabilities)!=null&&E.credentialAutofill&&(c.platform_capabilities={credential_autofill:!0}),s.sessionContext&&(c.session_context={authenticated:s.sessionContext.authenticated,...s.sessionContext.capabilities?{capabilities:s.sessionContext.capabilities}:{}}),s.isContinuation&&(c.is_continuation=!0,typeof s.chainStep=="number"&&(c.chain_step=s.chainStep),s.lastStep&&(c.last_step={type:s.lastStep.type,intent:s.lastStep.intent,...s.lastStep.label?{label:s.lastStep.label}:{},success:s.lastStep.success,...s.lastStep.error?{error:s.lastStep.error}:{},...s.lastStep.data?{data:s.lastStep.data}:{}}));let u=await In(`${t}/assistant/chat`,{method:"POST",headers:r(),body:JSON.stringify(c)},n,l==null?void 0:l.signal);if(!u.ok)throw await fr(u);let p;try{p=await u.json()}catch{throw new V("invalid_response")}let f=typeof p.task_status=="string"?p.task_status:"",m=f==="in_progress"||f==="blocked"?f:"complete";return{reply:((A=p.reply)!=null?A:"").trim(),audioBase64:(k=p.audio_base64)!=null?k:null,action:kt(p.action),wasTruncated:p.was_truncated===!0,taskStatus:m}},async previewTts(s,l){var c;try{let u=await In(`${t}/assistant/preview-tts`,{method:"POST",headers:r(),body:JSON.stringify({voice:s,text:l})},o);if(!u.ok)return null;let p=await u.json();return(c=p.audio_base64)!=null&&c.length?p.audio_base64:null}catch{return null}},async warmUp(){try{await In(`${t}/health`,{method:"GET",headers:r()},5e3)}catch{}},async fetchPublishedConfig(){let s=await In(`${t}/v1/client/config`,{method:"GET",headers:r()},8e3);if(!s.ok)throw await fr(s);return await s.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 Wa(e){var o,r,i;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 a=[{type:"action",intent:t,session_id:n}];return e.actionExecuted!=null&&e.actionExecuted.confirmed===!0&&a.push({type:"confirmation_completed",intent:t,session_id:n}),a}case"action_failed":return[{type:"action_failed",intent:t,session_id:n,error:((i=e.errorDetail)!=null?i:"").slice(0,200)||null}];case"action_confirmation_requested":return[{type:"confirmation_requested",intent:t,session_id:n}];default:return[]}}function mr(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 a(){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 s(){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:a(),body:JSON.stringify({events:p})})}catch{}})()}function l(){i||(i=setTimeout(s,n))}return{logEvent(p){let f=Wa(p);if(f.length!==0){for(let m of f)r.push(m);r.length>=o?s():l()}}}}var Ua="BACK";function Ha(){return typeof window=="undefined"||!window.location?null:`${window.location.pathname}${window.location.search}`}function gr(e){let t=null,n=!1;return{navigate(o){if(!o||o===Ua){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():Ha()},setCurrentRoute(o){t=o}}}function za(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 br(e={}){let t=za(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 Va(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 Ga(e,t){var r,i,a,s,l;if(!e.length)return;let n=t.toLowerCase(),o=(r=n.split("-")[0])!=null?r:n;return(l=(s=(a=(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?a:e.find(c=>{var u;return(u=c.lang)==null?void 0:u.toLowerCase().startsWith(o)}))!=null?s:e.find(c=>c.default))!=null?l:e[0]}function yr(){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 xr(){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 vr(e={}){let t=yr(),n=null,o="",r=null,i=!1,a=!1,s=null,l=null,c=null,u=!1,p=!1,f=[],m="",h=null,g=null;function w(){g&&(clearTimeout(g),g=null)}function C(){if(w(),c){c.onresult=null,c.onerror=null,c.onend=null,c.onstart=null;try{c.abort()}catch{}}c=null}function v(){w(),!(!u||p)&&(g=setTimeout(()=>{g=null,u&&!p&&O()},600))}function O(){let _=yr();if(!_||!u||p)return;if(typeof document!="undefined"&&document.hidden){v();return}let y=new _;c=y,y.lang=m,y.continuous=!0,y.interimResults=!0,y.maxAlternatives=1,y.onresult=T=>{var $;if(!u||p)return;let N="";for(let I=0;I<T.results.length;I+=1){let D=T.results[I];if(!D)continue;let Y=D[0];N=`${N} ${($=Y==null?void 0:Y.transcript)!=null?$:""}`.trim()}let L=Qt(N,f);if(!L.matched)return;p=!0;let G=h;C(),G==null||G.onDetected(L.command)},y.onerror=T=>{var N;T.error==="aborted"||T.error==="no-speech"||!u||p||(N=h==null?void 0:h.onError)==null||N.call(h,new Error(T.error||"wake recognition error"))},y.onend=()=>{!u||p||v()};try{y.start()}catch{v()}}let R=null,b=null;function E(){var y,T;if(typeof window=="undefined")return null;let _=window;return(T=(y=_.AudioContext)!=null?y:_.webkitAudioContext)!=null?T:null}function A(){if(R)return R;let _=E();if(!_)return null;try{R=new _}catch{R=null}return R}function k(_){let y=atob(_),T=y.length,N=new Uint8Array(T);for(let L=0;L<T;L+=1)N[L]=y.charCodeAt(L);return N.buffer}function H(){if(b){try{b.onended=null,b.stop()}catch{}b=null}}async function te(_){let y=A();if(!y)return!1;try{y.state==="suspended"&&await y.resume();let T=await y.decodeAudioData(k(_));return await new Promise(N=>{H();let L=y.createBufferSource();b=L,L.buffer=T,L.connect(y.destination),L.onended=()=>{L.onended=null,b===L&&(b=null),N(!0)},L.start()})}catch{return!1}}function X(){r&&(clearTimeout(r),r=null)}function re(){X(),n&&(n.onresult=null,n.onerror=null,n.onend=null,n.onstart=null),n=null}return{isRecognitionAvailable(){return t!=null},async startListening(_,y){var N,L,G;if(!t){(N=y.onError)==null||N.call(y,new Error("SpeechRecognition unavailable in this browser"));return}if(u&&(u=!1,p=!1,h=null,C()),n){i=!0;try{n.abort()}catch{}re()}o="",i=!1,a=!1;let T=new t;n=T,T.lang=_.locale,T.continuous=(L=_.continuous)!=null?L:!0,T.interimResults=!0,T.maxAlternatives=1,T.onresult=$=>{var Y,be;let I="";for(let he=$.resultIndex;he<$.results.length;he+=1){let ye=$.results[he];if(!ye)continue;let J=ye[0],Ee=(Y=J==null?void 0:J.transcript)!=null?Y:"";ye.isFinal?o=`${o} ${Ee}`.trim():I=`${I} ${Ee}`.trim()}let D=`${o} ${I}`.trim();D&&((be=y.onInterim)==null||be.call(y,D))},T.onerror=$=>{var I;$.error==="aborted"||i||$.error!=="no-speech"&&(a=!0,(I=y.onError)==null||I.call(y,new Error($.error||"speech recognition error")))},T.onend=()=>{var D,Y,be,he;X();let $=i,I=o.trim();if(re(),a){(D=y.onEnd)==null||D.call(y);return}if($){(Y=y.onEnd)==null||Y.call(y);return}I?(be=y.onFinal)==null||be.call(y,I):(he=y.onEnd)==null||he.call(y)};try{T.start()}catch($){re(),(G=y.onError)==null||G.call(y,$);return}_.maxSeconds&&_.maxSeconds>0&&(r=setTimeout(()=>{try{T.stop()}catch{}},_.maxSeconds*1e3))},stopListening(){if(X(),n)try{n.stop()}catch{}},cancelListening(){if(X(),i=!0,n)try{n.abort()}catch{}},primePlayback(){let _=A();if(_)try{_.state==="suspended"&&_.resume();let y=_.createBuffer(1,1,_.sampleRate),T=_.createBufferSource();T.buffer=y,T.connect(_.destination),T.start(0)}catch{}if(!e.disableDeviceTtsFallback&&typeof window!="undefined"&&window.speechSynthesis)try{let y=window.speechSynthesis;y.getVoices(),y.paused&&y.resume();let T=new SpeechSynthesisUtterance(" ");T.volume=0,y.speak(T)}catch{}},async playAudioBase64Mp3(_){if(typeof window!="undefined"&&(this.stopPlayback(),!await te(_)&&typeof Audio!="undefined"))return new Promise(y=>{try{let T=new Audio(`data:audio/mp3;base64,${_}`);s=T;let N=()=>{T.onended=null,T.onerror=null,s===T&&(s=null),y()};T.onended=N,T.onerror=N,T.play().catch(()=>N())}catch{y()}})},async speakWithDeviceTts(_,y){if(e.disableDeviceTtsFallback||typeof window=="undefined"||!window.speechSynthesis)return;let T=window.speechSynthesis,N=await Va(T);return new Promise(L=>{let G=null,$=()=>{G&&(clearInterval(G),G=null)};try{T.cancel();let I=new SpeechSynthesisUtterance(_);I.lang=y.locale;let D=Ga(N,y.locale);D&&(I.voice=D),I.volume=1,I.rate=1,I.pitch=1,l=I;let Y=()=>{$(),I.onstart=null,I.onend=null,I.onerror=null,l===I&&(l=null),L()};I.onend=Y,I.onerror=Y,T.speak(I),T.resume(),G=setInterval(()=>{if(!T.speaking&&!T.pending){$();return}T.pause(),T.resume()},9e3)}catch{$(),L()}})},stopPlayback(){if(H(),s){try{s.pause()}catch{}s=null}if(typeof window!="undefined"&&window.speechSynthesis)try{window.speechSynthesis.cancel()}catch{}},supportsWakeWordDetection(){return t!=null&&!xr()},isWakeWordListening(){return u},async startWakeWordDetection(_,y){var T;if(!t||xr()){(T=y.onError)==null||T.call(y,new Error("wake_word_unsupported"));return}f=_.phrases,m=_.locale,h=y,u=!0,p=!1,O()},stopWakeWordDetection(){u=!1,p=!1,h=null,C()}}}function Cr(){if(typeof navigator=="undefined")return null;let e=navigator;return e.credentials&&typeof e.credentials.get=="function"?e.credentials:null}function Ar(){if(typeof window=="undefined")return!1;let e=window;return typeof e.PasswordCredential=="function"&&e.isSecureContext!==!1}function Sr(){return{isSupported(){return Cr()!==null&&Ar()},async requestCredentials(){let e=Cr();if(!e||!Ar())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 On(e){let t=null;return{set(n,o){t={ownerId:n,snapshot:o}},clear(n){(t==null?void 0:t.ownerId)===n&&(t=null)},getText(){var r,i,a;let n=(r=t==null?void 0:t.snapshot.text)==null?void 0:r.trim();return n||((a=(i=e.routeFallback)==null?void 0:i.call(e,e.getCurrentRoute()))==null?void 0:a.trim())||null},getSnapshot(){var n;return(n=t==null?void 0:t.snapshot)!=null?n:null}}}function wr(e){let{adapter:t,locale:n,maxSeconds:o}=e,r={state:"idle",interimText:"",volumeLevel:0},i=new Set;function a(l){r={...r,...l};for(let c of i)c(r)}function s(){a({state:"idle",interimText:"",volumeLevel:0})}return{getSnapshot(){return r},subscribe(l){return i.add(l),()=>i.delete(l)},async start(){r.state==="idle"&&(a({state:"recording",interimText:"",volumeLevel:.85}),await t.startListening({locale:n,continuous:!0,maxSeconds:o},{onInterim:l=>a({interimText:l}),onFinal:l=>{s(),l.trim()&&e.onTranscript(l)},onEnd:()=>{r.state!=="idle"&&s()},onError:l=>{var c;s(),(c=e.onError)==null||c.call(e,l)}}))},stop(){r.state==="recording"&&(a({state:"transcribing",volumeLevel:0}),t.stopListening())},cancel(){t.cancelListening(),s()},dispose(){t.cancelListening(),i.clear()}}}function Ya(e,t){if(t)return e.actions.find(n=>n.intent===t)}async function Er(e){var l,c,u,p,f,m,h;let{action:t,manifest:n,executor:o,context:r,messages:i,userMessage:a,suppressEscort: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 g=Ya(n,t.intent);if(!((g==null?void 0:g.requireConfirmation)===!0))return{kind:"executed",result:await o.execute(t,r,{suppressEscort:s})};let C=await o.precheck(t,r);if(C.kind==="done")return{kind:"precheck-resolved",result:C.result};let v=(l=g==null?void 0:g.voiceConfirmation)!=null?l:"standard",O=v==="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:v,strictPhrase:O,remainingConfirmations:(g==null?void 0:g.doubleConfirmation)===!0?2:1,userMessage:a,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?on(r,t.strictPhrase,n):nn(r,n)}var Rr={thinkingWatchdogMs:25e3,maxListeningSeconds:60,confirmationVoiceWindowMs:8e3,minTranscriptChars:2},Ir={enabled:!0,maxSteps:6,dwellMs:450};var _r={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"},Ka={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"},Or={en:_r,es:Ka};function ja(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,a,s,l,c;let n=(i=t.catalogs)!=null?i:{},o=ja(e),r=(c=(l=(s=(a=n[e])!=null?a:Or[e])!=null?s:n[o])!=null?l:Or[o])!=null?c:_r;return t.overrides?{...r,...t.overrides}:r}var Xa=2;function qa(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Qa=e=>new Promise(t=>setTimeout(t,e)),Ge=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=qa();this.sessionStarted=!1;this.conversation=$e();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=Ae;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,a,s,l,c,u,p;ge(t.manifest),this.config=t,this.messages=$t(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:en(t.locale),this.sanitizer=(a=t.sanitizer)!=null?a:jt(),this.telemetry=Jt(t.telemetry),this.consent=Xt({storage:t.storage,appId:t.manifest.appId,version:t.consentVersion}),this.credentialAutofill=t.credentialAutofill===void 0?Sr():t.credentialAutofill,this.executor=zt({manifest:t.manifest,registries:t.registries,navigation:t.navigation,messages:this.messages,isAuthenticated:t.isAuthenticated,credentialAutofill:this.credentialAutofill}),this.timings={...Rr,...t.timings};let n={...Ir,...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((s=n.dwellMs)!=null?s:450)))},this.ttsLocale=(l=t.ttsLocale)!=null?l:t.sttLocale,this.notifyError=(c=t.notifyError)!=null?c:(f=>{console.error(`[fyodos] ${f}`)}),this.screenStore=On({getCurrentRoute:()=>t.navigation.getCurrentRoute(),routeFallback:(u=t.routeContextFallback)!=null?u:(f=>Wt(f,t.manifest,this.messages))}),this.speech=wr({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=ut((p=t.getUserId)==null?void 0:p.call(t)),this.restorePersistedConversation(),typeof window!="undefined"){let f=()=>{this.syncConversationIdentity()};window.addEventListener("focus",f),document.addEventListener("visibilitychange",f),this.removeIdentityListeners=()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",f)}}}async restorePersistedConversation(){var o;let t=this.conversationIdentity,n=await sn(this.config.storage,this.config.manifest.appId,Date.now(),this.conversationScope,t);!n||this.conversationIdentity!==t||this.conversation.turns.length>0||(o=this.conversation.uiArchive)!=null&&o.length||(this.conversation.turns=n.turns,this.conversation.summary=n.summary,this.conversation.uiArchive=n.uiArchive,this.conversation.lastActivityAt=n.lastActivityAt,this.emit())}persistConversation(){rn(this.config.storage,this.config.manifest.appId,this.conversation,this.conversationRetentionMinutes,this.conversationScope,this.conversationIdentity)}syncConversationIdentity(){var n,o;let t=ut((o=(n=this.config).getUserId)==null?void 0:o.call(n));return t===this.conversationIdentity?!1:(this.persistConversation(),this.conversation=$e(),this.conversationIdentity=t,this.lastExchange=null,this.emit(),this.restorePersistedConversation(),!0)}resetConversation(){this.cancelAll(),this.conversation=$e(),this.lastExchange=null,an(this.config.storage,this.config.manifest.appId,this.conversationScope,this.conversationIdentity),this.emit()}getState(){let t=this.speech.getSnapshot(),n=(this.phase==="listening"||this.phase==="confirming")&&t.state==="recording",o=this.phase==="thinking"||this.phase==="listening"&&t.state==="transcribing",r=lt(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||!lt(this.conversation,this.lastExchange,this.bubbleWindowSize,this.conversationOptions).hasOlder||(this.loadingOlderExchanges=!0,this.emit(),this.loadOlderTimer=setTimeout(()=>{this.loadOlderTimer=null,this.bubbleWindowSize+=Ae,this.loadingOlderExchanges=!1,this.emit()},350))}setConversationRetention(t,n=!1){this.conversationOptions=Ne(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=Ae}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,a=()=>{i||(i=!0,this.clearSpeakTimer(),r())};this.clearSpeakTimer(),this.speakTimer=setTimeout(()=>{this.config.voice.stopPlayback(),a()},o),t.then(a,a)})}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,a,s,l;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 c=this.messages.doubleConfirmationQuestion;this.confirmationMessage=c,this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:c}),this.emit(),await this.speakReply(c,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.success?{}:{errorDetail:(i=n.error)!=null?i:null}}),n.success||console.warn(`[fyodos] action "${t.intent}" failed: ${(a=n.error)!=null?a:"unknown error"}`),n.message&&(this.lastExchange&&(this.lastExchange={...this.lastExchange,replyText:n.message}),this.emit(),await this.speakReply(n.message,null));let o=this.chainState;if(o)if(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:(s=o.pendingStep)!=null?s:o.lastStep,visitedKeys:o.visitedKeys,recoveries:o.recoveries});else if(!n.success&&this.chaining.enabled){let c={type:"execute",intent:t.intent,label:this.actionLabel(t.intent),success:!1,...n.error?{error:String(n.error).slice(0,300)}:{}};await this.runChainLoop({userMessage:o.userMessage,step:o.step,lastStep:c,visitedKeys:o.visitedKeys,recoveries:((l=o.recoveries)!=null?l:0)+1})}else 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 a={};for(let[s,l]of Object.entries(i))typeof l=="boolean"&&(a[s]=l);Object.keys(a).length>0&&(r=a)}}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 C,v,O,R,b,E,A,k,H,te,X,re,_,y,T,N,L,G,$;let i=t.reply,a=t.audioBase64;i&&(this.serverTtsUnavailable=!a);let s=this.chaining.enabled&&t.taskStatus==="in_progress",l=await Er({action:t.action,manifest:this.config.manifest,executor:this.executor,context:o,messages:this.messages,userMessage:r,suppressEscort:s}),c=!1,u,p,f=!1,m=!1,h,g,w=!1;if(l.kind==="executed"){let I=l.result;if(I.success&&((C=t.action)==null?void 0:C.type)==="navigate"?this.setActivity({kind:"navigating",label:(R=(O=this.routeLabel((v=t.action.intent)!=null?v:""))!=null?O:t.action.intent)!=null?R:""}):I.success&&!I.recoverable&&((b=t.action)==null?void 0:b.type)==="execute"&&this.setActivity({kind:"executing",label:(k=(A=this.actionLabel((E=t.action.intent)!=null?E:""))!=null?A:t.action.intent)!=null?k:""}),((H=t.action)==null?void 0:H.type)==="navigate"?this.telemetry.logEvent({eventType:I.success?"navigation_executed":"navigation_failed",intentDetected:t.action.intent,sessionId:this.sessionId,currentRoute:n!=null?n:void 0}):((te=t.action)==null?void 0:te.type)==="execute"&&this.telemetry.logEvent({eventType:I.recoverable?"action_needs_context":I.success?"action_executed":"action_failed",intentDetected:t.action.intent,sessionId:this.sessionId,actionExecuted:{intent:t.action.intent,confirmed:!1},...!I.success&&!I.recoverable?{errorDetail:(X=I.error)!=null?X:null}:{}}),I.recoverable||((re=t.action)==null?void 0:re.type)==="navigate"&&I.success&&t.taskStatus==="in_progress"||(I.message?(i=I.message,a=null):I.success||(i=this.messages.actionFailed,a=null)),I.success||console.warn(`[fyodos] action "${(y=(_=t.action)==null?void 0:_.intent)!=null?y:"?"}" failed: ${(T=I.error)!=null?T:"unknown error"}`),((N=t.action)==null?void 0:N.type)==="execute"&&!I.success&&!I.recoverable){let D=(L=t.action.intent)!=null?L:"";u={type:"execute",intent:D,label:this.actionLabel(D),success:!1,...I.error?{error:String(I.error).slice(0,300)}:{}},w=!0,c=this.chaining.enabled}if(t.action&&(t.action.type==="navigate"||t.action.type==="execute")&&I.success&&!I.recoverable){t.action.type==="execute"?this.deferredEscortIntent=s&&(G=t.action.intent)!=null?G:null:this.deferredEscortIntent=null;let D=($=t.action.intent)!=null?$:"",Y=Yt(I.data);u={type:t.action.type,intent:D,label:t.action.type==="navigate"?this.routeLabel(D):this.actionLabel(D),success:!0,...Y?{data:Y}:{}},p=`${t.action.type}:${D}`,c=t.taskStatus==="in_progress"}}else if(l.kind==="precheck-resolved")l.result.message&&!l.result.recoverable&&(i=l.result.message,a=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 I=l.pending.intent||"";h={type:"execute",intent:I,label:this.actionLabel(I),success:!0},g=`execute:${I}`}return{reply:i,audioBase64:a,hasPending:f,canContinue:c,lastStep:u,actionKey:p,pendingInProgress:m,pendingStep:h,pendingKey:g,stepFailed:w}}async runChainLoop(t){var a,s,l,c,u,p,f,m,h,g,w,C;let n=t.step,o=t.lastStep,r=(a=t.recoveries)!=null?a:0,i=t.visitedKeys;this.setChainActive(!0);try{for(;n<this.chaining.maxSteps;){if(n+=1,this.chaining.dwellMs>0&&await Qa(this.chaining.dwellMs),this.pending!=null)return;let v=this.config.navigation.getCurrentRoute(),O=this.screenStore.getSnapshot(),R=rt((c=(l=(s=this.config).getUserContextText)==null?void 0:l.call(s))!=null?c:null,this.screenStore.getText(),{truncationSuffix:this.messages.contextTruncationSuffix,maxChars:this.config.contextMaxChars}),b=R?this.sanitizer(R).sanitized:void 0,E=at(this.conversation,Date.now(),this.conversationOptions);this.setPhase("thinking"),this.setActivity({kind:"thinking"});let A=new AbortController;this.abort=A;let k;try{let H=await this.config.backend.sendTurn({message:t.userMessage,language:this.config.locale,voice:this.getTtsVoice(),screenContext:b,currentRoute:v!=null?v:void 0,conversationHistory:E.history,conversationSummary:(u=E.summary)!=null?u: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:A.signal});k=await this.applyOutcome(H,v,(p=O==null?void 0:O.context)!=null?p:{},t.userMessage)}catch(H){this.abort=null;let te=H instanceof V&&H.code==="cancelled";if(te)this.phase==="thinking"&&this.setPhase("idle");else{H instanceof V&&H.code==="quota_exceeded"&&((m=(f=this.config).onQuotaExceeded)==null||m.call(f));let X=xo(H,this.config.locale);this.lastExchange={userText:t.userMessage,replyText:X},this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(X)}this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:te?"user_interrupt":"error"});return}if(this.abort=null,k.reply&&(this.lastExchange={userText:t.userMessage,replyText:k.reply},this.emit(),ct(this.conversation,t.userMessage,k.reply,Date.now(),this.conversationOptions),this.persistConversation()),await this.speakReply(k.reply,k.audioBase64),this.telemetry.logEvent({eventType:"agent_chain_step",intentDetected:(C=(w=(h=k.lastStep)==null?void 0:h.intent)!=null?w:(g=k.pendingStep)==null?void 0:g.intent)!=null?C:null,sessionId:this.sessionId,chainStep:n}),k.hasPending){this.chainState=k.pendingInProgress?{userMessage:t.userMessage,step:n,lastStep:o,visitedKeys:i,pendingKey:k.pendingKey,pendingStep:k.pendingStep,recoveries:r}:null,this.beginConfirmationVoiceWindow();return}if(this.phase!=="speaking"&&this.setPhase("idle"),k.stepFailed&&(r+=1,r>Xa)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(k.actionKey&&i.has(k.actionKey)){this.telemetry.logEvent({eventType:"agent_chain_aborted",sessionId:this.sessionId,chainStep:n,chainAbortReason:"no_progress"});return}if(k.actionKey&&i.add(k.actionKey),!k.canContinue){this.telemetry.logEvent({eventType:"agent_chain_completed",sessionId:this.sessionId,chainStep:n});return}o=k.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,w,C,v,O,R;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 E=(b=this.pendingTurnText)!=null?b: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:E,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 r=this.screenStore.getSnapshot(),i=rt((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}),a=i?this.sanitizer(i).sanitized:void 0,s=at(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:a,currentRoute:o!=null?o:void 0,conversationHistory:s.history,conversationSummary:(g=s.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,(w=r==null?void 0:r.context)!=null?w:{},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"&&((v=(C=this.config).onQuotaExceeded)==null||v.call(C));let E=xo(b,this.config.locale);this.lastExchange={userText:n,replyText:E},this.pendingTurnText=null,this.phase==="thinking"&&this.setPhase("idle"),this.emit(),this.notifyError(E);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(),ct(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,recoveries:c.stepFailed?1:0})}this.pending||this.setActivity(null),(R=(O=this.config).onTurnCompleted)==null||R.call(O)}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,a;if(!this.enabled)return;let o=t.trim();if(!o)return;let r=(a=(i=this.config).gateTurn)==null?void 0:a.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 Ja="http://www.w3.org/2000/svg",ce={accentColor:"#4f8cff",backgroundColor:"#1b2a4a",colorKey:"azul",glowIntensity:100,size:56};function oe(e,t){let n=document.createElementNS(Ja,e);for(let[o,r]of Object.entries(t))n.setAttribute(o,String(r));return n}function Lr(e){let{fillPx:t,interiorPx:n,exteriorPx:o,totalPx:r,fillRadius:i,midPx:a}=mt(e.fillDiameter,e.exteriorWidthSlider,e.interiorWidthSlider),s=typeof e.borderRadius=="number",l=s?`${i}px`:String(e.borderRadius),c=s?`${a/2}px`:String(e.borderRadius),u=s?`${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?cn(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?ln(e.fillDiameter):""}),h.appendChild(g),m.appendChild(h),{root:m,fill:g}}function Za(e,t){let{bars:n,color:o,radius:r}=dn(e,t),i=oe("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,"aria-hidden":"true"});i.style.display="block";let a=n.map(l=>{let c=oe("rect",{x:l.x,y:l.y,width:l.width,height:l.height,rx:r,ry:r,fill:o});return i.appendChild(c),c}),s=0;return{el:i,start(){let l=performance.now(),c=u=>{s=requestAnimationFrame(c);let p=(u-l)/1e3;n.forEach((f,m)=>{let h=pn(p,m,f.baseHalfHeight,f.maxHalfHeight);a[m].setAttribute("y",(f.centerY-h).toFixed(2)),a[m].setAttribute("height",(2*h).toFixed(2))})};s=requestAnimationFrame(c)},stop(){cancelAnimationFrame(s)}}}var ec=9,tc=[.25,.45,.65,.85,1,.85,.65,.45,.25],Pr=[0,.7,1.4,2.1,2.8,2.1,1.4,.7,0],nc=26;function oc(e,t){let n=t/nc,o=3*n,r=3*n,i=3*n,a=document.createElement("div");Object.assign(a.style,{display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:`${r}px`,height:`${t}px`,width:"100%",maxWidth:"88%"});let s=[];for(let h=0;h<ec;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"}),s.push(g),a.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,s.forEach((g,w)=>{var v,O,R;let C;if(p<.05){let b=(Math.sin(c+((v=Pr[w])!=null?v:0))+1)/2;C=f+b*(.22-f)}else{let b=Math.sin(c*2.3+((O=Pr[w])!=null?O:0))*.18+.82+Math.random()*.18;C=f+p*((R=tc[w])!=null?R:.5)*(1-f)*b}g.style.transform=`scaleY(${Math.min(1,Math.max(f,C))})`}))};return{el:a,start(){l||(u=typeof performance!="undefined"?performance.now():Date.now(),l=requestAnimationFrame(m))},stop(){l&&cancelAnimationFrame(l),l=0},setVolume(h){p=h}}}var Mr=8,Br=68,rc=360-Br,ic=Br/2,sc=[.15,.25,.35,.5,.65,.78,.88,1];function ac(e,t){var s;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=oe("svg",{width:n,height:n,viewBox:"0 0 40 40","aria-hidden":"true"}),a=rc/(Mr-1);for(let l=0;l<Mr;l++){let c=ic+a*l;i.appendChild(oe("rect",{x:"18.25",y:"5.5",width:"3.5",height:"11",rx:"1.75",fill:t,opacity:(s=sc[l])!=null?s:1,transform:`rotate(${c} 20 20)`}))}return r.appendChild(i),o.appendChild(r),o}var cc=118/380,lc=30/380,uc=2/380;function dc(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*cc,r=Math.max(1,e*uc);for(let s 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 ${s}s`}),n.appendChild(l)}let i=e*lc,a=document.createElement("div");return Object.assign(a.style,{width:`${i}px`,height:`${i}px`,borderRadius:"50%",background:t,opacity:"0.9",animation:"fy-opulse 1s ease-in-out infinite"}),n.appendChild(a),n}function pc(e,t,n){let o=Cn(e),r=1.8,{x:i,y:a}=An(o),s=oe("svg",{width:t,height:t,viewBox:o.viewBox,fill:"none","aria-hidden":"true"});s.style.display="block",s.style.pointerEvents="none";let l=oe("g",{transform:`translate(${i} ${a})`});if(o.keyboardFrame&&o.keyDots){let c=o.keyboardFrame;l.appendChild(oe("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(oe("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(oe("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(oe("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(oe("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(oe("path",{d:c.d,stroke:n,fill:"none","stroke-width":r,"stroke-linecap":"round","stroke-linejoin":"round"}));return s.appendChild(l),s}function Nr(e){var g,w,C,v,O,R,b;let{theme:t}=e,n=(g=t.size)!=null?g:30,o=(w=t.shape)!=null?w:"circle",r=o==="circle"?"50%":`${xn(o,n)}px`,i=(C=t.backgroundColor)!=null?C:e.backgroundColor,a=(v=t.borderColor)!=null?v:e.accentColor,s=vn(t.iconColor,i,e.accentColor),l=Ve(t.icon),c=yn((O=t.iconScale)!=null?O:1),u=Math.round(bn(n)*c),p=mt(n,(R=t.borderWidth)!=null?R: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}=Lr({fillDiameter:n,borderRadius:r,exteriorColor:a,exteriorWidthSlider:(b=t.borderWidth)!=null?b:100,interiorColor:ht(t.innerBorderColor),interiorWidthSlider:t.innerBorderWidth,fill:i,outerGlow:!1,fillDepth:!1});if(t.iconImageDataUrl){let E=document.createElement("img");E.src=t.iconImageDataUrl,E.alt="",Object.assign(E.style,{width:`${u}px`,height:`${u}px`,objectFit:"contain",display:"block"}),h.appendChild(E)}else h.appendChild(pc(l,u,s));return f.appendChild(m),f}function $r(e){let t=document.createElement("div");t.style.display="inline-flex";let n=e,o="idle",r=0,i=null,a=null,s=null;function l(){var w,C,v,O;let u=(w=n.size)!=null?w:ce.size,p=St({colorKey:(C=n.colorKey)!=null?C:ce.colorKey,backgroundColor:n.backgroundColor,accentColor:n.accentColor}),f=(v=n.glowColor)!=null&&v.startsWith("#")?n.glowColor:n.accentColor,m=ht(n.innerBorderColor);a==null||a.stop(),a=null,s==null||s.stop(),s=null,t.replaceChildren();let{root:h,fill:g}=Lr({fillDiameter:u,borderRadius:u,exteriorColor:f,exteriorWidthSlider:(O=n.glowIntensity)!=null?O:ce.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:ce.size,p=(m=n.waveformColor)!=null?m:"#ffffff";if(a==null||a.stop(),a=null,s==null||s.stop(),s=null,i.replaceChildren(),t.style.animation="",o==="thinking"){i.appendChild(ac(u,p));return}if(o==="listening"){a=oc(p,Math.round(u*.46)),a.setVolume(r),i.appendChild(a.el),a.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(dc(u,p));return}o==="idle"&&(s=Za(u,n.waveformColor),i.appendChild(s.el),s.start())}return l(),{element:t,applyAppearance(u){n=u,l()},applyState(u,p){r=p,u!==o?(o=u,c()):o==="listening"&&(a==null||a.setVolume(r))}}}var vo="fyodos:published-config:v1";function fc(){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 Fr(e,t){var i,a,s,l;let n=t.orbEnabled!==!1,o=e.theme;return{appearance:{accentColor:(i=o.accentColor)!=null?i:ce.accentColor,backgroundColor:(a=o.backgroundColor)!=null?a:ce.backgroundColor,glowColor:o.glowColor,colorKey:o.colorKey,glowIntensity:o.glowIntensity,hapticIntensity:o.hapticIntensity,innerBorderColor:o.innerBorderColor,innerBorderWidth:o.innerBorderWidth,size:(s=o.size)!=null?s:ce.size,waveformColor:o.waveformColor,logoDataUrl:e.logoDataUrl},keyboardChip:(l=o.keyboardChip)!=null?l:null,modalTheme:e.modalTheme,screenPosition:e.screenPosition,bubbleTheme:ze(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 Wr(e,t){var l;let n=e.config.backend.fetchPublishedConfig;if(!n)return t.onChange(null),()=>{};let o=!1,r=fc();r&&t.onChange(Fr(wt(r),r));let i=async()=>{try{let c=await n.call(e.config.backend);if(o)return;c.published?(t.onChange(Fr(wt(c.published),c.published)),Dr(c.published)):(t.onChange(null),Dr(null))}catch{}};i();let a=(l=t.pollMs)!=null?l:12e3,s=a>0?setInterval(()=>{i()},a):null;return()=>{o=!0,s&&clearInterval(s)}}function hc(){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 mc(e){return e.toLowerCase().startsWith("es")?"es-ES":"en-US"}function Et(e){let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}e.scrollLeft=e.scrollWidth}function Ur(e){let t=hc(),n=null,o=!1,r="",i=()=>{let s=n;if(s){s.onresult=null,n=null,o=!1;try{typeof s.abort=="function"?s.abort():s.stop()}catch{}}};return{isSupported:()=>t!=null,isListening:()=>o,stop:i,dispose:()=>{i()},toggle(s,l){if(!t)return;if(o){i();return}r=s();let c=new t;c.lang=mc(e),c.interimResults=!0,c.continuous=!0;let u="";c.onresult=p=>{var g,w;let f="";for(let C=p.resultIndex;C<p.results.length;C+=1){let v=p.results[C];if(!v)continue;let O=(w=(g=v[0])==null?void 0:g.transcript)!=null?w:"";v.isFinal?u+=O:f+=O}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 Hr="fyodos-orb-styles",gc=`
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;}
@@ -63,6 +63,6 @@
63
63
  .fyodos-modal-actions{display:flex;gap:10px;justify-content:flex-end;}
64
64
  .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;}
65
65
  .fyodos-btn-primary{appearance:none;border:none;border-radius:999px;padding:10px 18px;font-size:13px;font-weight:600;color:#fff;cursor:pointer;}
66
- `;function gc(){if(typeof document=="undefined"||document.getElementById(Hr))return;let e=document.createElement("style");e.id=Hr,e.textContent=mc,document.head.appendChild(e)}function zr(){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 bc(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 we={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(){}};gc();let n=($o=t.container)!=null?$o:document.body,o=(Do=t.zIndex)!=null?Do:2147483e3,r=t.enableTextInput!==!1,i=t.usePublishedPosition!==!1,a=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 s=Zn(()=>S().hapticIntensity),l=null,c=null,u,p=ze(null),f=!0,m=!0,h=!1,g=null,w=t.corner?bc(t.corner):{...Se};function S(){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 C=document.createElement("div");C.className="fyodos-orb-root",C.style.zIndex=String(o);let O=document.createElement("div");O.className="fyodos-orb-anchor";let R=$r(S()),b=document.createElement("button");b.className="fyodos-orb-btn",b.type="button",b.setAttribute("aria-label",a.orbLabel),b.appendChild(R.element),O.appendChild(b),C.appendChild(O);let v=null,A=document.createElement("div");A.className="fyodos-thought",A.setAttribute("role","button"),A.tabIndex=0,A.style.display="none",A.addEventListener("click",()=>{if(s.trigger("orbTap"),e.primeAudio(),r){Qe();return}Rt=!0,e.toggleListening()}),A.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),A.click())}),O.appendChild(A),n.appendChild(C);let N=null;function X(){var d;return(d=S().size)!=null?d:ae.size}function ce(){return N!=null?N:w}function q(){let d=X(),x=zr(),{left:E,top:k}=Sn({viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,contentWidth:x.width,contentHeight:x.height,orbDiameter:d,position:ce()});C.style.left=`${E}px`,C.style.top=`${k}px`,C.style.right="",C.style.bottom="",oe()}function oe(){let d=Ct(ce());v&&(v.style.position="absolute",v.style.top="50%",v.style.transform="translateY(-50%)",d.horizontal==="left"?(v.style.right="calc(100% + 10px)",v.style.left=""):(v.style.left="calc(100% + 10px)",v.style.right="")),A.style.display!=="none"&&Po()}window.addEventListener("resize",q);let _;typeof ResizeObserver!="undefined"&&document.documentElement&&(_=new ResizeObserver(()=>q()),_.observe(document.documentElement));let y=window.visualViewport,T=()=>{J&&Pn()};y==null||y.addEventListener("resize",T),y==null||y.addEventListener("scroll",T);let I=6,M=!1,z=!1,D=0,L=0,Q=0,j=0;function be(d){if(d.button!=null&&d.button!==0)return;let x=C.getBoundingClientRect();Q=x.left,j=x.top,D=d.clientX,L=d.clientY,M=!1;try{b.setPointerCapture(d.pointerId)}catch{}}function he(d){var se;if(!((se=b.hasPointerCapture)!=null&&se.call(b,d.pointerId)))return;let x=d.clientX-D,E=d.clientY-L;if(!M&&Math.hypot(x,E)<I)return;M=!0,d.preventDefault();let k=X(),B=zr(),P=8,W=B.width-P-k,G=B.height-P-k,U=Math.min(W,Math.max(P,Q+x)),Y=Math.min(G,Math.max(P,j+E));C.style.left=`${U}px`,C.style.top=`${Y}px`,C.style.right="",C.style.bottom="",N=En({centerX:U+k/2,centerY:Y+k/2,viewportWidth:B.width,viewportHeight:B.height,orbDiameter:k}),oe()}function ye(d){try{b.releasePointerCapture(d.pointerId)}catch{}M&&(z=!0,M=!1,N=wn(N!=null?N:ce()),C.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(()=>{C.style.transition=""},260))}b.draggable=!1,b.addEventListener("dragstart",d=>d.preventDefault()),b.addEventListener("pointerdown",be),b.addEventListener("pointermove",he),b.addEventListener("pointerup",ye),b.addEventListener("pointercancel",ye),b.addEventListener("lostpointercapture",ye);let J=!1,Ee=!1,xe=!1,Rt=!1,V=document.createElement("div");V.className="fyodos-bubble",V.style.display="none";function si(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function Pn(){V.style.position="fixed",V.style.left="50%",V.style.right="",V.style.top="",V.style.transform="translateX(-50%)",V.style.bottom=`${si()+16}px`,V.style.zIndex=String(o+5)}let Z=document.createElement("div");Z.className="fyodos-bubble-scroll";let ve=document.createElement("button");ve.type="button",ve.className="fyodos-bubble-close",ve.textContent="\xD7",ve.setAttribute("aria-label","Close"),ve.addEventListener("click",()=>qe(!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(),It(!1)});let Ye=document.createElement("div");Ye.className="fyodos-bubble-loader",Ye.append(document.createElement("span")),Ye.style.display="none";let Te=document.createElement("div");Te.className="fyodos-bubble-exchanges";let le=document.createElement("div");le.className="fyodos-bubble-greeting",le.style.display="none",Z.append(Ye,Te,le);function ai(){let d=_o();if(!d){le.style.display="none";return}let x={...we,...u!=null?u:{}};le.textContent=d,le.style.color=x.titleColor,le.style.display="",Z.scrollTop=Z.scrollHeight}function Mn(){le.style.display!=="none"&&(le.style.display="none")}let Ke="";function ci(d){let x=d.map(P=>`${P.userText}\0${P.replyText}`).join("");if(x===Ke)return;let E=Ke.length>0&&x.length>Ke.length&&x.endsWith(Ke),k=Z.scrollHeight-Z.scrollTop;Ke=x;let B={...we,...u!=null?u:{}};Te.replaceChildren();for(let P of d){let W=document.createElement("div");W.className="fyodos-bubble-exchange";let G=document.createElement("div");if(G.className="fyodos-bubble-user",G.textContent=P.userText,G.style.color=B.bodyColor,W.append(G),P.replyText){let U=document.createElement("div");U.className="fyodos-bubble-reply",U.textContent=P.replyText,U.style.color=B.titleColor,W.append(U)}Te.append(W)}Z.scrollTop=E?Z.scrollHeight-k:Z.scrollHeight}Z.addEventListener("scroll",()=>{if(!J||Z.scrollTop>12)return;let d=e.getState();d.hasOlderExchanges&&!d.loadingOlderExchanges&&e.loadOlderExchanges()});let Re=document.createElement("div");Re.className="fyodos-bubble-busy";let re=document.createElement("em");re.className="fyodos-busy-step",re.style.display="none",Re.appendChild(re),Re.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let Eo=null;function li(d){if(!h||!d.liveActivity)return null;let{kind:x,label:E}=d.liveActivity;switch(x){case"navigating":return a.activityNavigating.replace("{label}",E!=null?E:"");case"executing":return a.activityExecuting.replace("{label}",E!=null?E:"");case"waiting_confirmation":return a.activityWaitingConfirmation;default:return a.activityThinking}}function ui(d,x){let E=d?li(x):null;if(E!==Eo){if(Eo=E,!E){re.textContent="",re.style.display="none";return}re.style.display="",re.textContent=E,re.style.animation="none",re.offsetWidth,re.style.animation=""}}let Ln=document.createElement("div");Ln.className="fyodos-bubble-row";let F=document.createElement("input");F.type="text",F.placeholder=a.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",a.sendLabel),Ln.append(F,$,ie);let Ie=Ur(e.config.locale);Ie.isSupported()&&($.style.display="flex",$.setAttribute("aria-label",a.micLabel),$.title=a.micLabel,$.addEventListener("click",()=>{e.getState().isBusy||(Ie.toggle(()=>F.value,d=>{F.value=d,Et(F)}),je())}));function je(){var B,P;let d=(B=u==null?void 0:u.primaryButtonColor)!=null?B:S().accentColor,x=`${(P=u==null?void 0:u.sendButtonRadius)!=null?P:10}px`,E={...we,...u!=null?u:{}}.bodyColor,k=Ie.isListening();$.classList.toggle("is-listening",k),k?($.style.background=d,$.style.border="none",$.style.color=He(d),$.style.borderRadius=x):($.style.background="rgba(255,255,255,0.06)",$.style.border="1px solid rgba(148,163,184,0.4)",$.style.color=E,$.style.borderRadius="999px"),$.setAttribute("aria-label",k?a.micStopLabel:a.micLabel),$.title=k?a.micStopLabel:a.micLabel}V.append(ve,me,Z,Re,Ln),O.appendChild(V);function It(d){Ee!==d&&(Ee=d,V.classList.toggle("fyodos-bubble--expanded",d),me.style.display=d?"flex":"none",Pn())}let To=0,Ro=0,Xe=null,di=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=()=>{Xe!=null&&(window.clearTimeout(Xe),Xe=null)};V.addEventListener("pointerdown",d=>{To=d.clientX,Ro=d.clientY}),V.addEventListener("click",d=>{if(Ee)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-To,d.clientY-Ro)>di)return;if(d.detail>1){Bn();return}if(Bn(),!!!(x!=null&&x.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!Io()){It(!0);return}Xe=window.setTimeout(()=>{Xe=null,Io()||It(!0)},280)}),q();function Oo(){var k,B,P;let d={...we,...u!=null?u:{}},x=(k=u==null?void 0:u.primaryButtonColor)!=null?k:S().accentColor;V.style.background=d.cardBackgroundColor,V.style.borderColor=d.cardBorderColor,(u==null?void 0:u.borderRadius)!=null&&(V.style.borderRadius=`${u.borderRadius}px`),ve.style.color=d.bodyColor,me.style.color=d.bodyColor,Te.querySelectorAll(".fyodos-bubble-user").forEach(W=>{W.style.color=d.bodyColor}),Te.querySelectorAll(".fyodos-bubble-reply").forEach(W=>{W.style.color=d.titleColor});let E=(B=u==null?void 0:u.inputBackgroundColor)!=null?B:"#ffffff";F.style.background=E,F.style.color=He(E),F.style.setProperty("--fyodos-input-placeholder",un(E)),ie.style.background=x,ie.style.color=He(x),ie.style.borderRadius=`${(P=u==null?void 0:u.sendButtonRadius)!=null?P:10}px`,je(),Re.querySelectorAll("span").forEach(W=>{W.style.background=x}),re.style.color=d.titleColor}let Nn=`fyodos:panel-open:${e.config.manifest.appId}`;function pi(d){try{d?window.sessionStorage.setItem(Nn,"1"):window.sessionStorage.removeItem(Nn)}catch{}}function fi(){try{return window.sessionStorage.getItem(Nn)==="1"}catch{return!1}}function qe(d){J=d,V.style.display=d?"flex":"none",pi(d),d?(Oo(),Pn(),F.focus(),Un(e.getState())):(Ie.stop(),je(),Mn(),e.resetBubbleWindow(),xe=!1,Bn(),It(!1)),Dn(e.getState()),Ot(e.getState())}function $n(){if(e.getState().isBusy)return;let d=F.value.trim();d&&(Ie.stop(),je(),s.trigger("send"),F.value="",Mn(),e.submitTextTurn(d))}function Qe(d,x=!1){var P;let E=e.cancelAll(),k=(P=d==null?void 0:d.trim())!=null?P:"",B=k||E||"";F.value=B,qe(!0),B||ai(),x&&k&&queueMicrotask(()=>$n())}function Dn(d){if(!(r&&!J&&(d.phase==="listening"||xe))){v&&(v.remove(),v=null);return}if(v){oe();return}let E=S();v=Nr({theme:c!=null?c:{},accentColor:E.accentColor,backgroundColor:E.backgroundColor,label:a.keyboardChipLabel,onClick:()=>{s.trigger("keyboardChip"),Qe()}}),O.appendChild(v),oe()}function Fn(){var d,x;try{let E=(x=(d=e.config).getLocale)==null?void 0:x.call(d);if(typeof E=="string"&&E.trim())return E.trim()}catch{}return e.config.locale}function _o(){return Ft(ot(g,e.config.manifest.routes),e.messages,{locale:Fn(),actions:e.config.manifest.actions})}function hi(d){let x=p,{padH:E}=vt(x);A.style.width="",A.textContent=d;let k=A.scrollWidth,B=typeof window!="undefined"?window.innerWidth:280,P=Math.min(280,B*.7);if(!(k>P-x.borderWidth*2)){A.style.width="";return}let G=Math.max(0,k-E*2),U=Math.max(4,(G+48)/30);A.style.width=`${P}px`,A.textContent="";let Y=document.createElement("div");Y.className="fyodos-thought-track",Y.style.animation=`fyodos-marquee ${U}s linear infinite`;let se=document.createElement("span");se.textContent=d;let _e=document.createElement("span");_e.textContent=d,_e.setAttribute("aria-hidden","true"),Y.appendChild(se),Y.appendChild(_e),A.appendChild(Y)}function ko(d){let x=p,{fontPx:E,padH:k,approxHeight:B}=vt(x),P=mn(x,B,1,d);A.style.fontSize=`${E}px`,A.style.height=`${B}px`,A.style.padding=`0 ${k}px`,A.style.color=x.textColor,A.style.background=x.backgroundColor,A.style.border=`${x.borderWidth}px solid ${x.borderColor}`,gn(A,P)}function Po(){let d=Ct(ce());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 x=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!xe,E=f&&!J&&x?_o():null;if(!E){A.style.display="none";return}if(A.setAttribute("aria-label",E),A.style.display="flex",ko(),hi(E),p.shape==="cloud"){let k=A.offsetWidth;k>0&&ko(k)}Po()}let Je=null;function Ze(){Je&&(Je.remove(),Je=null)}function Mo(){let d={...we,...u!=null?u:{}},x=document.createElement("div");x.className="fyodos-overlay",x.style.zIndex=String(o+10);let E=document.createElement("div");return E.className="fyodos-modal",E.style.background=d.cardBackgroundColor,E.style.border=`1px solid ${d.cardBorderColor}`,E.style.color=d.titleColor,E.setAttribute("role","dialog"),E.setAttribute("aria-modal","true"),x.appendChild(E),{overlay:x,modal:E}}function mi(d,x){var _e;Ze();let E={...we,...u!=null?u:{}},k=(_e=u==null?void 0:u.primaryButtonColor)!=null?_e:S().accentColor,{overlay:B,modal:P}=Mo(),W=document.createElement("h3");W.textContent=a.confirmTitle;let G=document.createElement("p");if(G.style.color=E.bodyColor,G.textContent=d,P.append(W,G),x){let ke=document.createElement("div");ke.className="fyodos-hint",ke.style.color=E.bodyColor,ke.textContent=x,P.append(ke)}let U=document.createElement("div");U.className="fyodos-modal-actions";let Y=document.createElement("button");Y.className="fyodos-btn-ghost",Y.style.color=E.bodyColor,Y.textContent=a.cancelLabel,Y.onclick=()=>e.cancelPendingAction();let se=document.createElement("button");se.className="fyodos-btn-primary",se.style.background=k,se.textContent=a.confirmLabel,se.onclick=()=>{e.confirmPendingAction()},U.append(Y,se),P.append(U),B.onclick=ke=>{ke.target===B&&e.cancelPendingAction()},n.appendChild(B),Je=B}function gi(){var Y;Ze();let d={...we,...u!=null?u:{}},x=(Y=u==null?void 0:u.primaryButtonColor)!=null?Y:S().accentColor,{overlay:E,modal:k}=Mo(),B=document.createElement("h3");B.textContent=a.consentTitle;let P=document.createElement("p");P.style.color=d.bodyColor,P.textContent=a.consentBody;let W=document.createElement("div");W.className="fyodos-modal-actions";let G=document.createElement("button");G.className="fyodos-btn-ghost",G.style.color=d.bodyColor,G.textContent=a.consentDecline,G.onclick=()=>e.declineConsent();let U=document.createElement("button");U.className="fyodos-btn-primary",U.style.background=x,U.textContent=a.consentAccept,U.onclick=()=>{e.acceptConsent()},W.append(G,U),k.append(B,P,W),n.appendChild(E),Je=E}b.onclick=()=>{if(z){z=!1;return}if(e.primeAudio(),e.getState().showThinking){s.trigger("orbTap");let x=e.cancelAll();x&&J&&(F.value=x,Et(F));return}if(s.trigger("orbTap"),J){qe(!1);return}if(!m&&r){xe=!1,Qe();return}if(e.voiceAvailable&&m){xe=!1,Rt=!0,e.toggleListening();return}if(r){xe=!1,Qe();return}Rt=!0,e.toggleListening()},ie.onclick=()=>{let d=e.getState();if(d.isBusy||d.chainActive){s.trigger("orbTap");let x=e.cancelAll();x&&(F.value=x,Et(F)),F.focus();return}$n()},F.onkeydown=d=>{d.key==="Enter"&&$n(),d.key==="Escape"&&qe(!1)},F.addEventListener("input",()=>Et(F)),r||v&&(v.style.display="none");let Lo=null,Bo=!1,Wn=!1,_t=null;function Un(d){if(d.voiceBlocked&&!Wn){if(Wn=!0,Rt&&r&&!J&&!d.isBusy){Qe();return}}else d.voiceBlocked||(Wn=!1);d.phase!==_t&&(d.phase==="listening"?s.trigger("listenStart"):_t==="listening"&&s.trigger("listenStop"),_t==="thinking"&&s.trigger("response"),_t=d.phase);let x=d.showThinking?"thinking":d.showWaveform||xe?"listening":d.phase==="speaking"?"speaking":"idle";R.applyState(x,d.volumeLevel);let E=d.showThinking||d.chainActive;if(ui(E,d),J){d.isBusy&&Mn(),Ye.style.display=d.loadingOlderExchanges?"flex":"none",ci(d.recentExchanges),Z.style.display="flex",Re.style.display=E?"flex":"none";let k=d.isBusy||d.chainActive;ie.textContent=k?"\u25FC":"\u2191",ie.setAttribute("aria-label",k?a.cancelLabel:a.sendLabel),ie.style.opacity="1",ie.disabled=!1,$.style.opacity=k?"0.45":"1",$.disabled=k,je()}Dn(d),Ot(d),d.confirmationMessage!==Lo&&(Lo=d.confirmationMessage,d.confirmationMessage?mi(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||Ze()),d.consentModalVisible!==Bo&&(Bo=d.consentModalVisible,d.consentModalVisible?gi():d.confirmationMessage||Ze())}let bi=e.subscribe(Un);Un(e.getState()),r&&fi()&&qe(!0);let No=Fn(),Oe=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}let x=Fn();(d!==g||x!==No)&&(g=d,No=x,Ot(e.getState()))};Oe();let yi=window.setInterval(Oe,700);window.addEventListener("popstate",Oe),document.addEventListener("visibilitychange",Oe);let xi=Wr(e,{pollMs:t.appearancePollMs,onChange:d=>{let x=d!=null&&Rn(d.internalProfile,t.allowInternalOrb===!0);C.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&&(w=d.screenPosition)),R.applyAppearance(S()),q(),v&&(v.remove(),v=null),Dn(e.getState()),Ot(e.getState()),J&&Oo()}});return{unmount(){Ie.dispose(),bi(),xi(),window.clearInterval(yi),window.removeEventListener("popstate",Oe),document.removeEventListener("visibilitychange",Oe),window.removeEventListener("resize",q),_==null||_.disconnect(),y==null||y.removeEventListener("resize",T),y==null||y.removeEventListener("scroll",T),Ze(),v==null||v.remove(),C.remove()}}}var Vr="fiodos-dev-error-badge";function yc(){try{return!1}catch{return!1}}function Co(e,t){if(!yc()||typeof document=="undefined"||!document.body)return;let n=xc(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 a=document.createElement("div");a.setAttribute("data-fiodos-badge-msg",""),a.textContent=n;let s=document.createElement("div");s.style.cssText="margin-top:8px;color:rgba(255,255,255,0.55);font-size:11.5px",s.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(a),o.appendChild(s),document.body.appendChild(o)}function xc(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var _n="0.1.20",Gr="@fiodos/web-core";var Yr="https://api.fyodos.com";function Kr(e){return e.replace(/\/$/,"")}async function jr(e){let t=Kr(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 Xr=!1;function qr(){Xr=!0}function vc(){let e=typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);return Xr?e?"web-embed-mobile":"web-embed":e?"web-mobile":"web"}async function Ao(e){var n;if(!e.apiKey)return;let t=Kr(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:vc(),sdkVersion:_n,sdkPackage:Gr})})}catch{}}var Qr="fyodos:anon-caller:v1",fe=null;function Jr(){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 Cc(){if(fe)return fe;try{let e=window.localStorage.getItem(Qr);if(e)return fe=e,e;let t=Jr();return window.localStorage.setItem(Qr,t),fe=t,t}catch{return fe=fe!=null?fe:Jr(),fe}}function Zr(e){return()=>{let t=e==null?void 0:e();return t||Cc()}}function Ac(e){typeof window!="undefined"&&window.location&&window.location.assign(e)}function oi(){let e=typeof navigator!="undefined"&&navigator.language?navigator.language:"en-US";return{locale:e.split("-")[0]||"en",sttLocale:e}}function ei(){var e,t;return typeof document!="undefined"&&((t=(e=document.documentElement.lang)==null?void 0:e.split(/[-_]/)[0])==null?void 0:t.trim())||""}function ti(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 oi().locale;if(e.localeDetection==="document"){let a=ei();if(a)return a}let n=ei();return n||"en"}function ni(e,t,n){var p,f,m,h;let o=oi(),r=ti(e),i=(f=(p=e.sttLocale)!=null?p:e.locale)!=null?f:o.sttLocale,a=Zr(e.getUserId),s=hr({baseUrl:n,apiKey:e.apiKey,getUserId:a}),l=mr({baseUrl:n,apiKey:e.apiKey,getUserId:a}),c={manifest:t,locale:r,getLocale:()=>ti(e),sttLocale:i,navigation:gr({navigate:(m=e.navigate)!=null?m:Ac,getCurrentRoute:e.getCurrentRoute}),registries:(h=e.registries)!=null?h:{handlers:{},idempotencyCheckers:{}},backend:s,voice:vr(),storage:br(),telemetry:l,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},u=new Ge(c);return u.warmUp(),u}function ri(e){var s,l;let t=((s=e.baseUrl)!=null?s:Yr).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=ni(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;a=!0,(c=i.orb)==null||c.unmount(),(u=i.controller)==null||u.dispose()}},a=!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 jr({baseUrl:t,apiKey:e.apiKey});if(a)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=ge(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
66
+ `;function bc(){if(typeof document=="undefined"||document.getElementById(Hr))return;let e=document.createElement("style");e.id=Hr,e.textContent=gc,document.head.appendChild(e)}function zr(){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 yc(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 we={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(){}};bc();let n=($o=t.container)!=null?$o:document.body,o=(Do=t.zIndex)!=null?Do:2147483e3,r=t.enableTextInput!==!1,i=t.usePublishedPosition!==!1,a=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 s=Zn(()=>C().hapticIntensity),l=null,c=null,u,p=ze(null),f=!0,m=!0,h=!1,g=null,w=t.corner?yc(t.corner):{...Se};function C(){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 v=document.createElement("div");v.className="fyodos-orb-root",v.style.zIndex=String(o);let O=document.createElement("div");O.className="fyodos-orb-anchor";let R=$r(C()),b=document.createElement("button");b.className="fyodos-orb-btn",b.type="button",b.setAttribute("aria-label",a.orbLabel),b.appendChild(R.element),O.appendChild(b),v.appendChild(O);let E=null,A=document.createElement("div");A.className="fyodos-thought",A.setAttribute("role","button"),A.tabIndex=0,A.style.display="none",A.addEventListener("click",()=>{if(s.trigger("orbTap"),e.primeAudio(),r){Qe();return}Rt=!0,e.toggleListening()}),A.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),A.click())}),O.appendChild(A),n.appendChild(v);let k=null;function H(){var d;return(d=C().size)!=null?d:ce.size}function te(){return k!=null?k:w}function X(){let d=H(),x=zr(),{left:S,top:P}=Sn({viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,contentWidth:x.width,contentHeight:x.height,orbDiameter:d,position:te()});v.style.left=`${S}px`,v.style.top=`${P}px`,v.style.right="",v.style.bottom="",re()}function re(){let d=Ct(te());E&&(E.style.position="absolute",E.style.top="50%",E.style.transform="translateY(-50%)",d.horizontal==="left"?(E.style.right="calc(100% + 10px)",E.style.left=""):(E.style.left="calc(100% + 10px)",E.style.right="")),A.style.display!=="none"&&Po()}window.addEventListener("resize",X);let _;typeof ResizeObserver!="undefined"&&document.documentElement&&(_=new ResizeObserver(()=>X()),_.observe(document.documentElement));let y=window.visualViewport,T=()=>{J&&Pn()};y==null||y.addEventListener("resize",T),y==null||y.addEventListener("scroll",T);let N=6,L=!1,G=!1,$=0,I=0,D=0,Y=0;function be(d){if(d.button!=null&&d.button!==0)return;let x=v.getBoundingClientRect();D=x.left,Y=x.top,$=d.clientX,I=d.clientY,L=!1;try{b.setPointerCapture(d.pointerId)}catch{}}function he(d){var ae;if(!((ae=b.hasPointerCapture)!=null&&ae.call(b,d.pointerId)))return;let x=d.clientX-$,S=d.clientY-I;if(!L&&Math.hypot(x,S)<N)return;L=!0,d.preventDefault();let P=H(),B=zr(),M=8,U=B.width-M-P,j=B.height-M-P,z=Math.min(U,Math.max(M,D+x)),q=Math.min(j,Math.max(M,Y+S));v.style.left=`${z}px`,v.style.top=`${q}px`,v.style.right="",v.style.bottom="",k=En({centerX:z+P/2,centerY:q+P/2,viewportWidth:B.width,viewportHeight:B.height,orbDiameter:P}),re()}function ye(d){try{b.releasePointerCapture(d.pointerId)}catch{}L&&(G=!0,L=!1,k=wn(k!=null?k:te()),v.style.transition="left 220ms cubic-bezier(0.22, 1, 0.36, 1), top 220ms cubic-bezier(0.22, 1, 0.36, 1)",X(),window.setTimeout(()=>{v.style.transition=""},260))}b.draggable=!1,b.addEventListener("dragstart",d=>d.preventDefault()),b.addEventListener("pointerdown",be),b.addEventListener("pointermove",he),b.addEventListener("pointerup",ye),b.addEventListener("pointercancel",ye),b.addEventListener("lostpointercapture",ye);let J=!1,Ee=!1,xe=!1,Rt=!1,K=document.createElement("div");K.className="fyodos-bubble",K.style.display="none";function si(){let d=window.visualViewport;return d?Math.max(0,window.innerHeight-d.height-d.offsetTop):0}function Pn(){K.style.position="fixed",K.style.left="50%",K.style.right="",K.style.top="",K.style.transform="translateX(-50%)",K.style.bottom=`${si()+16}px`,K.style.zIndex=String(o+5)}let Z=document.createElement("div");Z.className="fyodos-bubble-scroll";let ve=document.createElement("button");ve.type="button",ve.className="fyodos-bubble-close",ve.textContent="\xD7",ve.setAttribute("aria-label","Close"),ve.addEventListener("click",()=>qe(!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(),It(!1)});let Ye=document.createElement("div");Ye.className="fyodos-bubble-loader",Ye.append(document.createElement("span")),Ye.style.display="none";let Te=document.createElement("div");Te.className="fyodos-bubble-exchanges";let le=document.createElement("div");le.className="fyodos-bubble-greeting",le.style.display="none",Z.append(Ye,Te,le);function ai(){let d=_o();if(!d){le.style.display="none";return}let x={...we,...u!=null?u:{}};le.textContent=d,le.style.color=x.titleColor,le.style.display="",Z.scrollTop=Z.scrollHeight}function Mn(){le.style.display!=="none"&&(le.style.display="none")}let Ke="";function ci(d){let x=d.map(M=>`${M.userText}\0${M.replyText}`).join("");if(x===Ke)return;let S=Ke.length>0&&x.length>Ke.length&&x.endsWith(Ke),P=Z.scrollHeight-Z.scrollTop;Ke=x;let B={...we,...u!=null?u:{}};Te.replaceChildren();for(let M of d){let U=document.createElement("div");U.className="fyodos-bubble-exchange";let j=document.createElement("div");if(j.className="fyodos-bubble-user",j.textContent=M.userText,j.style.color=B.bodyColor,U.append(j),M.replyText){let z=document.createElement("div");z.className="fyodos-bubble-reply",z.textContent=M.replyText,z.style.color=B.titleColor,U.append(z)}Te.append(U)}Z.scrollTop=S?Z.scrollHeight-P:Z.scrollHeight}Z.addEventListener("scroll",()=>{if(!J||Z.scrollTop>12)return;let d=e.getState();d.hasOlderExchanges&&!d.loadingOlderExchanges&&e.loadOlderExchanges()});let Re=document.createElement("div");Re.className="fyodos-bubble-busy";let ie=document.createElement("em");ie.className="fyodos-busy-step",ie.style.display="none",Re.appendChild(ie),Re.append(document.createElement("span"),document.createElement("span"),document.createElement("span"));let Eo=null;function li(d){if(!h||!d.liveActivity)return null;let{kind:x,label:S}=d.liveActivity;switch(x){case"navigating":return a.activityNavigating.replace("{label}",S!=null?S:"");case"executing":return a.activityExecuting.replace("{label}",S!=null?S:"");case"waiting_confirmation":return a.activityWaitingConfirmation;default:return a.activityThinking}}function ui(d,x){let S=d?li(x):null;if(S!==Eo){if(Eo=S,!S){ie.textContent="",ie.style.display="none";return}ie.style.display="",ie.textContent=S,ie.style.animation="none",ie.offsetWidth,ie.style.animation=""}}let Ln=document.createElement("div");Ln.className="fyodos-bubble-row";let W=document.createElement("input");W.type="text",W.placeholder=a.textPlaceholder;let F=document.createElement("button");F.type="button",F.className="fyodos-bubble-mic",F.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>',F.style.display="none";let se=document.createElement("button");se.textContent="\u2191",se.setAttribute("aria-label",a.sendLabel),Ln.append(W,F,se);let Ie=Ur(e.config.locale);Ie.isSupported()&&(F.style.display="flex",F.setAttribute("aria-label",a.micLabel),F.title=a.micLabel,F.addEventListener("click",()=>{e.getState().isBusy||(Ie.toggle(()=>W.value,d=>{W.value=d,Et(W)}),je())}));function je(){var B,M;let d=(B=u==null?void 0:u.primaryButtonColor)!=null?B:C().accentColor,x=`${(M=u==null?void 0:u.sendButtonRadius)!=null?M:10}px`,S={...we,...u!=null?u:{}}.bodyColor,P=Ie.isListening();F.classList.toggle("is-listening",P),P?(F.style.background=d,F.style.border="none",F.style.color=He(d),F.style.borderRadius=x):(F.style.background="rgba(255,255,255,0.06)",F.style.border="1px solid rgba(148,163,184,0.4)",F.style.color=S,F.style.borderRadius="999px"),F.setAttribute("aria-label",P?a.micStopLabel:a.micLabel),F.title=P?a.micStopLabel:a.micLabel}K.append(ve,me,Z,Re,Ln),O.appendChild(K);function It(d){Ee!==d&&(Ee=d,K.classList.toggle("fyodos-bubble--expanded",d),me.style.display=d?"flex":"none",Pn())}let To=0,Ro=0,Xe=null,di=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=()=>{Xe!=null&&(window.clearTimeout(Xe),Xe=null)};K.addEventListener("pointerdown",d=>{To=d.clientX,Ro=d.clientY}),K.addEventListener("click",d=>{if(Ee)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-To,d.clientY-Ro)>di)return;if(d.detail>1){Bn();return}if(Bn(),!!!(x!=null&&x.closest(".fyodos-bubble-user, .fyodos-bubble-reply"))&&!Io()){It(!0);return}Xe=window.setTimeout(()=>{Xe=null,Io()||It(!0)},280)}),X();function Oo(){var P,B,M;let d={...we,...u!=null?u:{}},x=(P=u==null?void 0:u.primaryButtonColor)!=null?P:C().accentColor;K.style.background=d.cardBackgroundColor,K.style.borderColor=d.cardBorderColor,(u==null?void 0:u.borderRadius)!=null&&(K.style.borderRadius=`${u.borderRadius}px`),ve.style.color=d.bodyColor,me.style.color=d.bodyColor,Te.querySelectorAll(".fyodos-bubble-user").forEach(U=>{U.style.color=d.bodyColor}),Te.querySelectorAll(".fyodos-bubble-reply").forEach(U=>{U.style.color=d.titleColor});let S=(B=u==null?void 0:u.inputBackgroundColor)!=null?B:"#ffffff";W.style.background=S,W.style.color=He(S),W.style.setProperty("--fyodos-input-placeholder",un(S)),se.style.background=x,se.style.color=He(x),se.style.borderRadius=`${(M=u==null?void 0:u.sendButtonRadius)!=null?M:10}px`,je(),Re.querySelectorAll("span").forEach(U=>{U.style.background=x}),ie.style.color=d.titleColor}let Nn=`fyodos:panel-open:${e.config.manifest.appId}`;function pi(d){try{d?window.sessionStorage.setItem(Nn,"1"):window.sessionStorage.removeItem(Nn)}catch{}}function fi(){try{return window.sessionStorage.getItem(Nn)==="1"}catch{return!1}}function qe(d){J=d,K.style.display=d?"flex":"none",pi(d),d?(Oo(),Pn(),W.focus(),Un(e.getState())):(Ie.stop(),je(),Mn(),e.resetBubbleWindow(),xe=!1,Bn(),It(!1)),Dn(e.getState()),Ot(e.getState())}function $n(){if(e.getState().isBusy)return;let d=W.value.trim();d&&(Ie.stop(),je(),s.trigger("send"),W.value="",Mn(),e.submitTextTurn(d))}function Qe(d,x=!1){var M;let S=e.cancelAll(),P=(M=d==null?void 0:d.trim())!=null?M:"",B=P||S||"";W.value=B,qe(!0),B||ai(),x&&P&&queueMicrotask(()=>$n())}function Dn(d){if(!(r&&!J&&(d.phase==="listening"||xe))){E&&(E.remove(),E=null);return}if(E){re();return}let S=C();E=Nr({theme:c!=null?c:{},accentColor:S.accentColor,backgroundColor:S.backgroundColor,label:a.keyboardChipLabel,onClick:()=>{s.trigger("keyboardChip"),Qe()}}),O.appendChild(E),re()}function Fn(){var d,x;try{let S=(x=(d=e.config).getLocale)==null?void 0:x.call(d);if(typeof S=="string"&&S.trim())return S.trim()}catch{}return e.config.locale}function _o(){return Ft(ot(g,e.config.manifest.routes),e.messages,{locale:Fn(),actions:e.config.manifest.actions})}function hi(d){let x=p,{padH:S}=vt(x);A.style.width="",A.textContent=d;let P=A.scrollWidth,B=typeof window!="undefined"?window.innerWidth:280,M=Math.min(280,B*.7);if(!(P>M-x.borderWidth*2)){A.style.width="";return}let j=Math.max(0,P-S*2),z=Math.max(4,(j+48)/30);A.style.width=`${M}px`,A.textContent="";let q=document.createElement("div");q.className="fyodos-thought-track",q.style.animation=`fyodos-marquee ${z}s linear infinite`;let ae=document.createElement("span");ae.textContent=d;let _e=document.createElement("span");_e.textContent=d,_e.setAttribute("aria-hidden","true"),q.appendChild(ae),q.appendChild(_e),A.appendChild(q)}function ko(d){let x=p,{fontPx:S,padH:P,approxHeight:B}=vt(x),M=mn(x,B,1,d);A.style.fontSize=`${S}px`,A.style.height=`${B}px`,A.style.padding=`0 ${P}px`,A.style.color=x.textColor,A.style.background=x.backgroundColor,A.style.border=`${x.borderWidth}px solid ${x.borderColor}`,gn(A,M)}function Po(){let d=Ct(te());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 x=!d.showThinking&&!d.showWaveform&&d.phase!=="speaking"&&!xe,S=f&&!J&&x?_o():null;if(!S){A.style.display="none";return}if(A.setAttribute("aria-label",S),A.style.display="flex",ko(),hi(S),p.shape==="cloud"){let P=A.offsetWidth;P>0&&ko(P)}Po()}let Je=null;function Ze(){Je&&(Je.remove(),Je=null)}function Mo(){let d={...we,...u!=null?u:{}},x=document.createElement("div");x.className="fyodos-overlay",x.style.zIndex=String(o+10);let S=document.createElement("div");return S.className="fyodos-modal",S.style.background=d.cardBackgroundColor,S.style.border=`1px solid ${d.cardBorderColor}`,S.style.color=d.titleColor,S.setAttribute("role","dialog"),S.setAttribute("aria-modal","true"),x.appendChild(S),{overlay:x,modal:S}}function mi(d,x){var _e;Ze();let S={...we,...u!=null?u:{}},P=(_e=u==null?void 0:u.primaryButtonColor)!=null?_e:C().accentColor,{overlay:B,modal:M}=Mo(),U=document.createElement("h3");U.textContent=a.confirmTitle;let j=document.createElement("p");if(j.style.color=S.bodyColor,j.textContent=d,M.append(U,j),x){let ke=document.createElement("div");ke.className="fyodos-hint",ke.style.color=S.bodyColor,ke.textContent=x,M.append(ke)}let z=document.createElement("div");z.className="fyodos-modal-actions";let q=document.createElement("button");q.className="fyodos-btn-ghost",q.style.color=S.bodyColor,q.textContent=a.cancelLabel,q.onclick=()=>e.cancelPendingAction();let ae=document.createElement("button");ae.className="fyodos-btn-primary",ae.style.background=P,ae.textContent=a.confirmLabel,ae.onclick=()=>{e.confirmPendingAction()},z.append(q,ae),M.append(z),B.onclick=ke=>{ke.target===B&&e.cancelPendingAction()},n.appendChild(B),Je=B}function gi(){var q;Ze();let d={...we,...u!=null?u:{}},x=(q=u==null?void 0:u.primaryButtonColor)!=null?q:C().accentColor,{overlay:S,modal:P}=Mo(),B=document.createElement("h3");B.textContent=a.consentTitle;let M=document.createElement("p");M.style.color=d.bodyColor,M.textContent=a.consentBody;let U=document.createElement("div");U.className="fyodos-modal-actions";let j=document.createElement("button");j.className="fyodos-btn-ghost",j.style.color=d.bodyColor,j.textContent=a.consentDecline,j.onclick=()=>e.declineConsent();let z=document.createElement("button");z.className="fyodos-btn-primary",z.style.background=x,z.textContent=a.consentAccept,z.onclick=()=>{e.acceptConsent()},U.append(j,z),P.append(B,M,U),n.appendChild(S),Je=S}b.onclick=()=>{if(G){G=!1;return}if(e.primeAudio(),e.getState().showThinking){s.trigger("orbTap");let x=e.cancelAll();x&&J&&(W.value=x,Et(W));return}if(s.trigger("orbTap"),J){qe(!1);return}if(!m&&r){xe=!1,Qe();return}if(e.voiceAvailable&&m){xe=!1,Rt=!0,e.toggleListening();return}if(r){xe=!1,Qe();return}Rt=!0,e.toggleListening()},se.onclick=()=>{let d=e.getState();if(d.isBusy||d.chainActive){s.trigger("orbTap");let x=e.cancelAll();x&&(W.value=x,Et(W)),W.focus();return}$n()},W.onkeydown=d=>{d.key==="Enter"&&$n(),d.key==="Escape"&&qe(!1)},W.addEventListener("input",()=>Et(W)),r||E&&(E.style.display="none");let Lo=null,Bo=!1,Wn=!1,_t=null;function Un(d){if(d.voiceBlocked&&!Wn){if(Wn=!0,Rt&&r&&!J&&!d.isBusy){Qe();return}}else d.voiceBlocked||(Wn=!1);d.phase!==_t&&(d.phase==="listening"?s.trigger("listenStart"):_t==="listening"&&s.trigger("listenStop"),_t==="thinking"&&s.trigger("response"),_t=d.phase);let x=d.showThinking?"thinking":d.showWaveform||xe?"listening":d.phase==="speaking"?"speaking":"idle";R.applyState(x,d.volumeLevel);let S=d.showThinking||d.chainActive;if(ui(S,d),J){d.isBusy&&Mn(),Ye.style.display=d.loadingOlderExchanges?"flex":"none",ci(d.recentExchanges),Z.style.display="flex",Re.style.display=S?"flex":"none";let P=d.isBusy||d.chainActive;se.textContent=P?"\u25FC":"\u2191",se.setAttribute("aria-label",P?a.cancelLabel:a.sendLabel),se.style.opacity="1",se.disabled=!1,F.style.opacity=P?"0.45":"1",F.disabled=P,je()}Dn(d),Ot(d),d.confirmationMessage!==Lo&&(Lo=d.confirmationMessage,d.confirmationMessage?mi(d.confirmationMessage,d.confirmationVoiceHint):d.consentModalVisible||Ze()),d.consentModalVisible!==Bo&&(Bo=d.consentModalVisible,d.consentModalVisible?gi():d.confirmationMessage||Ze())}let bi=e.subscribe(Un);Un(e.getState()),r&&fi()&&qe(!0);let No=Fn(),Oe=()=>{let d=null;try{d=e.config.navigation.getCurrentRoute()}catch{}let x=Fn();(d!==g||x!==No)&&(g=d,No=x,Ot(e.getState()))};Oe();let yi=window.setInterval(Oe,700);window.addEventListener("popstate",Oe),document.addEventListener("visibilitychange",Oe);let xi=Wr(e,{pollMs:t.appearancePollMs,onChange:d=>{let x=d!=null&&Rn(d.internalProfile,t.allowInternalOrb===!0);v.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&&(w=d.screenPosition)),R.applyAppearance(C()),X(),E&&(E.remove(),E=null),Dn(e.getState()),Ot(e.getState()),J&&Oo()}});return{unmount(){Ie.dispose(),bi(),xi(),window.clearInterval(yi),window.removeEventListener("popstate",Oe),document.removeEventListener("visibilitychange",Oe),window.removeEventListener("resize",X),_==null||_.disconnect(),y==null||y.removeEventListener("resize",T),y==null||y.removeEventListener("scroll",T),Ze(),E==null||E.remove(),v.remove()}}}var Vr="fiodos-dev-error-badge";function xc(){try{return!1}catch{return!1}}function Co(e,t){if(!xc()||typeof document=="undefined"||!document.body)return;let n=vc(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 a=document.createElement("div");a.setAttribute("data-fiodos-badge-msg",""),a.textContent=n;let s=document.createElement("div");s.style.cssText="margin-top:8px;color:rgba(255,255,255,0.55);font-size:11.5px",s.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(a),o.appendChild(s),document.body.appendChild(o)}function vc(e){return e.replace(/^\[fyodos\]\s*/i,"").trim()||"No se pudo montar el orbe."}var _n="0.1.22",Gr="@fiodos/web-core";var Yr="https://api.fyodos.com";function Kr(e){return e.replace(/\/$/,"")}async function jr(e){let t=Kr(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 Xr=!1;function qr(){Xr=!0}function Cc(){let e=typeof navigator!="undefined"&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);return Xr?e?"web-embed-mobile":"web-embed":e?"web-mobile":"web"}async function Ao(e){var n;if(!e.apiKey)return;let t=Kr(e.baseUrl);try{await fetch(`${t}/v1/client/orb-seen`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey},body:JSON.stringify({platform:(n=e.platform)!=null?n:Cc(),sdkVersion:_n,sdkPackage:Gr})})}catch{}}var Qr="fyodos:anon-caller:v1",fe=null;function Jr(){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 Ac(){if(fe)return fe;try{let e=window.localStorage.getItem(Qr);if(e)return fe=e,e;let t=Jr();return window.localStorage.setItem(Qr,t),fe=t,t}catch{return fe=fe!=null?fe:Jr(),fe}}function Zr(e){return()=>{let t=e==null?void 0:e();return t||Ac()}}function Sc(e){typeof window!="undefined"&&window.location&&window.location.assign(e)}function oi(){let e=typeof navigator!="undefined"&&navigator.language?navigator.language:"en-US";return{locale:e.split("-")[0]||"en",sttLocale:e}}function ei(){var e,t;return typeof document!="undefined"&&((t=(e=document.documentElement.lang)==null?void 0:e.split(/[-_]/)[0])==null?void 0:t.trim())||""}function ti(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 oi().locale;if(e.localeDetection==="document"){let a=ei();if(a)return a}let n=ei();return n||"en"}function ni(e,t,n){var p,f,m,h;let o=oi(),r=ti(e),i=(f=(p=e.sttLocale)!=null?p:e.locale)!=null?f:o.sttLocale,a=Zr(e.getUserId),s=hr({baseUrl:n,apiKey:e.apiKey,getUserId:a}),l=mr({baseUrl:n,apiKey:e.apiKey,getUserId:a}),c={manifest:t,locale:r,getLocale:()=>ti(e),sttLocale:i,navigation:gr({navigate:(m=e.navigate)!=null?m:Sc,getCurrentRoute:e.getCurrentRoute}),registries:(h=e.registries)!=null?h:{handlers:{},idempotencyCheckers:{}},backend:s,voice:vr(),storage:br(),telemetry:l,isAuthenticated:e.isAuthenticated,getSessionCapabilities:e.getSessionCapabilities,getUserId:e.getUserId,ttsVoice:e.ttsVoice,...e.configOverrides},u=new Ge(c);return u.warmUp(),u}function ri(e){var s,l;let t=((s=e.baseUrl)!=null?s:Yr).replace(/\/$/,""),n=e.mount!==!1,o=Symbol("fiodos-embed-host");if(e.manifest){let c=ni(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;a=!0,(c=i.orb)==null||c.unmount(),(u=i.controller)==null||u.dispose()}},a=!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 jr({baseUrl:t,apiKey:e.apiKey});if(a)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=ge(p.manifest);if(!f.valid)throw new Error(`[fyodos] Invalid manifest for "${p.manifest.appId}":
67
67
  - ${f.errors.join(`
68
- - `)}`);let m=ni(e,p.manifest,t);return a?(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 kn(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function Sc(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 wc(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return kn(o);if(Array.isArray(o)&&o.length)return kn(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?kn(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=Sc(t);return o?kn(o):null}return null}function So(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function wo(e,t={}){var h,g,w,S,C,O,R,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=(w=t.attributes)!=null&&w.length?new Set(t.attributes.map(v=>v.trim().toLowerCase()).filter(Boolean)):null,a=(S=t.maxAttributes)!=null?S:12,s={},l=0;(C=n.attributes)==null||C.forEach(v=>{let A;try{A=v.getName()}catch{return}if(!A)return;if(i){if(!i.has(A.toLowerCase()))return}else if(l>=a)return;let N=wc(v);N!=null&&(s[A]=N,l+=1)});let c;try{c=(R=(O=n.getPrimaryAttributeValue)==null?void 0:O.call(n))!=null?R:void 0}catch{c=void 0}let u=r?{id:r,kind:o,title:c,metadata:s}:null,p=Object.entries(s).map(([v,A])=>`${v}: ${A}`).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 ii(e,t,n={}){var a;let o=!1,r=()=>{if(o)return;let s=wo(t,n);s?e.setScreenContext(s):e.clearScreenContext()};r();let i=(a=t.data)==null?void 0:a.entity;if(i!=null&&i.addOnPostSave)try{i.addOnPostSave(r)}catch{}return{refresh:r,disconnect(){var s;if(!o){o=!0;try{(s=i==null?void 0:i.removeOnPostSave)==null||s.call(i,r)}catch{}e.clearScreenContext()}}}}qr();var Ec={version:_n,createFiodosAgent:ri,mountOrb:Tt,AgentController:Ge,createScreenContextStore:On,buildApiActionRegistries:Nt,validateManifest:ge,connectDynamicsFormContext:ii,dynamicsFormSnapshot:wo,normalizeDynamicsId:So};globalThis.Fiodos=Ec;})();
68
+ - `)}`);let m=ni(e,p.manifest,t);return a?(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 kn(e){let t=e.trim();return t.length>120?`${t.slice(0,119)}\u2026`:t}function wc(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 Ec(e){var n;try{let o=(n=e.getText)==null?void 0:n.call(e);if(typeof o=="string"&&o.trim())return kn(o);if(Array.isArray(o)&&o.length)return kn(o.join(", "))}catch{}let t;try{t=e.getValue()}catch{return null}if(t==null)return null;if(typeof t=="string")return t.trim()?kn(t):null;if(typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t)){let o=wc(t);return o?kn(o):null}return null}function So(e){return e.replace(/[{}]/g,"").trim().toLowerCase()}function wo(e,t={}){var h,g,w,C,v,O,R,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=(w=t.attributes)!=null&&w.length?new Set(t.attributes.map(E=>E.trim().toLowerCase()).filter(Boolean)):null,a=(C=t.maxAttributes)!=null?C:12,s={},l=0;(v=n.attributes)==null||v.forEach(E=>{let A;try{A=E.getName()}catch{return}if(!A)return;if(i){if(!i.has(A.toLowerCase()))return}else if(l>=a)return;let k=Ec(E);k!=null&&(s[A]=k,l+=1)});let c;try{c=(R=(O=n.getPrimaryAttributeValue)==null?void 0:O.call(n))!=null?R:void 0}catch{c=void 0}let u=r?{id:r,kind:o,title:c,metadata:s}:null,p=Object.entries(s).map(([E,A])=>`${E}: ${A}`).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 ii(e,t,n={}){var a;let o=!1,r=()=>{if(o)return;let s=wo(t,n);s?e.setScreenContext(s):e.clearScreenContext()};r();let i=(a=t.data)==null?void 0:a.entity;if(i!=null&&i.addOnPostSave)try{i.addOnPostSave(r)}catch{}return{refresh:r,disconnect(){var s;if(!o){o=!0;try{(s=i==null?void 0:i.removeOnPostSave)==null||s.call(i,r)}catch{}e.clearScreenContext()}}}}qr();var Tc={version:_n,createFiodosAgent:ri,mountOrb:Tt,AgentController:Ge,createScreenContextStore:On,buildApiActionRegistries:Nt,validateManifest:ge,connectDynamicsFormContext:ii,dynamicsFormSnapshot:wo,normalizeDynamicsId:So};globalThis.Fiodos=Tc;})();
@@ -147,6 +147,9 @@ export function createFiodosBackendClient(options) {
147
147
  intent: request.lastStep.intent,
148
148
  ...(request.lastStep.label ? { label: request.lastStep.label } : {}),
149
149
  success: request.lastStep.success,
150
+ // Technical error of a FAILED step: the backend renders it in the
151
+ // RECOVERY block so the model can diagnose and change path.
152
+ ...(request.lastStep.error ? { error: request.lastStep.error } : {}),
150
153
  // Bounded result payload of the executed step (product search
151
154
  // results…): the backend renders it so the model can read real
152
155
  // ids for the NEXT step's parameters.
@@ -25,6 +25,13 @@ import { createSpeechSession } from '../speech/speechSession.js';
25
25
  import { classifyPendingReply, decideAction, } from '../core/turnEngine.js';
26
26
  import { DEFAULT_AGENT_TIMINGS, DEFAULT_AGENT_CHAINING, } from '../config/types.js';
27
27
  import { resolveUiMessages } from '../ui/messages.js';
28
+ /**
29
+ * How many FAILED-step recovery turns one chain may consume. A failed action
30
+ * (invented handle → 404, wrong id kind → 422, transient 5xx) no longer kills
31
+ * the task: the model gets the technical error back and picks a different
32
+ * path — bounded so a persistently failing action can never loop.
33
+ */
34
+ const MAX_CHAIN_RECOVERIES = 2;
28
35
  function randomSessionId() {
29
36
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
30
37
  }
@@ -522,6 +529,28 @@ export class AgentController {
522
529
  step: chainState.step,
523
530
  lastStep: chainState.pendingStep ?? chainState.lastStep,
524
531
  visitedKeys: chainState.visitedKeys,
532
+ recoveries: chainState.recoveries,
533
+ });
534
+ }
535
+ else if (!result.success && this.chaining.enabled) {
536
+ // The CONFIRMED action failed: same recovery contract as any other
537
+ // failed step — the model reads the technical error and takes a
538
+ // different path (bounded by the recovery budget). The user's
539
+ // confirmation covered THIS intent; a recovery that re-attempts it
540
+ // stages a NEW confirmation, so the human gate is never bypassed.
541
+ const failedStep = {
542
+ type: 'execute',
543
+ intent: pending.intent,
544
+ label: this.actionLabel(pending.intent),
545
+ success: false,
546
+ ...(result.error ? { error: String(result.error).slice(0, 300) } : {}),
547
+ };
548
+ await this.runChainLoop({
549
+ userMessage: chainState.userMessage,
550
+ step: chainState.step,
551
+ lastStep: failedStep,
552
+ visitedKeys: chainState.visitedKeys,
553
+ recoveries: (chainState.recoveries ?? 0) + 1,
525
554
  });
526
555
  }
527
556
  else if (!result.success) {
@@ -689,6 +718,7 @@ export class AgentController {
689
718
  let pendingInProgress = false;
690
719
  let pendingStep;
691
720
  let pendingKey;
721
+ let stepFailed = false;
692
722
  if (decision.kind === 'executed') {
693
723
  const r = decision.result;
694
724
  // REAL activity for the panel: this action actually just ran — the
@@ -729,6 +759,15 @@ export class AgentController {
729
759
  if (r.recoverable) {
730
760
  /* keep the assistant's guiding reply; never speak a refusal. */
731
761
  }
762
+ else if (turn.action?.type === 'navigate' &&
763
+ r.success &&
764
+ turn.taskStatus === 'in_progress') {
765
+ // Mid-chain navigate housekeeping (e.g. the no-op "you're already on
766
+ // that screen"): the task CONTINUES with the next step, so replacing
767
+ // the reply here would speak an irrelevant aside ("Ya estás en esa
768
+ // pantalla") instead of the model's narration of what it is doing.
769
+ // Keep the LLM reply; the chain's final step sets the real outcome.
770
+ }
732
771
  else if (r.message) {
733
772
  // FEEDBACK GUARANTEE: the handler's outcome message (success,
734
773
  // idempotent or failure) is the ground truth that the action ran;
@@ -752,6 +791,24 @@ export class AgentController {
752
791
  // be findable in the console or every field report is undebuggable.
753
792
  console.warn(`[fyodos] action "${turn.action?.intent ?? '?'}" failed: ${r.error ?? 'unknown error'}`);
754
793
  }
794
+ // RECOVERY signal: the step RAN and FAILED (not a recoverable guidance
795
+ // case). Feed the technical error back as a failed lastStep so the model
796
+ // can diagnose (invented handle → 404, wrong id kind → 422…) and take a
797
+ // DIFFERENT path, exactly like a human agent. The chain loop bounds how
798
+ // many of these turns run (MAX_CHAIN_RECOVERIES); task_status is
799
+ // irrelevant here — the model believed the step would succeed.
800
+ if (turn.action?.type === 'execute' && !r.success && !r.recoverable) {
801
+ const intent = turn.action.intent ?? '';
802
+ lastStep = {
803
+ type: 'execute',
804
+ intent,
805
+ label: this.actionLabel(intent),
806
+ success: false,
807
+ ...(r.error ? { error: String(r.error).slice(0, 300) } : {}),
808
+ };
809
+ stepFailed = true;
810
+ canContinue = this.chaining.enabled;
811
+ }
755
812
  // Chain signal: only a cleanly EXECUTED, non-recoverable step may advance,
756
813
  // and only when the backend asked to continue (task_status=in_progress).
757
814
  if (turn.action &&
@@ -827,6 +884,7 @@ export class AgentController {
827
884
  pendingInProgress,
828
885
  pendingStep,
829
886
  pendingKey,
887
+ stepFailed,
830
888
  };
831
889
  }
832
890
  /**
@@ -837,6 +895,7 @@ export class AgentController {
837
895
  async runChainLoop(state) {
838
896
  let step = state.step;
839
897
  let lastStep = state.lastStep;
898
+ let recoveries = state.recoveries ?? 0;
840
899
  const visitedKeys = state.visitedKeys;
841
900
  // Keep the panel's live row visible for the WHOLE chain (including the
842
901
  // dwell between steps), so the real narration never flickers away.
@@ -933,6 +992,7 @@ export class AgentController {
933
992
  visitedKeys,
934
993
  pendingKey: oc.pendingKey,
935
994
  pendingStep: oc.pendingStep,
995
+ recoveries,
936
996
  }
937
997
  : null;
938
998
  this.beginConfirmationVoiceWindow();
@@ -940,6 +1000,21 @@ export class AgentController {
940
1000
  }
941
1001
  if (this.phase !== 'speaking')
942
1002
  this.setPhase('idle');
1003
+ // Failed step: consume one recovery slot. The budget is what keeps a
1004
+ // persistently failing action from looping; a chain that exhausts it
1005
+ // ends with the (honest) failure reply already on screen.
1006
+ if (oc.stepFailed) {
1007
+ recoveries += 1;
1008
+ if (recoveries > MAX_CHAIN_RECOVERIES) {
1009
+ this.telemetry.logEvent({
1010
+ eventType: 'agent_chain_aborted',
1011
+ sessionId: this.sessionId,
1012
+ chainStep: step,
1013
+ chainAbortReason: 'no_progress',
1014
+ });
1015
+ return;
1016
+ }
1017
+ }
943
1018
  if (oc.actionKey && visitedKeys.has(oc.actionKey)) {
944
1019
  this.telemetry.logEvent({
945
1020
  eventType: 'agent_chain_aborted',
@@ -1122,7 +1197,8 @@ export class AgentController {
1122
1197
  this.setPhase('idle');
1123
1198
  }
1124
1199
  // Kick off the autonomous chain when the first step executed cleanly and
1125
- // the backend asked to continue (no sensitive confirmation pending).
1200
+ // the backend asked to continue (no sensitive confirmation pending) — or
1201
+ // when the first step FAILED and a recovery turn should diagnose it.
1126
1202
  if (this.chaining.enabled && outcome.canContinue && !hasPending) {
1127
1203
  this.telemetry.logEvent({
1128
1204
  eventType: 'agent_chain_started',
@@ -1137,6 +1213,7 @@ export class AgentController {
1137
1213
  step: 1,
1138
1214
  lastStep: outcome.lastStep,
1139
1215
  visitedKeys,
1216
+ recoveries: outcome.stepFailed ? 1 : 0,
1140
1217
  });
1141
1218
  }
1142
1219
  // Final reply is on screen: the live narrative disappears (unless the
@@ -27,7 +27,7 @@ import { createScreenContextStore } from '../context/screenContextStore.js';
27
27
  import { connectDynamicsFormContext, dynamicsFormSnapshot, normalizeDynamicsId } from './dynamics.js';
28
28
  import { buildApiActionRegistries, validateManifest } from '@fiodos/core';
29
29
  declare const api: {
30
- readonly version: "0.1.20";
30
+ readonly version: "0.1.22";
31
31
  readonly createFiodosAgent: typeof createFiodosAgent;
32
32
  readonly mountOrb: typeof mountOrb;
33
33
  readonly AgentController: typeof AgentController;
@@ -5,5 +5,5 @@
5
5
  * Auto-generated by scripts/sync-sdk-version.mjs from package.json. Do not edit
6
6
  * by hand — change package.json `version` and re-run the sync/release script.
7
7
  */
8
- export declare const SDK_VERSION = "0.1.20";
8
+ export declare const SDK_VERSION = "0.1.22";
9
9
  export declare const SDK_PACKAGE = "@fiodos/web-core";
@@ -5,5 +5,5 @@
5
5
  * Auto-generated by scripts/sync-sdk-version.mjs from package.json. Do not edit
6
6
  * by hand — change package.json `version` and re-run the sync/release script.
7
7
  */
8
- export const SDK_VERSION = '0.1.20';
8
+ export const SDK_VERSION = '0.1.22';
9
9
  export const SDK_PACKAGE = '@fiodos/web-core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fiodos/web-core",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "description": "Framework-agnostic browser layer for the Fiodos agent: a vanilla AgentController (orchestrator), DOM adapters (navigation/voice/storage), HTTP client and decision engine over @fiodos/core. Shared base for @fiodos/vue, @fiodos/svelte and @fiodos/angular (no framework imports).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "publishConfig": {