@7ots/cli 0.1.37 → 0.1.38

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.
package/.env.example CHANGED
@@ -122,7 +122,8 @@ LOCALE=
122
122
  # Con PLATFORM=true el mismo servidor sirve el dashboard /app/ (entrar, crear y gestionar ots),
123
123
  # la API pública de cada ots en /api/o/<id>/* y edita cada ots en /backoffice/?ots=<id>.
124
124
  PLATFORM=false
125
- PLATFORM_URL=https://7ots.com
125
+ # Dev: http://localhost:8787. Si falta, el código cae a https://7ots.com.
126
+ PLATFORM_URL=http://localhost:8787
126
127
  PLATFORM_DB=./data/platform.db
127
128
  # Secreto de la plataforma (cifra las claves de cada ots y firma cookies): openssl rand -hex 32
128
129
  PLATFORM_SECRET=
@@ -150,16 +151,20 @@ PLATFORM_FREE_TTS=100
150
151
  PLATFORM_MAIL_INBOX=
151
152
  PLATFORM_MAIL_TOKEN=
152
153
  # Entrar con notlogin (OIDC). Redirect: <PLATFORM_URL>/auth/notlogin/callback
153
- NOTLOGIN_URL=https://notlogin.com
154
+ # Dev/test: Notlogin LOCAL (http://localhost:3000, ver «Dev y test» en CLAUDE.md), con un vendor 7ots de ESE Notlogin.
155
+ # Si falta, el código cae a https://notlogin.com (prod): no lo dejes vacío en un PC.
156
+ NOTLOGIN_URL=http://localhost:3000
154
157
  NOTLOGIN_CLIENT_ID=
155
158
  NOTLOGIN_CLIENT_SECRET=
156
159
  # Tokenizar con SpawnerBot (pestaña Tokenize): llave de partner sbp_… (SpawnerBot guarda solo su sha256)
157
160
  SPAWNERBOT_PARTNER_KEY=
158
- SPAWNERBOT_URL=https://spawnerbot.com
161
+ # Dev/test: SpawnerBot local (:4410) apuntando al mismo Notlogin local; default del código: https://spawnerbot.com
162
+ SPAWNERBOT_URL=http://localhost:4410
159
163
  # Identidades gratis de apuchat por cuenta y día (pestaña apuchat de cada ots; el hub es APUCHAT_HUB)
160
164
  PLATFORM_APUCHAT_IDENTITIES_PER_DAY=5
161
165
  # Orquesta: tareas que un ots puede encargar a un agente (OAuth con registro dinámico, sin client id fijo)
162
- ORQUESTA_URL=https://getorquesta.com
166
+ # Dev/test: Orquesta local (http://localhost:3113, backend en la devbox: devenv up orquesta); default del código: https://getorquesta.com
167
+ ORQUESTA_URL=http://localhost:3113
163
168
  # VM alojada: horas sin trabajo antes de que Orquesta la apague (se despierta sola con el próximo job; 0 = nunca)
164
169
  ORQUESTA_VM_IDLE_HOURS=4
165
170
  # MicroVM de Orquesta por ot (proveedor orquesta_microvm): 1 = abierto a todas las cuentas (si no, solo vm_enabled).
package/README.md CHANGED
@@ -46,6 +46,9 @@ Para respuestas reales, en `.env`:
46
46
  ```bash
47
47
  LLM_PROVIDER=anthropic # usa ANTHROPIC_API_KEY · modelo por defecto claude-opus-5-5
48
48
  # o
49
+
50
+ <!-- credenciales:readme v1 -->
51
+ > **Credenciales y accesos:** este repo sigue el protocolo S18 (ver «Credenciales y accesos» en `CLAUDE.md`). Ningún secreto va al repo, a issues ni a chats.
49
52
  LLM_PROVIDER=openai # usa OPENAI_API_KEY · LLM_BASE_URL para compatibles (Groq, Ollama…)
50
53
  ```
51
54
 
@@ -74,11 +74,11 @@ export const me = () => api('/me');
74
74
  * account, so a pet without APUCHAT_VOICE_TOKEN speaks with its ot's voice there (the account's monthly free quota).
75
75
  * @returns {Promise<{ audio: Buffer, contentType: string }>} or throws an Error with .status and the server's reason
76
76
  */
77
- export async function cloudSpeak(otsId, { text, voiceId, lang }) {
77
+ export async function cloudSpeak(otsId, { text, voiceId, lang, model }) {
78
78
  const res = await fetch(`${SEVENOTS_URL}/api/device/ots/${encodeURIComponent(otsId)}/tts`, {
79
79
  method: 'POST',
80
80
  headers: { Authorization: `Bearer ${env().SEVENOTS_TOKEN}`, 'Content-Type': 'application/json' },
81
- body: JSON.stringify({ text, voiceId, lang }),
81
+ body: JSON.stringify({ text, voiceId, lang, ...(model ? { model } : {}) }),
82
82
  signal: AbortSignal.timeout(25000),
83
83
  });
84
84
  if (!res.ok) {
@@ -35,6 +35,8 @@ const SITES = [
35
35
  [/\blinked ?in\b/i, 'https://www.linkedin.com', { en: 'LinkedIn', es: 'LinkedIn', pt: 'LinkedIn' }],
36
36
  [/\b(twitter|x\.com)\b/i, 'https://x.com', { en: 'X', es: 'X', pt: 'X' }],
37
37
  [/\b(google meet|meet)\b/i, 'https://meet.google.com', { en: 'Meet', es: 'Meet', pt: 'Meet' }],
38
+ [/\b(facebook|fb)\b/i, 'https://www.facebook.com', { en: 'Facebook', es: 'Facebook', pt: 'Facebook' }],
39
+ [/\b(youtube|yt)\b/i, 'https://www.youtube.com', { en: 'YouTube', es: 'YouTube', pt: 'YouTube' }],
38
40
  ];
39
41
 
40
42
  const T = {
@@ -57,7 +59,7 @@ const T = {
57
59
  offloadFail: (e) => `My server could not finish it: ${e}`,
58
60
  offloadLocal: (k) => `On it: I'm working on it here on your computer (${k}). I'll tell you when it's done.`,
59
61
  localFail: (e) => `I couldn't finish it here on your computer: ${e}`,
60
- help: 'I can set reminders ("remind me to check email in 10 minutes"), open sites ("open my calendar") and remember notes ("remember that…"). Seeing your screen: coming soon.',
62
+ help: 'I can set reminders ("remind me to check email in 10 minutes"), open sites ("open my calendar") and remember notes ("remember that…"). I can also see your screen (enable it in Settings).',
61
63
  },
62
64
  es: {
63
65
  watch: (w) => (w.kind === 'price' ? `Vigilando ${w.coin}: te aviso cuando esté ${w.op} ${fmt(w.value)} ${w.vs.toUpperCase()}.` : `Vigilando "${w.match}": te aviso cuando ${w.until === 'start' ? 'empiece' : 'termine'}.`),
@@ -80,7 +82,7 @@ const T = {
80
82
  offloadFail: (e) => `Mi servidor no pudo terminarlo: ${e}`,
81
83
  offloadLocal: (k) => `Voy: lo estoy viendo acá en tu computador (${k}). Te aviso cuando termine.`,
82
84
  localFail: (e) => `No pude terminarlo acá en tu computador: ${e}`,
83
- help: 'Puedo poner recordatorios ("recuérdame ver el correo en 10 minutos"), abrir sitios ("abre mi calendario") y recordar notas ("anota que…"). Ver tu pantalla: muy pronto.',
85
+ help: 'Puedo poner recordatorios ("recuérdame ver el correo en 10 minutos"), abrir sitios ("abre mi calendario") y recordar notas ("anota que…"). También puedo ver tu pantalla (actívalo en Ajustes).',
84
86
  },
85
87
  pt: {
86
88
  watch: (w) => (w.kind === 'price' ? `Vigiando ${w.coin}: te aviso quando estiver ${w.op} ${fmt(w.value)} ${w.vs.toUpperCase()}.` : `Vigiando "${w.match}": te aviso quando ${w.until === 'start' ? 'começar' : 'terminar'}.`),
@@ -102,7 +104,7 @@ const T = {
102
104
  offloadFail: (e) => `Meu servidor não conseguiu terminar: ${e}`,
103
105
  offloadLocal: (k) => `Já vou: estou vendo isso aqui no seu computador (${k}). Te aviso quando terminar.`,
104
106
  localFail: (e) => `Não consegui terminar aqui no seu computador: ${e}`,
105
- help: 'Posso criar lembretes ("me lembre de ver o e-mail em 10 minutos"), abrir sites ("abra minha agenda") e lembrar notas ("anote que…"). Ver sua tela: em breve.',
107
+ help: 'Posso criar lembretes ("me lembre de ver o e-mail em 10 minutos"), abrir sites ("abra minha agenda") e lembrar notas ("anote que…"). Também posso ver sua tela (ative nas Configurações).',
106
108
  },
107
109
  };
108
110
 
@@ -141,7 +143,7 @@ const IN_RE = W('\\b(?:en|in|em|dentro de|daqui a)\\s+(\\d+|un|una|uno|uma|um|an
141
143
  const HALF_RE = W('\\b(?:en|in|em|dentro de)\\s+(?:media hora|half an hour|meia hora)\\b');
142
144
  const AT_RE = W('\\b(?:a las|a la|at|às|as)\\s+(\\d{1,2})(?:[:.h](\\d{2}))?\\s*(am|pm|hrs?|horas?)?\\b');
143
145
  const TOMORROW_RE = W('\\b(mañana|manana|tomorrow|amanh[aã])\\b');
144
- const REMIND_RE = W('\\b(recu[eé]rd[aá]me|recordame|recu[eé]rdame|av[ií]same|remind me|me lembr[ae]|lembre-me|lembra-me)\\b');
146
+ const REMIND_RE = W('\\b(recu[eé]rd[aá]me|recordame|recu[eé]rdame|av[ií]same|pon(?:me)?(?:\\s+una?)\\s+recordatorio|crea(?:me)?(?:\\s+una?)\\s+recordatorio|setea(?:\\s+una?)\\s+recordatorio|set\\s+(?:a\\s+)?reminder|create\\s+(?:a\\s+)?reminder|schedule\\s+(?:a\\s+)?reminder|cri(?:a|e)(?:me)?(?:\\s+um)?\\s+lembrete|remind me|me lembr[ae]|lembre-me|lembra-me)\\b');
145
147
  const NOTE_RE = W('^\\s*(?:anota(?:\\s+que)?|apunta(?:\\s+que)?|recuerda que|aprende que|remember(?:\\s+that)?|note(?:\\s+that)?|anote(?:\\s+que)?|lembre que|lembra que)\\s+');
146
148
  const OPEN_RE = W('^\\s*(?:abre|abr[ií]|abrime|[aá]breme|open|abra|abrir)\\b');
147
149
  const LIST_RE = W('\\b(mis recordatorios|qu[eé] recordatorios|recordatorios pendientes|my reminders|list reminders|reminders|meus lembretes|lembretes)\\b');
@@ -586,6 +586,7 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
586
586
  }
587
587
  return {};
588
588
  },
589
+ refresh() { return checkCloud(true); },
589
590
  };
590
591
  }
591
592
 
@@ -201,7 +201,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
201
201
  const voiceAudio = async (kind, text, voice) => {
202
202
  const keys = env();
203
203
  if (kind === 'apuchat' && !keys.APUCHAT_VOICE_TOKEN && keys.SEVENOTS_TOKEN && config.account?.otsId) {
204
- return cloudSpeak(config.account.otsId, { text: stripSpeechTags(text), voiceId: voice.voiceId || '', lang: voice.lang || '' });
204
+ return cloudSpeak(config.account.otsId, { text: stripSpeechTags(text), voiceId: voice.voiceId || '', lang: voice.lang || '', model: voice.model || '' });
205
205
  }
206
206
  const { synthesize } = await import('../../server/tts.mjs');
207
207
  // process.env too: XAI_TTS_VOICE, FISH_VOICE_ID, APUCHAT_VOICE_URL… (the keys still come from env())
@@ -272,6 +272,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
272
272
  orquestaLoginAt = Date.now();
273
273
  log(`orquesta: connected${r.organizationName ? ` (${r.organizationName})` : ''}`);
274
274
  broadcast({ orquesta: true });
275
+ extras?.refresh?.();
275
276
  return r;
276
277
  })
277
278
  .finally(() => (connecting = null)));
@@ -411,7 +412,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
411
412
  syncing = false;
412
413
  }
413
414
  }
414
- const syncTimer = setInterval(cloudSync, 60_000);
415
+ const syncTimer = setInterval(cloudSync, 30_000);
415
416
  const syncFirst = setTimeout(cloudSync, 8000);
416
417
  const syncLater = () => (clearTimeout(syncSoon), (syncSoon = setTimeout(cloudSync, 3000)));
417
418
 
@@ -427,6 +428,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
427
428
  },
428
429
  });
429
430
 
431
+ let extras; // captured for refresh after Orquesta connects
430
432
  // The assistant: reminders that speak, notify and open the tab; notes it learns.
431
433
  const assistant = createAssistant({
432
434
  brain,
@@ -454,7 +456,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
454
456
  log,
455
457
  }),
456
458
  // logs, email, Orquesta agents, custom integrations (settings → Permissions)
457
- extra: createExtras({
459
+ extra: (extras = createExtras({
458
460
  config: () => config,
459
461
  brain,
460
462
  log,
@@ -467,7 +469,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
467
469
  if (config.access.notify !== false) notify(`${identity.name} · 7ots`, text);
468
470
  broadcast({ say: text, gesture: 'wave', effect: 'exclaim', point: 'user', stir: pet.asleep });
469
471
  },
470
- }),
472
+ })),
471
473
  onFire: (r, text) => {
472
474
  lastSpoke = Date.now();
473
475
  pet.lastTalk = lastSpoke;
@@ -1445,6 +1447,7 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1445
1447
  for (const [k, v] of Object.entries(d.keys)) {
1446
1448
  if (!SETTABLE_KEYS.includes(k) || typeof v !== 'string' || v.length > (k === 'SENSES_ICS_URL' ? 2000 : 400)) return 'key';
1447
1449
  saveKey(k, v.trim()); // '' removes it
1450
+ if (k === 'ORQUESTA_TOKEN' && v.trim()) next.integrations = { ...next.integrations, orquesta: { ...next.integrations?.orquesta, on: true } };
1448
1451
  }
1449
1452
  }
