@7ots/cli 0.1.36 → 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) => {
@@ -259,7 +262,10 @@ function makeOt(opt = {}) {
259
262
  session.defaultSession.setPermissionRequestHandler((wc, perm, cb, d) => cb(perm === 'media' && ours(d?.requestingUrl || wc.getURL())));
260
263
  session.defaultSession.setPermissionCheckHandler((wc, perm, origin) => perm === 'media' && ours(origin));
261
264
  const alive = () => !win.isDestroyed();
262
- const page = (js) => alive() && win.webContents.executeJavaScript(js).catch(() => {});
265
+ // While the page loads (a reload after the settings, 2D ↔ 3D) executeJavaScript waits for it on a
266
+ // did-stop-loading listener of its own: the 60 ms timers piled them up (MaxListenersExceededWarning)
267
+ const ready = () => alive() && !win.webContents.isLoadingMainFrame();
268
+ const page = (js) => ready() && win.webContents.executeJavaScript(js).catch(() => {});
263
269
 
264
270
  let still = false;
265
271
  let lastBounds = null;
@@ -316,12 +322,14 @@ function makeOt(opt = {}) {
316
322
  let gameWin = null;
317
323
  const watchGame = (url) => {
318
324
  if (!/^https:\/\/[^/]+\/stream\/s_[a-z0-9]+$/i.test(String(url || ''))) return;
319
- 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();
320
327
  const w = 480;
321
328
  const h = 300;
322
329
  const [wx, wy] = win.getPosition();
323
- const x = Math.max(area.x, Math.min(right - w, wx + size.w / 2 - w - 40));
324
- 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));
325
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 } });
326
334
  gameWin.removeMenu?.();
327
335
  gameWin.setAlwaysOnTop(true, 'floating');
@@ -331,7 +339,7 @@ function makeOt(opt = {}) {
331
339
  gameWin.webContents.setWindowOpenHandler(({ url: u }) => (shell.openExternal(u).catch(() => {}), { action: 'deny' }));
332
340
  gameWin.webContents.on('will-navigate', (e, u) => String(u).startsWith(`${origin}/stream/`) || (e.preventDefault(), shell.openExternal(u).catch(() => {})));
333
341
  gameWin.loadURL(url);
334
- gameWin.once('ready-to-show', () => gameWin.showInactive());
342
+ gameWin.once('ready-to-show', () => { gameWin.showInactive(); win.moveTop(); });
335
343
  gameWin.on('closed', () => (gameWin = null));
336
344
  };
337
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.
@@ -346,8 +354,9 @@ function makeOt(opt = {}) {
346
354
  const w = 400;
347
355
  const h = 330;
348
356
  const [wx, wy] = win.getPosition();
349
- const x = Math.max(area.x, Math.min(right - w, wx + size.w / 2 - w - 40));
350
- 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));
351
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 } });
352
361
  photoWin.removeMenu?.();
353
362
  photoWin.setAlwaysOnTop(true, 'floating');
