@7ots/cli 0.1.11 → 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.
@@ -48,7 +48,7 @@ export const CONFIG_DEFAULTS = Object.freeze({
48
48
  home: { kind: 'local' },
49
49
  brain: { kind: 'lines' },
50
50
  voice: { kind: 'browser' },
51
- pet: { mode: 'ask', annoy: 2, music: 'synth', musicVol: 0.5 },
51
+ pet: { mode: 'ask', annoy: 2, music: 'synth', musicVol: 0.5, entrance: { onStart: false, kind: 'wwe', dance: '' } },
52
52
  access: { agent: true, memory: true, open: true, notify: true, sites: true, screen: false, processes: false, logs: false, inbox: false, vm: false, vmKinds: ['research', 'browse', 'long'] },
53
53
  screen: { every: 5 },
54
54
  // conversation memory: recent turns up to `tokens` (≈chars/4), older ones compacted into a summary; 0 = off
@@ -47,7 +47,7 @@ import { createInferenceLog, otherInferences } from './inferences.mjs';
47
47
 
48
48
  const MAX_INF = 300;
49
49
  import { AI_CLIS, createBrain, detectClis, petSystem } from './brain.mjs';
50
- import { env, loadConfig, saveConfig, saveKey } from './config.mjs';
50
+ import { CONFIG_DEFAULTS, env, loadConfig, saveConfig, saveKey } from './config.mjs';
51
51
  import { loadIdentity } from './identity.mjs';
52
52
  import { readJson, writeJson } from './paths.mjs';
53
53
  import { sttProvider, transcribe } from './stt.mjs';
@@ -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';
@@ -72,6 +72,7 @@ const SCENE_NAMES = ['rocky', 'sf', 'dbz', 'matrix', 'duel', 'sw', 'fight', 'twi
72
72
  const SCENE_EVERY = ['rare', 'normal', 'often'];
73
73
  // dances and their music (pet.html plays them; music: synthesized, your own files in ~/.7ots/music, or none)
74
74
  const MUSIC_MODES = ['synth', 'files', 'off'];
75
+ const ENTRANCE_KINDS = ['wwe', 'rock', 'magic'];
75
76
  const MUSIC_TYPES = { mp3: 'audio/mpeg', ogg: 'audio/ogg', oga: 'audio/ogg', opus: 'audio/ogg', wav: 'audio/wav', m4a: 'audio/mp4', aac: 'audio/aac', flac: 'audio/flac', webm: 'audio/webm' };
76
77
  const MUSIC_FILE = /^[^/\\\0]{1,160}\.(mp3|ogg|oga|opus|wav|m4a|aac|flac|webm)$/i;
77
78
  function musicFiles() {
@@ -455,7 +456,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
455
456
 
456
457
  const page = (file = 'pet.html', extra = {}) =>
457
458
  readFileSync(join(PKG_ROOT, 'cli', 'pet', file), 'utf8')
458
- .replace('__BOOT__', JSON.stringify({ token, pid: process.pid, companion: !!process.env.SEVENOTS_COMPANION, identity, otsId: config.account?.otsId || '', voice: config.voice, lang, annoy, brain: brainLabel(config.brain), activity, stt: sttProvider(env()), ...extra }).replace(/</g, '\\u003c'));
459
+ .replace('__BOOT__', JSON.stringify({ token, pid: process.pid, companion: !!process.env.SEVENOTS_COMPANION, identity, otsId: config.account?.otsId || '', voice: config.voice, lang, annoy, brain: brainLabel(config.brain), activity, stt: sttProvider(env()), backdrop: config.pet.backdrop !== false, ...extra }).replace(/</g, '\\u003c'));
459
460
 
460
461
  // Visitors: other ots of the account invited onto this desktop (their look, saved so they come offline too).
461
462
  // The desktop shell opens a window for each and stages scenes between them (see electron/director.cjs).
@@ -508,6 +509,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
508
509
  } catch {}
509
510
  return fetch(`${c.url}/quit`, { method: 'POST', headers: { 'X-7ots-Token': t, 'Content-Type': 'application/json' }, body: '{}' }).catch(() => {});
510
511
  };
512
+ let entranceDone = false;
511
513
  const fullOnes = () => visitors().filter((v) => v.full);
512
514
  if (!process.env.SEVENOTS_COMPANION) fullOnes().forEach((v) => startCompanion(v).catch((e) => log(`companion: ${e.message}`)));
513
515
 
@@ -968,7 +970,15 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
968
970
  if (p === '/dance' || p === '/entrance') {
969
971
  const dance = musicFor(data);
970
972
  if (p === '/dance') broadcast({ dance });
971
- else broadcast({ entrance: { ...dance, name: identity.name || 'ot' } });
973
+ else {
974
+ // { start: true } = the page just opened: only once per run, and only if the owner wants it
975
+ const ec = { ...CONFIG_DEFAULTS.pet.entrance, ...config.pet.entrance };
976
+ if (data.start && (entranceDone || !ec.onStart)) return json(200, { ok: false });
977
+ entranceDone = true;
978
+ const want = ENTRANCE_KINDS.includes(data.kind) ? data.kind : ENTRANCE_KINDS.includes(ec.kind) ? ec.kind : ENTRANCE_KINDS[Math.floor(Math.random() * ENTRANCE_KINDS.length)];
979
+ const dn = DANCES.includes(data.name) ? data.name : DANCES.includes(ec.dance) ? ec.dance : '';
980
+ broadcast({ entrance: { ...dance, dance: dn, kind: want, name: identity.name || 'ot' } });
981
+ }
972
982
  log(`${p.slice(1)}: ${dance.name}${dance.music ? ` ♪ ${dance.music.file || dance.music.style}` : ''}`);
973
983
  return json(200, { ok: true, dance: dance.name, music: dance.music });
974
984
  }
@@ -1003,6 +1013,8 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1003
1013
  // the catalog without its 3D models (the page only draws the 2D previews)
1004
1014
  modLibrary: modLibrary(),
1005
1015
  musicFiles: musicFiles(),
1016
+ dances: DANCES,
1017
+ ttsModels: TTS_MODELS,
1006
1018
  modCatalog: MOD_CATALOG.map((m) => normalizeMod(m)).map((m) => ({ ...m, parts: m.parts.map((x) => ({ ...x, glb: x.glb ? '3d' : '' })) })),
1007
1019
  integrations: config.integrations,
1008
1020
  character: config.character,
@@ -1041,10 +1053,19 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1041
1053
  } else return 'kind';
1042
1054
  }
