@7ots/cli 0.1.12 → 0.1.13

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.
@@ -61,7 +61,7 @@ import { cloudStatus, createExtras, lettaSync, normalizeCharacter, normalizeInte
61
61
  import { spawn } from 'node:child_process';
62
62
  import { openSync } from 'node:fs';
63
63
  import { line } from './lines.mjs';
64
- import { defineIdentity, GROK_VOICES, OPENAI_VOICES } from '../../src/identity/schema.js';
64
+ import { defineIdentity, GROK_VOICES, OPENAI_VOICES, TTS_MODELS } from '../../src/identity/schema.js';
65
65
  import { normalizeMod, normalizeMods, MAX_MODS } from '../../src/character/mods.js';
66
66
  import { MOD_CATALOG } from '../../src/character/mods/index.js';
67
67
  import { DANCES } from '../../src/character/motion.js';
@@ -1014,6 +1014,7 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1014
1014
  modLibrary: modLibrary(),
1015
1015
  musicFiles: musicFiles(),
1016
1016
  dances: DANCES,
1017
+ ttsModels: TTS_MODELS,
1017
1018
  modCatalog: MOD_CATALOG.map((m) => normalizeMod(m)).map((m) => ({ ...m, parts: m.parts.map((x) => ({ ...x, glb: x.glb ? '3d' : '' })) })),
1018
1019
  integrations: config.integrations,
1019
1020
  character: config.character,
@@ -494,7 +494,7 @@
494
494
  customH: 'Custom integrations', customD: 'Anything else: tell it what it is and how to use it. Optional: a URL it can GET or a command it can run (with a token from an environment variable).', customAdd: 'Add integration', customName: 'Name', customInstr: 'Instructions for the brain', customUrl: 'URL (optional)', customCmd: 'Command (optional)', customEnv: 'Token env var (optional)', customEnvHint: 'Read from this computer’s environment or ~/.7ots/keys.json, never shown.', edit: 'Edit', remove: 'Remove', untitled: 'New integration',
495
495
  charH: 'Character sheet', charHint: 'Who it is. This weighs more than the traits from 7ots.com: backstory, how it talks, its quirks and example dialogues.',
496
496
  chBackstory: 'Backstory', chStyle: 'How it talks', chQuirks: 'Quirks', chScenario: 'Scenario (optional)', chGreeting: 'Greeting (optional)', chExamples: 'Example dialogues',
497
- vcConf: 'Configure voice', vcNow: 'Voice: {v} · change', vcId: 'Voice id', vcIdPh: 'Empty = provider default', vcPick: 'Pick one of your {n} voices…', vcNoList: 'No voices in your account yet', vcModel: 'Model', vcDefault: 'Default', vcStyle: 'Style (how it speaks)', vcStylePh: 'E.g.: warm, a bit sarcastic, fast', vcTest: 'Try', vcTesting: 'Generating…', vcSave: 'Use this voice', vcPage: 'Browse voices on the site', vcKeyFirst: 'Save the key first to list your voices.', chExamplesPh: 'Human: how are you?\n{name}: …', chIdeaPh: 'Idea (optional): a grumpy retired wizard who loves trains…', chAi: 'Fill with AI', chAiWait: 'The AI is writing the sheet in {lang}… (up to a minute)', chAiLang: 'Language of the sheet', chAiPartial: 'Draft ready, but these came back empty: {f}. Try again.', chAiDone: 'Draft ready: review it and Save', chAiBrain: 'Pick an AI brain first (Brain section)', importCard: 'Import card', exportCard: 'Export card', imported: 'Imported ✓', badCard: 'That file has no character card (chara_card_v2 JSON or PNG).',
497
+ vcConf: 'Configure voice', vcNow: 'Voice: {v} · change', vcId: 'Voice id', vcIdPh: 'Empty = provider default', vcPick: 'Pick one of your {n} voices…', vcNoList: 'No voices in your account yet', vcModel: 'Model', vcOneModel: 'xAI has a single voice model.', vcDefault: 'Default', vcStyle: 'Style (how it speaks)', vcStylePh: 'E.g.: warm, a bit sarcastic, fast', vcTest: 'Try', vcTesting: 'Generating…', vcSave: 'Use this voice', vcPage: 'Browse voices on the site', vcKeyFirst: 'Save the key first to list your voices.', chExamplesPh: 'Human: how are you?\n{name}: …', chIdeaPh: 'Idea (optional): a grumpy retired wizard who loves trains…', chAi: 'Fill with AI', chAiWait: 'The AI is writing the sheet in {lang}… (up to a minute)', chAiLang: 'Language of the sheet', chAiPartial: 'Draft ready, but these came back empty: {f}. Try again.', chAiDone: 'Draft ready: review it and Save', chAiBrain: 'Pick an AI brain first (Brain section)', importCard: 'Import card', exportCard: 'Export card', imported: 'Imported ✓', badCard: 'That file has no character card (chara_card_v2 JSON or PNG).',
498
498
  lettaH: 'Letta memory (optional)', lettaD: 'Keeps the persona in a Letta agent’s core memory, and reads it back into its prompt.', lettaAgent: 'Letta agent ID (empty: create one)', lettaKey: 'Letta API key', lettaSync: 'Sync with Letta', lettaOk: 'Synced ✓', lettaNew: 'Agent created ✓',
499
499
  e_customName: 'every integration needs a name', e_customUrl: 'the URL must start with http:// or https://', e_customEnv: 'the env var must look like MY_TOKEN', e_inbox: 'that inbox address isn’t valid', e_lettaAgent: 'invalid Letta agent ID', e_custom: 'up to 20 integrations', e_project: 'invalid project',
500
500
  },
@@ -515,7 +515,7 @@
515
515
  customH: 'Integraciones propias', customD: 'Cualquier otra cosa: dile qué es y cómo usarla. Opcional: una URL a la que puede hacer GET o un comando que puede ejecutar (con un token de una variable de entorno).', customAdd: 'Agregar integración', customName: 'Nombre', customInstr: 'Instrucciones para el cerebro', customUrl: 'URL (opcional)', customCmd: 'Comando (opcional)', customEnv: 'Variable con el token (opcional)', customEnvHint: 'Se lee del entorno de este computador o de ~/.7ots/keys.json, nunca se muestra.', edit: 'Editar', remove: 'Quitar', untitled: 'Nueva integración',
516
516
  charH: 'Ficha del personaje', charHint: 'Quién es. Pesa más que los rasgos de 7ots.com: historia, cómo habla, sus manías y diálogos de ejemplo.',
517
517
  chBackstory: 'Historia', chStyle: 'Cómo habla', chQuirks: 'Manías', chScenario: 'Escenario (opcional)', chGreeting: 'Saludo (opcional)', chExamples: 'Diálogos de ejemplo',
518
- vcConf: 'Configurar voz', vcNow: 'Voz: {v} · cambiar', vcId: 'Id de la voz', vcIdPh: 'Vacío = la del proveedor', vcPick: 'Elige una de tus {n} voces…', vcNoList: 'Aún no hay voces en tu cuenta', vcModel: 'Modelo', vcDefault: 'Por defecto', vcStyle: 'Estilo (cómo habla)', vcStylePh: 'Ej.: cálido, algo sarcástico, rápido', vcTest: 'Probar', vcTesting: 'Generando…', vcSave: 'Usar esta voz', vcPage: 'Ver voces en su sitio', vcKeyFirst: 'Guarda primero la key para listar tus voces.', chExamplesPh: 'Human: ¿cómo estás?\n{name}: …', chIdeaPh: 'Idea (opcional): un mago jubilado gruñón que ama los trenes…', chAi: 'Rellenar con IA', chAiWait: 'La IA está escribiendo la ficha en {lang}… (hasta un minuto)', chAiLang: 'Idioma de la ficha', chAiPartial: 'Borrador listo, pero estos vinieron vacíos: {f}. Prueba de nuevo.', chAiDone: 'Borrador listo: revísalo y Guarda', chAiBrain: 'Elige primero un cerebro con IA (sección Cerebro)', importCard: 'Importar ficha', exportCard: 'Exportar ficha', imported: 'Importada ✓', badCard: 'Ese archivo no trae una ficha de personaje (JSON o PNG chara_card_v2).',
518
+ vcConf: 'Configurar voz', vcNow: 'Voz: {v} · cambiar', vcId: 'Id de la voz', vcIdPh: 'Vacío = la del proveedor', vcPick: 'Elige una de tus {n} voces…', vcNoList: 'Aún no hay voces en tu cuenta', vcModel: 'Modelo', vcOneModel: 'xAI tiene un único modelo de voz.', vcDefault: 'Por defecto', vcStyle: 'Estilo (cómo habla)', vcStylePh: 'Ej.: cálido, algo sarcástico, rápido', vcTest: 'Probar', vcTesting: 'Generando…', vcSave: 'Usar esta voz', vcPage: 'Ver voces en su sitio', vcKeyFirst: 'Guarda primero la key para listar tus voces.', chExamplesPh: 'Human: ¿cómo estás?\n{name}: …', chIdeaPh: 'Idea (opcional): un mago jubilado gruñón que ama los trenes…', chAi: 'Rellenar con IA', chAiWait: 'La IA está escribiendo la ficha en {lang}… (hasta un minuto)', chAiLang: 'Idioma de la ficha', chAiPartial: 'Borrador listo, pero estos vinieron vacíos: {f}. Prueba de nuevo.', chAiDone: 'Borrador listo: revísalo y Guarda', chAiBrain: 'Elige primero un cerebro con IA (sección Cerebro)', importCard: 'Importar ficha', exportCard: 'Exportar ficha', imported: 'Importada ✓', badCard: 'Ese archivo no trae una ficha de personaje (JSON o PNG chara_card_v2).',
519
519
  lettaH: 'Memoria Letta (opcional)', lettaD: 'Guarda la persona en la memoria central de un agente Letta y la vuelve a leer en su prompt.', lettaAgent: 'ID del agente Letta (vacío: crear uno)', lettaKey: 'API key de Letta', lettaSync: 'Sincronizar con Letta', lettaOk: 'Sincronizado ✓', lettaNew: 'Agente creado ✓',
520
520
  e_customName: 'cada integración necesita un nombre', e_customUrl: 'la URL debe empezar con http:// o https://', e_customEnv: 'la variable debe verse como MI_TOKEN', e_inbox: 'esa dirección de bandeja no es válida', e_lettaAgent: 'ID de agente Letta inválido', e_custom: 'máximo 20 integraciones', e_project: 'proyecto inválido',
521
521
  },
@@ -536,7 +536,7 @@
536
536
  customH: 'Integrações próprias', customD: 'Qualquer outra coisa: diga o que é e como usar. Opcional: uma URL para fazer GET ou um comando para rodar (com um token de uma variável de ambiente).', customAdd: 'Adicionar integração', customName: 'Nome', customInstr: 'Instruções para o cérebro', customUrl: 'URL (opcional)', customCmd: 'Comando (opcional)', customEnv: 'Variável com o token (opcional)', customEnvHint: 'Lida do ambiente deste computador ou de ~/.7ots/keys.json, nunca mostrada.', edit: 'Editar', remove: 'Remover', untitled: 'Nova integração',
537
537
  charH: 'Ficha do personagem', charHint: 'Quem ele é. Pesa mais que os traços do 7ots.com: história, jeito de falar, manias e diálogos de exemplo.',
538
538
  chBackstory: 'História', chStyle: 'Jeito de falar', chQuirks: 'Manias', chScenario: 'Cenário (opcional)', chGreeting: 'Saudação (opcional)', chExamples: 'Diálogos de exemplo',