@@ -393,8 +402,10 @@ function makeOt(opt = {}) {
393
402
  if (fs.existsSync(file)) img = nativeImage.createFromPath(file);
394
403
  else if (/^https:\/\//.test(g.cover || '')) {
395
404
  const r = await fetch(g.cover, { signal: AbortSignal.timeout(6000) });
396
- const type = (r.headers.get('content-type') || 'image/webp').split(';')[0];
397
- 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) {
398
409
  const src = `data:${type};base64,${Buffer.from(await r.arrayBuffer()).toString('base64')}`;
399
410
  const png = await win.webContents.executeJavaScript(`(async () => { const i = new Image(); i.src = ${JSON.stringify(src)}; await i.decode();
400
411
  const h = 40, w = 30, c = document.createElement('canvas'); c.width = w * 2; c.height = h * 2; const x = c.getContext('2d');
@@ -407,7 +418,8 @@ function makeOt(opt = {}) {
407
418
  }
408
419
  } catch {}
409
420
  img = img && !img.isEmpty() ? img.resize({ width: 30, height: 40, quality: 'best' }) : null;
410
- 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);
411
423
  return img;
412
424
  };
413
425
  const lastPlayed = () => {
@@ -503,8 +515,9 @@ function makeOt(opt = {}) {
503
515
  if (!grabbing.moved) page('postMessage({ carried: true })'); // the page stretches it toward the pull
504
516
  grabbing.moved = true;
505
517
  dragged = Date.now();
506
- pos.x = Math.max(area.x + size.w / 2 - 40, Math.min(right - size.w / 2 + 40, p.x + grabbing.dx));
507
- 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));
508
521
  place();
509
522
  }, 16);
510
523
  }
@@ -528,13 +541,15 @@ function makeOt(opt = {}) {
528
541
  window.__goal = null;
529
542
  return { rects: out, goal, need: window.__need?.(), busy: document.body.classList.contains('talking') || document.body.classList.contains('listening') || !!document.querySelector('.bubble.on'), asleep: document.body.classList.contains('asleep') };
530
543
  })()`;
544
+ let hitting = false; // one at a time: a busy renderer doesn't get a queue of them
531
545
  const hitTimer = setInterval(() => {
532
- if (!alive()) return;
546
+ if (!ready() || hitting) return;
547
+ hitting = true;
533
548
  win.webContents.executeJavaScript(HIT).then((r) => {
534
549
  ({ rects, busy, asleep } = r);
535
550
  need = r.need || null;
536
551
  if (r.goal) goTo(r.goal);
537
- }).catch(() => {});
552
+ }).catch(() => {}).finally(() => (hitting = false));
538
553
  }, 120);
539
554
 
540
555
  // Click-through: only the ot, its buttons and the talk box take the mouse; the transparent rest lets
@@ -564,10 +579,14 @@ function makeOt(opt = {}) {
564
579
  if (over) hoverUntil = Date.now() + 900;
565
580
  // anywhere over its window (not only the drawn parts): it stays put so it can be clicked or dragged
566
581
  if (x >= 0 && y >= 0 && x <= size.w && y <= size.h) stillUntil = Date.now() + 1200;
567
- // the eyes follow the cursor anywhere on screen (the page only sees it inside the window)
568
- if (!lastLook || Math.abs(x - lastLook[0]) + Math.abs(y - lastLook[1]) > 6) {
569
- lastLook = [x, y];
570
- 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)}] })`);
571
590
  }
572
591
  // dropped after a drag: a little dizzy
573
592
  if (dragged && !droppedSaid && Date.now() - dragged > 350) {
@@ -593,9 +612,10 @@ function makeOt(opt = {}) {
593
612
  // 16 px steps to avoid resizing for every pixel.
594
613
  const hover = Date.now() < hoverUntil;
595
614
  const step = (v) => Math.ceil(v / 16) * 16;
615
+ const rca = curArea();
596
616
  const want = {
597
- w: step(Math.min(area.width, Math.max(MIN.w, need?.w || 0, hover ? BIG.w : 0, held?.w || 0))),
598
- 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))),
599
619
  };
600
620
  const grow = want.w > size.w || want.h > size.h;
601
621
  const differs = want.w !== size.w || want.h !== size.h;
@@ -663,6 +683,7 @@ function makeOt(opt = {}) {
663
683
  let lastT = Date.now();
664
684
 
665
685
  function next() {
686
+ const { minX, maxX } = dispBounds();
666
687
  const now = Date.now();
667
688
  const r = Math.random();
668
689
  if (r < 0.38) return { mode: 'idle', until: now + rnd(1800, 7000) };
@@ -683,6 +704,7 @@ function makeOt(opt = {}) {
683
704
  const now = Date.now();
684
705
  const dt = Math.min(0.05, (now - lastT) / 1000);
685
706
  lastT = now;
707
+ const { minX, maxX, minY, floor } = dispBounds(); // current display, shadows the primary-display consts
686
708
  const errand = plan.mode === 'point';
687
709
  const scene = plan.mode === 'scene' || plan.mode === 'fling';
688
710
  // the cursor on it stops it, scenes too (the director sees interrupted() and ends the scene): something
@@ -765,7 +787,9 @@ function makeOt(opt = {}) {
765
787
  if (plan.mode === 'scene' || plan.mode === 'fling' || still || asleep || Date.now() - dragged < 2000) return;
766
788
  enterUntil = Date.now() + 12000;
767
789
  const to = { ...pos };
768
- const mid = area.x + area.width / 2;
790
+ const { minX, maxX } = dispBounds();
791
+ const ca = curArea();
792
+ const mid = ca.x + ca.width / 2;
769
793
  pos.x = Math.max(minX, Math.min(maxX, to.x + (to.x > mid ? -1 : 1) * 520));
770
794
  vel.x = vel.y = 0;
771
795
  place();
@@ -809,6 +833,7 @@ function makeOt(opt = {}) {
809
833
  async function goTo(goal) {
810
834
  if (still || plan.mode === 'scene' || plan.mode === 'fling') return; // a scene with another ot goes first
811
835
  if (goal === 'browser') await new Promise((r) => setTimeout(r, 900)); // let the site open first
836
+ const { minX, maxX, minY, floor } = dispBounds();
812
837
  const c = cursorPoint();
813
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 };
814
839
  const cx = rect.x + rect.w / 2;
@@ -855,14 +880,14 @@ function makeOt(opt = {}) {
855
880
  host: HOST,
856
881
  home: () => homeAnchor(),
857
882
  pos: () => ({ ...pos }),
858
- bounds: () => ({ minX, maxX, floor }),
883
+ bounds: () => { const b = dispBounds(); return { minX: b.minX, maxX: b.maxX, floor: b.floor }; },
859
884
  close,
860
885
  // free to join a scene: shown, loaded, not held still, dragged, hovered, talking or on an errand
861
886
  daemon: { url: base, token: opt.token || TOKEN }, // its own daemon (settings there can ask for a scene)
862
887
  // for a scene asked from settings: errands (pointing at the terminal while an agent works) may be cut short
863
888
  ready: () => alive() && win.isVisible() && !win.webContents.isLoading() && !asleep && Date.now() - dragged > 3000 && Date.now() > hoverUntil + 1500 && plan.mode !== 'scene' && plan.mode !== 'fling',
864
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),
865
- 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 }; },
866
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,
867
892
  face: (dir) => {
868
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' },
@@ -301,14 +301,14 @@
301
301
  $('#brain').innerHTML = '';
302
302
  $('#brain').append(t('brain', { b: '' }), Object.assign(document.createElement('b'), { textContent: BOOT.brain === 'lines' ? t('lines') : BOOT.brain }));
303
303
 
304
- const { createCharacter, loadCharacter3D, playBeat, DANCES = [], DANCE_STYLE = {}, AURA_MOVES = [], AURA_STYLE = {} } = await import('/dist/7ots.esm.js');
304
+ const { createCharacter, loadCharacter3D, playBeat, stripMarkdown = (x) => x, DANCES = [], DANCE_STYLE = {}, AURA_MOVES = [], AURA_STYLE = {} } = await import('/dist/7ots.esm.js');
305
305
  const spec = id.look?.character || {};
306
306
  let ch = null;
307
307
  if (new URLSearchParams(location.search).has('3d')) {
308
308
  // three comes from the CDN; without WebGL or network the 2D ot takes over
309
309
  try {
310
310
  const m = await loadCharacter3D();
311
- ch = m.createCharacter3D($('#face'), spec, { material: id.look?.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 } });
311
+ ch = m.createCharacter3D($('#face'), spec, { material: id.look?.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, fps: desktop ? 30 : 0 } });
312
312
  if (ch.fallback) console.warn('[7ots pet] no WebGL: 2D ot');
313
313
  } catch (err) {
314
314
  console.warn('[7ots pet] 3D ot unavailable, using 2D:', err?.message || err);
@@ -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));
@@ -684,7 +685,8 @@
684
685
  ch.gesture(Math.random() < 0.5 ? 'nod' : 'wiggle');
685
686
  }
686
687
  // speech tags ([laugh], <whisper>…: settings → Voice → expressions) go to the voice, never to the bubble (as src/voice/tags.js)
687
- const clean = (t) => String(t ?? '').replace(/<\/?(loud|soft|whisper|fast|slow|singing)>/gi, '').replace(/\s*\[(pause|long-pause|laugh|cry|mouth-click|breath|sigh)\]\s*/gi, ' ').replace(/\s{2,}/g, ' ').trim();
688
+ // what is said: no markdown ("## Hoteles", "**4.5**", "---") nor voice tags
689
+ const clean = (t) => stripMarkdown(String(t ?? '')).replace(/<\/?(loud|soft|whisper|fast|slow|singing)>/gi, '').replace(/\s*\[(pause|long-pause|laugh|cry|mouth-click|breath|sigh)\]\s*/gi, ' ').replace(/\s{2,}/g, ' ').trim();
688
690
  function say(raw, withFace = false, ambient = false, photo = null) {
689
691
  if (ambient && speak.cur && speak.reply) return void alog('skip ambient (an answer is playing)'); // small talk waits for the answer to finish
690
692
  const text = clean(raw);
@@ -976,7 +978,7 @@
976
978
  if (d.listen) listen();
977
979
  if (d.dropped) (ch.gesture('dizzy'), ch.effect?.('dizzy'));
978
980
  if (d.follow) ch.effect?.(Math.random() < 0.6 ? 'hearts' : 'question');
979
- 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
980
982
  });
981
983
 
982
984
  // ── scenes with other ots: the shell's director sends lines, gestures and acts to each one ──