1043
1055
  const viewWas = next.pet.view || '2d';
1056
+ const bdWas = next.pet.backdrop !== false;
1044
1057
  if (d.pet) {
1045
1058
  if (d.pet.annoy !== undefined) next.pet.annoy = Math.max(0, Math.min(3, Math.round(Number(d.pet.annoy)) || 0));
1046
1059
  if (['2d', '3d'].includes(d.pet.view)) next.pet.view = d.pet.view;
1060
+ if (d.pet.backdrop !== undefined) next.pet.backdrop = !!d.pet.backdrop;
1047
1061
  if (MUSIC_MODES.includes(d.pet.music)) next.pet.music = d.pet.music;
1062
+ if (d.pet.entrance && typeof d.pet.entrance === 'object') {
1063
+ const e = { ...CONFIG_DEFAULTS.pet.entrance, ...next.pet.entrance };
1064
+ if (d.pet.entrance.onStart !== undefined) e.onStart = !!d.pet.entrance.onStart;
1065
+ if ([...ENTRANCE_KINDS, 'random'].includes(d.pet.entrance.kind)) e.kind = d.pet.entrance.kind;
1066
+ if (d.pet.entrance.dance === '' || DANCES.includes(d.pet.entrance.dance)) e.dance = d.pet.entrance.dance;
1067
+ next.pet.entrance = e;
1068
+ }
1048
1069
  if (d.pet.musicVol !== undefined) next.pet.musicVol = Math.max(0, Math.min(1, Math.round(Number(d.pet.musicVol) * 100) / 100 || 0));
1049
1070
  if (d.pet.scenes) {
1050
1071
  const c = { ...sceneConf(next), ...d.pet.scenes };
@@ -1104,6 +1125,7 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1104
1125
  if (config.voice.kind === 'local') warmLocal();
1105
1126
  if (reload) setTimeout(() => broadcast({ reload: true }), 100); // the page reads its voice at load
1106
1127
  // 2D ↔ 3D: open pet windows switch now (the page, or the desktop shell when it needs the GPU back on).
1128
+ if ((config.pet.backdrop !== false) !== bdWas) setTimeout(() => broadcast({ backdrop: config.pet.backdrop !== false }), 100);
1107
1129
  else if ((config.pet.view || '2d') !== viewWas) (viewSet = config.pet.view), setTimeout(() => broadcast({ view: viewSet }), 100);
1108
1130
  log(`settings: brain ${brainLabel(config.brain)}`);
1109
1131
  return null;
package/cli/pet/pet.html CHANGED
@@ -142,6 +142,9 @@
142
142
  .props .flash { top: 44%; width: 30px; height: 30px; margin: -15px; border-radius: 50%; background: radial-gradient(#fff, #ffd35a 40%, #ff7a1a 60%, transparent 70%); }
143
143
  /* entrances (wrestling style): spotlights from above, pyro columns, the name slammed in */
144
144
  .props .spot { left: 50%; bottom: 0; width: 120px; height: 140%; margin-left: -60px; transform-origin: 50% 0; top: -40%; background: linear-gradient(180deg, rgb(255 250 220 / .0), rgb(255 250 220 / .32) 70%, rgb(255 250 220 / .0)); clip-path: polygon(44% 0, 56% 0, 100% 100%, 0 100%); filter: blur(2px); mix-blend-mode: screen; }
145
+ .props .spot.rock { animation: rockhue 1s linear infinite; }
146
+ @keyframes rockhue { from { filter: blur(2px) hue-rotate(0deg) saturate(4); } to { filter: blur(2px) hue-rotate(360deg) saturate(4); } }
147
+ .props .smoke { bottom: 4%; width: 110px; height: 80px; margin-left: -55px; border-radius: 50%; background: radial-gradient(closest-side, rgb(235 230 255 / .9), rgb(190 170 255 / .5) 60%, transparent); filter: blur(6px); }
145
148
  .props .pyro { bottom: 6%; width: 16px; height: 120px; margin-left: -8px; transform-origin: 50% 100%; border-radius: 8px 8px 4px 4px; background: linear-gradient(0deg, #fff6c0, #ffb627 30%, #ff5a1f 65%, transparent); filter: blur(1px) drop-shadow(0 0 10px #ff8a1f); }
146
149
  .props .title { left: 50%; top: 4%; transform: translateX(-50%); font: 900 30px/1 Impact, 'Anton', system-ui, sans-serif; letter-spacing: 2px; text-transform: uppercase; white-space: nowrap; color: #fff; background: linear-gradient(180deg, #fff 30%, #ffd84a 55%, #ff8a1f); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; -webkit-text-stroke: 1.5px #2a0f00; filter: drop-shadow(0 3px 0 #1a0a00) drop-shadow(0 0 12px rgb(255 160 40 / .7)); }
147
150
  .props .pow { left: 50%; top: 6%; font: 900 22px/1 system-ui, sans-serif; color: #ffd400; -webkit-text-stroke: 2px #1a1020; transform: translateX(-50%); white-space: nowrap; }
@@ -277,14 +280,14 @@
277
280
  // three comes from the CDN; without WebGL or network the 2D ot takes over
278
281
  try {
279
282
  const m = await loadCharacter3D();
280
- ch = m.createCharacter3D($('#face'), spec, { material: 'plush', backdrop: !desktop, orbit: !desktop, bleed: desktop ? 'window' : 0, stage: { key: 'pet', zIndex: 3, maxDpr: 2, minDpr: 1.25, supersample: desktop } });
283
+ ch = m.createCharacter3D($('#face'), spec, { material: 'plush', backdrop: !desktop && BOOT.backdrop !== false, orbit: !desktop, bleed: desktop ? 'window' : 0, stage: { key: 'pet', zIndex: 3, maxDpr: 2, minDpr: 1.25, supersample: desktop } });
281
284
  if (ch.fallback) console.warn('[7ots pet] no WebGL: 2D ot');
282
285
  } catch (err) {
283
286
  console.warn('[7ots pet] 3D ot unavailable, using 2D:', err?.message || err);
284
287
  ch = null;
285
288
  }
286
289
  }
287
- ch ||= createCharacter($('#face'), spec, { locale: lang, title: id.name });
290
+ ch ||= createCharacter($('#face'), spec, { locale: lang, title: id.name, backdrop: BOOT.backdrop !== false });
288
291
  const is3d = !!ch.character;
289
292
  document.body.classList.toggle('ot3d', is3d);
290
293
  // While a gesture/effect/morph plays the ot needs room around it (wings, hearts, confetti): the desktop
@@ -713,6 +716,7 @@
713
716
  const m = JSON.parse(e.data);
714
717
  if (m.reload) return location.reload(); // e.g. the voice changed in the settings
715
718
  if (m.restart) return waitAndReload(); // it became another ot: a new daemon is starting
719
+ if (m.backdrop !== undefined) return location.reload(); // its style's background on/off (settings)
716
720
  if (m.view && setView(m.view === '3d')) return; // 2D ↔ 3D changed in the settings
717
721
  if (guest) return; // the host's events are the host's
718
722
  if (m.stir || (m.say && asleep && Date.now() < stirUntil)) stir(); // awake until it has said it
@@ -999,21 +1003,31 @@
999
1003
  const ms = 12000;
1000
1004
  entering = Date.now() + ms;
1001
1005
  stir();
1002
- music(d.music && !d.music.file ? { ...d.music, style: 'entrance' } : d.music, ms, 'entrance');
1006
+ const kind = ['wwe', 'rock', 'magic'].includes(d.kind) ? d.kind : 'wwe';
1007
+ const style = { wwe: 'entrance', rock: 'hype', magic: 'chip' }[kind];
1008
+ music(d.music && !d.music.file ? { ...d.music, style } : d.music, ms, style);
1003
1009
  if (desktop) console.debug('§7enter'); // the shell walks it in from the side
1004
1010
  actRoom = 190;
1005
1011
  actTall = 150;
1006
1012
  actUntil = Date.now() + ms;
1007
1013
  tellNeed();
1008
1014
  // walking in under two crossing spotlights
1009
- for (const k of [-1, 1]) {
1010
- const sp = prop('spot');
1015
+ for (const k of kind === 'magic' ? [] : [-1, 1]) {
1016
+ const sp = prop(kind === 'rock' ? 'spot rock' : 'spot');
1011
1017
  gone(sp, sp.animate([{ opacity: 0, transform: `rotate(${k * 28}deg)` }, { opacity: 1, transform: `rotate(${-k * 18}deg)`, offset: 0.25 }, { opacity: 1, transform: `rotate(${k * 12}deg)`, offset: 0.5 }, { opacity: 1, transform: `rotate(${-k * 6}deg)`, offset: 0.75 }, { opacity: 0, transform: 'rotate(0deg)' }], { duration: ms, easing: 'ease-in-out' }));
1012
1018
  }
1013
1019
  ch.gesture('groove', { ms: INTRO + 1800 });
1014
1020
  // pyro on each boom of the music (1.0 s and 1.6 s), both sides
1015
1021
  const pyro = (at) =>
1016
1022
  setTimeout(() => {
1023
+ if (kind === 'rock') return ch.effect?.('confetti'), ch.effect?.('notes');
1024
+ if (kind === 'magic') {
1025
+ for (const x of [-1, 0, 1]) {
1026
+ const p = prop('smoke', { left: `calc(50% + ${x * (actRoom - 50)}px)` });
1027
+ gone(p, p.animate([{ transform: 'scale(.3)', opacity: 0.9 }, { transform: 'scale(1.6) translateY(-20px)', opacity: 0 }], { duration: 1600, easing: 'ease-out' }));
1028
+ }
1029
+ return ch.effect?.('sparkles');
1030
+ }
1017
1031
  for (const x of [-1, 1]) {
1018
1032
  const p = prop('pyro', { left: `calc(50% + ${x * (actRoom - 30)}px)` });
1019
1033
  gone(p, p.animate([{ transform: 'scaleY(0)', opacity: 1 }, { transform: 'scaleY(1.1)', opacity: 1, offset: 0.25 }, { transform: 'scaleY(.8)', opacity: 0.9, offset: 0.6 }, { transform: 'scaleY(.2)', opacity: 0 }], { duration: 1100, easing: 'ease-out' }));
@@ -1039,6 +1053,8 @@
1039
1053
  ch.gesture(name, { ms: ms - INTRO - 3600 });
1040
1054
  }, INTRO + 3400);
1041
1055
  }
1056
+ // an entrance when the pet starts, if the owner turned it on (the server says yes once per run)
1057
+ if (!guest) setTimeout(() => post('/entrance', { start: true }).catch(() => {}), 2500);
1042
1058
  $('#danceBtn').title = t('dance');
1043
1059
  if (!guest)
1044
1060
  $('#danceBtn')?.addEventListener('click', () => post('/dance', {}).catch(() => dance({})));
@@ -306,6 +306,11 @@
306
306
  <input type="range" id="muVol" min="0" max="1" step="0.05" style="max-width:10rem" aria-label="volume">
307
307
  </div>
308
308
  <p class="hint" id="muFiles"></p>
309
+ <div class="row">
310
+ <label class="chip"><input type="checkbox" id="enOn"> <span data-t="enOn"></span></label>
311
+ <div class="chips" id="enKind"></div>
312
+ <select id="enDance" aria-label="dance"></select>
313
+ </div>
309
314
  <div class="row">
310
315
  <button type="button" id="muDance" data-t="muDance"></button>
311
316
  <button type="button" id="muEnter" data-t="muEnter"></button>
@@ -395,7 +400,7 @@
395
400
  notify: 'Notifications', notifyD: 'A desktop notification when a reminder fires.',
396
401
  soon: 'coming soon', screen: 'See your screen', screenD: 'Look at what’s open to help with it.', procs: 'Processes and apps', procsD: 'See which programs run (name, CPU, memory) and wait for one to finish. Command arguments that look like keys are hidden.', inbox: 'Read mail and calendar', inboxD: 'Summaries and replies, not just opening the tab.',
397
402
  petH: 'How chatty', annoyHint: 'How often it comments on what you do.', a0: 'Quiet', a1: 'A little', a2: 'Normal', a3: 'Chatty',
398
- muH: 'Dances & music', muHint: 'Your ot dances to a beat it makes itself, or to your own songs. Entrance: it walks in like a wrestler with lights, fireworks and its name.', muMode: { synth: 'Built-in beat', files: 'My songs', off: 'Silent' }, muNone: 'Put .mp3/.ogg/.wav files in {dir} to use your own songs.', muSome: '{n} songs in {dir}', muDance: '▶ Dance', muEnter: '▶ Entrance', muDone: 'Here it goes!', scH: 'Scenes between ots', scHint: 'When two ots share the desktop they meet now and then and act out a famous fight.', scVisitor: 'How often and which ones is set in the main ot\'s settings.', scOn: 'On', scEvery: { rare: 'Rarely', normal: 'Normal', often: 'Often' }, scPlay: '▶ Play one now', scPlayed: 'Done — it starts as soon as two ots are free.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Western duel', sw: 'Star Wars', fight: 'Fight & hug', twist: 'Twist' },
403
+ bd: 'Background', bdHint: 'The background of its art style behind the ot', enOn: 'Make an entrance when it starts', enKind: { wwe: 'Wrestler', rock: 'Rock star', magic: 'Magic', random: 'Surprise me' }, enAny: 'any dance', muH: 'Dances & music', muHint: 'Your ot dances to a beat it makes itself, or to your own songs. Entrance: it walks in like a wrestler with lights, fireworks and its name.', muMode: { synth: 'Built-in beat', files: 'My songs', off: 'Silent' }, muNone: 'Put .mp3/.ogg/.wav files in {dir} to use your own songs.', muSome: '{n} songs in {dir}', muDance: '▶ Dance', muEnter: '▶ Entrance', muDone: 'Here it goes!', scH: 'Scenes between ots', scHint: 'When two ots share the desktop they meet now and then and act out a famous fight.', scVisitor: 'How often and which ones is set in the main ot\'s settings.', scOn: 'On', scEvery: { rare: 'Rarely', normal: 'Normal', often: 'Often' }, scPlay: '▶ Play one now', scPlayed: 'Done — it starts as soon as two ots are free.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Western duel', sw: 'Star Wars', fight: 'Fight & hug', twist: 'Twist' },
399
404
  view: 'Look:', v2d: '2D', v3d: '3D plush', viewNext: 'Changed — the ot switches right away.',
400
405
  notesH: 'What it knows about you', notesHint: 'Its notes. Tell it “remember that…” to add one.', noNotes: 'Nothing yet.', forget: 'Forget', forgetAll: 'Forget everything', sure: 'Click again to forget everything',
401
406
  remH: 'Processes', remHint: 'What {name} is doing for you: reminders, alerts and the programs it’s waiting on. Ask it “remind me…”, “let me know if BTC reaches 85k” or “tell me when the build finishes”.', infTotal: 'Last {n} calls: {in} in → {out} out · {all} tokens', petRuns: 'What {name} is running', pcRuns: 'On this computer', refreshPs: 'Refresh', noRems: 'Nothing pending: no reminders or alerts.', psOff: '{name} can’t see your programs. Turn on “Processes and apps” to list them and let it wait for one to finish.', psOn: 'Turn on', screenEvery: 'Looks at your screen every {n} min', lastSeen: 'last: {what}', priceW: '{coin} {op} {value} {vs}', priceNow: 'now {p}', procW: '“{m}” {until}', untilExit: 'when it ends', untilStart: 'when it starts', running: 'running', notRunning: 'not running', remind: 'Reminder', cpu: 'CPU', mem: 'Mem', up: 'Up', prog: 'Program', cancel: 'Cancel',
@@ -429,7 +434,7 @@
429
434
  notify: 'Notificaciones', notifyD: 'Una notificación de escritorio cuando suena un recordatorio.',
430
435
  soon: 'próximamente', screen: 'Ver tu pantalla', screenD: 'Mirar lo que tienes abierto para ayudarte.', procs: 'Procesos y apps', procsD: 'Ver qué programas corren (nombre, CPU, memoria) y esperar a que uno termine. Los argumentos que parecen claves se ocultan.', inbox: 'Leer correo y calendario', inboxD: 'Resúmenes y respuestas, no solo abrir la pestaña.',
431
436
  petH: 'Cuánto habla', annoyHint: 'Qué tan seguido comenta lo que haces.', a0: 'Callado', a1: 'Poco', a2: 'Normal', a3: 'Charlatán',
432
- muH: 'Bailes y música', muHint: 'Tu ot baila con un ritmo que arma solo, o con tus propias canciones. Entrada: llega como luchador, con luces, fuegos y su nombre.', muMode: { synth: 'Ritmo propio', files: 'Mis canciones', off: 'Sin música' }, muNone: 'Pon archivos .mp3/.ogg/.wav en {dir} para usar tus canciones.', muSome: '{n} canciones en {dir}', muDance: '▶ Bailar', muEnter: '▶ Entrada', muDone: '¡Ahí va!', scH: 'Escenas entre ots', scHint: 'Cuando dos ots comparten el escritorio, cada tanto se juntan y actúan una pelea famosa.', scVisitor: 'Cada cuánto y cuáles se ajusta en los ajustes del ot principal.', scOn: 'Activadas', scEvery: { rare: 'Poco', normal: 'Normal', often: 'Seguido' }, scPlay: '▶ Jugar una ahora', scPlayed: 'Listo: empieza apenas haya dos ots libres.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Duelo', sw: 'Star Wars', fight: 'Pelea y abrazo', twist: 'Twist' },
437
+ bd: 'Fondo', bdHint: 'El fondo de su estilo artístico detrás del ot', enOn: 'Entrar con entrada al iniciar', enKind: { wwe: 'Luchador', rock: 'Estrella de rock', magic: 'Magia', random: 'Sorpréndeme' }, enAny: 'cualquier baile', muH: 'Bailes y música', muHint: 'Tu ot baila con un ritmo que arma solo, o con tus propias canciones. Entrada: llega como luchador, con luces, fuegos y su nombre.', muMode: { synth: 'Ritmo propio', files: 'Mis canciones', off: 'Sin música' }, muNone: 'Pon archivos .mp3/.ogg/.wav en {dir} para usar tus canciones.', muSome: '{n} canciones en {dir}', muDance: '▶ Bailar', muEnter: '▶ Entrada', muDone: '¡Ahí va!', scH: 'Escenas entre ots', scHint: 'Cuando dos ots comparten el escritorio, cada tanto se juntan y actúan una pelea famosa.', scVisitor: 'Cada cuánto y cuáles se ajusta en los ajustes del ot principal.', scOn: 'Activadas', scEvery: { rare: 'Poco', normal: 'Normal', often: 'Seguido' }, scPlay: '▶ Jugar una ahora', scPlayed: 'Listo: empieza apenas haya dos ots libres.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Duelo', sw: 'Star Wars', fight: 'Pelea y abrazo', twist: 'Twist' },
433
438
  view: 'Aspecto:', v2d: '2D', v3d: 'Peluche 3D', viewNext: 'Listo: el ot cambia al instante.',
434
439
  notesH: 'Lo que sabe de ti', notesHint: 'Sus notas. Dile “anota que…” para agregar una.', noNotes: 'Nada todavía.', forget: 'Olvidar', forgetAll: 'Olvidar todo', sure: 'Haz clic otra vez para olvidar todo',
435
440
  remH: 'Procesos', remHint: 'Lo que {name} está haciendo por ti: recordatorios, alertas y los programas que está esperando. Pídele “recuérdame…”, “avísame si BTC llega a 85 mil” o “avísame cuando termine el build”.', infTotal: 'Últimas {n} llamadas: {in} entrada → {out} salida · {all} tokens', petRuns: 'Lo que {name} tiene corriendo', pcRuns: 'En este computador', refreshPs: 'Actualizar', noRems: 'Nada pendiente: sin recordatorios ni alertas.', psOff: '{name} no ve tus programas. Activa “Procesos y apps” para listarlos y que pueda esperar a que uno termine.', psOn: 'Activar', screenEvery: 'Mira tu pantalla cada {n} min', lastSeen: 'última: {what}', priceW: '{coin} {op} {value} {vs}', priceNow: 'ahora {p}', procW: '“{m}” {until}', untilExit: 'cuando termine', untilStart: 'cuando empiece', running: 'corriendo', notRunning: 'no está corriendo', remind: 'Recordatorio', cpu: 'CPU', mem: 'Mem', up: 'Hace', prog: 'Programa', cancel: 'Cancelar',
@@ -463,7 +468,7 @@
463
468
  notify: 'Notificações', notifyD: 'Uma notificação na área de trabalho quando um lembrete toca.',
464
469
  soon: 'em breve', screen: 'Ver sua tela', screenD: 'Olhar o que está aberto para ajudar.', procs: 'Processos e apps', procsD: 'Ver quais programas rodam (nome, CPU, memória) e esperar um terminar. Argumentos que parecem chaves ficam ocultos.', inbox: 'Ler e-mail e agenda', inboxD: 'Resumos e respostas, não só abrir a aba.',
465
470
  petH: 'Quanto fala', annoyHint: 'Com que frequência comenta o que você faz.', a0: 'Calado', a1: 'Pouco', a2: 'Normal', a3: 'Tagarela',
466
- muH: 'Danças e música', muHint: 'Seu ot dança com uma batida que ele mesmo cria, ou com suas músicas. Entrada: chega como lutador, com luzes, fogos e o nome dele.', muMode: { synth: 'Batida própria', files: 'Minhas músicas', off: 'Sem música' }, muNone: 'Coloque arquivos .mp3/.ogg/.wav em {dir} para usar suas músicas.', muSome: '{n} músicas em {dir}', muDance: '▶ Dançar', muEnter: '▶ Entrada', muDone: 'Lá vai!', scH: 'Cenas entre ots', scHint: 'Quando dois ots dividem a área de trabalho, de vez em quando se encontram e encenam uma luta famosa.', scVisitor: 'Frequência e quais se ajustam nas configurações do ot principal.', scOn: 'Ativadas', scEvery: { rare: 'Pouco', normal: 'Normal', often: 'Frequente' }, scPlay: '▶ Jogar uma agora', scPlayed: 'Pronto: começa assim que houver dois ots livres.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Duelo', sw: 'Star Wars', fight: 'Briga e abraço', twist: 'Twist' },
471
+ bd: 'Fundo', bdHint: 'O fundo do estilo artístico atrás do ot', enOn: 'Entrar com entrada ao iniciar', enKind: { wwe: 'Lutador', rock: 'Astro do rock', magic: 'Mágica', random: 'Surpreenda-me' }, enAny: 'qualquer dança', muH: 'Danças e música', muHint: 'Seu ot dança com uma batida que ele mesmo cria, ou com suas músicas. Entrada: chega como lutador, com luzes, fogos e o nome dele.', muMode: { synth: 'Batida própria', files: 'Minhas músicas', off: 'Sem música' }, muNone: 'Coloque arquivos .mp3/.ogg/.wav em {dir} para usar suas músicas.', muSome: '{n} músicas em {dir}', muDance: '▶ Dançar', muEnter: '▶ Entrada', muDone: 'Lá vai!', scH: 'Cenas entre ots', scHint: 'Quando dois ots dividem a área de trabalho, de vez em quando se encontram e encenam uma luta famosa.', scVisitor: 'Frequência e quais se ajustam nas configurações do ot principal.', scOn: 'Ativadas', scEvery: { rare: 'Pouco', normal: 'Normal', often: 'Frequente' }, scPlay: '▶ Jogar uma agora', scPlayed: 'Pronto: começa assim que houver dois ots livres.', scNames: { rocky: 'Rocky', sf: 'Street Fighter', dbz: 'Dragon Ball', matrix: 'Matrix', duel: 'Duelo', sw: 'Star Wars', fight: 'Briga e abraço', twist: 'Twist' },
467
472
  view: 'Visual:', v2d: '2D', v3d: 'Pelúcia 3D', viewNext: 'Pronto: o ot muda na hora.',
468
473
  notesH: 'O que ele sabe de você', notesHint: 'As notas dele. Diga “anote que…” para adicionar.', noNotes: 'Nada ainda.', forget: 'Esquecer', forgetAll: 'Esquecer tudo', sure: 'Clique de novo para esquecer tudo',
469
474
  remH: 'Processos', remHint: 'O que {name} está fazendo por você: lembretes, alertas e os programas que está esperando. Peça “me lembre…”, “me avise se o BTC chegar a 85 mil” ou “me avise quando o build terminar”.', infTotal: 'Últimas {n} chamadas: {in} entrada → {out} saída · {all} tokens', petRuns: 'O que {name} está rodando', pcRuns: 'Neste computador', refreshPs: 'Atualizar', noRems: 'Nada pendente: sem lembretes nem alertas.', psOff: '{name} não vê seus programas. Ative “Processos e apps” para listá-los e esperar um terminar.', psOn: 'Ativar', screenEvery: 'Olha sua tela a cada {n} min', lastSeen: 'última: {what}', priceW: '{coin} {op} {value} {vs}', priceNow: 'agora {p}', procW: '“{m}” {until}', untilExit: 'quando terminar', untilStart: 'quando começar', running: 'rodando', notRunning: 'não está rodando', remind: 'Lembrete', cpu: 'CPU', mem: 'Mem', up: 'Há', prog: 'Programa', cancel: 'Cancelar',
@@ -489,7 +494,7 @@
489
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',
490
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.',
491
496
  chBackstory: 'Backstory', chStyle: 'How it talks', chQuirks: 'Quirks', chScenario: 'Scenario (optional)', chGreeting: 'Greeting (optional)', chExamples: 'Example dialogues',
492
- 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).',
493
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 ✓',
494
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',
495
500
  },
@@ -510,7 +515,7 @@
510
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',
511
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.',
512
517
  chBackstory: 'Historia', chStyle: 'Cómo habla', chQuirks: 'Manías', chScenario: 'Escenario (opcional)', chGreeting: 'Saludo (opcional)', chExamples: 'Diálogos de ejemplo',
513
- 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).',
514
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 ✓',
515
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',
516
521
  },