1450
1453
  saveConfig(next);
@@ -60,8 +60,8 @@ app.whenReady().then(() => globalThis.sevenotsReady).then(() => setTimeout(start
60
60
  if (!h?.pid) return ++misses > 4 && app.quit(); // gone for ~25 s
61
61
  misses = 0;
62
62
  pid ||= h.pid;
63
- // The packaged app owns its shell: a daemon that restarted itself (new identity) is adopted, not a reason to leave.
64
- if (h.pid !== pid) process.env.SEVENOTS_PET_APP ? (pid = h.pid) : app.quit();
63
+ // Adopt a new PID: daemon restarted itself (sync/account change) — stay alive in all modes.
64
+ if (h.pid !== pid) pid = h.pid;
65
65
  }, 5000);
66
66
  }
67
67
 
@@ -202,6 +202,9 @@ function makeOt(opt = {}) {
202
202
  const area = screen.getPrimaryDisplay().workArea;
203
203
  const right = area.x + area.width;
204
204
  const floor = area.y + area.height;
205
+ // Dynamic bounds: the display the ot is currently on (pos must be defined before calling).
206
+ const curArea = () => screen.getDisplayNearestPoint({ x: Math.round(pos.x), y: Math.round(pos.y) }).workArea;
207
+ const dispBounds = () => { const ca = curArea(); return { minX: ca.x + 136, maxX: ca.x + ca.width - 136, minY: ca.y + BIG.h, floor: ca.y + ca.height }; };
205
208
 
206
209
  // The ot lives at an anchor (bottom-center of the window). The window is sized to what is in use:
207
210
  // SMALL is just the body; BIG (room for the bubble, the buttons and the talk box) only while needed.
@@ -210,7 +213,7 @@ function makeOt(opt = {}) {
210
213
  let home = null;
211
214
  try {
212
215
  const h = JSON.parse(require('node:fs').readFileSync(HOME_FILE, 'utf8'));
213
- if (h.x >= area.x && h.x <= right && h.y >= area.y + 80 && h.y <= floor) home = { x: h.x, y: h.y };
216
+ if (screen.getAllDisplays().some(d => { const wa = d.workArea; return h.x >= wa.x && h.x <= wa.x + wa.width && h.y >= wa.y + 80 && h.y <= wa.y + wa.height; })) home = { x: h.x, y: h.y };
214
217
  } catch {}
215
218
  let homeSave = null;
216
219
  const setHome = (p) => {
@@ -319,12 +322,14 @@ function makeOt(opt = {}) {
319
322
  let gameWin = null;
320
323
  const watchGame = (url) => {
321
324
  if (!/^https:\/\/[^/]+\/stream\/s_[a-z0-9]+$/i.test(String(url || ''))) return;
322
- if (gameWin && !gameWin.isDestroyed()) return gameWin.loadURL(url), gameWin.showInactive();
325
+ url += '?bare=1'; // byte's game-only view: no header, crew grid or avatar (the ot is already on the desktop)
326
+ if (gameWin && !gameWin.isDestroyed()) return gameWin.loadURL(url), gameWin.showInactive(), win.moveTop();
323
327
  const w = 480;
324
328
  const h = 300;
325
329
  const [wx, wy] = win.getPosition();
326
- const x = Math.max(area.x, Math.min(right - w, wx + size.w / 2 - w - 40));
327
- const y = Math.max(area.y, Math.min(floor - h, wy + size.h - h));
330
+ const gca = curArea();
331
+ const x = Math.max(gca.x, Math.min(gca.x + gca.width - w, wx + size.w / 2 - w - 40));
332
+ const y = Math.max(gca.y, Math.min(gca.y + gca.height - h, wy + size.h - h));
328
333
  gameWin = new BrowserWindow({ x, y, width: w, height: h, minWidth: 320, minHeight: 200, alwaysOnTop: true, title: 'byte arena', icon: ICON, autoHideMenuBar: true, backgroundColor: '#0b0b12', show: false, webPreferences: { contextIsolation: true, sandbox: true } });
329
334
  gameWin.removeMenu?.();
330
335
  gameWin.setAlwaysOnTop(true, 'floating');
@@ -334,7 +339,7 @@ function makeOt(opt = {}) {
334
339
  gameWin.webContents.setWindowOpenHandler(({ url: u }) => (shell.openExternal(u).catch(() => {}), { action: 'deny' }));
335
340
  gameWin.webContents.on('will-navigate', (e, u) => String(u).startsWith(`${origin}/stream/`) || (e.preventDefault(), shell.openExternal(u).catch(() => {})));
336
341
  gameWin.loadURL(url);
337
- gameWin.once('ready-to-show', () => gameWin.showInactive());
342
+ gameWin.once('ready-to-show', () => { gameWin.showInactive(); win.moveTop(); });
338
343
  gameWin.on('closed', () => (gameWin = null));
339
344
  };
340
345
  // what it saw when you asked it to look at you ("¿cómo me ves?"): a small window beside it, like the game's.
@@ -349,8 +354,9 @@ function makeOt(opt = {}) {
349
354
  const w = 400;
350
355
  const h = 330;
351
356
  const [wx, wy] = win.getPosition();
352
- const x = Math.max(area.x, Math.min(right - w, wx + size.w / 2 - w - 40));
353
- const y = Math.max(area.y, Math.min(floor - h, wy + size.h - h));
357
+ const pca = curArea();
358
+ const x = Math.max(pca.x, Math.min(pca.x + pca.width - w, wx + size.w / 2 - w - 40));
359
+ const y = Math.max(pca.y, Math.min(pca.y + pca.height - h, wy + size.h - h));
354
360
  photoWin = new BrowserWindow({ x, y, width: w, height: h, minWidth: 240, minHeight: 200, alwaysOnTop: true, title, icon: ICON, autoHideMenuBar: true, backgroundColor: '#0b0b12', show: false, webPreferences: { contextIsolation: true, sandbox: true, javascript: false } });
355
361
  photoWin.removeMenu?.();
356
362
  photoWin.setAlwaysOnTop(true, 'floating');
@@ -396,8 +402,10 @@ function makeOt(opt = {}) {
396
402
  if (fs.existsSync(file)) img = nativeImage.createFromPath(file);
397
403
  else if (/^https:\/\//.test(g.cover || '')) {
398
404
  const r = await fetch(g.cover, { signal: AbortSignal.timeout(6000) });
399
- const type = (r.headers.get('content-type') || 'image/webp').split(';')[0];
400
- if (r.ok && /^image\//.test(type)) {
405
+ // byte serves some covers as application/octet-stream (Meme Kart's .webp): the bytes are still an image
406
+ const raw = (r.headers.get('content-type') || '').split(';')[0];
407
+ const type = /^image\//.test(raw) ? raw : 'image/webp';
408
+ if (r.ok) {
401
409
  const src = `data:${type};base64,${Buffer.from(await r.arrayBuffer()).toString('base64')}`;
402
410
  const png = await win.webContents.executeJavaScript(`(async () => { const i = new Image(); i.src = ${JSON.stringify(src)}; await i.decode();
403
411
  const h = 40, w = 30, c = document.createElement('canvas'); c.width = w * 2; c.height = h * 2; const x = c.getContext('2d');
@@ -410,7 +418,8 @@ function makeOt(opt = {}) {
410
418
  }
411
419
  } catch {}
412
420
  img = img && !img.isEmpty() ? img.resize({ width: 30, height: 40, quality: 'best' }) : null;
413
- thumbs.set(g.slug, img);
421
+ // a miss is not remembered: a game without a cover yet (byte paints them later) gets it on the next menu
422
+ if (img) thumbs.set(g.slug, img);
414
423
  return img;
415
424
  };
416
425
  const lastPlayed = () => {
@@ -506,8 +515,9 @@ function makeOt(opt = {}) {
506
515
  if (!grabbing.moved) page('postMessage({ carried: true })'); // the page stretches it toward the pull
507
516
  grabbing.moved = true;
508
517
  dragged = Date.now();
509
- pos.x = Math.max(area.x + size.w / 2 - 40, Math.min(right - size.w / 2 + 40, p.x + grabbing.dx));
510
- pos.y = Math.max(area.y + size.h - 40, Math.min(floor + 40, p.y + grabbing.dy));
518
+ const allWAs = screen.getAllDisplays().map(d => d.workArea);
519
+ pos.x = Math.max(Math.min(...allWAs.map(a => a.x)) + size.w / 2 - 40, Math.min(Math.max(...allWAs.map(a => a.x + a.width)) - size.w / 2 + 40, p.x + grabbing.dx));
520
+ pos.y = Math.max(Math.min(...allWAs.map(a => a.y)) + size.h - 40, Math.min(Math.max(...allWAs.map(a => a.y + a.height)) + 40, p.y + grabbing.dy));
511
521
  place();
512
522
  }, 16);
513
523
  }
@@ -569,10 +579,14 @@ function makeOt(opt = {}) {
569
579
  if (over) hoverUntil = Date.now() + 900;
570
580
  // anywhere over its window (not only the drawn parts): it stays put so it can be clicked or dragged
571
581
  if (x >= 0 && y >= 0 && x <= size.w && y <= size.h) stillUntil = Date.now() + 1200;
572
- // the eyes follow the cursor anywhere on screen (the page only sees it inside the window)
573
- if (!lastLook || Math.abs(x - lastLook[0]) + Math.abs(y - lastLook[1]) > 6) {
574
- lastLook = [x, y];
575
- page(`postMessage({ look: [${x}, ${y}] })`);
582
+ // the eyes follow the cursor anywhere on screen: normalize by display size so look is proportional, not maxed
583
+ const ldisp = screen.getDisplayNearestPoint({ x: c.x, y: c.y });
584
+ const lsw = ldisp.size.width, lsh = ldisp.size.height;
585
+ const lx = Math.max(-1, Math.min(1, (c.x - pos.x) / (lsw / 2)));
586
+ const ly = Math.max(-1, Math.min(1, (c.y - (pos.y - size.h / 2)) / (lsh / 2)));
587
+ if (!lastLook || Math.abs(lx - lastLook[0]) + Math.abs(ly - lastLook[1]) > 0.04) {
588
+ lastLook = [lx, ly];
589
+ page(`postMessage({ look: [${lx.toFixed(3)}, ${ly.toFixed(3)}] })`);
576
590
  }
577
591
  // dropped after a drag: a little dizzy
578
592
  if (dragged && !droppedSaid && Date.now() - dragged > 350) {
@@ -598,9 +612,10 @@ function makeOt(opt = {}) {
598
612
  // 16 px steps to avoid resizing for every pixel.
599
613
  const hover = Date.now() < hoverUntil;
600
614
  const step = (v) => Math.ceil(v / 16) * 16;
615
+ const rca = curArea();
601
616
  const want = {
602
- w: step(Math.min(area.width, Math.max(MIN.w, need?.w || 0, hover ? BIG.w : 0, held?.w || 0))),
603
- h: step(Math.min(area.height, Math.max(MIN.h, need?.h || 0, hover ? BIG.h : 0, held?.h || 0))),
617
+ w: step(Math.min(rca.width, Math.max(MIN.w, need?.w || 0, hover ? BIG.w : 0, held?.w || 0))),
618
+ h: step(Math.min(rca.height, Math.max(MIN.h, need?.h || 0, hover ? BIG.h : 0, held?.h || 0))),
604
619
  };
605
620
  const grow = want.w > size.w || want.h > size.h;
606
621
  const differs = want.w !== size.w || want.h !== size.h;
@@ -668,6 +683,7 @@ function makeOt(opt = {}) {
668
683
  let lastT = Date.now();
669
684
 
670
685
  function next() {
686
+ const { minX, maxX } = dispBounds();
671
687
  const now = Date.now();
672
688
  const r = Math.random();
673
689
  if (r < 0.38) return { mode: 'idle', until: now + rnd(1800, 7000) };
@@ -688,6 +704,7 @@ function makeOt(opt = {}) {
688
704
  const now = Date.now();
689
705
  const dt = Math.min(0.05, (now - lastT) / 1000);
690
706
  lastT = now;
707
+ const { minX, maxX, minY, floor } = dispBounds(); // current display, shadows the primary-display consts
691
708
  const errand = plan.mode === 'point';
692
709
  const scene = plan.mode === 'scene' || plan.mode === 'fling';
693
710
  // the cursor on it stops it, scenes too (the director sees interrupted() and ends the scene): something
@@ -770,7 +787,9 @@ function makeOt(opt = {}) {
770
787
  if (plan.mode === 'scene' || plan.mode === 'fling' || still || asleep || Date.now() - dragged < 2000) return;
771
788
  enterUntil = Date.now() + 12000;
772
789
  const to = { ...pos };
773
- const mid = area.x + area.width / 2;
790
+ const { minX, maxX } = dispBounds();
791
+ const ca = curArea();
792
+ const mid = ca.x + ca.width / 2;
774
793
  pos.x = Math.max(minX, Math.min(maxX, to.x + (to.x > mid ? -1 : 1) * 520));
775
794
  vel.x = vel.y = 0;
776
795
  place();
@@ -814,6 +833,7 @@ function makeOt(opt = {}) {
814
833
  async function goTo(goal) {
815
834
  if (still || plan.mode === 'scene' || plan.mode === 'fling') return; // a scene with another ot goes first
816
835
  if (goal === 'browser') await new Promise((r) => setTimeout(r, 900)); // let the site open first
836
+ const { minX, maxX, minY, floor } = dispBounds();
817
837
  const c = cursorPoint();
818
838
  const rect = (goal === 'agent' ? await findWindow(TERM) : goal === 'browser' ? await findWindow(BROWSER) : null) || { x: c.x - 1, y: c.y - 1, w: 2, h: 2, cursor: true };
819
839
  const cx = rect.x + rect.w / 2;
@@ -860,14 +880,14 @@ function makeOt(opt = {}) {
860
880
  host: HOST,
861
881
  home: () => homeAnchor(),
862
882
  pos: () => ({ ...pos }),
863
- bounds: () => ({ minX, maxX, floor }),
883
+ bounds: () => { const b = dispBounds(); return { minX: b.minX, maxX: b.maxX, floor: b.floor }; },
864
884
  close,
865
885
  // free to join a scene: shown, loaded, not held still, dragged, hovered, talking or on an errand
866
886
  daemon: { url: base, token: opt.token || TOKEN }, // its own daemon (settings there can ask for a scene)
867
887
  // for a scene asked from settings: errands (pointing at the terminal while an agent works) may be cut short
868
888
  ready: () => alive() && win.isVisible() && !win.webContents.isLoading() && !asleep && Date.now() - dragged > 3000 && Date.now() > hoverUntil + 1500 && plan.mode !== 'scene' && plan.mode !== 'fling',
869
889
  free: () => alive() && win.isVisible() && !win.webContents.isLoading() && !still && !asleep && Date.now() > enterUntil && Date.now() - dragged > 8000 && Date.now() > hoverUntil + 1500 && !busy && /idle|go|hop/.test(plan.mode),
870
- walkTo: (x, y = pos.y, speed = 120) => (plan = { mode: 'scene', tx: Math.max(minX, Math.min(maxX, x)), ty: Math.max(minY, Math.min(floor, y)), speed, dir: plan.dir || 0 }),
890
+ walkTo: (x, y = pos.y, speed = 120) => { const { minX, maxX, minY, floor } = dispBounds(); plan = { mode: 'scene', tx: Math.max(minX, Math.min(maxX, x)), ty: Math.max(minY, Math.min(floor, y)), speed, dir: plan.dir || 0 }; },
871
891
  arrivedAt: () => plan.mode === 'scene' && Math.abs(plan.tx - pos.x) < 6 && Math.abs(plan.ty - pos.y) < 6 && Math.hypot(vel.x, vel.y) < 10,
872
892
  face: (dir) => {
873
893
  if (plan.mode === 'scene' || plan.mode === 'fling') plan.dir = dir;
package/cli/pet/pet.html CHANGED
@@ -258,17 +258,17 @@
258
258
  <script type="module">
259
259
  const BOOT = __BOOT__;
260
260
  const T = {
261
- en: { wakeOn: 'Say “hey {name}” and I listen', game: 'Play byte', dance: 'Dance', aura: 'Farm aura', settings: 'Settings', card: 'Card', dismiss: 'Send home', listen: 'Listen', listening: 'Listening… 🎙️', noStt: 'Voice control needs an OpenAI or ElevenLabs key (Settings).', noMic: 'I can’t reach the microphone.', sttErr: 'I didn’t catch that.', talk: 'Talk', askPh: 'Remind me to check email in 10 min…', feed: 'Treat', play: 'Play', sleep: 'Sleep', wake: 'Wake', food: 'Food', energy: 'Energy', fun: 'Fun', level: 'Level {l}', xp: '{x} / {n} xp', live: 'Live', off: 'Reconnecting…', approve: 'Approve', reject: 'Reject',
261
+ en: { wakeOn: 'Say “hey {name}” and I listen', game: 'Play byte', dance: 'Dance', aura: 'Farm aura', settings: 'Settings', card: 'Card', dismiss: 'Send home', listen: 'Listen', listening: 'Listening… 🎙️', noStt: ‘Voice control needs an OpenAI or ElevenLabs key (Settings).’, noMic: ‘I can’t reach the microphone. Allow microphone access in system settings.’, sttErr: 'I didn’t catch that.', talk: 'Talk', askPh: 'Remind me to check email in 10 min…', feed: 'Treat', play: 'Play', sleep: 'Sleep', wake: 'Wake', food: 'Food', energy: 'Energy', fun: 'Fun', level: 'Level {l}', xp: '{x} / {n} xp', live: 'Live', off: 'Reconnecting…', approve: 'Approve', reject: 'Reject',
262
262
  activity: 'Activity', empty: 'Nothing yet. Run a command or ask your coding agent something.', tally: '{ok} ok · {fail} failed · turns {turns}',
263
263
  brain: 'Brain: {b}', age: 'Born {d}', lines: 'built-in phrases', now: 'now', m: '{n}m', h: '{n}h',
264
264
  moods: { happy: 'Happy', neutral: 'Calm', sad: 'Sad', disgust: 'Bored', sleep: 'Asleep', thinking: 'Thinking' },
265
265
  kind: { tool: 'Tool', shell: 'Shell', prompt: 'You asked', stop: 'Turn finished', notify: 'Needs you', start: 'Session started' } },
266
- es: { wakeOn: 'Di “oye {name}” y te escucho', game: 'Jugar byte', dance: 'Bailar', aura: 'Farmear aura', settings: 'Ajustes', card: 'Tarjeta', dismiss: 'Despedir', listen: 'Escuchar', listening: 'Te escucho… 🎙️', noStt: 'Para hablarme por voz falta una key de OpenAI o ElevenLabs (Ajustes).', noMic: 'No puedo usar el micrófono.', sttErr: 'No te entendí.', talk: 'Hablar', askPh: 'Recuérdame ver el correo en 10 min…', feed: 'Mimar', play: 'Jugar', sleep: 'Dormir', wake: 'Despertar', food: 'Comida', energy: 'Energía', fun: 'Diversión', level: 'Nivel {l}', xp: '{x} / {n} xp', live: 'En vivo', off: 'Reconectando…', approve: 'Aprobar', reject: 'Rechazar',
266
+ es: { wakeOn: 'Di “oye {name}” y te escucho', game: 'Jugar byte', dance: 'Bailar', aura: 'Farmear aura', settings: 'Ajustes', card: 'Tarjeta', dismiss: 'Despedir', listen: 'Escuchar', listening: 'Te escucho… 🎙️', noStt: 'Para hablarme por voz falta una key de OpenAI o ElevenLabs (Ajustes).', noMic: 'No puedo usar el micrófono. Permite el acceso en ajustes del sistema.', sttErr: 'No te entendí.', talk: 'Hablar', askPh: 'Recuérdame ver el correo en 10 min…', feed: 'Mimar', play: 'Jugar', sleep: 'Dormir', wake: 'Despertar', food: 'Comida', energy: 'Energía', fun: 'Diversión', level: 'Nivel {l}', xp: '{x} / {n} xp', live: 'En vivo', off: 'Reconectando…', approve: 'Aprobar', reject: 'Rechazar',
267
267
  activity: 'Actividad', empty: 'Nada todavía. Ejecuta un comando o pregúntale algo a tu agente.', tally: '{ok} ok · {fail} fallos · turnos {turns}',
268
268
  brain: 'Cerebro: {b}', age: 'Nació {d}', lines: 'frases propias', now: 'ahora', m: '{n} min', h: '{n} h',
269
269
  moods: { happy: 'Feliz', neutral: 'Tranquilo', sad: 'Triste', disgust: 'Aburrido', sleep: 'Dormido', thinking: 'Pensando' },
270
270
  kind: { tool: 'Herramienta', shell: 'Terminal', prompt: 'Preguntaste', stop: 'Turno terminado', notify: 'Te necesita', start: 'Sesión iniciada' } },
271
- pt: { wakeOn: 'Diga “ei {name}” e eu ouço', game: 'Jogar byte', dance: 'Dançar', aura: 'Farmar aura', settings: 'Ajustes', card: 'Carta', dismiss: 'Despedir', listen: 'Ouvir', listening: 'Estou ouvindo… 🎙️', noStt: 'Para falar por voz falta uma key da OpenAI ou ElevenLabs (Ajustes).', noMic: 'Não consigo usar o microfone.', sttErr: 'Não entendi.', talk: 'Falar', askPh: 'Me lembre de ver o e-mail em 10 min…', feed: 'Mimar', play: 'Brincar', sleep: 'Dormir', wake: 'Acordar', food: 'Comida', energy: 'Energia', fun: 'Diversão', level: 'Nível {l}', xp: '{x} / {n} xp', live: 'Ao vivo', off: 'Reconectando…', approve: 'Aprovar', reject: 'Recusar',
271
+ pt: { wakeOn: 'Diga “ei {name}” e eu ouço', game: 'Jogar byte', dance: 'Dançar', aura: 'Farmar aura', settings: 'Ajustes', card: 'Carta', dismiss: 'Despedir', listen: 'Ouvir', listening: 'Estou ouvindo… 🎙️', noStt: 'Para falar por voz falta uma key da OpenAI ou ElevenLabs (Ajustes).', noMic: 'Não consigo usar o microfone. Permita o acesso nas configurações do sistema.', sttErr: 'Não entendi.', talk: 'Falar', askPh: 'Me lembre de ver o e-mail em 10 min…', feed: 'Mimar', play: 'Brincar', sleep: 'Dormir', wake: 'Acordar', food: 'Comida', energy: 'Energia', fun: 'Diversão', level: 'Nível {l}', xp: '{x} / {n} xp', live: 'Ao vivo', off: 'Reconectando…', approve: 'Aprovar', reject: 'Recusar',
272
272
  activity: 'Atividade', empty: 'Nada ainda. Rode um comando ou pergunte algo ao seu agente.', tally: '{ok} ok · {fail} falhas · turnos {turns}',
273
273
  brain: 'Cérebro: {b}', age: 'Nasceu {d}', lines: 'frases próprias', now: 'agora', m: '{n} min', h: '{n} h',
274
274
  moods: { happy: 'Feliz', neutral: 'Tranquilo', sad: 'Triste', disgust: 'Entediado', sleep: 'Dormindo', thinking: 'Pensando' },
@@ -639,6 +639,7 @@
639
639
  } catch (e) {
640
640
  alog(`tts #${turn} threw ${e?.message || e}`);
641
641
  }
642
+ return; // non-browser provider configured: don't fall back to robotic browser voice on failure
642
643
  }
643
644
  if (turn !== speak.turn || !('speechSynthesis' in window)) return;
644
645
  const u = new SpeechSynthesisUtterance(clean(text));
@@ -977,7 +978,7 @@
977
978
  if (d.listen) listen();
978
979
  if (d.dropped) (ch.gesture('dizzy'), ch.effect?.('dizzy'));
979
980
  if (d.follow) ch.effect?.(Math.random() < 0.6 ? 'hearts' : 'question');
980
- if (d.look && Date.now() > lookFree) ch.lookAtPoint(d.look[0], d.look[1]); // the cursor anywhere on screen
981
+ if (d.look && Date.now() > lookFree) ch.lookAt(d.look[0], d.look[1]); // pre-normalized -1..1 by shell
981
982
  });
982
983
 
983
984
  // ── scenes with other ots: the shell's director sends lines, gestures and acts to each one ──
package/dist/7ots.esm.js CHANGED
@@ -344,7 +344,7 @@ uniform vec3 uGravity;`,vc=`vec3 dN = normal;
344
344
  </div>
345
345
  <p class="otr-keys" data-keys hidden>${Ea(a("room.keys"))}</p>
346
346
  <p class="otr-prompt" data-prompt hidden></p>
347
- <div class="otr-pad" data-pad hidden>${["up","left","use","right","down"].map(I=>`<button type="button" data-d="${I}" aria-label="${Ea(a(`room.pad.${I}`))}">${{up:"\u25B2",left:"\u25C0",use:"E",right:"\u25B6",down:"\u25BC"}[I]}</button>`).join("")}</div>`;let l=I=>n.querySelector(I);l("[data-name]").textContent=s;let h=document.createElement("canvas");h.setAttribute("aria-label",a("room.inRoom")),e.append(h,n);let f=new Te.WebGLRenderer({canvas:h,antialias:!0,powerPreference:"high-performance"});f.setPixelRatio(Math.min(o.maxDpr||1.5,devicePixelRatio||1)),f.outputColorSpace=Te.SRGBColorSpace,f.toneMapping=Te.NeutralToneMapping,f.toneMappingExposure=1.05;let c=new Te.PMREMGenerator(f),d=c.fromScene(new r0.RoomEnvironment,.04);c.dispose();let p=new Te.Scene;p.background=new Te.Color("#2a1f55"),p.environment=d.texture,p.environmentIntensity=.45;let u=new Te.HemisphereLight(15265023,4206670,.56),g=new Te.DirectionalLight(16773600,2.4*.55);g.position.set(2.2,3.4,3.2);let m=new Te.DirectionalLight(13623551,2.2*.55);m.position.set(-2.6,2.2,-3);let w=new Te.DirectionalLight(16770804,.5*.55);w.position.set(-3,.5,2);let k=new Te.AmbientLight("#ffe9d6",.25);p.add(u,g,m,w,k);let b=null,x=I=>{b&&(p.remove(b.group),a0(b.group)),b=e0(p,I);let K=b.look;p.background.set(K.bg),e.style.background=K.bg,p.environmentIntensity=K.env,f.toneMappingExposure=K.exposure,u.color.set(K.hemi[0]),u.groundColor.set(K.hemi[1]),u.intensity=K.hemi[2],k.color.set(K.amb[0]),k.intensity=K.amb[1],g.intensity=2.4*.55*K.key,m.intensity=2.2*.55*K.key,w.intensity=.5*.55*K.key};x(o.theme||Ks);let E=new Te.PerspectiveCamera(36,1,.1,80),T=null,v=new Te.Vector3(.9,0,2),_=.2,C=.2,L=0,z=0,N=0,Q=1,F=null,A=null,B=null,W="auto",ae=new Set,Me=new Te.Vector3(-.4,.6,-.6),te=l("[data-bubble]"),ue=0,be=(I,K=2600)=>{te.textContent=I,te.hidden=!1,ue=performance.now()+K},fe=I=>{l("[data-doing]").textContent=I},Fe=I=>{T&&(p.remove(T.root),T.dispose()),T=new sa(I,{quality:"high",material:o.material||"plush"}),T.root.scale.setScalar(Mu/T.H),p.add(T.root)},Y=(I,K,ie)=>{let Pe=(K-I+Math.PI)%(Math.PI*2)-Math.PI;return Pe<-Math.PI&&(Pe+=Math.PI*2),I+Pe*ie},$e=(I,K)=>I<Xs[0]||I>Xs[1]||K<Xs[2]||K>Xs[3]||Eu.some(([ie,Pe,Re,Ue])=>I>ie-Js&&I<Re+Js&&K>Pe-Js&&K<Ue+Js),Oe=(I,K,ie=1)=>new Promise(Pe=>{F={x:I,z:K,sp:ie,res:Pe}}),Ge=(I,K=520)=>new Promise(ie=>{A={from:new Te.Vector3(v.x,L,v.z),to:new Te.Vector3(...I),t0:performance.now(),ms:K,res:ie}}),qe=async()=>{if(!B)return;let I=B;B=null,T.moodName==="sleep"&&T.mood("neutral"),await Ge([I.at[0],0,I.at[1]])},Ze=0,lo=new Set,We=I=>new Promise(K=>{let ie=setTimeout(()=>{lo.delete(ie),K()},I);lo.add(ie)}),st=I=>{let K=++Ze;F=null,I(()=>K!==Ze).catch(()=>{})},Ne=I=>async K=>{let ie=await K;if(I())throw 0;return ie};async function Gt(I,K,{hurry:ie=!1,line:Pe=null}={}){let Re=Ne(K),Ue=br[I];if(await Re(qe()),T.mood("neutral"),fe(a(ie?"room.run":"room.walk")),await Re(Oe(Ue.at[0],Ue.at[1],ie?2.2:1)),C=Ue.face,fe(a(`room.doing.${I}`)),await Re(We(350)),Ue.seat&&(B=Ue,await Re(Ge(Ue.seat)),C=Ue.face),I==="window")T.gesture("think"),be(a("room.say.window")),await Re(We(3200)),T.effect("sparkles"),await Re(We(2400));else if(I==="sofa")T.mood("happy"),await Re(We(2200)),T.gesture("yawn"),be(a("room.say.sofa")),await Re(We(4200));else if(I==="rug")for(let Mt of["dance","groove","disco"].sort(()=>Math.random()-.5).slice(0,2))T.gesture(Mt),T.effect("notes"),await Re(We(2600));else if(I==="bed"){T.mood("sleep"),be("zzz\u2026",1800);for(let Mt=0;Mt<4;Mt++)T.effect("zzz"),await Re(We(2200));T.mood("neutral"),T.gesture("yawn"),await Re(We(1600))}else I==="desk"?(T.gesture("think"),T.effect("thought"),be(Pe||a("room.say.desk")),await Re(We(3400)),T.gesture("nod"),await Re(We(1600))):I==="plant"?(T.gesture("point"),be(a("room.say.plant")),await Re(We(2800)),T.effect("hearts"),await Re(We(1400))):I==="front"&&(T.gesture("wave"),be(a("room.say.hello",{name:s})),await Re(We(2600)))}let co="front",Co=I=>st(async K=>{let ie=Ne(K);for(I||await ie(Gt("front",K));;){let Pe=Object.keys(br).filter(Re=>Re!==co);co=Pe[Math.floor(Math.random()*Pe.length)],await ie(Gt(co,K)),T.mood("neutral"),await ie(We(600+Math.random()*1200))}}),vr=()=>{W==="auto"?Co(!0):fe(a("room.you"))},Ya=I=>st(async K=>{let ie=Ne(K);T.effect("exclaim"),T.gesture("surprise"),be(a("room.say.gotMsg"),2200),await ie(We(900)),await ie(Gt("desk",K,{hurry:!0,line:I?`\xAB${String(I).slice(0,90)}\xBB`:null})),T.mood("happy"),T.gesture("thumbsup"),be(a("room.say.replied")),await ie(We(2400)),vr()}),rs=(I,K)=>{if(I==="message")return Ya(K);if(I==="plaza")return st(async ie=>{await Ne(ie)(Gt("desk",ie,{line:K||null})),vr()});if(I==="poke")return T.gesture("wave"),T.effect("hearts"),be(K||a("room.say.hello",{name:s}));T.effect(I),K&&be(K)},Ka=()=>{let I=null,K=1.3;for(let[ie,Pe]of Object.entries(br)){let Re=Math.hypot(v.x-Pe.at[0],v.z-Pe.at[1]);Re<K&&(K=Re,I=ie)}return I},_a=()=>{if(W!=="ctl")return;if(B)return st(async K=>{await Ne(K)(qe()),T.mood("neutral")});let I=Ka();I?st(K=>Gt(I,K)):T.gesture("jump")},Ta=I=>{!r&&I==="ctl"||(W=I,n.querySelectorAll("[data-mode]").forEach(K=>K.setAttribute("aria-pressed",K.dataset.mode===I)),l("[data-keys]").hidden=I!=="ctl"||i,l("[data-pad]").hidden=I!=="ctl"||!(i||e.clientWidth<640),I==="auto"?(l("[data-prompt]").hidden=!0,Co(!0)):(Ze++,F=null,fe(a("room.you")),be(a("room.say.takeMe"),1600),e.focus({preventScroll:!0})))},Xa={KeyW:"up",ArrowUp:"up",KeyS:"down",ArrowDown:"down",KeyA:"left",ArrowLeft:"left",KeyD:"right",ArrowRight:"right"},Ja=!1,Wo=I=>{if(!r||I.target.closest?.("input,textarea,select,[contenteditable]"))return;let K=Xa[I.code];if(I.type==="keyup"){K&&ae.delete(K);return}(Ja||e.contains(document.activeElement))&&(W==="auto"&&(K||I.code==="Space")&&Ta("ctl"),K&&(I.preventDefault(),ae.add(K)),I.code==="Space"&&(I.preventDefault(),T.gesture("jump")),I.code==="KeyE"&&_a())},er=()=>ae.clear();addEventListener("keydown",Wo),addEventListener("keyup",Wo),addEventListener("blur",er),e.addEventListener("pointerenter",()=>{Ja=!0}),e.addEventListener("pointerleave",()=>{Ja=!1});let tr=l("[data-pad]");tr.addEventListener("pointerdown",I=>{let K=I.target.closest("[data-d]")?.dataset.d;K&&(I.preventDefault(),K==="use"?_a():ae.add(K))});let ss=I=>{let K=I.target.closest?.("[data-d]")?.dataset.d;K&&ae.delete(K)};tr.addEventListener("pointerup",ss),tr.addEventListener("pointercancel",ss),tr.addEventListener("pointerleave",er);let Sa=new Te.Raycaster,or=new Te.Vector2;h.addEventListener("pointerdown",I=>{let K=h.getBoundingClientRect();if(or.set((I.clientX-K.left)/K.width*2-1,-((I.clientY-K.top)/K.height)*2+1),Sa.setFromCamera(or,E),!r){Sa.intersectObject(T.root,!0).length&&rs("poke");return}let ie=Sa.intersectObject(b.floor)[0];if(!ie)return;W==="auto"&&Ta("ctl");let{x:Pe,z:Re}=ie.point;if(Math.hypot(Pe-v.x,Re-v.z)<.25){T.gesture("jump");return}let Ue=Object.keys(br).find(Mt=>{let ca=br[Mt];return Math.hypot(Pe-(ca.seat?.[0]??ca.at[0]),Re-(ca.seat?.[2]??ca.at[1]))<.9});if(Ue&&(br[Ue].seat||$e(Pe,Re)))return st(Mt=>Gt(Ue,Mt));$e(Pe,Re)||st(async Mt=>{await Ne(Mt)(qe()),fe(a("room.walk")),await Ne(Mt)(Oe(Pe,Re,1.3)),fe(a("room.you"))})}),n.addEventListener("click",I=>{let K=I.target.closest("button");K&&(K.dataset.mode?Ta(K.dataset.mode):K.dataset.msg!=null?Ya():K.dataset.edit!=null&&o.onEdit?.())});let q=0,D=0,J=()=>{let I=Math.max(1,e.clientWidth),K=Math.max(1,e.clientHeight);if(I===q&&K===D)return;q=I,D=K,f.setSize(I,K,!1);let ie=I/K;E.aspect=ie,E.fov=ie<1?50:36,E.updateProjectionMatrix(),W==="ctl"&&(l("[data-pad]").hidden=!(i||I<640))},ee=new ResizeObserver(J);ee.observe(e);let ne=new Te.Vector3,we=new Te.Vector3,Le=new Te.Vector3,lt=new Te.Vector3;function Ee(I,K){let ie=K/1e3,Pe=E.aspect;b.tick(I,K);let Re=!1;if(W==="ctl"&&ae.size&&!A&&(B?st(async ct=>{await Ne(ct)(qe())}):(E.getWorldDirection(ne),ne.y=0,ne.normalize(),we.crossVectors(ne,E.up).normalize(),Le.set(0,0,0),ae.has("up")&&Le.add(ne),ae.has("down")&&Le.sub(ne),ae.has("right")&&Le.add(we),ae.has("left")&&Le.sub(we),Le.lengthSq()>0&&(Ze&&F&&(Ze++,F=null,T.mood("neutral"),fe(a("room.you"))),Le.normalize().multiplyScalar(2.1*ie),$e(v.x+Le.x,v.z)||(v.x+=Le.x),$e(v.x,v.z+Le.z)||(v.z+=Le.z),C=Math.atan2(Le.x,Le.z),Re=!0,Q=1.4))),A){let ct=Math.min(1,(performance.now()-A.t0)/A.ms),Ht=ct<.5?2*ct*ct:1-(-2*ct+2)**2/2;if(v.x=Te.MathUtils.lerp(A.from.x,A.to.x,Ht),v.z=Te.MathUtils.lerp(A.from.z,A.to.z,Ht),L=Te.MathUtils.lerp(A.from.y,A.to.y,Ht)+Math.sin(Math.PI*ct)*.55,ct>.05&&ct<.6&&(C=Math.atan2(A.to.x-A.from.x,A.to.z-A.from.z)||C),ct>=1){let Se=A.res;L=A.to.y,A=null,Se()}}else if(F&&!Re){let ct=F.x-v.x,Ht=F.z-v.z,Se=Math.hypot(ct,Ht),oe=Math.min(Se,1.5*F.sp*ie);if(Se<.04){let ot=F.res;F=null,ot()}else v.x+=ct/Se*oe,v.z+=Ht/Se*oe,C=Math.atan2(ct,Ht),Re=!0,Q=F.sp}N+=((Re?1:0)-N)*Math.min(1,ie*10),z+=ie*11*Q,_=Y(_,C,Math.min(1,ie*9));let Ue=Math.abs(Math.sin(z))*.08*N;T.root.position.set(v.x,L+Ue,v.z),T.root.rotation.set(0,_,Math.sin(z)*.07*N),T.shadow&&(T.shadow.position.y=.002-Ue/T.root.scale.y,T.shadow.material.opacity=1-Math.min(.7,Ue*4)),T.tick(I,K),T.lod(Math.min(320,D*.35));let Mt=Pe<1?.75:.3,ca=Le.set(Te.MathUtils.lerp(-.3,v.x,Mt),.5,Te.MathUtils.lerp(-.6,v.z,Mt));Me.lerp(ca,Math.min(1,ie*2.5));let ar=Pe<1?10.5:o.compact?11.4:12.6;if(E.position.set(Me.x+ar*.42,Me.y+ar*.62,Me.z+ar*.66),E.lookAt(Me),f.render(p,E),te.hidden||(performance.now()>ue&&(te.hidden=!0),lt.set(0,T.H*1.12,0).applyMatrix4(T.root.matrixWorld).project(E),te.style.left=`${(lt.x+1)/2*q}px`,te.style.top=`${(1-lt.y)/2*D}px`),W==="ctl"){let ct=!F&&!A&&Ka(),Ht=B?a("room.getOff"):ct?a("room.use",{label:a(`room.places.${ct}`)}):"",Se=l("[data-prompt]");Se.textContent!==Ht&&(Se.textContent=Ht),Se.hidden=!Ht}}let se=0,tt=0,Xt=!0,ho=!1,Ro=I=>{if(se=0,ho||!Xt||document.hidden)return;let K=Math.min(100,tt?I-tt:16);tt=I,J(),Ee(I,K),se=requestAnimationFrame(Ro)},vt=()=>{!se&&!ho&&Xt&&!document.hidden&&(tt=0,se=requestAnimationFrame(Ro))},Uo=new IntersectionObserver(([I])=>{Xt=I.isIntersecting,vt()},{rootMargin:"64px"});return Uo.observe(e),document.addEventListener("visibilitychange",vt),Fe(t),J(),Co(!1),vt(),{el:e,say:be,message:Ya,react:rs,setMode:Ta,get mode(){return W},setName(I){s=I||"ot",l("[data-name]").textContent=s},setSpec(I){let K=T.moodName;Fe(I),T.mood(K||"neutral"),T.gesture("celebrate")},setTheme(I){ho||(x(I),vt())},get theme(){return b.id},destroy(){ho=!0,Ze++,cancelAnimationFrame(se);for(let I of lo)clearTimeout(I);Uo.disconnect(),ee.disconnect(),removeEventListener("keydown",Wo),removeEventListener("keyup",Wo),removeEventListener("blur",er),document.removeEventListener("visibilitychange",vt),T.dispose(),p.remove(T.root),a0(p),d.dispose(),f.dispose(),f.forceContextLoss?.(),h.remove(),n.remove(),e.classList.remove("otr","compact")}}}var Te,r0,Ea,Mu,br,Eu,Xs,Js,_u,o0,Tu,a0,i0=Ye(()=>{Te=_t(Do(),1),r0=_t(sn(),1);wn();t0();vn();Qe();Ea=e=>String(e??"").replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),Mu=1.3,br={window:{at:[-1.2,-3],face:Math.PI},sofa:{at:[-3.2,.5],seat:[-4.15,.66,.5],face:Math.PI/2},rug:{at:[.6,.9],face:.35},bed:{at:[1.9,-2.2],seat:[3.55,.68,-2.3],face:.3},desk:{at:[.95,-2.75],face:Math.PI},plant:{at:[-3.5,-2.6],face:-2.3},front:{at:[.9,2],face:.25}},Eu=[[-5,-.95,-3.7,1.95],[-4.75,-1.85,-3.85,-1.05],[2.45,-4,4.65,-.95],[0,-4,2.05,-3],[-4.8,-3.85,-3.9,-2.95]],Xs=[-4.6,4.6,-3.6,3.6],Js=.32,_u=`
347
+ <div class="otr-pad" data-pad hidden>${["up","left","use","right","down"].map(I=>`<button type="button" data-d="${I}" aria-label="${Ea(a(`room.pad.${I}`))}">${{up:"\u25B2",left:"\u25C0",use:"E",right:"\u25B6",down:"\u25BC"}[I]}</button>`).join("")}</div>`;let l=I=>n.querySelector(I);l("[data-name]").textContent=s;let h=document.createElement("canvas");h.setAttribute("aria-label",a("room.inRoom")),e.append(h,n);let f=new Te.WebGLRenderer({canvas:h,antialias:!0,powerPreference:"high-performance"});f.setPixelRatio(Math.min(o.maxDpr||1.5,devicePixelRatio||1)),f.outputColorSpace=Te.SRGBColorSpace,f.toneMapping=Te.NeutralToneMapping,f.toneMappingExposure=1.05;let c=new Te.PMREMGenerator(f),d=c.fromScene(new r0.RoomEnvironment,.04);c.dispose();let p=new Te.Scene;p.background=new Te.Color("#2a1f55"),p.environment=d.texture,p.environmentIntensity=.45;let u=new Te.HemisphereLight(15265023,4206670,.56),g=new Te.DirectionalLight(16773600,2.4*.55);g.position.set(2.2,3.4,3.2);let m=new Te.DirectionalLight(13623551,2.2*.55);m.position.set(-2.6,2.2,-3);let w=new Te.DirectionalLight(16770804,.5*.55);w.position.set(-3,.5,2);let k=new Te.AmbientLight("#ffe9d6",.25);p.add(u,g,m,w,k);let b=null,x=I=>{b&&(p.remove(b.group),a0(b.group)),b=e0(p,I);let K=b.look;p.background.set(K.bg),e.style.background=K.bg,p.environmentIntensity=K.env,f.toneMappingExposure=K.exposure,u.color.set(K.hemi[0]),u.groundColor.set(K.hemi[1]),u.intensity=K.hemi[2],k.color.set(K.amb[0]),k.intensity=K.amb[1],g.intensity=2.4*.55*K.key,m.intensity=2.2*.55*K.key,w.intensity=.5*.55*K.key};x(o.theme||Ks);let E=new Te.PerspectiveCamera(36,1,.1,80),T=null,v=new Te.Vector3(.9,0,2),_=.2,C=.2,L=0,z=0,N=0,Q=1,F=null,A=null,B=null,W="auto",ae=new Set,Me=new Te.Vector3(-.4,.6,-.6),te=l("[data-bubble]"),ue=0,be=(I,K=2600)=>{te.textContent=I,te.hidden=!1,ue=performance.now()+K},fe=I=>{l("[data-doing]").textContent=I},Fe=I=>{T&&(p.remove(T.root),T.dispose()),T=new sa(I,{quality:"high",material:o.material||"plush"}),T.root.scale.setScalar(Mu/T.H),p.add(T.root)},Y=(I,K,ie)=>{let Pe=(K-I+Math.PI)%(Math.PI*2)-Math.PI;return Pe<-Math.PI&&(Pe+=Math.PI*2),I+Pe*ie},$e=(I,K)=>I<Xs[0]||I>Xs[1]||K<Xs[2]||K>Xs[3]||Eu.some(([ie,Pe,Re,Ue])=>I>ie-Js&&I<Re+Js&&K>Pe-Js&&K<Ue+Js),Oe=(I,K,ie=1)=>new Promise(Pe=>{F={x:I,z:K,sp:ie,res:Pe}}),Ge=(I,K=520)=>new Promise(ie=>{A={from:new Te.Vector3(v.x,L,v.z),to:new Te.Vector3(...I),t0:performance.now(),ms:K,res:ie}}),qe=async()=>{if(!B)return;let I=B;B=null,T.moodName==="sleep"&&T.mood("neutral"),await Ge([I.at[0],0,I.at[1]])},Ze=0,lo=new Set,We=I=>new Promise(K=>{let ie=setTimeout(()=>{lo.delete(ie),K()},I);lo.add(ie)}),st=I=>{let K=++Ze;F=null,I(()=>K!==Ze).catch(()=>{})},Ne=I=>async K=>{let ie=await K;if(I())throw 0;return ie};async function Gt(I,K,{hurry:ie=!1,line:Pe=null}={}){let Re=Ne(K),Ue=br[I];if(await Re(qe()),T.mood("neutral"),fe(a(ie?"room.run":"room.walk")),await Re(Oe(Ue.at[0],Ue.at[1],ie?2.2:1)),C=Ue.face,fe(a(`room.doing.${I}`)),await Re(We(350)),Ue.seat&&(B=Ue,await Re(Ge(Ue.seat)),C=Ue.face),I==="window")T.gesture("think"),be(a("room.say.window")),await Re(We(3200)),T.effect("sparkles"),await Re(We(2400));else if(I==="sofa")T.mood("happy"),await Re(We(2200)),T.gesture("yawn"),be(a("room.say.sofa")),await Re(We(4200));else if(I==="rug")for(let Mt of["dance","groove","disco"].sort(()=>Math.random()-.5).slice(0,2))T.gesture(Mt),T.effect("notes"),await Re(We(2600));else if(I==="bed"){T.mood("sleep"),be("zzz\u2026",1800);for(let Mt=0;Mt<4;Mt++)T.effect("zzz"),await Re(We(2200));T.mood("neutral"),T.gesture("yawn"),await Re(We(1600))}else I==="desk"?(T.gesture("think"),T.effect("thought"),be(Pe||a("room.say.desk")),await Re(We(3400)),T.gesture("nod"),await Re(We(1600))):I==="plant"?(T.gesture("point"),be(a("room.say.plant")),await Re(We(2800)),T.effect("hearts"),await Re(We(1400))):I==="front"&&(T.gesture("wave"),be(a("room.say.hello",{name:s})),await Re(We(2600)))}let co="front",Co=I=>st(async K=>{let ie=Ne(K);for(I||await ie(Gt("front",K));;){let Pe=Object.keys(br).filter(Re=>Re!==co);co=Pe[Math.floor(Math.random()*Pe.length)],await ie(Gt(co,K)),T.mood("neutral"),await ie(We(600+Math.random()*1200))}}),vr=()=>{W==="auto"?Co(!0):fe(a("room.you"))},Ya=I=>st(async K=>{let ie=Ne(K);T.effect("exclaim"),T.gesture("surprise"),be(a("room.say.gotMsg"),2200),await ie(We(900)),await ie(Gt("desk",K,{hurry:!0,line:I?`\xAB${String(I).slice(0,90)}\xBB`:null})),T.mood("happy"),T.gesture("thumbsup"),be(a("room.say.replied")),await ie(We(2400)),vr()}),rs=(I,K)=>{if(I==="message")return Ya(K);if(I==="plaza")return st(async ie=>{await Ne(ie)(Gt("desk",ie,{line:K||null})),vr()});if(I==="poke")return T.gesture("wave"),T.effect("hearts"),be(K||a("room.say.hello",{name:s}));T.effect(I),K&&be(K)},Ka=()=>{let I=null,K=1.3;for(let[ie,Pe]of Object.entries(br)){let Re=Math.hypot(v.x-Pe.at[0],v.z-Pe.at[1]);Re<K&&(K=Re,I=ie)}return I},_a=()=>{if(W!=="ctl")return;if(B)return st(async K=>{await Ne(K)(qe()),T.mood("neutral")});let I=Ka();I?st(K=>Gt(I,K)):T.gesture("jump")},Ta=I=>{!r&&I==="ctl"||(W=I,n.querySelectorAll("[data-mode]").forEach(K=>K.setAttribute("aria-pressed",K.dataset.mode===I)),l("[data-keys]").hidden=I!=="ctl"||i,l("[data-pad]").hidden=I!=="ctl"||!(i||e.clientWidth<640),I==="auto"?(l("[data-prompt]").hidden=!0,Co(!0)):(Ze++,F=null,fe(a("room.you")),be(a("room.say.takeMe"),1600),e.focus({preventScroll:!0})))},Xa={KeyW:"up",ArrowUp:"up",KeyS:"down",ArrowDown:"down",KeyA:"left",ArrowLeft:"left",KeyD:"right",ArrowRight:"right"},Ja=!1,Wo=I=>{if(!r||I.target.closest?.("input,textarea,select,[contenteditable]"))return;let K=Xa[I.code];if(I.type==="keyup"){K&&ae.delete(K);return}(Ja||e.contains(document.activeElement))&&(W==="auto"&&(K||I.code==="Space")&&Ta("ctl"),K&&(I.preventDefault(),ae.add(K)),I.code==="Space"&&(I.preventDefault(),T.gesture("jump")),I.code==="KeyE"&&_a())},er=()=>ae.clear();addEventListener("keydown",Wo),addEventListener("keyup",Wo),addEventListener("blur",er),e.addEventListener("pointerenter",()=>{Ja=!0}),e.addEventListener("pointerleave",()=>{Ja=!1});let tr=l("[data-pad]");tr.addEventListener("pointerdown",I=>{let K=I.target.closest("[data-d]")?.dataset.d;K&&(I.preventDefault(),K==="use"?_a():ae.add(K))});let ss=I=>{let K=I.target.closest?.("[data-d]")?.dataset.d;K&&ae.delete(K)};tr.addEventListener("pointerup",ss),tr.addEventListener("pointercancel",ss),tr.addEventListener("pointerleave",er);let Sa=new Te.Raycaster,or=new Te.Vector2;h.addEventListener("pointerdown",I=>{let K=h.getBoundingClientRect();if(or.set((I.clientX-K.left)/K.width*2-1,-((I.clientY-K.top)/K.height)*2+1),Sa.setFromCamera(or,E),!r){Sa.intersectObject(T.root,!0).length&&rs("poke");return}let ie=Sa.intersectObject(b.floor)[0];if(!ie)return;W==="auto"&&Ta("ctl");let{x:Pe,z:Re}=ie.point;if(Math.hypot(Pe-v.x,Re-v.z)<.25){T.gesture("jump");return}let Ue=Object.keys(br).find(Mt=>{let ca=br[Mt];return Math.hypot(Pe-(ca.seat?.[0]??ca.at[0]),Re-(ca.seat?.[2]??ca.at[1]))<.9});if(Ue&&(br[Ue].seat||$e(Pe,Re)))return st(Mt=>Gt(Ue,Mt));$e(Pe,Re)||st(async Mt=>{await Ne(Mt)(qe()),fe(a("room.walk")),await Ne(Mt)(Oe(Pe,Re,1.3)),fe(a("room.you")),e.focus({preventScroll:!0})})}),n.addEventListener("click",I=>{let K=I.target.closest("button");K&&(K.dataset.mode?Ta(K.dataset.mode):K.dataset.msg!=null?Ya():K.dataset.edit!=null&&o.onEdit?.())});let q=0,D=0,J=()=>{let I=Math.max(1,e.clientWidth),K=Math.max(1,e.clientHeight);if(I===q&&K===D)return;q=I,D=K,f.setSize(I,K,!1);let ie=I/K;E.aspect=ie,E.fov=ie<1?50:36,E.updateProjectionMatrix(),W==="ctl"&&(l("[data-pad]").hidden=!(i||I<640))},ee=new ResizeObserver(J);ee.observe(e);let ne=new Te.Vector3,we=new Te.Vector3,Le=new Te.Vector3,lt=new Te.Vector3;function Ee(I,K){let ie=K/1e3,Pe=E.aspect;b.tick(I,K);let Re=!1;if(W==="ctl"&&ae.size&&!A&&(B?st(async ct=>{await Ne(ct)(qe())}):(E.getWorldDirection(ne),ne.y=0,ne.normalize(),we.crossVectors(ne,E.up).normalize(),Le.set(0,0,0),ae.has("up")&&Le.add(ne),ae.has("down")&&Le.sub(ne),ae.has("right")&&Le.add(we),ae.has("left")&&Le.sub(we),Le.lengthSq()>0&&(Ze&&F&&(Ze++,F=null,T.mood("neutral"),fe(a("room.you"))),Le.normalize().multiplyScalar(2.1*ie),$e(v.x+Le.x,v.z)||(v.x+=Le.x),$e(v.x,v.z+Le.z)||(v.z+=Le.z),C=Math.atan2(Le.x,Le.z),Re=!0,Q=1.4))),A){let ct=Math.min(1,(performance.now()-A.t0)/A.ms),Ht=ct<.5?2*ct*ct:1-(-2*ct+2)**2/2;if(v.x=Te.MathUtils.lerp(A.from.x,A.to.x,Ht),v.z=Te.MathUtils.lerp(A.from.z,A.to.z,Ht),L=Te.MathUtils.lerp(A.from.y,A.to.y,Ht)+Math.sin(Math.PI*ct)*.55,ct>.05&&ct<.6&&(C=Math.atan2(A.to.x-A.from.x,A.to.z-A.from.z)||C),ct>=1){let Se=A.res;L=A.to.y,A=null,Se()}}else if(F&&!Re){let ct=F.x-v.x,Ht=F.z-v.z,Se=Math.hypot(ct,Ht),oe=Math.min(Se,1.5*F.sp*ie);if(Se<.04){let ot=F.res;F=null,ot()}else v.x+=ct/Se*oe,v.z+=Ht/Se*oe,C=Math.atan2(ct,Ht),Re=!0,Q=F.sp}N+=((Re?1:0)-N)*Math.min(1,ie*10),z+=ie*11*Q,_=Y(_,C,Math.min(1,ie*9));let Ue=Math.abs(Math.sin(z))*.08*N;T.root.position.set(v.x,L+Ue,v.z),T.root.rotation.set(0,_,Math.sin(z)*.07*N),T.shadow&&(T.shadow.position.y=.002-Ue/T.root.scale.y,T.shadow.material.opacity=1-Math.min(.7,Ue*4)),T.tick(I,K),T.lod(Math.min(320,D*.35));let Mt=Pe<1?.75:.3,ca=Le.set(Te.MathUtils.lerp(-.3,v.x,Mt),.5,Te.MathUtils.lerp(-.6,v.z,Mt));Me.lerp(ca,Math.min(1,ie*2.5));let ar=Pe<1?10.5:o.compact?11.4:12.6;if(E.position.set(Me.x+ar*.42,Me.y+ar*.62,Me.z+ar*.66),E.lookAt(Me),f.render(p,E),te.hidden||(performance.now()>ue&&(te.hidden=!0),lt.set(0,T.H*1.12,0).applyMatrix4(T.root.matrixWorld).project(E),te.style.left=`${(lt.x+1)/2*q}px`,te.style.top=`${(1-lt.y)/2*D}px`),W==="ctl"){let ct=!F&&!A&&Ka(),Ht=B?a("room.getOff"):ct?a("room.use",{label:a(`room.places.${ct}`)}):"",Se=l("[data-prompt]");Se.textContent!==Ht&&(Se.textContent=Ht),Se.hidden=!Ht}}let se=0,tt=0,Xt=!0,ho=!1,Ro=I=>{if(se=0,ho||!Xt||document.hidden)return;let K=Math.min(100,tt?I-tt:16);tt=I,J(),Ee(I,K),se=requestAnimationFrame(Ro)},vt=()=>{!se&&!ho&&Xt&&!document.hidden&&(tt=0,se=requestAnimationFrame(Ro))},Uo=new IntersectionObserver(([I])=>{Xt=I.isIntersecting,vt()},{rootMargin:"64px"});return Uo.observe(e),document.addEventListener("visibilitychange",vt),Fe(t),J(),Co(!1),vt(),{el:e,say:be,message:Ya,react:rs,setMode:Ta,get mode(){return W},setName(I){s=I||"ot",l("[data-name]").textContent=s},setSpec(I){let K=T.moodName;Fe(I),T.mood(K||"neutral"),T.gesture("celebrate")},setTheme(I){ho||(x(I),vt())},get theme(){return b.id},destroy(){ho=!0,Ze++,cancelAnimationFrame(se);for(let I of lo)clearTimeout(I);Uo.disconnect(),ee.disconnect(),removeEventListener("keydown",Wo),removeEventListener("keyup",Wo),removeEventListener("blur",er),document.removeEventListener("visibilitychange",vt),T.dispose(),p.remove(T.root),a0(p),d.dispose(),f.dispose(),f.forceContextLoss?.(),h.remove(),n.remove(),e.classList.remove("otr","compact")}}}var Te,r0,Ea,Mu,br,Eu,Xs,Js,_u,o0,Tu,a0,i0=Ye(()=>{Te=_t(Do(),1),r0=_t(sn(),1);wn();t0();vn();Qe();Ea=e=>String(e??"").replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),Mu=1.3,br={window:{at:[-1.2,-3],face:Math.PI},sofa:{at:[-3.2,.5],seat:[-4.15,.66,.5],face:Math.PI/2},rug:{at:[.6,.9],face:.35},bed:{at:[1.9,-2.2],seat:[3.55,.68,-2.3],face:.3},desk:{at:[.95,-2.75],face:Math.PI},plant:{at:[-3.5,-2.6],face:-2.3},front:{at:[.9,2],face:.25}},Eu=[[-5,-.95,-3.7,1.95],[-4.75,-1.85,-3.85,-1.05],[2.45,-4,4.65,-.95],[0,-4,2.05,-3],[-4.8,-3.85,-3.9,-2.95]],Xs=[-4.6,4.6,-3.6,3.6],Js=.32,_u=`
348
348
  .otr{position:relative;overflow:hidden;border-radius:inherit;min-height:260px;background:#2a1f55;outline:none;--otr-glass:rgb(10 7 32 / .62);--otr-line:rgb(255 255 255 / .14);--otr-accent:#ffd23f;--otr-accent-ink:#1a1240;color:#f4f1ff}
349
349
  .otr canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:crosshair}
350
350
  .otr button{font:inherit;color:inherit;cursor:pointer}
@@ -541,7 +541,7 @@ ${sd(this.brain?.persona?.locale||this.brain?.persona?.language)}`;await this.br
541
541
  fill="${this.color}" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>
542
542
  <div class="tag"><span class="n"></span><small class="s"></small></div>
543
543
  </div>`,o.querySelector(".n").textContent=this.name,o.querySelector(".s").textContent=this.t("widget.pointer.hint"),document.documentElement.appendChild(t),this._host=t,this._place(this.x,this.y)}_show(){this.visible&&(this._mount(),this._host.shadowRoot.querySelector(".n").textContent=this.name,clearTimeout(this._hideTimer),this._raise(),this._host.classList.add("on"))}_raise(){let t=this._host;if(t?.showPopover)try{if(t.matches(":popover-open")){if(!document.querySelector("dialog:modal"))return;t.hidePopover()}t.showPopover()}catch{}}_scheduleHide(){clearTimeout(this._hideTimer),this._hideTimer=setTimeout(()=>this._host?.classList.remove("on"),2500)}_label(t){let o=this._host?.shadowRoot.querySelector(".s");o&&(o.textContent=t||this.t("widget.pointer.hint"))}_ripple(){let t=this._host?.shadowRoot.querySelector(".ring");t&&(t.classList.remove("go"),t.offsetWidth,t.classList.add("go"))}},zi=(e,t,o)=>Math.max(t,Math.min(o,e));async function wd(e,t){let o=e.getBoundingClientRect();if(t)return o;for(let a=0;a<30;a++){await ms(40);let s=e.getBoundingClientRect();if(Math.abs(s.top-o.top)<1&&Math.abs(s.left-o.left)<1)return s;o=s}return o}function xd(e){let t=e.getBoundingClientRect();return(t.width<2||t.height<2||getComputedStyle(e).opacity==="0")&&e.labels?.length?e.labels[0]:e}function kd(e){return e.closest?.("label")?.control||null}function tl(e){let t=[];for(let o=e;o&&o.nodeType===1;o=o.parentElement||o.getRootNode()?.host)t.push(o);return t}function vd(e){let t=(e.getAttribute?.("aria-label")||e.innerText||"").trim().replace(/\s+/g," ").slice(0,50),o=e.id?`#${e.id}`:"";return`${e.tagName.toLowerCase()}${o}${t?` \xAB${t}\xBB`:""}`}function La(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e}function Li(e){let t=e.closest?.(Hi)||(e.matches?.(Hi)?e:null);t&&La()!==t&&t.focus({preventScroll:!0})}function rl(e){return e.isContentEditable?!0:e.tagName==="TEXTAREA"?!e.readOnly&&!e.disabled:e.tagName!=="INPUT"?!1:!e.readOnly&&!e.disabled&&/^(text|search|email|url|tel|number|password|date|time|datetime-local|month|week)?$/.test(e.type==="text"?"":e.type)}function sl(e){if(e.select)e.select();else if(e.isContentEditable){let t=document.createRange();t.selectNodeContents(e);let o=getSelection();o.removeAllRanges(),o.addRange(t)}}function $s(e,t){let o=e.value??e.textContent,a=!1;try{a=document.execCommand("insertText",!1,t)}catch{}let s=e.value??e.textContent;if(a&&s!==o)return;if(e.isContentEditable){e.textContent+=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}));return}let r=null;try{r=e.selectionStart}catch{}let i=e.value;if(r==null)gs(e,i+t);else{let n=e.selectionEnd;gs(e,i.slice(0,r)+t+i.slice(n));try{e.setSelectionRange(r+t.length,r+t.length)}catch{}}e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))}function gs(e,t){let o=e.tagName==="TEXTAREA"?HTMLTextAreaElement.prototype:e.tagName==="SELECT"?HTMLSelectElement.prototype:HTMLInputElement.prototype;Object.getOwnPropertyDescriptor(o,"value").set.call(e,t)}function Md(){return[...document.querySelectorAll(Hi)].filter(e=>{if(e.closest("[data-ots-root], [inert], [hidden]"))return!1;let t=e.getBoundingClientRect();return t.width>0&&t.height>0&&getComputedStyle(e).visibility!=="hidden"})}function Ed(e,t){for(let o=e;o&&o!==document.body&&o!==document.documentElement;o=o.parentElement){let a=getComputedStyle(o),s=t==="x"?a.overflowX:a.overflowY;if((t==="x"?o.scrollWidth>o.clientWidth:o.scrollHeight>o.clientHeight)&&/(auto|scroll|overlay)/.test(s))return o}return document.scrollingElement||document.documentElement}var _d={enter:"Enter",return:"Enter",tab:"Tab",esc:"Escape",escape:"Escape",space:" ",spacebar:" ",backspace:"Backspace",delete:"Delete",supr:"Delete",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown"};function Td(e){return _d[e.toLowerCase()]||(e.length===1?e:e[0].toUpperCase()+e.slice(1))}function Sd(e){return/^[a-z]$/i.test(e)?`Key${e.toUpperCase()}`:/^\d$/.test(e)?`Digit${e}`:e===" "?"Space":e.length>1?e:""}function Cd(e,t,o){let a=e.tagName,s=rl(e);if((o.ctrlKey||o.metaKey)&&t.toLowerCase()==="a")return sl(e);if(!(o.ctrlKey||o.metaKey||o.altKey))switch(t){case"Enter":return a==="TEXTAREA"||e.isContentEditable?$s(e,`
544
- `):a==="INPUT"&&e.form&&!/^(checkbox|radio|button|submit|reset)$/.test(e.type)?e.form.requestSubmit?e.form.requestSubmit():e.form.submit():e.matches("a[href], button, summary, [role=button], [role=link], [role=tab], [role=menuitem], input[type=submit], input[type=button]")?e.click():void 0;case" ":return s?$s(e," "):e.matches("button, summary, [role=button], [role=checkbox], [role=switch], [role=tab], input[type=checkbox], input[type=radio]")?e.click():window.scrollBy({top:window.innerHeight*.8});case"Tab":{let r=Md(),i=r.indexOf(e);return r[(i+(o.shiftKey?-1:1)+r.length)%r.length]?.focus()}case"Backspace":return s?document.execCommand("delete")||ol(e,-1):void 0;case"Delete":return s?document.execCommand("forwardDelete")||ol(e,1):void 0;case"ArrowUp":case"ArrowDown":{let r=t==="ArrowDown"?1:-1;if(a==="SELECT"){let i=zi(e.selectedIndex+r,0,e.options.length-1);i!==e.selectedIndex&&(e.selectedIndex=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})));return}return a==="INPUT"&&(e.type==="number"||e.type==="range")?al(e,r):s?void 0:window.scrollBy({top:r*60})}case"ArrowLeft":case"ArrowRight":return a==="INPUT"&&e.type==="range"?al(e,t==="ArrowRight"?1:-1):void 0;case"PageDown":case"PageUp":s||window.scrollBy({top:(t==="PageDown"?1:-1)*window.innerHeight*.85});return;case"Home":case"End":s||window.scrollTo({top:t==="Home"?0:document.documentElement.scrollHeight});return;default:t.length===1&&s&&$s(e,t)}}function ol(e,t){if(e.value==null)return;let o=e.selectionStart??e.value.length,a=e.selectionEnd??o;o===a&&(t<0?o=Math.max(0,o-1):a=Math.min(e.value.length,a+1)),gs(e,e.value.slice(0,o)+e.value.slice(a)),e.setSelectionRange?.(o,o),e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:t<0?"deleteContentBackward":"deleteContentForward"}))}function al(e,t){try{t>0?e.stepUp():e.stepDown()}catch{return}e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}Qe();var dl="input[type=password], [autocomplete^=cc-], [autocomplete=one-time-code], [data-ots-private], [data-ots-private] *",Rd=1500,jr=class{constructor({actions:t,context:o,bus:a,pointer:s=null,t:r=pe()}){this.t=r,this.actions=t,this.context=o,this.bus=a,this.pointer=s,this._tools=new Map,this._offs=[],this._timer=null}start(){let t=()=>{clearTimeout(this._timer),this._timer=setTimeout(()=>this.scan(),250)};this._offs.push(this.bus.on("context:mutation",t),this.bus.on("context:route",t)),this.scan()}stop(){clearTimeout(this._timer),this._offs.forEach(t=>t?.()),this._offs=[];for(let t of this._tools.keys())this.actions.unregister(t);this._tools.clear()}scan(){let t=new Map;for(let o of document.querySelectorAll("[data-ots-tool]")){if(o.closest("[data-ots-ignore], [data-ots-root]"))continue;let a=String(o.dataset.otsTool).trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_").slice(0,64);if(!(!a||t.has(a))){if(this.actions.has(a)&&!this._tools.has(a)){console.warn(`[7ots] data-ots-tool="${a}" choca con una acci\xF3n existente; se ignora.`);continue}t.set(a,o)}}for(let[o,a]of this._tools)t.get(o)!==a&&(this.actions.unregister(o),this._tools.delete(o));for(let[o,a]of t)this._tools.get(o)!==a&&(this.actions.register(a.tagName==="FORM"?this._formTool(o,a):this._buttonTool(o,a)),this._tools.set(o,a))}list(){return[...this._tools.keys()]}_formTool(t,o){let a=Ad(o),s={},r=[];for(let n of a)s[n.name]=n.schema,n.required&&r.push(n.name);let i=[...o.querySelectorAll(dl)].some(n=>n.required);return{name:t,category:"page",title:o.dataset.otsTitle||t,description:`[p\xE1gina] ${o.dataset.otsDescription||o.getAttribute("aria-label")||o.querySelector("legend, h2, h3")?.textContent?.trim()||t}`+(i?" (tiene campos privados que el usuario debe escribir antes)":""),parameters:{type:"object",properties:s,required:r},requiresAuth:o.hasAttribute("data-ots-auth"),confirm:il(o,this.t),timeoutMs:6e4,handler:async(n,{ui:l})=>{if(!o.isConnected)return{ok:!1,error:"El formulario ya no est\xE1 en la p\xE1gina."};let h=ys(o);for(let d of a){if(!(d.name in n))continue;let p=n[d.name],u=d.pick(p);if(!u)return{ok:!1,error:`Valor no v\xE1lido para ${d.name}: ${p}`};if(this.pointer&&h&&ys(u))if(d.kind==="text")await this.pointer.type(u,String(p),{clear:!0}),u.dispatchEvent(new Event("change",{bubbles:!0}));else if(d.kind==="check"||d.kind==="radio"){let g=d.kind==="radio"?!0:p===!0||p==="true";u.checked!==g&&await this.pointer.click(u)}else await this.pointer.moveTo(u),Hr(u,d.kind==="number"?String(p):p);else Hr(u,String(p))}if(!o.checkValidity()){let d=[...o.elements].filter(p=>p.willValidate&&!p.validity.valid);return h&&o.reportValidity(),{ok:!1,error:`El formulario no es v\xE1lido: ${d.map(p=>`${p.name||p.id}: ${p.validationMessage}`).join("; ")}`}}let f=o.querySelector("[type=submit], button:not([type])");this.pointer&&h&&f&&ys(f)&&await this.pointer.moveTo(f);let c=nl(o);return o.requestSubmit?o.requestSubmit(f||void 0):o.submit(),h||l?.toast?.({message:this.t("widget.pageTools.done",{title:o.dataset.otsTitle||t.replace(/_/g," ")}),type:"success"}),{ok:!0,data:await c??"Enviado."}}}}_buttonTool(t,o){return{name:t,category:"page",title:o.dataset.otsTitle||t,description:`[p\xE1gina] ${o.dataset.otsDescription||o.getAttribute("aria-label")||o.textContent.trim().slice(0,80)||t}`,parameters:{type:"object",properties:{}},requiresAuth:o.hasAttribute("data-ots-auth"),confirm:il(o,this.t),handler:async()=>{if(!o.isConnected)return{ok:!1,error:"El bot\xF3n ya no est\xE1 en la p\xE1gina."};let a=nl(o);return this.pointer&&ys(o)?await this.pointer.click(o):o.click(),{ok:!0,data:await a??"Hecho."}}}}};function Ad(e){let t=new Map;for(let a of e.elements)!a.name||a.disabled||a.matches(dl)||a.closest("[data-ots-ignore]")||/^(hidden|submit|button|reset|file|image)$/.test(a.type)||(t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a));let o=[];for(let[a,s]of t){let r=s[0],i=r.dataset.otsDescription||cl(r)||r.placeholder||a,n,l="text",h=()=>r;r.type==="radio"?(l="radio",n={type:"string",enum:s.map(c=>c.value),description:`${cl(r.closest("fieldset")?.querySelector("legend"))||i}`},h=c=>s.find(d=>d.value===c)||null):r.type==="checkbox"?(l="check",n={type:"boolean",description:i}):r.tagName==="SELECT"?(l="select",n={type:"string",enum:[...r.options].filter(f=>!f.disabled&&f.value!=="").map(f=>f.value),description:i}):r.type==="number"||r.type==="range"?(l="number",n={type:"number",description:[i,r.min&&`m\xEDn. ${r.min}`,r.max&&`m\xE1x. ${r.max}`].filter(Boolean).join(", ")}):n={type:"string",description:i+(r.type&&r.type!=="text"&&r.tagName==="INPUT"?` (${r.type})`:"")},o.push({name:a,schema:n,kind:l,pick:h,required:s.some(f=>f.required)})}return o}function il(e,t=pe()){let o=e.dataset.otsConfirm;if(o==="false")return!1;let a=e.dataset.otsTitle||e.dataset.otsTool.replace(/_/g," ");return s=>{if(o&&o!=="true")return o.replace(/\{(\w+)\}/g,(i,n)=>String(s?.[n]??""));let r=Object.entries(s||{}).map(([i,n])=>`${i}: **${n}**`).join(", ");return r?t("widget.confirm.pageToolWith",{title:a,detail:r}):t("widget.confirm.pageTool",{title:a})}}function nl(e){let t=e.closest("form, [role=dialog], section, main")||document.body,o=ll(t);return new Promise(a=>{let s=n=>{clearTimeout(i),e.removeEventListener("ots-result",r),a(n)},r=n=>s(n.detail??"Hecho."),i=setTimeout(()=>{let n=ll(t.isConnected?t:document.body);s(n&&n!==o?n:null)},Rd);e.addEventListener("ots-result",r)})}function ll(e){return[...e.querySelectorAll("[role=status], [role=alert], [aria-live]")].map(t=>t.innerText?.trim()).filter(Boolean).join(" \xB7 ").slice(0,500)}function cl(e){if(!e)return"";let t=e.labels?.[0]||(e.tagName==="LEGEND"?e:null);return(t?[...t.childNodes].filter(a=>a.nodeType===3).map(a=>a.textContent).join(" "):e.getAttribute?.("aria-label")||"").replace(/\s+/g," ").trim().slice(0,80)}function ys(e){if(!e.isConnected||e.closest("[hidden], [inert]"))return!1;let t=e.getBoundingClientRect();return t.width>0&&t.height>0}var Or=class{constructor({endpoint:t,siteKey:o=null,timeoutMs:a=6e4,locale:s=null}={}){if(!t)throw new Error("[7ots] llm.endpoint es obligatorio");this.endpoint=t.replace(/\/$/,""),this.siteKey=o,this.timeoutMs=a,this.locale=s,this.session=Ld()}async step({system:t,messages:o,tools:a,signal:s}){let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);s?.addEventListener("abort",()=>r.abort(),{once:!0});try{let n=await fetch(`${this.endpoint}/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Lo(this.locale)},body:JSON.stringify({system:t,messages:o,tools:a,session:this.session}),signal:r.signal});if(!n.ok){let l=await n.text().catch(()=>"");throw new Error(`LLM proxy ${n.status}: ${l.slice(0,200)}`)}return await n.json()}finally{clearTimeout(i)}}};function Lo(e){let t=typeof e=="function"?e():e;return t?{"Accept-Language":String(t)}:{}}function Ld(){let e=rr("llm"),t=e.get("session");if(!t){let o=new Uint8Array(12);globalThis.crypto?.getRandomValues?.(o),t=[...o].map(a=>(a||Math.floor(Math.random()*256)).toString(16).padStart(2,"0")).join(""),e.set("session",t)}return t}mo();var Au="0.170.0",Lu=`https://cdn.jsdelivr.net/npm/three@${Au}`,oi=()=>String(globalThis.OTS_THREE_BASE||Lu).replace(/\/$/,"");function Hu(){return{imports:{three:`${oi()}/build/three.module.js`,"three/addons/":`${oi()}/examples/jsm/`}}}function En(){if(typeof document>"u")return!1;for(let t of document.querySelectorAll('script[type="importmap"]'))try{if(JSON.parse(t.textContent||"{}").imports?.three)return!0}catch{}let e=document.createElement("script");return e.type="importmap",e.textContent=JSON.stringify(Hu()),(document.head||document.documentElement).prepend(e),!0}var ti=null;function Pu(){return ti??=(async()=>{if(globalThis.__OTS_THREE__?.three)return globalThis.__OTS_THREE__;let e=i=>`${oi()}/${i}/+esm`,[t,o,a,s,r]=await Promise.all([import(`${oi()}/+esm`),import(e("examples/jsm/utils/BufferGeometryUtils.js")),import(e("examples/jsm/environments/RoomEnvironment.js")),import(e("examples/jsm/loaders/GLTFLoader.js")),import(e("examples/jsm/geometries/RoundedBoxGeometry.js"))]);return globalThis.__OTS_THREE__={three:t,BufferGeometryUtils:o,RoomEnvironment:a,GLTFLoader:s,RoundedBoxGeometry:r}})(),ti.catch(()=>{ti=null}),ti}async function ia(){return En(),await Pu(),Promise.resolve().then(()=>(h0(),d0))}var zu="https://cdn.jsdelivr.net/gh/met4citizen/TalkingHead@1.7.0/modules/talkinghead.mjs",ju="https://cdn.jsdelivr.net/gh/met4citizen/TalkingHead@1.7.0/avatars/brunette.glb",_n=["neutral","happy","angry","sad","fear","disgust","love","sleep"],Tn=["handup","index","ok","thumbup","thumbdown","side","shrug","namaste"],Sn=[..._n,"surprised"],Cn=[...new Set([...Tn,...Fr,...Object.keys(za)])],p0={wave:"handup",hi:"handup",hello:"handup",celebrate:"thumbup",thumbsup:"thumbup",thumbsdown:"thumbdown",point:"index",nod:"ok",yes:"ok",shrug:"shrug",bow:"namaste",wiggle:"side",think:"index",clap:"thumbup",cheer:"thumbup"},Ou={es:"fi",it:"fi",pt:"fi",ca:"fi",en:"en",de:"de",fr:"fr",fi:"fi",lt:"lt"},Qa=class{constructor({container:t,config:o={},language:a=document.documentElement.lang||"es"}){this.container=t,this.cfg=o===!1?!1:{url:ju,body:"F",mood:"neutral",cameraView:"upper",module:zu,...o},this.lang=this.cfg&&this.cfg.lipsyncLang||Ou[a.slice(0,2).toLowerCase()]||"en",this.head=null,this.mode="none",this._ctx=null,this._src=null,this._mimicTimer=null,this._speakTimer=null,this._resolveSpeak=null}async load(t){if(this.cfg&&this.cfg.mode==="3d-plush"&&this.cfg.character&&!this.cfg.image)return this._loadPlush();if(this.cfg===!1||this.cfg.mode==="2d"||this.cfg.mode==="3d-plush"||this.cfg.character&&!this.cfg.url&&this.cfg.mode!=="3d")return this._load2D();if(!u0())return console.info("[7ots] el navegador no tiene WebGL: avatar 2D"),this._load2D();try{En();let{TalkingHead:o}=await import(this.cfg.module);this.head=new o(this.container,{ttsEndpoint:"",lipsyncModules:[this.lang],lipsyncLang:this.lang,cameraView:this.cfg.cameraView,avatarMood:this.cfg.mood,modelFPS:30}),await this.head.showAvatar({url:this.cfg.url,body:this.cfg.body,avatarMood:this.cfg.mood,lipsyncLang:this.lang},a=>t?.(a.lengthComputable?a.loaded/a.total:null)),this.mode="3d",this._vis=()=>document.hidden?this.head?.stop():this.head?.start(),document.addEventListener("visibilitychange",this._vis)}catch(o){console.warn("[7ots] avatar 3D no disponible, uso 2D:",o?.message||o);try{this.head?.dispose?.()}catch{}this.head=null,this.container.replaceChildren(),this._load2D()}return this.mode}async _loadPlush(){let t=this._plushToken={};if(!u0())return this._load2D();try{let o=await ia();if(this._plushToken!==t||!this.cfg)return this.mode;this._ch?.destroy(),this.container.replaceChildren(),this._mouth=null,this._face=null;let a=o.createCharacter3D(this.container,this.cfg.character,{material:this.cfg.material||"plush",orbit:this.cfg.orbit===!0,quality:this.cfg.quality||"high",stage:{key:"overlay",zIndex:2147483001,maxDpr:1.5}});this._ch=a,this.mode=a.fallback?"2d":"3d-plush",this.cfg.mood&&a.mood(this.cfg.mood,{fx:!1})}catch(o){console.warn("[7ots] ot 3D no disponible, uso 2D:",o?.message||o),this._ch?.destroy?.(),this._ch=null,this.container.replaceChildren(),this._load2D()}return this.mode}_load2D(){this.mode="2d",this._ch?.destroy(),this._ch=null;let t=this.cfg&&this.cfg.character;if(t&&!this.cfg.image)return this.container.replaceChildren(),this._mouth=null,this._face=null,this._ch=Ut(this.container,t,{title:""}),this.cfg.mood&&this._ch.mood(this.cfg.mood),this.mode;let o=this.cfg&&this.cfg.image;if(o){this.container.innerHTML='<div class="ots-portrait"><img alt="" referrerpolicy="no-referrer"></div>';let a=this.container.querySelector("img");return a.onerror=()=>this._drawFace(),a.src=o,this._mouth=null,this._face=this.container.querySelector(".ots-portrait"),this.mode}return this._drawFace()}_drawFace(){this.mode="2d";let t=this.cfg&&this.cfg.face||{},o=[t.skin&&`--face-bg:${t.skin}`,t.eyes&&`--face-fg:${t.eyes}`].filter(Boolean).join(";");return this.container.innerHTML=`
544
+ `):a==="INPUT"&&e.form&&!/^(checkbox|radio|button|submit|reset)$/.test(e.type)?e.form.requestSubmit?e.form.requestSubmit():e.form.submit():e.matches("a[href], button, summary, [role=button], [role=link], [role=tab], [role=menuitem], input[type=submit], input[type=button]")?e.click():void 0;case" ":return s?$s(e," "):e.matches("button, summary, [role=button], [role=checkbox], [role=switch], [role=tab], input[type=checkbox], input[type=radio]")?e.click():window.scrollBy({top:window.innerHeight*.8});case"Tab":{let r=Md(),i=r.indexOf(e);return r[(i+(o.shiftKey?-1:1)+r.length)%r.length]?.focus()}case"Backspace":return s?document.execCommand("delete")||ol(e,-1):void 0;case"Delete":return s?document.execCommand("forwardDelete")||ol(e,1):void 0;case"ArrowUp":case"ArrowDown":{let r=t==="ArrowDown"?1:-1;if(a==="SELECT"){let i=zi(e.selectedIndex+r,0,e.options.length-1);i!==e.selectedIndex&&(e.selectedIndex=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})));return}return a==="INPUT"&&(e.type==="number"||e.type==="range")?al(e,r):s?void 0:window.scrollBy({top:r*60})}case"ArrowLeft":case"ArrowRight":return a==="INPUT"&&e.type==="range"?al(e,t==="ArrowRight"?1:-1):void 0;case"PageDown":case"PageUp":s||window.scrollBy({top:(t==="PageDown"?1:-1)*window.innerHeight*.85});return;case"Home":case"End":s||window.scrollTo({top:t==="Home"?0:document.documentElement.scrollHeight});return;default:t.length===1&&s&&$s(e,t)}}function ol(e,t){if(e.value==null)return;let o=e.selectionStart??e.value.length,a=e.selectionEnd??o;o===a&&(t<0?o=Math.max(0,o-1):a=Math.min(e.value.length,a+1)),gs(e,e.value.slice(0,o)+e.value.slice(a)),e.setSelectionRange?.(o,o),e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:t<0?"deleteContentBackward":"deleteContentForward"}))}function al(e,t){try{t>0?e.stepUp():e.stepDown()}catch{return}e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}Qe();var dl="input[type=password], [autocomplete^=cc-], [autocomplete=one-time-code], [data-ots-private], [data-ots-private] *",Rd=1500,jr=class{constructor({actions:t,context:o,bus:a,pointer:s=null,t:r=pe()}){this.t=r,this.actions=t,this.context=o,this.bus=a,this.pointer=s,this._tools=new Map,this._offs=[],this._timer=null}start(){let t=()=>{clearTimeout(this._timer),this._timer=setTimeout(()=>this.scan(),250)};this._offs.push(this.bus.on("context:mutation",t),this.bus.on("context:route",t)),this.scan()}stop(){clearTimeout(this._timer),this._offs.forEach(t=>t?.()),this._offs=[];for(let t of this._tools.keys())this.actions.unregister(t);this._tools.clear()}scan(){let t=new Map;for(let o of document.querySelectorAll("[data-ots-tool]")){if(o.closest("[data-ots-ignore], [data-ots-root]"))continue;let a=String(o.dataset.otsTool).trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_").slice(0,64);if(!(!a||t.has(a))){if(this.actions.has(a)&&!this._tools.has(a)){console.warn(`[7ots] data-ots-tool="${a}" choca con una acci\xF3n existente; se ignora.`);continue}t.set(a,o)}}for(let[o,a]of this._tools)t.get(o)!==a&&(this.actions.unregister(o),this._tools.delete(o));for(let[o,a]of t)this._tools.get(o)!==a&&(this.actions.register(a.tagName==="FORM"?this._formTool(o,a):this._buttonTool(o,a)),this._tools.set(o,a))}list(){return[...this._tools.keys()]}_formTool(t,o){let a=Ad(o),s={},r=[];for(let n of a)s[n.name]=n.schema,n.required&&r.push(n.name);let i=[...o.querySelectorAll(dl)].some(n=>n.required);return{name:t,category:"page",title:o.dataset.otsTitle||t,description:`[p\xE1gina] ${o.dataset.otsDescription||o.getAttribute("aria-label")||o.querySelector("legend, h2, h3")?.textContent?.trim()||t}`+(i?" (tiene campos privados que el usuario debe escribir antes)":""),parameters:{type:"object",properties:s,required:r},requiresAuth:o.hasAttribute("data-ots-auth"),confirm:il(o,this.t),timeoutMs:6e4,handler:async(n,{ui:l})=>{if(!o.isConnected)return{ok:!1,error:"El formulario ya no est\xE1 en la p\xE1gina."};let h=ys(o);for(let d of a){if(!(d.name in n))continue;let p=n[d.name],u=d.pick(p);if(!u)return{ok:!1,error:`Valor no v\xE1lido para ${d.name}: ${p}`};if(this.pointer&&h&&ys(u))if(d.kind==="text")await this.pointer.type(u,String(p),{clear:!0}),u.dispatchEvent(new Event("change",{bubbles:!0}));else if(d.kind==="check"||d.kind==="radio"){let g=d.kind==="radio"?!0:p===!0||p==="true";u.checked!==g&&await this.pointer.click(u)}else await this.pointer.moveTo(u),Hr(u,d.kind==="number"?String(p):p);else Hr(u,String(p))}if(!o.checkValidity()){let d=[...o.elements].filter(p=>p.willValidate&&!p.validity.valid);return h&&o.reportValidity(),{ok:!1,error:`El formulario no es v\xE1lido: ${d.map(p=>`${p.name||p.id}: ${p.validationMessage}`).join("; ")}`}}let f=o.querySelector("[type=submit], button:not([type])");this.pointer&&h&&f&&ys(f)&&await this.pointer.moveTo(f);let c=nl(o);return o.requestSubmit?o.requestSubmit(f||void 0):o.submit(),h||l?.toast?.({message:this.t("widget.pageTools.done",{title:o.dataset.otsTitle||t.replace(/_/g," ")}),type:"success"}),{ok:!0,data:await c??"Enviado."}}}}_buttonTool(t,o){return{name:t,category:"page",title:o.dataset.otsTitle||t,description:`[p\xE1gina] ${o.dataset.otsDescription||o.getAttribute("aria-label")||o.textContent.trim().slice(0,80)||t}`,parameters:{type:"object",properties:{}},requiresAuth:o.hasAttribute("data-ots-auth"),confirm:il(o,this.t),handler:async()=>{if(!o.isConnected)return{ok:!1,error:"El bot\xF3n ya no est\xE1 en la p\xE1gina."};let a=nl(o);return this.pointer&&ys(o)?await this.pointer.click(o):o.click(),{ok:!0,data:await a??"Hecho."}}}}};function Ad(e){let t=new Map;for(let a of e.elements)!a.name||a.disabled||a.matches(dl)||a.closest("[data-ots-ignore]")||/^(hidden|submit|button|reset|file|image)$/.test(a.type)||(t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a));let o=[];for(let[a,s]of t){let r=s[0],i=r.dataset.otsDescription||cl(r)||r.placeholder||a,n,l="text",h=()=>r;r.type==="radio"?(l="radio",n={type:"string",enum:s.map(c=>c.value),description:`${cl(r.closest("fieldset")?.querySelector("legend"))||i}`},h=c=>s.find(d=>d.value===c)||null):r.type==="checkbox"?(l="check",n={type:"boolean",description:i}):r.tagName==="SELECT"?(l="select",n={type:"string",enum:[...r.options].filter(f=>!f.disabled&&f.value!=="").map(f=>f.value),description:i}):r.type==="number"||r.type==="range"?(l="number",n={type:"number",description:[i,r.min&&`m\xEDn. ${r.min}`,r.max&&`m\xE1x. ${r.max}`].filter(Boolean).join(", ")}):n={type:"string",description:i+(r.type&&r.type!=="text"&&r.tagName==="INPUT"?` (${r.type})`:"")},o.push({name:a,schema:n,kind:l,pick:h,required:s.some(f=>f.required)})}return o}function il(e,t=pe()){let o=e.dataset.otsConfirm;if(o==="false")return!1;let a=e.dataset.otsTitle||e.dataset.otsTool.replace(/_/g," ");return s=>{if(o&&o!=="true")return o.replace(/\{(\w+)\}/g,(i,n)=>String(s?.[n]??""));let r=Object.entries(s||{}).map(([i,n])=>`${i}: **${n}**`).join(", ");return r?t("widget.confirm.pageToolWith",{title:a,detail:r}):t("widget.confirm.pageTool",{title:a})}}function nl(e){let t=e.closest("form, [role=dialog], section, main")||document.body,o=ll(t);return new Promise(a=>{let s=n=>{clearTimeout(i),e.removeEventListener("ots-result",r),a(n)},r=n=>s(n.detail??"Hecho."),i=setTimeout(()=>{let n=ll(t.isConnected?t:document.body);s(n&&n!==o?n:null)},Rd);e.addEventListener("ots-result",r)})}function ll(e){return[...e.querySelectorAll("[role=status], [role=alert], [aria-live]")].map(t=>t.innerText?.trim()).filter(Boolean).join(" \xB7 ").slice(0,500)}function cl(e){if(!e)return"";let t=e.labels?.[0]||(e.tagName==="LEGEND"?e:null);return(t?[...t.childNodes].filter(a=>a.nodeType===3).map(a=>a.textContent).join(" "):e.getAttribute?.("aria-label")||"").replace(/\s+/g," ").trim().slice(0,80)}function ys(e){if(!e.isConnected||e.closest("[hidden], [inert]"))return!1;let t=e.getBoundingClientRect();return t.width>0&&t.height>0}var Or=class{constructor({endpoint:t,siteKey:o=null,timeoutMs:a=6e4,locale:s=null}={}){if(!t)throw new Error("[7ots] llm.endpoint es obligatorio");this.endpoint=t.replace(/\/$/,""),this.siteKey=o,this.timeoutMs=a,this.locale=s,this.session=Ld()}async step({system:t,messages:o,tools:a,signal:s}){let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);s?.addEventListener("abort",()=>r.abort(),{once:!0});try{let n=await fetch(`${this.endpoint}/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.siteKey?{"X-Site-Key":this.siteKey}:{},...Lo(this.locale)},body:JSON.stringify({system:t,messages:o,tools:a,session:this.session}),signal:r.signal});if(!n.ok){let l=await n.text().catch(()=>"");throw new Error(`LLM proxy ${n.status}: ${l.slice(0,200)}`)}return await n.json()}finally{clearTimeout(i)}}};function Lo(e){let t=typeof e=="function"?e():e;return t?{"Accept-Language":String(t)}:{}}function Ld(){let e=rr("llm"),t=e.get("session");if(!t){let o=new Uint8Array(12);globalThis.crypto?.getRandomValues?.(o),t=[...o].map(a=>(a||Math.floor(Math.random()*256)).toString(16).padStart(2,"0")).join(""),e.set("session",t)}return t}mo();var Au="0.170.0",Lu=`https://cdn.jsdelivr.net/npm/three@${Au}`,oi=()=>String(globalThis.OTS_THREE_BASE||Lu).replace(/\/$/,"");function Hu(){return{imports:{three:`${oi()}/build/three.module.js`,"three/addons/":`${oi()}/examples/jsm/`}}}function En(){if(typeof document>"u")return!1;for(let t of document.querySelectorAll('script[type="importmap"]'))try{if(JSON.parse(t.textContent||"{}").imports?.three)return!0}catch{}let e=document.createElement("script");return e.type="importmap",e.textContent=JSON.stringify(Hu()),(document.head||document.documentElement).prepend(e),!0}var ti=null;function Pu(){return ti??=(async()=>{if(globalThis.__OTS_THREE__?.three)return globalThis.__OTS_THREE__;let e=i=>`${oi()}/${i}/+esm`,[t,o,a,s,r]=await Promise.all([import(`${oi()}/+esm`),import(e("examples/jsm/utils/BufferGeometryUtils.js")),import(e("examples/jsm/environments/RoomEnvironment.js")),import(e("examples/jsm/loaders/GLTFLoader.js")),import(e("examples/jsm/geometries/RoundedBoxGeometry.js"))]);return globalThis.__OTS_THREE__={three:t,BufferGeometryUtils:o,RoomEnvironment:a,GLTFLoader:s,RoundedBoxGeometry:r}})(),ti.catch(()=>{ti=null}),ti}async function ia(){return En(),await Pu(),Promise.resolve().then(()=>(h0(),d0))}var zu="https://cdn.jsdelivr.net/gh/met4citizen/TalkingHead@1.7.0/modules/talkinghead.mjs",ju="https://cdn.jsdelivr.net/gh/met4citizen/TalkingHead@1.7.0/avatars/brunette.glb",_n=["neutral","happy","angry","sad","fear","disgust","love","sleep"],Tn=["handup","index","ok","thumbup","thumbdown","side","shrug","namaste"],Sn=[..._n,"surprised"],Cn=[...new Set([...Tn,...Fr,...Object.keys(za)])],p0={wave:"handup",hi:"handup",hello:"handup",celebrate:"thumbup",thumbsup:"thumbup",thumbsdown:"thumbdown",point:"index",nod:"ok",yes:"ok",shrug:"shrug",bow:"namaste",wiggle:"side",think:"index",clap:"thumbup",cheer:"thumbup"},Ou={es:"fi",it:"fi",pt:"fi",ca:"fi",en:"en",de:"de",fr:"fr",fi:"fi",lt:"lt"},Qa=class{constructor({container:t,config:o={},language:a=document.documentElement.lang||"es"}){this.container=t,this.cfg=o===!1?!1:{url:ju,body:"F",mood:"neutral",cameraView:"upper",module:zu,...o},this.lang=this.cfg&&this.cfg.lipsyncLang||Ou[a.slice(0,2).toLowerCase()]||"en",this.head=null,this.mode="none",this._ctx=null,this._src=null,this._mimicTimer=null,this._speakTimer=null,this._resolveSpeak=null}async load(t){if(this.cfg&&this.cfg.mode==="3d-plush"&&this.cfg.character&&!this.cfg.image)return this._loadPlush();if(this.cfg===!1||this.cfg.mode==="2d"||this.cfg.mode==="3d-plush"||this.cfg.character&&!this.cfg.url&&this.cfg.mode!=="3d")return this._load2D();if(!u0())return console.info("[7ots] el navegador no tiene WebGL: avatar 2D"),this._load2D();try{En();let{TalkingHead:o}=await import(this.cfg.module);this.head=new o(this.container,{ttsEndpoint:"",lipsyncModules:[this.lang],lipsyncLang:this.lang,cameraView:this.cfg.cameraView,avatarMood:this.cfg.mood,modelFPS:30}),await this.head.showAvatar({url:this.cfg.url,body:this.cfg.body,avatarMood:this.cfg.mood,lipsyncLang:this.lang},a=>t?.(a.lengthComputable?a.loaded/a.total:null)),this.mode="3d",this._vis=()=>document.hidden?this.head?.stop():this.head?.start(),document.addEventListener("visibilitychange",this._vis)}catch(o){console.warn("[7ots] avatar 3D no disponible, uso 2D:",o?.message||o);try{this.head?.dispose?.()}catch{}this.head=null,this.container.replaceChildren(),this._load2D()}return this.mode}async _loadPlush(){let t=this._plushToken={};if(!u0())return this._load2D();try{let o=await ia();if(this._plushToken!==t||!this.cfg)return this.mode;this._ch?.destroy(),this.container.replaceChildren(),this._mouth=null,this._face=null;let a=o.createCharacter3D(this.container,this.cfg.character,{material:this.cfg.material||"plush",orbit:this.cfg.orbit===!0,quality:this.cfg.quality||"high",stage:{key:"overlay",zIndex:2147483001,maxDpr:2}});this._ch=a,this.mode=a.fallback?"2d":"3d-plush",this.cfg.mood&&a.mood(this.cfg.mood,{fx:!1})}catch(o){console.warn("[7ots] ot 3D no disponible, uso 2D:",o?.message||o),this._ch?.destroy?.(),this._ch=null,this.container.replaceChildren(),this._load2D()}return this.mode}_load2D(){this.mode="2d",this._ch?.destroy(),this._ch=null;let t=this.cfg&&this.cfg.character;if(t&&!this.cfg.image)return this.container.replaceChildren(),this._mouth=null,this._face=null,this._ch=Ut(this.container,t,{title:""}),this.cfg.mood&&this._ch.mood(this.cfg.mood),this.mode;let o=this.cfg&&this.cfg.image;if(o){this.container.innerHTML='<div class="ots-portrait"><img alt="" referrerpolicy="no-referrer"></div>';let a=this.container.querySelector("img");return a.onerror=()=>this._drawFace(),a.src=o,this._mouth=null,this._face=this.container.querySelector(".ots-portrait"),this.mode}return this._drawFace()}_drawFace(){this.mode="2d";let t=this.cfg&&this.cfg.face||{},o=[t.skin&&`--face-bg:${t.skin}`,t.eyes&&`--face-fg:${t.eyes}`].filter(Boolean).join(";");return this.container.innerHTML=`
545
545
  <svg class="ots-face" viewBox="0 0 120 120" aria-hidden="true"${o?` style="${o}"`:""}>
546
546
  <circle cx="60" cy="60" r="54" class="ots-face-bg"/>
547
547
  <g class="ots-eyes"><ellipse cx="42" cy="50" rx="6" ry="8"/><ellipse cx="78" cy="50" rx="6" ry="8"/></g>