539
- vcConf: 'Configurar voz', vcNow: 'Voz: {v} · trocar', vcId: 'Id da voz', vcIdPh: 'Vazio = a do provedor', vcPick: 'Escolha uma das suas {n} vozes…', vcNoList: 'Ainda não há vozes na sua conta', vcModel: 'Modelo', vcDefault: 'Padrão', vcStyle: 'Estilo (como fala)', vcStylePh: 'Ex.: caloroso, meio sarcástico, rápido', vcTest: 'Testar', vcTesting: 'Gerando…', vcSave: 'Usar esta voz', vcPage: 'Ver vozes no site', vcKeyFirst: 'Salve a key primeiro para listar suas vozes.', chExamplesPh: 'Human: tudo bem?\n{name}: …', chIdeaPh: 'Ideia (opcional): um mago aposentado ranzinza que ama trens…', chAi: 'Preencher com IA', chAiWait: 'A IA está escrevendo a ficha em {lang}… (até um minuto)', chAiLang: 'Idioma da ficha', chAiPartial: 'Rascunho pronto, mas estes vieram vazios: {f}. Tente de novo.', chAiDone: 'Rascunho pronto: revise e Salve', chAiBrain: 'Escolha antes um cérebro com IA (seção Cérebro)', importCard: 'Importar ficha', exportCard: 'Exportar ficha', imported: 'Importada ✓', badCard: 'Esse arquivo não tem uma ficha de personagem (JSON ou PNG chara_card_v2).',
539
+ vcConf: 'Configurar voz', vcNow: 'Voz: {v} · trocar', vcId: 'Id da voz', vcIdPh: 'Vazio = a do provedor', vcPick: 'Escolha uma das suas {n} vozes…', vcNoList: 'Ainda não há vozes na sua conta', vcModel: 'Modelo', vcOneModel: 'O xAI tem um único modelo de voz.', vcDefault: 'Padrão', vcStyle: 'Estilo (como fala)', vcStylePh: 'Ex.: caloroso, meio sarcástico, rápido', vcTest: 'Testar', vcTesting: 'Gerando…', vcSave: 'Usar esta voz', vcPage: 'Ver vozes no site', vcKeyFirst: 'Salve a key primeiro para listar suas vozes.', chExamplesPh: 'Human: tudo bem?\n{name}: …', chIdeaPh: 'Ideia (opcional): um mago aposentado ranzinza que ama trens…', chAi: 'Preencher com IA', chAiWait: 'A IA está escrevendo a ficha em {lang}… (até um minuto)', chAiLang: 'Idioma da ficha', chAiPartial: 'Rascunho pronto, mas estes vieram vazios: {f}. Tente de novo.', chAiDone: 'Rascunho pronto: revise e Salve', chAiBrain: 'Escolha antes um cérebro com IA (seção Cérebro)', importCard: 'Importar ficha', exportCard: 'Exportar ficha', imported: 'Importada ✓', badCard: 'Esse arquivo não tem uma ficha de personagem (JSON ou PNG chara_card_v2).',
540
540
  lettaH: 'Memória Letta (opcional)', lettaD: 'Guarda a persona na memória central de um agente Letta e a lê de volta no prompt.', lettaAgent: 'ID do agente Letta (vazio: criar um)', lettaKey: 'API key da Letta', lettaSync: 'Sincronizar com Letta', lettaOk: 'Sincronizado ✓', lettaNew: 'Agente criado ✓',
541
541
  e_customName: 'cada integração precisa de um nome', e_customUrl: 'a URL deve começar com http:// ou https://', e_customEnv: 'a variável deve parecer MEU_TOKEN', e_inbox: 'esse endereço de caixa não é válido', e_lettaAgent: 'ID de agente Letta inválido', e_custom: 'no máximo 20 integrações', e_project: 'projeto inválido',
542
542
  },
@@ -970,13 +970,14 @@
970
970
  const P = VPROV[kind];
971
971
  const vfield = (label, input) => el('label', { className: 'f' }, label, input);
972
972
  const cur = S.config.voice?.providers?.[kind] || {};
973
- const has = S.voices.keys[kind];
973
+ let has = S.voices.keys[kind];
974
974
  const msg = el('span', { className: 'msg', role: 'status' });
975
975
  const idIn = el('input', { type: 'text', value: cur.voiceId || '', placeholder: t('vcIdPh'), autocomplete: 'off' });
976
976
  const pick = el('select', { hidden: true });
977
- const model = el('input', { type: 'text', value: cur.model || '', placeholder: P.models[0] || t('vcDefault'), autocomplete: 'off' });
978
- if (P.models.length) model.setAttribute('list', `vm-${kind}`);
979
- const dl = el('datalist', { id: `vm-${kind}` }, ...P.models.map((m) => el('option', { value: m })));
977
+ // The provider's models as a list (first = what it uses when none is picked); a hand-set one stays selectable.
978
+ const models = (S.ttsModels || {})[kind] || P.models;
979
+ const model = el('select', {}, el('option', { value: '', textContent: models.length ? `${t('vcDefault')} (${models[0]})` : t('vcDefault') }), ...[...models, ...(cur.model && !models.includes(cur.model) ? [cur.model] : [])].map((m) => el('option', { value: m, textContent: m, selected: m === cur.model })));
980
+ const dl = null;
980
981
  const style = el('textarea', { rows: 2, value: cur.style || '', placeholder: t('vcStylePh') });
981
982
  const loadList = async () => {
982
983
  if (!P.list || !has) return;
@@ -991,12 +992,23 @@
991
992
  }
992
993
  };
993
994
  pick.addEventListener('change', () => pick.value && (idIn.value = pick.value));
995
+ // The key typed in this card's field goes along with Try / Use this voice (not only with the section's Save).
996
+ const keyIn = () => box.closest('.more')?.querySelector('input[type=password]');
997
+ const saveKeyFirst = async () => {
998
+ const k = keyIn(), v = k?.value.trim();
999
+ if (!v) return;
1000
+ S = await api('/config', { keys: { [k.name.replace(/_V$/, '')]: v } });
1001
+ k.value = '';
1002
+ has = S.voices.keys[kind];
1003
+ loadList();
1004
+ };
994
1005
  const test = el('button', {}, ico('volume-2', 15), ' ', t('vcTest'));