@@ -531,7 +536,7 @@
531
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',
532
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.',
533
538
  chBackstory: 'História', chStyle: 'Jeito de falar', chQuirks: 'Manias', chScenario: 'Cenário (opcional)', chGreeting: 'Saudação (opcional)', chExamples: 'Diálogos de exemplo',
534
- 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).',
535
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 ✓',
536
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',
537
542
  },
@@ -965,13 +970,14 @@
965
970
  const P = VPROV[kind];
966
971
  const vfield = (label, input) => el('label', { className: 'f' }, label, input);
967
972
  const cur = S.config.voice?.providers?.[kind] || {};
968
- const has = S.voices.keys[kind];
973
+ let has = S.voices.keys[kind];
969
974
  const msg = el('span', { className: 'msg', role: 'status' });
970
975
  const idIn = el('input', { type: 'text', value: cur.voiceId || '', placeholder: t('vcIdPh'), autocomplete: 'off' });
971
976
  const pick = el('select', { hidden: true });
972
- const model = el('input', { type: 'text', value: cur.model || '', placeholder: P.models[0] || t('vcDefault'), autocomplete: 'off' });
973
- if (P.models.length) model.setAttribute('list', `vm-${kind}`);
974
- 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;
975
981
  const style = el('textarea', { rows: 2, value: cur.style || '', placeholder: t('vcStylePh') });
976
982
  const loadList = async () => {
977
983
  if (!P.list || !has) return;
@@ -986,12 +992,23 @@
986
992
  }
987
993
  };
988
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
+ };
989
1005
  const test = el('button', {}, ico('volume-2', 15), ' ', t('vcTest'));
990
1006
  test.addEventListener('click', async (e) => {
991
1007
  e.preventDefault();
992
1008
  test.disabled = true;
993
1009
  flash(msg, t('vcTesting'), 'ok');
994
1010
  try {
1011
+ await saveKeyFirst();
995
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 }) });
996
1013
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
997
1014
  const a = new Audio(URL.createObjectURL(await r.blob()));
@@ -1006,6 +1023,7 @@
1006
1023
  const ok = el('button', { className: 'primary', textContent: t('vcSave') });
1007
1024
  ok.addEventListener('click', async (e) => {
1008
1025
  e.preventDefault();
1026
+ try { await saveKeyFirst(); } catch (x) { return flash(msg, t('err', { e: errText(x) }), 'err'); }
1009
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);
1010
1028
  S.config.voice = { ...S.config.voice, kind, providers: { ...(S.config.voice?.providers || {}), [kind]: { voiceId: idIn.value, model: model.value, style: style.value } } };
1011
1029
  const r = box.querySelector(`#v-${kind}`);
@@ -1018,7 +1036,7 @@
1018
1036
  has || !P.list ? null : el('small', { textContent: t('vcKeyFirst') }),
1019
1037
  pick,
1020
1038
  vfield(t('vcId'), idIn),
1021
- vfield(t('vcModel'), model), dl,
1039
+ kind === 'grok' ? el('small', { textContent: t('vcOneModel') }) : models.length ? vfield(t('vcModel'), model) : null, dl,
1022
1040
  P.style ? vfield(t('vcStyle'), style) : null,
1023
1041
  el('div', { className: 'row' }, test, ok, page, msg)));