995
1006
  test.addEventListener('click', async (e) => {
996
1007
  e.preventDefault();
997
1008
  test.disabled = true;
998
1009
  flash(msg, t('vcTesting'), 'ok');
999
1010
  try {
1011
+ await saveKeyFirst();
1000
1012
  const r = await fetch('/voice/test', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-7ots-Token': BOOT.token }, body: JSON.stringify({ kind, voiceId: idIn.value, model: model.value, style: style.value }) });
1001
1013
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
1002
1014
  const a = new Audio(URL.createObjectURL(await r.blob()));
@@ -1011,6 +1023,7 @@
1011
1023
  const ok = el('button', { className: 'primary', textContent: t('vcSave') });
1012
1024
  ok.addEventListener('click', async (e) => {
1013
1025
  e.preventDefault();
1026
+ try { await saveKeyFirst(); } catch (x) { return flash(msg, t('err', { e: errText(x) }), 'err'); }
1014
1027
  await save({ voice: { kind, providers: { [kind]: { voiceId: idIn.value, model: model.value, style: style.value, name: pick.value === idIn.value ? pick.selectedOptions[0]?.textContent || '' : '' } } } }, msg);
1015
1028
  S.config.voice = { ...S.config.voice, kind, providers: { ...(S.config.voice?.providers || {}), [kind]: { voiceId: idIn.value, model: model.value, style: style.value } } };
1016
1029
  const r = box.querySelector(`#v-${kind}`);
@@ -1023,7 +1036,7 @@
1023
1036
  has || !P.list ? null : el('small', { textContent: t('vcKeyFirst') }),
1024
1037
  pick,
1025
1038
  vfield(t('vcId'), idIn),
1026
- vfield(t('vcModel'), model), dl,
1039
+ kind === 'grok' ? el('small', { textContent: t('vcOneModel') }) : models.length ? vfield(t('vcModel'), model) : null, dl,
1027
1040
  P.style ? vfield(t('vcStyle'), style) : null,
1028
1041
  el('div', { className: 'row' }, test, ok, page, msg)));
1029
1042
  box.addEventListener('toggle', () => box.open && !pick.options.length && loadList(), { once: false });
package/dist/7ots.esm.js CHANGED
@@ -409,7 +409,7 @@ ${Gc(this.brain?.persona?.locale||this.brain?.persona?.language)}`;await this.br
409
409
  <button class="b-body" aria-label="${Se(this.t("widget.companion.talkTo",{name:this.name}))}" title="${Se(this.name)}">
410
410
  <span class="b-stage"></span><span class="b-shadow"></span>
411
411
  </button>
412
- <span class="b-arrow" aria-hidden="true" hidden></span>`,"popover"in t&&(t.popover="manual"),this.root.appendChild(t),this.el=t,this._raise(),this.stage&&t.querySelector(".b-stage").appendChild(this.stage),t.style.setProperty("--bs",`${this.size}px`);let o=t.querySelector(".b-body"),r=null;o.addEventListener("pointerdown",i=>{i.button===0&&(r={sx:i.clientX,sy:i.clientY,x:this.x,y:this.y,moved:!1},o.setPointerCapture(i.pointerId))}),o.addEventListener("pointermove",i=>{if(!r)return;let n=i.clientX-r.sx,l=i.clientY-r.sy;!r.moved&&Math.hypot(n,l)<6||(r.moved=!0,this._anchor=null,this._place(r.x+n,r.y+l,0))}),o.addEventListener("pointerup",()=>{r?.moved?this._home={x:this.x,y:this.y}:r&&this.onActivate?.(),r=null}),o.addEventListener("pointercancel",()=>r=null),t.querySelector(".b-say").addEventListener("click",()=>this.onActivate?.());let s=0,a=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{t.style.setProperty("--bs",`${this.size}px`),this._anchor?.isConnected?this._placeNear(this._anchor,0):this.home({instant:!0})})};addEventListener("scroll",a,{passive:!0,capture:!0}),addEventListener("resize",a),this._offs.push(()=>removeEventListener("scroll",a,{capture:!0}),()=>removeEventListener("resize",a)),this.home({instant:!0}),this._idleLook(),this.setBehavior(this.cfg)}relabel(){let t=this.el?.querySelector(".b-body");t&&(t.setAttribute("aria-label",this.t("widget.companion.talkTo",{name:this.name})),t.title=this.name)}setBehavior({wanderMs:t=this.cfg.wanderMs,watchCursor:o=this.cfg.watchCursor}={}){if(this.cfg.wanderMs=t,this.cfg.watchCursor=o,this._scheduleWander(),this._offCursor?.(),this._offCursor=null,o){let r=0,s=a=>{let i=Date.now();i-r<300||this._busyLooking()||(r=i,this.avatar?.lookAt?.(a.clientX,a.clientY,700))};addEventListener("pointermove",s,{passive:!0}),this._offCursor=()=>removeEventListener("pointermove",s),this._offs.push(()=>this._offCursor?.())}}_busyLooking(){return document.hidden||this.el.classList.contains("walking")||!this.el.querySelector(".b-arrow").hidden}_scheduleWander(){clearTimeout(this._timers.wander);let t=this.cfg.wanderMs;t&&(this._timers.wander=setTimeout(()=>{this._wander().finally(()=>this._scheduleWander())},t*(.7+Math.random()*.6)))}async _wander(){if(document.hidden||this._anchor||!this.canWander()||!this.el.querySelector(".b-say").hidden)return;let t=this.size,o=[...document.querySelectorAll("h1, h2, h3, img, button, a[class*=btn], a[class*=button], [class*=card], figure, table")].filter(a=>{if(a.closest("[data-ots-root], [data-ots-ignore]"))return!1;let i=a.getBoundingClientRect();return i.width>30&&i.height>16&&i.top>40&&i.bottom<innerHeight-40&&i.width<innerWidth*.9&&a!==this._lastWander});if(!o.length)return;let r=o[Math.floor(Math.random()*o.length)];if(this._lastWander=r,this.el.classList.add("curious"),await this._placeNear(r),this._anchor)return this.el.classList.remove("curious");let s=r.getBoundingClientRect();this.avatar?.lookAt?.(s.left+s.width/2,s.top+s.height/2,2e3),Math.random()<.35&&this.avatar?.gesture?.(["index","shrug","handup"][Math.floor(Math.random()*3)],1.6,s.left+s.width/2<this.x+t/2),await Jo(2600+Math.random()*2e3),this.el.classList.remove("curious"),!this._anchor&&this.canWander()&&this.home()}destroy(){Object.values(this._timers).forEach(clearTimeout),this._offs.forEach(t=>t()),this.el?.remove()}panelChanged(t){this.el.classList.toggle("behind",t&&innerWidth<640),(t||!this._anchor)&&this.home()}home({instant:t=!1}={}){this._anchor=null;let o=this.size,r,s;if(this._home)({x:r,y:s}=this._home);else{let i=this.panelOpen()&&innerWidth>=640?Math.min(380,innerWidth-24)+32:20;r=this.side==="left"?i:innerWidth-o-i,s=innerHeight-o-20}return this._place(r,s,t?0:void 0)}async goTo(t){if(!t?.isConnected)throw new Error("El elemento ya no est\xE1 en la p\xE1gina");let o=t.getBoundingClientRect();(o.bottom<0||o.top>innerHeight||o.right<0||o.left>innerWidth)&&(Oo(t),await Eh(t)),this._anchor=t,await this._placeNear(t),this._touch()}async pointAt(t,o="",{signal:r}={}){if(await this.goTo(t),r?.aborted)return;let s=t.getBoundingClientRect(),a=s.left+s.width/2,i=s.top+s.height/2,n=this.x+this.size/2;this.avatar?.lookAt?.(a,i,2500),this.avatar?.gesture?.("index",2.5,a<n),this._arrow(a,i),this.ui?.highlight?.(t,{duration:2600,scroll:!1}),o?await this.say(o,{signal:r}):await Jo(1200,r)}async tour(t,{signal:o,resolve:r}={}){let s=0;for(let a of t){if(o?.aborted)break;let i=r(a.target);i&&(await this.pointAt(i,a.message||"",{signal:o}),s++,await Jo(350,o))}return s}follow(t){!this.cfg.follow||!t?.isConnected||(this._anchor=t,this._placeNear(t),this._touch())}_placeNear(t,o){let r=this.size,s=t.getBoundingClientRect(),a=innerWidth,i=innerHeight,n=s.top+s.height/2-r/2,l=s.left+s.width/2-r/2,h=gr(n,st,i-r-st),u=gr(l,st,a-r-st),c=[s.right+ts,h],d=[s.left-r-ts,h],$=[...this.side==="left"?[d,c]:[c,d],[u,s.bottom+ts],[u,s.top-r-ts]],f=([x,v])=>x>=st&&v>=st&&x+r<=a-st&&v+r<=i-st,[m,g]=$.find(f)||[this.side==="left"?Math.max(s.left,0)+st:Math.min(s.right,a)-r-st,Math.max(s.top,0)+st];return this._place(m,g,o)}_place(t,o,r){let s=this.size;t=gr(t,st,innerWidth-s-st),o=gr(o,st,innerHeight-s-st);let a=Math.hypot(t-this.x,o-this.y),i=document.hidden||matchMedia("(prefers-reduced-motion: reduce)").matches,n=r??(i?0:gr(a*1.1,0,1300)),l=this.el;return n>0&&a>4&&(l.classList.add("walking"),l.classList.toggle("to-left",t<this.x),clearTimeout(this._timers.walk),this._timers.walk=setTimeout(()=>l.classList.remove("walking"),n)),this._raise(),l.style.transitionDuration=`${n}ms`,l.style.transform=`translate(${Math.round(t)}px, ${Math.round(o)}px)`,l.dataset.v=o<innerHeight/2?"top":"bottom",l.dataset.h=t+s/2<innerWidth/2?"left":"right",this.x=t,this.y=o,Jo(n)}_raise(){let t=this.el;if(t?.showPopover)try{if(t.matches(":popover-open")){if(!document.querySelector("dialog:modal"))return;t.hidePopover()}t.showPopover()}catch{}}_arrow(t,o){let r=this.el.querySelector(".b-arrow"),s=this.size/2,a=Math.atan2(o-(this.y+s),t-(this.x+s)),i=s*.95;r.style.transform=`translate(${s+Math.cos(a)*i}px, ${s+Math.sin(a)*i}px) rotate(${a}rad)`,r.hidden=!1,r.classList.remove("go"),r.offsetWidth,r.classList.add("go"),clearTimeout(this._timers.arrow),this._timers.arrow=setTimeout(()=>r.hidden=!0,2600)}async say(t,{speak:o=!0,signal:r}={}){let s=++this._sayToken,a=this.el.querySelector(".b-say"),i=String(t||"").trim();a.querySelector(".b-say-text").innerHTML=Ft(i.length>240?`${i.slice(0,237)}\u2026`:i),a.hidden=!1,this._touch();let n=gr(i.length*55,1800,9e3),l=o&&this.speak?this.speak(i).catch(()=>{}):null;await Promise.race([Promise.all([l||Jo(n),Jo(Math.min(n,1500))]),_h(r)]),clearTimeout(this._timers.say),this._timers.say=setTimeout(()=>{s===this._sayToken&&(a.hidden=!0)},2500)}hush(){this._sayToken++,this.el.querySelector(".b-say").hidden=!0}_touch(){clearTimeout(this._timers.idle),this._timers.idle=setTimeout(()=>{this._anchor&&this.home()},this.cfg.idleHomeMs)}_idleLook(){clearTimeout(this._timers.look),this._timers.look=setTimeout(()=>{!document.hidden&&!this.el.classList.contains("walking")&&this.avatar?.lookAt?.(Math.random()*innerWidth,Math.random()*innerHeight*.7,1200),this._idleLook()},7e3+Math.random()*9e3)}};function xi(e,{t=e.t||le()}={}){let o={type:"string",description:'Ref (p. ej. "e12") o selector CSS del elemento'},r=(s,a)=>{let i=s.resolve(a);if(!i)throw new Error(`No encuentro "${a}" en la p\xE1gina. Usa get_page_context o find_on_page.`);return i};return[{name:"point_at",category:"ui",title:()=>t("widget.companion.pointAt"),description:"Tu avatar camina por la p\xE1gina hasta el elemento, lo se\xF1ala y dice el mensaje en un bocadillo (y en voz alta). \xDAsalo para ense\xF1ar d\xF3nde est\xE1 algo. El mensaje debe ser corto (una frase).",parameters:{type:"object",properties:{target:o,message:{type:"string",description:"Lo que dices al se\xF1alarlo (breve)"}},required:["target"]},handler:async({target:s,message:a=""},{context:i,signal:n})=>{let l=r(i,s);return await e.pointAt(l,a,{signal:n}),{ok:!0,data:`Se\xF1alado "${Th(l)}".`}}},{name:"tour",category:"ui",title:()=>t("widget.companion.tour"),description:'Visita guiada: tu avatar recorre varios elementos en orden, se\xF1alando y comentando cada uno. Ideal para "ens\xE9\xF1ame la p\xE1gina" o explicar un formulario. M\xE1ximo 8 pasos, mensajes breves.',parameters:{type:"object",properties:{steps:{type:"array",maxItems:8,items:{type:"object",properties:{target:o,message:{type:"string"}},required:["target","message"]}}},required:["steps"]},timeoutMs:12e4,handler:async({steps:s},{context:a,signal:i})=>{let n=await e.tour(s.slice(0,8),{signal:i,resolve:l=>a.resolve(l)});return e.home(),{ok:!0,data:`Recorrido hecho: ${n} de ${s.length} pasos.`}}},{name:"go_home",category:"ui",title:()=>t("widget.companion.goHome"),description:"Tu avatar vuelve a su rinc\xF3n de la pantalla.",parameters:{type:"object",properties:{}},handler:async()=>(await e.home(),{ok:!0})}]}function gr(e,t,o){return Math.max(t,Math.min(o,e))}function Jo(e,t){return new Promise(o=>{let r=setTimeout(o,e);t?.addEventListener("abort",()=>(clearTimeout(r),o()),{once:!0})})}function _h(e){return new Promise(t=>e?.addEventListener("abort",t,{once:!0}))}async function Eh(e){let t=null;for(let o=0;o<18;o++){await Jo(50);let r=e.getBoundingClientRect().top;if(t!==null&&Math.abs(r-t)<1)return;t=r}}function Th(e){return(e.getAttribute("aria-label")||e.querySelector?.("h1, h2, h3, legend")?.innerText||e.innerText||e.getAttribute("alt")||e.tagName.toLowerCase()).replace(/\s+/g," ").trim().slice(0,60)}Le();var er=class{constructor({bus:t,avatar:o,config:r={},store:s,t:a=le()}){this.bus=t,this.t=a,this.avatar=o,this.store=s,this.cfg={tts:"proxy",stt:!0,rate:1.05,pitch:1,lang:document.documentElement.lang||"es-ES",...r},this.muted=s.get("muted",!1),this._queue=[],this._speaking=!1,this._gen=0,this._rec=null,this.listening=!1}get canListen(){return!!(this.cfg.stt&&(window.SpeechRecognition||window.webkitSpeechRecognition))}configure(t={}){for(let[o,r]of Object.entries(t))r!==void 0&&(this.cfg[o]=r);t.tts!==void 0&&(this._proxyBroken=!1)}setMuted(t){this.muted=t,this.store.set("muted",t),t&&this.interrupt()}say(t){let o=Vi(t);return!o||this.muted||this.cfg.tts===!1?Promise.resolve():new Promise(r=>{this._queue.push({text:o,resolve:r}),this._drain()})}interrupt(){this._gen++;for(let t of this._queue)t.resolve();this._queue=[];try{speechSynthesis.cancel()}catch{}this.avatar?.stop()}async _drain(){if(!this._speaking){for(this._speaking=!0,this.bus.emit("voice:start",{});this._queue.length;){let{text:t,resolve:o}=this._queue.shift(),r=this._gen;try{await this._speakOne(t,r)}catch(s){console.warn("[7ots] voz fall\xF3:",s?.message||s)}o()}this._speaking=!1,this.bus.emit("voice:end",{})}}async _speakOne(t,o){if(this.cfg.tts==="proxy"&&this.cfg.endpoint&&!this._proxyBroken)try{let r=await this._fetchTts(t);return o!==this._gen?void 0:this.avatar?await this.avatar.speak({text:t,audio:r}):await Ch(r)}catch(r){(r.status===404||r.status===501)&&(this._proxyBroken=!0),console.warn("[7ots] TTS del proxy no disponible, uso la voz del navegador")}if(o===this._gen)return this._speakBrowser(t)}async _fetchTts(t){let o=await fetch(`${this.cfg.endpoint.replace(/\/$/,"")}/tts`,{method:"POST",headers:{"Content-Type":"application/json",...this.cfg.siteKey?{"X-Site-Key":this.cfg.siteKey}:{},...Zt(this.t.locale)},body:JSON.stringify({text:t,lang:this.cfg.lang})});if(!o.ok){let r=new Error(`TTS ${o.status}`);throw r.status=o.status,r}return o.arrayBuffer()}_speakBrowser(t){return"speechSynthesis"in window?new Promise(o=>{let r=new SpeechSynthesisUtterance(t);r.lang=this.cfg.lang,r.rate=this.cfg.rate,r.pitch=this.cfg.pitch??1;let s=Sh(this.cfg.lang,this.cfg.voice);s&&(r.voice=s);let a=t.length/14/r.rate*1e3;r.onstart=()=>this.avatar?.mimic({text:t,durationMs:a}),r.onboundary=i=>this.avatar?.mimicSync?.(i.charIndex),r.onend=r.onerror=()=>{this.avatar?.stop(),o()},speechSynthesis.speak(r)}):Promise.resolve()}listen({onPartial:t}={}){if(!this.canListen)return Promise.resolve("");this.interrupt();let o=window.SpeechRecognition||window.webkitSpeechRecognition,r=new o;r.lang=this.cfg.lang,r.interimResults=!0,r.continuous=!1,this._rec=r,this.listening=!0,this.bus.emit("voice:listen",{on:!0});let s="";return new Promise(a=>{r.onresult=i=>{let n="";for(let l=i.resultIndex;l<i.results.length;l++){let h=i.results[l];h.isFinal?s+=h[0].transcript:n+=h[0].transcript}t?.((s+n).trim())},r.onerror=i=>{i.error==="not-allowed"&&this.bus.emit("agent:error",{error:new Error(this.t("widget.voice.micDenied"))})},r.onend=()=>{this.listening=!1,this._rec=null,this.bus.emit("voice:listen",{on:!1}),a(s.trim())};try{r.start()}catch{r.onend()}})}stopListening(){try{this._rec?.stop()}catch{}}};function Sh(e,t){let o=speechSynthesis.getVoices();if(!o.length)return null;if(t){let s=o.find(a=>a.name===t||a.voiceURI===t);if(s)return s}let r=e.slice(0,2).toLowerCase();return o.find(s=>s.lang.toLowerCase()===e.toLowerCase()&&/natural|neural|google|online/i.test(s.name))||o.find(s=>s.lang.toLowerCase()===e.toLowerCase())||o.find(s=>s.lang.toLowerCase().startsWith(r))||null}async function Ch(e){let t=URL.createObjectURL(new Blob([e],{type:"audio/mpeg"})),o=new Audio(t);try{await o.play(),await new Promise(r=>o.onended=r)}finally{URL.revokeObjectURL(t)}}Le();var Ah=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;function ki({endpoint:e,siteKey:t,getTranscript:o,categories:r=["soporte","ventas","facturacion","otro"],t:s=le()}){return[{name:"send_email_ticket",category:"contact",description:"Env\xEDa un correo/ticket al equipo del sitio (v\xEDa apumail) con el resumen del caso y la conversaci\xF3n adjunta. \xDAsalo cuando el usuario quiere dejar un mensaje, pedir algo que requiere a una persona sin esperar en l\xEDnea, o reportar un problema. Antes, aseg\xFArate de tener un email de respuesta (el de la sesi\xF3n o uno que el usuario te d\xE9).",parameters:{type:"object",properties:{subject:{type:"string",description:"Asunto breve y concreto"},message:{type:"string",description:"Resumen claro del caso en tercera persona, con los datos relevantes"},category:{type:"string",enum:r},email:{type:"string",description:"Email de respuesta si el usuario no ha iniciado sesi\xF3n"},include_transcript:{type:"boolean",description:"Adjuntar la conversaci\xF3n (por defecto true)"}},required:["subject","message","category"]},confirm:(a,{auth:i})=>{let n=a.email||i?.publicUser()?.email||s("widget.contact.noEmail");return s("widget.contact.mailPreview",{subject:a.subject,to:n,message:a.message})},timeoutMs:2e4,handler:async(a,{auth:i})=>{let n=i?.publicUser()||null,l=(a.email||n?.email||"").trim();if(!Ah.test(l))return{ok:!1,error:"Falta un email de respuesta v\xE1lido. P\xEDdeselo al usuario."};let h=await fetch(`${e.replace(/\/$/,"")}/contact/apumail`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Zt(s.locale)},body:JSON.stringify({subject:a.subject,message:a.message,category:a.category,replyTo:l,user:n,page:{url:location.href,title:document.title},transcript:a.include_transcript===!1?[]:o().slice(-40)})}),u=await h.json().catch(()=>({}));return h.ok?{ok:!0,data:{sent:!0,ticketId:u.ticketId||null,replyTo:l}}:{ok:!1,error:u.error||`No se pudo enviar (HTTP ${h.status})`}}}]}Le();var Lh=8192,oa=class{constructor({endpoint:t,siteKey:o,bus:r,store:s,t:a=le()}){this.t=a,this.base=`${t.replace(/\/$/,"")}/contact/apuchat`,this.siteKey=o,this.bus=r,this.store=s,this.session=s.get("apuchat",null),this.session&&!this.session.token&&(this.session=null),this._stop=null}get active(){return!!this.session}get callUrl(){return this.session?.call_url_public||null}resume(){this.session&&!this._stop&&this._loop()}join({handoff_id:t,handoff_token:o,call_url_public:r}){this.session={id:t,token:o,since:null,call_url_public:r||null},this._save(),this._loop(),this.bus.emit("handoff:start",{callUrl:this.callUrl})}async send(t){if(!this.session)throw new Error("No hay conversaci\xF3n con una persona activa");let o=await this._post("send",{text:String(t).slice(0,Lh)});if(o.status===404||o.status===410)throw this.end(this.t("widget.handoff.closed")),new Error("canal cerrado");if(!o.ok)throw new Error(`apuchat send ${o.status}`)}_loop(){let t=!1,o=new AbortController;this._stop=()=>{t=!0,o.abort()},(async()=>{let s=1e3;for(;!t&&this.session;){let a=this.session;try{let i=await this._post("wait",{since:a.since},o.signal);if(i.status===404||i.status===410)return this.end(this.t("widget.handoff.closed"));if(!i.ok)throw new Error(`wait ${i.status}`);let{messages:n=[],since:l,ended:h}=await i.json();if(h)return this.end(this.t("widget.handoff.closed"));l!=null&&(a.since=l);for(let u of n)this.bus.emit("handoff:message",{from:u.from,text:u.text});this._save(),s=1e3}catch{if(t)return;await new Promise(n=>setTimeout(n,s)),s=Math.min(s*2,15e3)}}})()}end(t=""){if(this._stop?.(),this._stop=null,!this.session)return;let{id:o,token:r}=this.session;this.session=null,this.store.remove("apuchat"),this._post("end",{id:o,token:r},void 0,!0).catch(()=>{}),this.bus.emit("handoff:end",{reason:t})}suspend(){this._stop?.(),this._stop=null}_post(t,o,r,s=!1){let{id:a,token:i}=this.session||{};return fetch(`${this.base}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Zt(this.t.locale)},body:JSON.stringify({id:a,token:i,...o}),signal:r,keepalive:s})}_save(){this.store.set("apuchat",this.session)}};function vi({endpoint:e,siteKey:t,bridge:o,getTranscript:r,t:s=o?.t||le()}){return[{name:"escalate_to_human",category:"contact",description:"Conecta al usuario en vivo con una persona del equipo (chat en este mismo widget, con opci\xF3n de videollamada) v\xEDa apuchat. \xDAsalo si el usuario lo pide, si est\xE1 frustrado, o si el caso requiere una persona (pagos, reclamaciones, excepciones). Incluye un resumen para que la persona no tenga que volver a preguntar.",parameters:{type:"object",properties:{reason:{type:"string",description:"Motivo en pocas palabras"},summary:{type:"string",description:"Resumen del caso y lo que ya se intent\xF3"},urgency:{type:"string",enum:["baja","normal","alta"]}},required:["reason","summary"]},confirm:()=>s("widget.contact.humanConfirm"),enabled:()=>!o.active,timeoutMs:3e4,handler:async(a,{auth:i,ui:n})=>{let l=i?.publicUser()||null,h=await fetch(`${e.replace(/\/$/,"")}/contact/apuchat`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Zt(s.locale)},body:JSON.stringify({reason:a.reason,summary:a.summary,urgency:a.urgency||"normal",user:l,page:{url:location.href,title:document.title},transcript:r().slice(-30)})}),u=await h.json().catch(()=>({}));return h.ok?(o.join(u),await o.send(s("widget.contact.handoffIntro",{name:l?.name||s("widget.contact.visitor"),reason:a.reason,summary:a.summary,url:location.href})).catch(()=>{}),n?.toast({message:s("widget.contact.connected"),type:"success"}),{ok:!0,data:{connected:!0,operatorNotified:u.operatorNotified!==!1,note:"El usuario ya est\xE1 en el chat con una persona; tus pr\xF3ximos mensajes no ser\xE1n necesarios hasta que vuelva. Desp\xEDdete en una frase."}}):{ok:!1,error:u.error||`No se pudo contactar con soporte (HTTP ${h.status}). Ofrece dejar un correo.`}}}]}Nt();Le();Le();var Hh={identity:{card:{label:"Tarjeta de {name}",loadError:"No se pudo cargar la tarjeta del agente.",loading:"Cargando\u2026",chat:"Chatear aqu\xED",chatSub:"En esta p\xE1gina",mail:"Escribir un correo",mailInstant:"{email} \xB7 contesta al momento",mailSubject:"Hola, {name}",apuchatSub:"En la app de apuchat",apuchatInstant:"En la app de apuchat \xB7 contesta y te llama",apuchatCopied:"Copiado @{handle}: b\xFAscalo en la app de apuchat y escr\xEDbele.",apuchatSearch:"Busca @{handle} en la app de apuchat y escr\xEDbele.",call:"Videollamada ahora",callSub:"Cara a cara en meet.apuchat.com",callPreparing:"Preparando la llamada con {name}\u2026",callReady:"{name} ya te espera en la llamada.",callError:"No se pudo abrir la llamada: {error}",listen:"Escuchar su voz",save:"Guardar contacto",saveSub:"vCard",footer:"Identidad de agente"},greeting:{intro:"Hola, soy {name}.",introRole:"Hola, soy {name}, {role}.",offer:"\xBFEn qu\xE9 te ayudo?"},face:{subtitles:"Subt\xEDtulos",loadError:"No se pudo cargar la identidad ({status})"},prompt:{youAre:"Eres {name}.",youAreRole:"Eres {name}, {role}.",about:"Sobre ti: {bio}",tone:"Tu tono: {tone}.",traits:"Rasgos: {traits}."}}},Rh={identity:{card:{label:"{name}\u2019s card",loadError:"Couldn\u2019t load the agent\u2019s card.",loading:"Loading\u2026",chat:"Chat here",chatSub:"On this page",mail:"Send an email",mailInstant:"{email} \xB7 replies instantly",mailSubject:"Hi, {name}",apuchatSub:"In the apuchat app",apuchatInstant:"In the apuchat app \xB7 replies and calls you",apuchatCopied:"Copied @{handle}: look it up in the apuchat app and send a message.",apuchatSearch:"Look up @{handle} in the apuchat app and send a message.",call:"Video call now",callSub:"Face to face on meet.apuchat.com",callPreparing:"Setting up the call with {name}\u2026",callReady:"{name} is waiting for you on the call.",callError:"Couldn\u2019t open the call: {error}",listen:"Hear their voice",save:"Save contact",saveSub:"vCard",footer:"Agent identity"},greeting:{intro:"Hi, I\u2019m {name}.",introRole:"Hi, I\u2019m {name}, {role}.",offer:"How can I help you?"},face:{subtitles:"Subtitles",loadError:"Couldn\u2019t load the identity ({status})"},prompt:{youAre:"You are {name}.",youAreRole:"You are {name}, {role}.",about:"About you: {bio}",tone:"Your tone: {tone}.",traits:"Traits: {traits}."}}},Ph={identity:{card:{label:"Cart\xE3o de {name}",loadError:"N\xE3o foi poss\xEDvel carregar o cart\xE3o do agente.",loading:"Carregando\u2026",chat:"Conversar aqui",chatSub:"Nesta p\xE1gina",mail:"Enviar um e-mail",mailInstant:"{email} \xB7 responde na hora",mailSubject:"Ol\xE1, {name}",apuchatSub:"No app do apuchat",apuchatInstant:"No app do apuchat \xB7 responde e liga para voc\xEA",apuchatCopied:"Copiado @{handle}: procure no app do apuchat e mande uma mensagem.",apuchatSearch:"Procure @{handle} no app do apuchat e mande uma mensagem.",call:"Videochamada agora",callSub:"Cara a cara no meet.apuchat.com",callPreparing:"Preparando a chamada com {name}\u2026",callReady:"{name} j\xE1 est\xE1 esperando voc\xEA na chamada.",callError:"N\xE3o foi poss\xEDvel abrir a chamada: {error}",listen:"Ouvir a voz",save:"Salvar contato",saveSub:"vCard",footer:"Identidade de agente"},greeting:{intro:"Ol\xE1, eu sou {name}.",introRole:"Ol\xE1, eu sou {name}, {role}.",offer:"Como posso ajudar?"},face:{subtitles:"Legendas",loadError:"N\xE3o foi poss\xEDvel carregar a identidade ({status})"},prompt:{youAre:"Voc\xEA \xE9 {name}.",youAreRole:"Voc\xEA \xE9 {name}, {role}.",about:"Sobre voc\xEA: {bio}",tone:"Seu tom: {tone}.",traits:"Tra\xE7os: {traits}."}}};Tt({es:Hh,en:Rh,pt:Ph});var jh=["character","plush","image","realistic"];var zh=["plush","vinyl"],as=["shibu","shino","fumiriya","victoria","vita","vivi","kuro","maya","ingrid","kenji","viktor","marcus","leo","mei","claire","doctor","amira"],ss=["studio","beach","castle","space","sunset","forest","night","office","neon"],Oh=["auto","apuchat","elevenlabs","grok","fish","openai","browser"],qh=["eve","ara","leo","rex","sal"],Qh=["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"],Bh=["neutral","happy","angry","sad","fear","disgust","love","sleep"],tr=Object.freeze({id:"asistente",name:"Asistente",role:"asistente virtual",tagline:"",seed:"",bio:"",language:"es",languages:[],personality:{tone:"cercano y claro",traits:[],instructions:""},look:{kind:"",character:null,material:"plush",color:"#6d5dfc",accent:"#22d3ee",emoji:"",image:"",avatar:{url:"",body:"F",mood:"neutral",cameraView:"upper"},face:{skin:"",eyes:""},meetAvatar:"vivi",meetScene:""},voice:{provider:"auto",voiceId:"",model:"",style:"",lang:"es-ES",rate:1.05,pitch:1,browserVoice:""},contact:{site:"",email:"",apuchat:"",meet:!0,call:!0,hours:""}}),Nh={backstory:3e3,style:1500,quirks:1500,scenario:1500,greeting:600,examples:4e3};function vt(e={},t=tr){let o=e&&typeof e=="object"?e:{},r=t,s={...r.look,...os(o.look)},a={...r.voice,...os(o.voice)},i={...r.contact,...os(o.contact)},n={...r.personality,...os(o.personality)};return{id:Xl(o.id)||(r.id!==tr.id?r.id:Xl(o.name))||tr.id,name:ft(o.name??r.name,60)||tr.name,role:ft(o.role??r.role,120),tagline:ft(o.tagline??r.tagline,160),seed:String(o.seed??r.seed??"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),bio:ft(o.bio??r.bio,1200),language:Jl(o.language??r.language)||"es",languages:Kl(o.languages??r.languages,12).map(Jl).filter(Boolean),personality:{tone:ft(n.tone,120),traits:Kl(n.traits,12).map(h=>ft(h,40)).filter(Boolean),instructions:ft(n.instructions,4e3),sheet:Object.fromEntries(Object.entries(Nh).map(([h,u])=>[h,ft(n.sheet?.[h],u)]).filter(([,h])=>h))},look:{kind:jh.includes(s.kind)?s.kind:s.image?"image":"character",character:Be(s.character||{}),material:zh.includes(s.material)?s.material:"plush",color:rs(s.color)||tr.look.color,accent:rs(s.accent)||tr.look.accent,emoji:ft(s.emoji,8),image:Mi(s.image),card:{foil:["holo","prism","cosmos","gold","none"].includes(s.card?.foil)?s.card.foil:""},avatar:{url:Mi(s.avatar?.url),body:s.avatar?.body==="M"?"M":"F",mood:Bh.includes(s.avatar?.mood)?s.avatar.mood:"neutral",cameraView:["full","mid","upper","head"].includes(s.avatar?.cameraView)?s.avatar.cameraView:"upper"},face:{skin:rs(s.face?.skin),eyes:rs(s.face?.eyes)},meetAvatar:as.includes(String(s.meetAvatar).toLowerCase())?String(s.meetAvatar).toLowerCase():"vivi",meetScene:ss.includes(String(s.meetScene).toLowerCase())?String(s.meetScene).toLowerCase():""},voice:{provider:Oh.includes(a.provider)?a.provider:"auto",voiceId:ft(a.voiceId,80),model:ft(a.model,80),style:ft(a.style,400),lang:/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(String(a.lang))?a.lang:"es-ES",rate:ec(a.rate,.5,2,1.05),pitch:ec(a.pitch,0,2,1),browserVoice:ft(a.browserVoice,120)},contact:{site:Mi(i.site),email:/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(i.email||""))?String(i.email).toLowerCase():"",apuchat:String(i.apuchat||"").trim().replace(/^https?:\/\/[^/]+\//i,"").replace(/^@/,"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),meet:i.meet!==!1,call:i.call!==!1,hours:ft(i.hours,120)}}}function Gh(e,t={}){let o=t.apuchat||e.contact.apuchat||"";return{"@type":"7ots/agent",version:1,id:e.id,name:e.name,role:e.role,tagline:e.tagline,seed:e.seed||void 0,bio:e.bio,language:e.language,languages:e.languages,personality:{tone:e.personality.tone,traits:e.personality.traits},look:e.look,voice:{provider:e.voice.provider,lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,browserVoice:e.voice.browserVoice},contact:{site:e.contact.site,hours:e.contact.hours,email:e.contact.email,apuchat:o,meet:!!(e.contact.meet&&o&&t.meet!==!1),call:!!(e.contact.call&&t.meet),answers:{email:!!t.email,apuchat:!!t.apuchat,meet:!!t.meet}}}}function Dh(e,{baseUrl:t=""}={}){let o=s=>String(s||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/([,;])/g,"\\$1"),r=["BEGIN:VCARD","VERSION:4.0","KIND:individual",`FN:${o(e.name)}`,`UID:urn:7ots:${e.id}`];return e.role&&r.push(`TITLE:${o(e.role)}`),(e.bio||e.tagline)&&r.push(`NOTE:${o(e.tagline||e.bio)}`),e.contact.email&&r.push(`EMAIL;TYPE=work:${e.contact.email}`),e.contact.apuchat&&r.push(`IMPP;PREF=1:apuchat:${e.contact.apuchat}`),e.contact.site&&r.push(`URL:${e.contact.site}`),e.look.image&&r.push(`PHOTO:${e.look.image}`),e.language&&r.push(`LANG:${e.language}`),t&&r.push(`SOURCE:${t}`),r.push("END:VCARD"),r.join(`\r
412
+ <span class="b-arrow" aria-hidden="true" hidden></span>`,"popover"in t&&(t.popover="manual"),this.root.appendChild(t),this.el=t,this._raise(),this.stage&&t.querySelector(".b-stage").appendChild(this.stage),t.style.setProperty("--bs",`${this.size}px`);let o=t.querySelector(".b-body"),r=null;o.addEventListener("pointerdown",i=>{i.button===0&&(r={sx:i.clientX,sy:i.clientY,x:this.x,y:this.y,moved:!1},o.setPointerCapture(i.pointerId))}),o.addEventListener("pointermove",i=>{if(!r)return;let n=i.clientX-r.sx,l=i.clientY-r.sy;!r.moved&&Math.hypot(n,l)<6||(r.moved=!0,this._anchor=null,this._place(r.x+n,r.y+l,0))}),o.addEventListener("pointerup",()=>{r?.moved?this._home={x:this.x,y:this.y}:r&&this.onActivate?.(),r=null}),o.addEventListener("pointercancel",()=>r=null),t.querySelector(".b-say").addEventListener("click",()=>this.onActivate?.());let s=0,a=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{t.style.setProperty("--bs",`${this.size}px`),this._anchor?.isConnected?this._placeNear(this._anchor,0):this.home({instant:!0})})};addEventListener("scroll",a,{passive:!0,capture:!0}),addEventListener("resize",a),this._offs.push(()=>removeEventListener("scroll",a,{capture:!0}),()=>removeEventListener("resize",a)),this.home({instant:!0}),this._idleLook(),this.setBehavior(this.cfg)}relabel(){let t=this.el?.querySelector(".b-body");t&&(t.setAttribute("aria-label",this.t("widget.companion.talkTo",{name:this.name})),t.title=this.name)}setBehavior({wanderMs:t=this.cfg.wanderMs,watchCursor:o=this.cfg.watchCursor}={}){if(this.cfg.wanderMs=t,this.cfg.watchCursor=o,this._scheduleWander(),this._offCursor?.(),this._offCursor=null,o){let r=0,s=a=>{let i=Date.now();i-r<300||this._busyLooking()||(r=i,this.avatar?.lookAt?.(a.clientX,a.clientY,700))};addEventListener("pointermove",s,{passive:!0}),this._offCursor=()=>removeEventListener("pointermove",s),this._offs.push(()=>this._offCursor?.())}}_busyLooking(){return document.hidden||this.el.classList.contains("walking")||!this.el.querySelector(".b-arrow").hidden}_scheduleWander(){clearTimeout(this._timers.wander);let t=this.cfg.wanderMs;t&&(this._timers.wander=setTimeout(()=>{this._wander().finally(()=>this._scheduleWander())},t*(.7+Math.random()*.6)))}async _wander(){if(document.hidden||this._anchor||!this.canWander()||!this.el.querySelector(".b-say").hidden)return;let t=this.size,o=[...document.querySelectorAll("h1, h2, h3, img, button, a[class*=btn], a[class*=button], [class*=card], figure, table")].filter(a=>{if(a.closest("[data-ots-root], [data-ots-ignore]"))return!1;let i=a.getBoundingClientRect();return i.width>30&&i.height>16&&i.top>40&&i.bottom<innerHeight-40&&i.width<innerWidth*.9&&a!==this._lastWander});if(!o.length)return;let r=o[Math.floor(Math.random()*o.length)];if(this._lastWander=r,this.el.classList.add("curious"),await this._placeNear(r),this._anchor)return this.el.classList.remove("curious");let s=r.getBoundingClientRect();this.avatar?.lookAt?.(s.left+s.width/2,s.top+s.height/2,2e3),Math.random()<.35&&this.avatar?.gesture?.(["index","shrug","handup"][Math.floor(Math.random()*3)],1.6,s.left+s.width/2<this.x+t/2),await Jo(2600+Math.random()*2e3),this.el.classList.remove("curious"),!this._anchor&&this.canWander()&&this.home()}destroy(){Object.values(this._timers).forEach(clearTimeout),this._offs.forEach(t=>t()),this.el?.remove()}panelChanged(t){this.el.classList.toggle("behind",t&&innerWidth<640),(t||!this._anchor)&&this.home()}home({instant:t=!1}={}){this._anchor=null;let o=this.size,r,s;if(this._home)({x:r,y:s}=this._home);else{let i=this.panelOpen()&&innerWidth>=640?Math.min(380,innerWidth-24)+32:20;r=this.side==="left"?i:innerWidth-o-i,s=innerHeight-o-20}return this._place(r,s,t?0:void 0)}async goTo(t){if(!t?.isConnected)throw new Error("El elemento ya no est\xE1 en la p\xE1gina");let o=t.getBoundingClientRect();(o.bottom<0||o.top>innerHeight||o.right<0||o.left>innerWidth)&&(Oo(t),await Eh(t)),this._anchor=t,await this._placeNear(t),this._touch()}async pointAt(t,o="",{signal:r}={}){if(await this.goTo(t),r?.aborted)return;let s=t.getBoundingClientRect(),a=s.left+s.width/2,i=s.top+s.height/2,n=this.x+this.size/2;this.avatar?.lookAt?.(a,i,2500),this.avatar?.gesture?.("index",2.5,a<n),this._arrow(a,i),this.ui?.highlight?.(t,{duration:2600,scroll:!1}),o?await this.say(o,{signal:r}):await Jo(1200,r)}async tour(t,{signal:o,resolve:r}={}){let s=0;for(let a of t){if(o?.aborted)break;let i=r(a.target);i&&(await this.pointAt(i,a.message||"",{signal:o}),s++,await Jo(350,o))}return s}follow(t){!this.cfg.follow||!t?.isConnected||(this._anchor=t,this._placeNear(t),this._touch())}_placeNear(t,o){let r=this.size,s=t.getBoundingClientRect(),a=innerWidth,i=innerHeight,n=s.top+s.height/2-r/2,l=s.left+s.width/2-r/2,h=gr(n,st,i-r-st),u=gr(l,st,a-r-st),c=[s.right+ts,h],d=[s.left-r-ts,h],$=[...this.side==="left"?[d,c]:[c,d],[u,s.bottom+ts],[u,s.top-r-ts]],f=([x,v])=>x>=st&&v>=st&&x+r<=a-st&&v+r<=i-st,[m,g]=$.find(f)||[this.side==="left"?Math.max(s.left,0)+st:Math.min(s.right,a)-r-st,Math.max(s.top,0)+st];return this._place(m,g,o)}_place(t,o,r){let s=this.size;t=gr(t,st,innerWidth-s-st),o=gr(o,st,innerHeight-s-st);let a=Math.hypot(t-this.x,o-this.y),i=document.hidden||matchMedia("(prefers-reduced-motion: reduce)").matches,n=r??(i?0:gr(a*1.1,0,1300)),l=this.el;return n>0&&a>4&&(l.classList.add("walking"),l.classList.toggle("to-left",t<this.x),clearTimeout(this._timers.walk),this._timers.walk=setTimeout(()=>l.classList.remove("walking"),n)),this._raise(),l.style.transitionDuration=`${n}ms`,l.style.transform=`translate(${Math.round(t)}px, ${Math.round(o)}px)`,l.dataset.v=o<innerHeight/2?"top":"bottom",l.dataset.h=t+s/2<innerWidth/2?"left":"right",this.x=t,this.y=o,Jo(n)}_raise(){let t=this.el;if(t?.showPopover)try{if(t.matches(":popover-open")){if(!document.querySelector("dialog:modal"))return;t.hidePopover()}t.showPopover()}catch{}}_arrow(t,o){let r=this.el.querySelector(".b-arrow"),s=this.size/2,a=Math.atan2(o-(this.y+s),t-(this.x+s)),i=s*.95;r.style.transform=`translate(${s+Math.cos(a)*i}px, ${s+Math.sin(a)*i}px) rotate(${a}rad)`,r.hidden=!1,r.classList.remove("go"),r.offsetWidth,r.classList.add("go"),clearTimeout(this._timers.arrow),this._timers.arrow=setTimeout(()=>r.hidden=!0,2600)}async say(t,{speak:o=!0,signal:r}={}){let s=++this._sayToken,a=this.el.querySelector(".b-say"),i=String(t||"").trim();a.querySelector(".b-say-text").innerHTML=Ft(i.length>240?`${i.slice(0,237)}\u2026`:i),a.hidden=!1,this._touch();let n=gr(i.length*55,1800,9e3),l=o&&this.speak?this.speak(i).catch(()=>{}):null;await Promise.race([Promise.all([l||Jo(n),Jo(Math.min(n,1500))]),_h(r)]),clearTimeout(this._timers.say),this._timers.say=setTimeout(()=>{s===this._sayToken&&(a.hidden=!0)},2500)}hush(){this._sayToken++,this.el.querySelector(".b-say").hidden=!0}_touch(){clearTimeout(this._timers.idle),this._timers.idle=setTimeout(()=>{this._anchor&&this.home()},this.cfg.idleHomeMs)}_idleLook(){clearTimeout(this._timers.look),this._timers.look=setTimeout(()=>{!document.hidden&&!this.el.classList.contains("walking")&&this.avatar?.lookAt?.(Math.random()*innerWidth,Math.random()*innerHeight*.7,1200),this._idleLook()},7e3+Math.random()*9e3)}};function xi(e,{t=e.t||le()}={}){let o={type:"string",description:'Ref (p. ej. "e12") o selector CSS del elemento'},r=(s,a)=>{let i=s.resolve(a);if(!i)throw new Error(`No encuentro "${a}" en la p\xE1gina. Usa get_page_context o find_on_page.`);return i};return[{name:"point_at",category:"ui",title:()=>t("widget.companion.pointAt"),description:"Tu avatar camina por la p\xE1gina hasta el elemento, lo se\xF1ala y dice el mensaje en un bocadillo (y en voz alta). \xDAsalo para ense\xF1ar d\xF3nde est\xE1 algo. El mensaje debe ser corto (una frase).",parameters:{type:"object",properties:{target:o,message:{type:"string",description:"Lo que dices al se\xF1alarlo (breve)"}},required:["target"]},handler:async({target:s,message:a=""},{context:i,signal:n})=>{let l=r(i,s);return await e.pointAt(l,a,{signal:n}),{ok:!0,data:`Se\xF1alado "${Th(l)}".`}}},{name:"tour",category:"ui",title:()=>t("widget.companion.tour"),description:'Visita guiada: tu avatar recorre varios elementos en orden, se\xF1alando y comentando cada uno. Ideal para "ens\xE9\xF1ame la p\xE1gina" o explicar un formulario. M\xE1ximo 8 pasos, mensajes breves.',parameters:{type:"object",properties:{steps:{type:"array",maxItems:8,items:{type:"object",properties:{target:o,message:{type:"string"}},required:["target","message"]}}},required:["steps"]},timeoutMs:12e4,handler:async({steps:s},{context:a,signal:i})=>{let n=await e.tour(s.slice(0,8),{signal:i,resolve:l=>a.resolve(l)});return e.home(),{ok:!0,data:`Recorrido hecho: ${n} de ${s.length} pasos.`}}},{name:"go_home",category:"ui",title:()=>t("widget.companion.goHome"),description:"Tu avatar vuelve a su rinc\xF3n de la pantalla.",parameters:{type:"object",properties:{}},handler:async()=>(await e.home(),{ok:!0})}]}function gr(e,t,o){return Math.max(t,Math.min(o,e))}function Jo(e,t){return new Promise(o=>{let r=setTimeout(o,e);t?.addEventListener("abort",()=>(clearTimeout(r),o()),{once:!0})})}function _h(e){return new Promise(t=>e?.addEventListener("abort",t,{once:!0}))}async function Eh(e){let t=null;for(let o=0;o<18;o++){await Jo(50);let r=e.getBoundingClientRect().top;if(t!==null&&Math.abs(r-t)<1)return;t=r}}function Th(e){return(e.getAttribute("aria-label")||e.querySelector?.("h1, h2, h3, legend")?.innerText||e.innerText||e.getAttribute("alt")||e.tagName.toLowerCase()).replace(/\s+/g," ").trim().slice(0,60)}Le();var er=class{constructor({bus:t,avatar:o,config:r={},store:s,t:a=le()}){this.bus=t,this.t=a,this.avatar=o,this.store=s,this.cfg={tts:"proxy",stt:!0,rate:1.05,pitch:1,lang:document.documentElement.lang||"es-ES",...r},this.muted=s.get("muted",!1),this._queue=[],this._speaking=!1,this._gen=0,this._rec=null,this.listening=!1}get canListen(){return!!(this.cfg.stt&&(window.SpeechRecognition||window.webkitSpeechRecognition))}configure(t={}){for(let[o,r]of Object.entries(t))r!==void 0&&(this.cfg[o]=r);t.tts!==void 0&&(this._proxyBroken=!1)}setMuted(t){this.muted=t,this.store.set("muted",t),t&&this.interrupt()}say(t){let o=Vi(t);return!o||this.muted||this.cfg.tts===!1?Promise.resolve():new Promise(r=>{this._queue.push({text:o,resolve:r}),this._drain()})}interrupt(){this._gen++;for(let t of this._queue)t.resolve();this._queue=[];try{speechSynthesis.cancel()}catch{}this.avatar?.stop()}async _drain(){if(!this._speaking){for(this._speaking=!0,this.bus.emit("voice:start",{});this._queue.length;){let{text:t,resolve:o}=this._queue.shift(),r=this._gen;try{await this._speakOne(t,r)}catch(s){console.warn("[7ots] voz fall\xF3:",s?.message||s)}o()}this._speaking=!1,this.bus.emit("voice:end",{})}}async _speakOne(t,o){if(this.cfg.tts==="proxy"&&this.cfg.endpoint&&!this._proxyBroken)try{let r=await this._fetchTts(t);return o!==this._gen?void 0:this.avatar?await this.avatar.speak({text:t,audio:r}):await Ch(r)}catch(r){(r.status===404||r.status===501)&&(this._proxyBroken=!0),console.warn("[7ots] TTS del proxy no disponible, uso la voz del navegador")}if(o===this._gen)return this._speakBrowser(t)}async _fetchTts(t){let o=await fetch(`${this.cfg.endpoint.replace(/\/$/,"")}/tts`,{method:"POST",headers:{"Content-Type":"application/json",...this.cfg.siteKey?{"X-Site-Key":this.cfg.siteKey}:{},...Zt(this.t.locale)},body:JSON.stringify({text:t,lang:this.cfg.lang})});if(!o.ok){let r=new Error(`TTS ${o.status}`);throw r.status=o.status,r}return o.arrayBuffer()}_speakBrowser(t){return"speechSynthesis"in window?new Promise(o=>{let r=new SpeechSynthesisUtterance(t);r.lang=this.cfg.lang,r.rate=this.cfg.rate,r.pitch=this.cfg.pitch??1;let s=Sh(this.cfg.lang,this.cfg.voice);s&&(r.voice=s);let a=t.length/14/r.rate*1e3;r.onstart=()=>this.avatar?.mimic({text:t,durationMs:a}),r.onboundary=i=>this.avatar?.mimicSync?.(i.charIndex),r.onend=r.onerror=()=>{this.avatar?.stop(),o()},speechSynthesis.speak(r)}):Promise.resolve()}listen({onPartial:t}={}){if(!this.canListen)return Promise.resolve("");this.interrupt();let o=window.SpeechRecognition||window.webkitSpeechRecognition,r=new o;r.lang=this.cfg.lang,r.interimResults=!0,r.continuous=!1,this._rec=r,this.listening=!0,this.bus.emit("voice:listen",{on:!0});let s="";return new Promise(a=>{r.onresult=i=>{let n="";for(let l=i.resultIndex;l<i.results.length;l++){let h=i.results[l];h.isFinal?s+=h[0].transcript:n+=h[0].transcript}t?.((s+n).trim())},r.onerror=i=>{i.error==="not-allowed"&&this.bus.emit("agent:error",{error:new Error(this.t("widget.voice.micDenied"))})},r.onend=()=>{this.listening=!1,this._rec=null,this.bus.emit("voice:listen",{on:!1}),a(s.trim())};try{r.start()}catch{r.onend()}})}stopListening(){try{this._rec?.stop()}catch{}}};function Sh(e,t){let o=speechSynthesis.getVoices();if(!o.length)return null;if(t){let s=o.find(a=>a.name===t||a.voiceURI===t);if(s)return s}let r=e.slice(0,2).toLowerCase();return o.find(s=>s.lang.toLowerCase()===e.toLowerCase()&&/natural|neural|google|online/i.test(s.name))||o.find(s=>s.lang.toLowerCase()===e.toLowerCase())||o.find(s=>s.lang.toLowerCase().startsWith(r))||null}async function Ch(e){let t=URL.createObjectURL(new Blob([e],{type:"audio/mpeg"})),o=new Audio(t);try{await o.play(),await new Promise(r=>o.onended=r)}finally{URL.revokeObjectURL(t)}}Le();var Ah=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;function ki({endpoint:e,siteKey:t,getTranscript:o,categories:r=["soporte","ventas","facturacion","otro"],t:s=le()}){return[{name:"send_email_ticket",category:"contact",description:"Env\xEDa un correo/ticket al equipo del sitio (v\xEDa apumail) con el resumen del caso y la conversaci\xF3n adjunta. \xDAsalo cuando el usuario quiere dejar un mensaje, pedir algo que requiere a una persona sin esperar en l\xEDnea, o reportar un problema. Antes, aseg\xFArate de tener un email de respuesta (el de la sesi\xF3n o uno que el usuario te d\xE9).",parameters:{type:"object",properties:{subject:{type:"string",description:"Asunto breve y concreto"},message:{type:"string",description:"Resumen claro del caso en tercera persona, con los datos relevantes"},category:{type:"string",enum:r},email:{type:"string",description:"Email de respuesta si el usuario no ha iniciado sesi\xF3n"},include_transcript:{type:"boolean",description:"Adjuntar la conversaci\xF3n (por defecto true)"}},required:["subject","message","category"]},confirm:(a,{auth:i})=>{let n=a.email||i?.publicUser()?.email||s("widget.contact.noEmail");return s("widget.contact.mailPreview",{subject:a.subject,to:n,message:a.message})},timeoutMs:2e4,handler:async(a,{auth:i})=>{let n=i?.publicUser()||null,l=(a.email||n?.email||"").trim();if(!Ah.test(l))return{ok:!1,error:"Falta un email de respuesta v\xE1lido. P\xEDdeselo al usuario."};let h=await fetch(`${e.replace(/\/$/,"")}/contact/apumail`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Zt(s.locale)},body:JSON.stringify({subject:a.subject,message:a.message,category:a.category,replyTo:l,user:n,page:{url:location.href,title:document.title},transcript:a.include_transcript===!1?[]:o().slice(-40)})}),u=await h.json().catch(()=>({}));return h.ok?{ok:!0,data:{sent:!0,ticketId:u.ticketId||null,replyTo:l}}:{ok:!1,error:u.error||`No se pudo enviar (HTTP ${h.status})`}}}]}Le();var Lh=8192,oa=class{constructor({endpoint:t,siteKey:o,bus:r,store:s,t:a=le()}){this.t=a,this.base=`${t.replace(/\/$/,"")}/contact/apuchat`,this.siteKey=o,this.bus=r,this.store=s,this.session=s.get("apuchat",null),this.session&&!this.session.token&&(this.session=null),this._stop=null}get active(){return!!this.session}get callUrl(){return this.session?.call_url_public||null}resume(){this.session&&!this._stop&&this._loop()}join({handoff_id:t,handoff_token:o,call_url_public:r}){this.session={id:t,token:o,since:null,call_url_public:r||null},this._save(),this._loop(),this.bus.emit("handoff:start",{callUrl:this.callUrl})}async send(t){if(!this.session)throw new Error("No hay conversaci\xF3n con una persona activa");let o=await this._post("send",{text:String(t).slice(0,Lh)});if(o.status===404||o.status===410)throw this.end(this.t("widget.handoff.closed")),new Error("canal cerrado");if(!o.ok)throw new Error(`apuchat send ${o.status}`)}_loop(){let t=!1,o=new AbortController;this._stop=()=>{t=!0,o.abort()},(async()=>{let s=1e3;for(;!t&&this.session;){let a=this.session;try{let i=await this._post("wait",{since:a.since},o.signal);if(i.status===404||i.status===410)return this.end(this.t("widget.handoff.closed"));if(!i.ok)throw new Error(`wait ${i.status}`);let{messages:n=[],since:l,ended:h}=await i.json();if(h)return this.end(this.t("widget.handoff.closed"));l!=null&&(a.since=l);for(let u of n)this.bus.emit("handoff:message",{from:u.from,text:u.text});this._save(),s=1e3}catch{if(t)return;await new Promise(n=>setTimeout(n,s)),s=Math.min(s*2,15e3)}}})()}end(t=""){if(this._stop?.(),this._stop=null,!this.session)return;let{id:o,token:r}=this.session;this.session=null,this.store.remove("apuchat"),this._post("end",{id:o,token:r},void 0,!0).catch(()=>{}),this.bus.emit("handoff:end",{reason:t})}suspend(){this._stop?.(),this._stop=null}_post(t,o,r,s=!1){let{id:a,token:i}=this.session||{};return fetch(`${this.base}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Zt(this.t.locale)},body:JSON.stringify({id:a,token:i,...o}),signal:r,keepalive:s})}_save(){this.store.set("apuchat",this.session)}};function vi({endpoint:e,siteKey:t,bridge:o,getTranscript:r,t:s=o?.t||le()}){return[{name:"escalate_to_human",category:"contact",description:"Conecta al usuario en vivo con una persona del equipo (chat en este mismo widget, con opci\xF3n de videollamada) v\xEDa apuchat. \xDAsalo si el usuario lo pide, si est\xE1 frustrado, o si el caso requiere una persona (pagos, reclamaciones, excepciones). Incluye un resumen para que la persona no tenga que volver a preguntar.",parameters:{type:"object",properties:{reason:{type:"string",description:"Motivo en pocas palabras"},summary:{type:"string",description:"Resumen del caso y lo que ya se intent\xF3"},urgency:{type:"string",enum:["baja","normal","alta"]}},required:["reason","summary"]},confirm:()=>s("widget.contact.humanConfirm"),enabled:()=>!o.active,timeoutMs:3e4,handler:async(a,{auth:i,ui:n})=>{let l=i?.publicUser()||null,h=await fetch(`${e.replace(/\/$/,"")}/contact/apuchat`,{method:"POST",headers:{"Content-Type":"application/json",...t?{"X-Site-Key":t}:{},...Zt(s.locale)},body:JSON.stringify({reason:a.reason,summary:a.summary,urgency:a.urgency||"normal",user:l,page:{url:location.href,title:document.title},transcript:r().slice(-30)})}),u=await h.json().catch(()=>({}));return h.ok?(o.join(u),await o.send(s("widget.contact.handoffIntro",{name:l?.name||s("widget.contact.visitor"),reason:a.reason,summary:a.summary,url:location.href})).catch(()=>{}),n?.toast({message:s("widget.contact.connected"),type:"success"}),{ok:!0,data:{connected:!0,operatorNotified:u.operatorNotified!==!1,note:"El usuario ya est\xE1 en el chat con una persona; tus pr\xF3ximos mensajes no ser\xE1n necesarios hasta que vuelva. Desp\xEDdete en una frase."}}):{ok:!1,error:u.error||`No se pudo contactar con soporte (HTTP ${h.status}). Ofrece dejar un correo.`}}}]}Nt();Le();Le();var Hh={identity:{card:{label:"Tarjeta de {name}",loadError:"No se pudo cargar la tarjeta del agente.",loading:"Cargando\u2026",chat:"Chatear aqu\xED",chatSub:"En esta p\xE1gina",mail:"Escribir un correo",mailInstant:"{email} \xB7 contesta al momento",mailSubject:"Hola, {name}",apuchatSub:"En la app de apuchat",apuchatInstant:"En la app de apuchat \xB7 contesta y te llama",apuchatCopied:"Copiado @{handle}: b\xFAscalo en la app de apuchat y escr\xEDbele.",apuchatSearch:"Busca @{handle} en la app de apuchat y escr\xEDbele.",call:"Videollamada ahora",callSub:"Cara a cara en meet.apuchat.com",callPreparing:"Preparando la llamada con {name}\u2026",callReady:"{name} ya te espera en la llamada.",callError:"No se pudo abrir la llamada: {error}",listen:"Escuchar su voz",save:"Guardar contacto",saveSub:"vCard",footer:"Identidad de agente"},greeting:{intro:"Hola, soy {name}.",introRole:"Hola, soy {name}, {role}.",offer:"\xBFEn qu\xE9 te ayudo?"},face:{subtitles:"Subt\xEDtulos",loadError:"No se pudo cargar la identidad ({status})"},prompt:{youAre:"Eres {name}.",youAreRole:"Eres {name}, {role}.",about:"Sobre ti: {bio}",tone:"Tu tono: {tone}.",traits:"Rasgos: {traits}."}}},Rh={identity:{card:{label:"{name}\u2019s card",loadError:"Couldn\u2019t load the agent\u2019s card.",loading:"Loading\u2026",chat:"Chat here",chatSub:"On this page",mail:"Send an email",mailInstant:"{email} \xB7 replies instantly",mailSubject:"Hi, {name}",apuchatSub:"In the apuchat app",apuchatInstant:"In the apuchat app \xB7 replies and calls you",apuchatCopied:"Copied @{handle}: look it up in the apuchat app and send a message.",apuchatSearch:"Look up @{handle} in the apuchat app and send a message.",call:"Video call now",callSub:"Face to face on meet.apuchat.com",callPreparing:"Setting up the call with {name}\u2026",callReady:"{name} is waiting for you on the call.",callError:"Couldn\u2019t open the call: {error}",listen:"Hear their voice",save:"Save contact",saveSub:"vCard",footer:"Agent identity"},greeting:{intro:"Hi, I\u2019m {name}.",introRole:"Hi, I\u2019m {name}, {role}.",offer:"How can I help you?"},face:{subtitles:"Subtitles",loadError:"Couldn\u2019t load the identity ({status})"},prompt:{youAre:"You are {name}.",youAreRole:"You are {name}, {role}.",about:"About you: {bio}",tone:"Your tone: {tone}.",traits:"Traits: {traits}."}}},Ph={identity:{card:{label:"Cart\xE3o de {name}",loadError:"N\xE3o foi poss\xEDvel carregar o cart\xE3o do agente.",loading:"Carregando\u2026",chat:"Conversar aqui",chatSub:"Nesta p\xE1gina",mail:"Enviar um e-mail",mailInstant:"{email} \xB7 responde na hora",mailSubject:"Ol\xE1, {name}",apuchatSub:"No app do apuchat",apuchatInstant:"No app do apuchat \xB7 responde e liga para voc\xEA",apuchatCopied:"Copiado @{handle}: procure no app do apuchat e mande uma mensagem.",apuchatSearch:"Procure @{handle} no app do apuchat e mande uma mensagem.",call:"Videochamada agora",callSub:"Cara a cara no meet.apuchat.com",callPreparing:"Preparando a chamada com {name}\u2026",callReady:"{name} j\xE1 est\xE1 esperando voc\xEA na chamada.",callError:"N\xE3o foi poss\xEDvel abrir a chamada: {error}",listen:"Ouvir a voz",save:"Salvar contato",saveSub:"vCard",footer:"Identidade de agente"},greeting:{intro:"Ol\xE1, eu sou {name}.",introRole:"Ol\xE1, eu sou {name}, {role}.",offer:"Como posso ajudar?"},face:{subtitles:"Legendas",loadError:"N\xE3o foi poss\xEDvel carregar a identidade ({status})"},prompt:{youAre:"Voc\xEA \xE9 {name}.",youAreRole:"Voc\xEA \xE9 {name}, {role}.",about:"Sobre voc\xEA: {bio}",tone:"Seu tom: {tone}.",traits:"Tra\xE7os: {traits}."}}};Tt({es:Hh,en:Rh,pt:Ph});var jh=["character","plush","image","realistic"];var zh=["plush","vinyl"],as=["shibu","shino","fumiriya","victoria","vita","vivi","kuro","maya","ingrid","kenji","viktor","marcus","leo","mei","claire","doctor","amira"],ss=["studio","beach","castle","space","sunset","forest","night","office","neon"],Oh=["auto","apuchat","elevenlabs","grok","fish","openai","browser"],qh=["eve","ara","leo","rex","sal"];var Qh=["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"],Bh=["neutral","happy","angry","sad","fear","disgust","love","sleep"],tr=Object.freeze({id:"asistente",name:"Asistente",role:"asistente virtual",tagline:"",seed:"",bio:"",language:"es",languages:[],personality:{tone:"cercano y claro",traits:[],instructions:""},look:{kind:"",character:null,material:"plush",color:"#6d5dfc",accent:"#22d3ee",emoji:"",image:"",avatar:{url:"",body:"F",mood:"neutral",cameraView:"upper"},face:{skin:"",eyes:""},meetAvatar:"vivi",meetScene:""},voice:{provider:"auto",voiceId:"",model:"",style:"",lang:"es-ES",rate:1.05,pitch:1,browserVoice:""},contact:{site:"",email:"",apuchat:"",meet:!0,call:!0,hours:""}}),Nh={backstory:3e3,style:1500,quirks:1500,scenario:1500,greeting:600,examples:4e3};function vt(e={},t=tr){let o=e&&typeof e=="object"?e:{},r=t,s={...r.look,...os(o.look)},a={...r.voice,...os(o.voice)},i={...r.contact,...os(o.contact)},n={...r.personality,...os(o.personality)};return{id:Xl(o.id)||(r.id!==tr.id?r.id:Xl(o.name))||tr.id,name:ft(o.name??r.name,60)||tr.name,role:ft(o.role??r.role,120),tagline:ft(o.tagline??r.tagline,160),seed:String(o.seed??r.seed??"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),bio:ft(o.bio??r.bio,1200),language:Jl(o.language??r.language)||"es",languages:Kl(o.languages??r.languages,12).map(Jl).filter(Boolean),personality:{tone:ft(n.tone,120),traits:Kl(n.traits,12).map(h=>ft(h,40)).filter(Boolean),instructions:ft(n.instructions,4e3),sheet:Object.fromEntries(Object.entries(Nh).map(([h,u])=>[h,ft(n.sheet?.[h],u)]).filter(([,h])=>h))},look:{kind:jh.includes(s.kind)?s.kind:s.image?"image":"character",character:Be(s.character||{}),material:zh.includes(s.material)?s.material:"plush",color:rs(s.color)||tr.look.color,accent:rs(s.accent)||tr.look.accent,emoji:ft(s.emoji,8),image:Mi(s.image),card:{foil:["holo","prism","cosmos","gold","none"].includes(s.card?.foil)?s.card.foil:""},avatar:{url:Mi(s.avatar?.url),body:s.avatar?.body==="M"?"M":"F",mood:Bh.includes(s.avatar?.mood)?s.avatar.mood:"neutral",cameraView:["full","mid","upper","head"].includes(s.avatar?.cameraView)?s.avatar.cameraView:"upper"},face:{skin:rs(s.face?.skin),eyes:rs(s.face?.eyes)},meetAvatar:as.includes(String(s.meetAvatar).toLowerCase())?String(s.meetAvatar).toLowerCase():"vivi",meetScene:ss.includes(String(s.meetScene).toLowerCase())?String(s.meetScene).toLowerCase():""},voice:{provider:Oh.includes(a.provider)?a.provider:"auto",voiceId:ft(a.voiceId,80),model:ft(a.model,80),style:ft(a.style,400),lang:/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(String(a.lang))?a.lang:"es-ES",rate:ec(a.rate,.5,2,1.05),pitch:ec(a.pitch,0,2,1),browserVoice:ft(a.browserVoice,120)},contact:{site:Mi(i.site),email:/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(i.email||""))?String(i.email).toLowerCase():"",apuchat:String(i.apuchat||"").trim().replace(/^https?:\/\/[^/]+\//i,"").replace(/^@/,"").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,32),meet:i.meet!==!1,call:i.call!==!1,hours:ft(i.hours,120)}}}function Gh(e,t={}){let o=t.apuchat||e.contact.apuchat||"";return{"@type":"7ots/agent",version:1,id:e.id,name:e.name,role:e.role,tagline:e.tagline,seed:e.seed||void 0,bio:e.bio,language:e.language,languages:e.languages,personality:{tone:e.personality.tone,traits:e.personality.traits},look:e.look,voice:{provider:e.voice.provider,lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,browserVoice:e.voice.browserVoice},contact:{site:e.contact.site,hours:e.contact.hours,email:e.contact.email,apuchat:o,meet:!!(e.contact.meet&&o&&t.meet!==!1),call:!!(e.contact.call&&t.meet),answers:{email:!!t.email,apuchat:!!t.apuchat,meet:!!t.meet}}}}function Dh(e,{baseUrl:t=""}={}){let o=s=>String(s||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/([,;])/g,"\\$1"),r=["BEGIN:VCARD","VERSION:4.0","KIND:individual",`FN:${o(e.name)}`,`UID:urn:7ots:${e.id}`];return e.role&&r.push(`TITLE:${o(e.role)}`),(e.bio||e.tagline)&&r.push(`NOTE:${o(e.tagline||e.bio)}`),e.contact.email&&r.push(`EMAIL;TYPE=work:${e.contact.email}`),e.contact.apuchat&&r.push(`IMPP;PREF=1:apuchat:${e.contact.apuchat}`),e.contact.site&&r.push(`URL:${e.contact.site}`),e.look.image&&r.push(`PHOTO:${e.look.image}`),e.language&&r.push(`LANG:${e.language}`),t&&r.push(`SOURCE:${t}`),r.push("END:VCARD"),r.join(`\r
413
413
  `)+`\r
414
414
  `}function or(e){let t=e.look.avatar,o=e.look.kind||"character",r=o==="plush"?{mode:"3d-plush",character:e.look.character,material:e.look.material||"plush",mood:t.mood}:o==="image"&&e.look.image?{mode:"2d",image:e.look.image,face:e.look.face,mood:t.mood}:{mode:"2d",character:e.look.character,mood:t.mood};return{agent:{name:e.name,role:e.role,language:e.language},avatar:r,voice:{lang:e.voice.lang,rate:e.voice.rate,pitch:e.voice.pitch,...e.voice.browserVoice?{voice:e.voice.browserVoice}:{},...e.voice.provider==="browser"?{tts:"browser"}:{}},theme:{primary:e.look.color,accent:e.look.accent}}}function os(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ft(e,t){return e==null?"":String(e).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g,"").trim().slice(0,t)}function Kl(e,t){return typeof e=="string"&&(e=e.split(",")),Array.isArray(e)?e.slice(0,t):[]}function Xl(e){return String(e||"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function Jl(e){let t=String(e||"").trim().toLowerCase().match(/^[a-z]{2,3}/);return t?t[0]:""}function rs(e){let t=String(e||"").trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)?t:""}function Mi(e){let t=String(e||"").trim();if(!t)return"";if(t.startsWith("/")&&!t.startsWith("//"))return t.slice(0,500);try{let o=new URL(t);return o.protocol==="https:"||o.protocol==="http:"?o.href.slice(0,500):""}catch{return""}}function ec(e,t,o,r){let s=Number(e);return Number.isFinite(s)?Math.min(o,Math.max(t,s)):r}Le();var Ih=new Set(["click","hover","type_text","press_key","drag_and_drop","fill_form","highlight","scroll_to","read_element"]),tc={endpoint:"/api/agent",siteKey:null,llm:null,agent:{name:null,role:"asistente virtual",language:null,instructions:"",expressive:!0},locale:null,avatar:{},voice:{},auth:{},context:{},navigation:{},proactive:{},actions:[],mcp:[],templates:{},contact:{apuchat:!0,apumail:!0},theme:{},open:!1,confirmClicks:"submit",pointer:{},pageTools:!0,mode:"panel",companion:{},namespace:"default",identity:null},is=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this._started=!1,this._offs=[]}connectedCallback(){this.setAttribute("data-ots-root","widget"),!this._started&&!this._pendingConfig&&queueMicrotask(()=>{if(this._started)return;let t=o=>this.getAttribute(o);this.configure({endpoint:t("endpoint")||void 0,siteKey:t("site-key")||void 0,identity:t("identity")===""||t("identity")==="true"?!0:t("identity")||void 0,locale:t("locale")||void 0,agent:{name:t("name")||void 0,siteName:t("site-name")||void 0},avatar:t("avatar")==="false"?!1:t("avatar-url")?{url:t("avatar-url")}:{}})})}disconnectedCallback(){queueMicrotask(()=>{this.isConnected||this.destroy()})}configure(t={}){if(this._started)return this;this._started=!0;let o=t.identity;this._userConfig=t,this.identity=o&&typeof o=="object"?vt(o):null;let r=this.identity?Ei(tc,or(this.identity)):tc,s=this.config=Ei(r,t);this._t=le(lt(s.locale));let a=this.t=(c,d)=>this._t(c,d);Object.defineProperty(a,"locale",{get:()=>this._t.locale}),a.has=c=>this._t.has(c),this._autoName=!s.agent.name,this._autoName&&(s.agent.name=a("widget.defaultName")),this._voiceLangAuto=s.voice!==!1&&!s.voice?.lang;let i=this._voiceLangAuto?_i(a.locale,[s.locale,s.agent.language]):s.voice?.lang||_i(a.locale);this.bus=new zo,this.store=sr(s.namespace),this.auth=new Hr({bus:this.bus,config:s.auth}),this.ui=new Cr({bus:this.bus,theme:s.theme,t:a}),this.context=new Er({bus:this.bus,...s.context}),this.pointer=s.pointer===!1?null:new Rr({name:s.agent.name,color:s.theme.primary||"#4f46e5",t:a,...s.pointer,onCancel:()=>{this.brain?.abort(),this.ui.toast({message:a("widget.pointer.stopped"),type:"info"})}}),this.actions=new Sr({bus:this.bus,auth:this.auth,ui:this.ui,context:this.context,pointer:this.pointer,agent:null,t:a}),this.llm=s.llm||new jr({endpoint:s.endpoint,siteKey:s.siteKey,locale:()=>a.locale}),this.brain=new _r({llm:this.llm,actions:this.actions,context:this.context,auth:this.auth,bus:this.bus,store:this.store,t:a,persona:{...s.agent,locale:a.locale,siteName:s.agent.siteName||document.title.split(/[|–—-]/)[0].trim(),instructions:[s.agent.instructions,s.mode==="companion"?"Modo compa\xF1ero: tu avatar vive SOBRE la p\xE1gina, no solo en el chat. Cuando hables de algo que est\xE1 en pantalla, ve y se\xF1\xE1lalo con point_at (mensaje de una frase); para explicar varias cosas usa tour. S\xE9 cercano y juguet\xF3n, pero breve.":""].filter(Boolean).join(`
415
415
  `)}});let n=new Set(s.builtins?.exclude||[]);this.actions.registerMany(Ls({navigation:s.navigation,confirmClicks:s.builtins?.confirmClicks??s.confirmClicks,beforeNavigate:(c,d)=>this._beforeNavigate(c,d),pointer:this.pointer,t:a}).filter(c=>!n.has(c.name))),this.pageTools=s.pageTools===!1?null:new Pr({actions:this.actions,context:this.context,bus:this.bus,pointer:this.pointer,t:a});let l=()=>this.brain.transcript();if(this.apuchat=null,s.contact?.apumail){let c=typeof s.contact.apumail=="object"?s.contact.apumail:{};this.actions.registerMany(ki({endpoint:s.endpoint,siteKey:s.siteKey,getTranscript:l,t:a,...c}))}s.contact?.apuchat&&(this.apuchat=new oa({endpoint:s.endpoint,siteKey:s.siteKey,bus:this.bus,store:this.store,t:a}),this.actions.registerMany(vi({endpoint:s.endpoint,siteKey:s.siteKey,bridge:this.apuchat,getTranscript:l,t:a})));for(let c of s.actions)this.actions.register(c);for(let[c,d]of Object.entries(s.templates))this.ui.registerTemplate(c,d);if(this._render(),this.avatar=s.avatar===!1?null:new Xo({container:this.$(".stage"),config:s.avatar,language:i}),this.companion=null,s.mode==="companion"&&(this.companion=new ta({root:this.shadowRoot,stage:this.avatar?this.$(".stage"):null,avatar:this.avatar,ui:this.ui,name:s.agent.name,t:a,side:s.theme.position==="left"?"left":"right",config:s.companion,speak:c=>this.voice&&!this.voice.muted?this.voice.say(c):Promise.reject(),onActivate:()=>this.isOpen?this.close():this.open(),panelOpen:()=>this.isOpen}),this.shadowRoot.host.classList.add("companion"),this.$(".launcher").hidden=!0,this.$(".stage-wrap").hidden=!0,this.actions.registerMany(xi(this.companion,{t:a})),this.companion.mount(),this.avatar||(this.companion.el.querySelector(".b-stage").innerHTML=`<span class="b-initial">${Se(s.agent.name.slice(0,1))}</span>`)),this.voice=s.voice===!1?null:new er({bus:this.bus,avatar:this.avatar,store:this.store,t:a,config:{endpoint:s.endpoint,siteKey:s.siteKey,lang:i,...s.voice}}),this.proactivity=s.proactive===!1?null:new $a({bus:this.bus,brain:this.brain,context:this.context,store:this.store,config:{...s.proactive,greet:s.proactive.greet!==!1&&!this.brain.history.length}}),this.ui.cardAnchor=()=>this.companion?.el.querySelector(".b-body")||(this.isOpen?this.$(".panel"):null),this.companion){this.companion.canWander=()=>!this.brain.busy&&!this.isOpen;let c=this.proactivity?.cfg;c&&this.companion.setBehavior({wanderMs:s.companion.wanderMs??c.wanderMs,watchCursor:s.companion.watchCursor??c.watchCursor}),this._offs.push(this.bus.on("proactive:level",({config:d})=>this.companion.setBehavior({wanderMs:d.wanderMs,watchCursor:d.watchCursor})))}if(this.actions.deps.agent=this.api=Vh(this),o===!0||typeof o=="string"){let c=o===!0?`${s.endpoint.replace(/\/$/,"")}/identity`:o;this._identityReady=Promise.race([fetch(c,{credentials:"omit",headers:Zt(a.locale)}).then(d=>d.ok?d.json():Promise.reject(new Error(`identidad ${d.status}`))).then(d=>this.setIdentity(d)).catch(d=>console.warn("[7ots] no se pudo cargar la identidad:",d.message)),new Promise(d=>setTimeout(d,3e3))])}this._wireEvents(),this.context.start(),this.ui.mount(),this.pageTools?.start();for(let c of this.brain.transcript())this._addMessage(c.from,c.text,{name:c.name,restore:!0});let h=this.store.get("pendingNav",null);this.store.remove("pendingNav"),this.store.get("open",s.open)&&this.open({focus:!1}),this.apuchat?.active&&(this.apuchat.resume(),this._setHandoff(!0)),this._connectMcp();let u=async()=>{this.companion&&this._loadAvatar(),this.proactivity?.start(),h&&Date.now()-h.at<6e4&&await this.brain.notify(`La navegaci\xF3n a ${location.pathname} termin\xF3 (motivo: ${h.reason||"petici\xF3n del usuario"}). Contin\xFAa con la tarea que el usuario pidi\xF3, usando el contexto de esta p\xE1gina. Si ya est\xE1 completa, d\xEDselo en una frase.`,{allowNoop:!1})};return document.readyState==="complete"?u():window.addEventListener("load",u,{once:!0}),this.bus.emit("ready",{api:this.api}),this}$(t){return this.shadowRoot.querySelector(t)}setIdentity(t){let o=this.identity=vt(t),r=or(o),s=this._userConfig||{},a=(l,h)=>s[l]&&typeof s[l]=="object"&&s[l][h]!==void 0,i=l=>Object.fromEntries(Object.entries(r[l]).filter(([h])=>!a(l,h))),n=i("agent");if(n.name?this._autoName=!1:delete n.name,Object.assign(this.config.agent,n),Object.assign(this.brain.persona,n),this._relabel(),a("theme","primary")||(this.config.theme.primary=o.look.color,this.style.setProperty("--p",o.look.color),this.ui.setPrimary?.(o.look.color),this.pointer&&(this.pointer.color=o.look.color)),this.voice&&this.config.voice!==!1){let l=i("voice");l.lang&&(this._voiceLangAuto=!1),this.voice.configure(l)}if(this.avatar&&s.avatar!==!1){let l=s.avatar&&typeof s.avatar=="object"?s.avatar:{};this.avatar.applyLook({...i("avatar"),...l}).then(h=>{let u=this.$(".stage-wrap");u&&h!=="none"&&(u.dataset.mode=h)})}return this.bus.emit("identity:change",{identity:o}),o}setLocale(t){if(!this._started)return this.t?.locale;let o=this.t.locale;this._t=le(lt(t));let r=this.t.locale;return this._autoName&&(this.config.agent.name=this.t("widget.defaultName"),this.brain.persona.name=this.config.agent.name),this.brain.setLocale(r),this.voice&&this._voiceLangAuto&&this.voice.configure({lang:_i(r,[t])}),this._relabel(),r!==o&&this.bus.emit("locale:change",{locale:r,previous:o}),r}_relabel(){let t=this.t,o=this.config.agent.name,r={name:o},s=this.shadowRoot;s.querySelectorAll("[data-t]").forEach(h=>h.textContent=t(h.dataset.t,r)),s.querySelectorAll("[data-t-aria]").forEach(h=>h.setAttribute("aria-label",t(h.dataset.tAria,r))),s.querySelectorAll("[data-t-title]").forEach(h=>h.title=t(h.dataset.tTitle,r));let a=this.$(".who strong");a&&(a.textContent=o);let i=this.$(".sub");i&&(i.textContent=t(this._statusKey||"widget.status.online"));let n=this.$("textarea");n&&(n.placeholder=t(this._handoffOn?"widget.composer.placeholderTeam":"widget.composer.placeholder")),this.$(".typing")?.setAttribute("aria-label",t("widget.typing"));let l=this.$('[data-more="proactive"] .lbl');if(l&&this.store&&(l.textContent=t(this.store.get("pro:muted",!1)?"widget.menu.unmuteSuggestions":"widget.menu.muteSuggestions")),this._paintVoice?.(),this.pointer&&(this.pointer.name=o),this.companion){this.companion.name=o,this.companion.relabel();let h=this.companion.el?.querySelector(".b-initial");h&&(h.textContent=o.slice(0,1))}}_render(){let t=this.config.theme,o=Se(this.config.agent.name),r=this.config.contact&&(this.config.contact.apuchat||this.config.contact.apumail);this.shadowRoot.innerHTML=`