1024
1042
  box.addEventListener('toggle', () => box.open && !pick.options.length && loadList(), { once: false });
@@ -1161,6 +1179,10 @@
1161
1179
  r.addEventListener('change', () => save({ pet: { view: k } }, $('#petMsg'), t('viewNext')));
1162
1180
  return el('label', { className: 'chip' }, r, t(`v${k}`));
1163
1181
  }));
1182
+ // its art style's background (comic panel, ukiyo-e…) behind the ot, or the ot alone
1183
+ const bd = el('input', { type: 'checkbox', checked: S.config.pet.backdrop !== false });
1184
+ bd.addEventListener('change', () => save({ pet: { backdrop: bd.checked } }, $('#petMsg'), t('viewNext')));
1185
+ $('#view').append(el('label', { className: 'chip', title: t('bdHint') }, bd, ' ', t('bd')));
1164
1186
  }
1165
1187
 
1166
1188
  // ── scenes between ots (pet/electron/director.cjs reads them from GET /scenes) ──
@@ -1207,6 +1229,17 @@
1207
1229
  const n = (S.musicFiles || []).length;
1208
1230
  $('#muFiles').hidden = mode !== 'files';
1209
1231
  $('#muFiles').textContent = t(n ? 'muSome' : 'muNone', { n, dir: '~/.7ots/music' });
1232
+ const en = { onStart: false, kind: 'wwe', dance: '', ...p.entrance };
1233
+ const putE = (e) => put({ entrance: e });
1234
+ $('#enOn').checked = !!en.onStart;
1235
+ $('#enOn').onchange = (e) => putE({ onStart: e.target.checked });
1236
+ $('#enKind').replaceChildren(...['wwe', 'rock', 'magic', 'random'].map((k) => {
1237
+ const r = el('input', { type: 'radio', name: 'enKind', value: k, checked: en.kind === k });
1238
+ r.addEventListener('change', () => putE({ kind: k }));
1239
+ return el('label', { className: 'chip' }, r, (T[lang].enKind || T.en.enKind)[k]);
1240
+ }));
1241
+ $('#enDance').replaceChildren(el('option', { value: '', textContent: t('enAny') }), ...(S.dances || []).map((d) => el('option', { value: d, textContent: d, selected: en.dance === d })));
1242
+ $('#enDance').onchange = (e) => putE({ dance: e.target.value });
1210
1243
  }
1211
1244
  for (const [id, path] of [['#muDance', '/dance'], ['#muEnter', '/entrance']])
1212
1245
  $(id).addEventListener('click', async () => {
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=`