@7ots/cli 0.1.19 → 0.1.37

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.
Files changed (104) hide show
  1. package/.env.example +14 -0
  2. package/brand/logos/base.svg +1 -0
  3. package/brand/logos/clawpump.png +0 -0
  4. package/brand/logos/conductors.svg +1 -0
  5. package/brand/logos/notlogin.svg +12 -0
  6. package/brand/logos/pumpfun.png +0 -0
  7. package/brand/logos/solana.png +0 -0
  8. package/brand/logos/spawnerbot.svg +1 -0
  9. package/brand/logos/virtuals.png +0 -0
  10. package/cli/7ots.mjs +59 -1
  11. package/cli/lib/account.mjs +23 -3
  12. package/cli/lib/assistant.mjs +88 -13
  13. package/cli/lib/brain.mjs +76 -8
  14. package/cli/lib/config.mjs +14 -3
  15. package/cli/lib/desktop-sync.mjs +177 -0
  16. package/cli/lib/i18n.mjs +9 -0
  17. package/cli/lib/inferences.mjs +19 -2
  18. package/cli/lib/integrations.mjs +61 -6
  19. package/cli/lib/pet-server.mjs +316 -41
  20. package/cli/lib/prompts.mjs +1 -1
  21. package/cli/lib/senses/gestures.mjs +121 -0
  22. package/cli/lib/senses/index.mjs +490 -0
  23. package/cli/lib/senses/rules.mjs +159 -0
  24. package/cli/lib/senses/sources/activity.mjs +95 -0
  25. package/cli/lib/senses/sources/calendar.mjs +75 -0
  26. package/cli/lib/senses/sources/index.mjs +17 -0
  27. package/cli/lib/senses/sources/mail.mjs +48 -0
  28. package/cli/lib/senses/sources/system.mjs +39 -0
  29. package/cli/lib/senses/util.mjs +41 -0
  30. package/cli/lib/senses/vendor.mjs +78 -0
  31. package/cli/lib/stt-local.py +16 -8
  32. package/cli/lib/stt.mjs +53 -6
  33. package/cli/lib/tooluse.mjs +56 -0
  34. package/cli/lib/vm.mjs +1 -1
  35. package/cli/lib/wake-local.py +109 -0
  36. package/cli/lib/wake.mjs +102 -0
  37. package/cli/pet/electron/main.cjs +145 -16
  38. package/cli/pet/pet.html +127 -27
  39. package/cli/pet/senses.html +342 -0
  40. package/cli/pet/settings.html +787 -86
  41. package/dist/7ots.esm.js +374 -146
  42. package/dist/7ots.esm.js.map +4 -4
  43. package/dist/7ots.iife.js +374 -146
  44. package/dist/7ots.iife.js.map +4 -4
  45. package/llms.txt +27 -0
  46. package/package.json +5 -2
  47. package/server/channels/apuchat.mjs +2 -0
  48. package/server/errors.mjs +90 -0
  49. package/server/notify.mjs +78 -0
  50. package/server/server.mjs +68 -12
  51. package/server/settings.mjs +3 -0
  52. package/server/site.mjs +401 -0
  53. package/server/tts.mjs +29 -5
  54. package/src/avatar/AvatarStage.js +2 -2
  55. package/src/avatar/three.js +3 -2
  56. package/src/character/AvatarEditor.js +2 -1
  57. package/src/character/Character.js +1 -1
  58. package/src/character/TradingCard.js +2 -0
  59. package/src/character/beat.js +64 -2
  60. package/src/character/mods/orc.js +8 -1
  61. package/src/character/mods.js +104 -10
  62. package/src/character/motion.js +162 -0
  63. package/src/character/parts.js +40 -38
  64. package/src/character/styles.js +40 -38
  65. package/src/character3d/Character3D.js +26 -5
  66. package/src/character3d/body.js +14 -12
  67. package/src/character3d/export.js +693 -0
  68. package/src/character3d/fx.js +13 -0
  69. package/src/character3d/index.js +2 -0
  70. package/src/character3d/materials.js +106 -10
  71. package/src/character3d/room-themes.js +1184 -0
  72. package/src/character3d/room.js +487 -0
  73. package/src/character3d/stage.js +9 -3
  74. package/src/creator/StepCreator.js +316 -0
  75. package/src/i18n/index.js +3 -3
  76. package/src/i18n/messages/character.js +352 -4
  77. package/src/i18n/messages/creator.js +138 -0
  78. package/src/i18n/messages/identity.js +89 -1
  79. package/src/i18n/messages/platform.js +255 -1
  80. package/src/i18n/messages/server.js +443 -1
  81. package/src/i18n/messages/widget.js +233 -0
  82. package/src/identity/random.js +14 -2
  83. package/src/identity/schema.js +2 -1
  84. package/src/index.js +10 -2
  85. package/src/voice/tags.js +22 -0
  86. package/server/platform/apuchat.mjs +0 -266
  87. package/server/platform/auth.mjs +0 -337
  88. package/server/platform/byte.mjs +0 -291
  89. package/server/platform/connect.mjs +0 -391
  90. package/server/platform/crypto.mjs +0 -80
  91. package/server/platform/db.mjs +0 -293
  92. package/server/platform/device.mjs +0 -247
  93. package/server/platform/integrations.mjs +0 -169
  94. package/server/platform/look.mjs +0 -20
  95. package/server/platform/mods.mjs +0 -222
  96. package/server/platform/orquesta.mjs +0 -611
  97. package/server/platform/profile.mjs +0 -182
  98. package/server/platform/routes.mjs +0 -589
  99. package/server/platform/runtime.mjs +0 -286
  100. package/server/platform/sites.mjs +0 -146
  101. package/server/platform/stage3d.mjs +0 -82
  102. package/server/platform/store.mjs +0 -469
  103. package/server/platform/vm.mjs +0 -1057
  104. package/server/platform/wallet.mjs +0 -255
package/cli/lib/stt.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Speech to text for voice control: the pet page records a short clip (webm/opus) and POSTs it to /stt.
3
- * Local first: faster-whisper in the venv ~/.7ots/stt (free, the audio never leaves the machine):
3
+ * Local first: faster-whisper in the venv ~/.7ots/stt (free, the audio never leaves the machine), one worker kept loaded:
4
4
  * python3 -m venv ~/.7ots/stt && ~/.7ots/stt/bin/pip install faster-whisper
5
5
  * otherwise whichever key is configured: OpenAI (OPENAI_API_KEY), then ElevenLabs (ELEVENLABS_API_KEY).
6
6
  * Without any, voice control is off and the page says so.
7
7
  */
8
8
 
9
- import { execFile } from 'node:child_process';
9
+ import { spawn } from 'node:child_process';
10
10
  import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
11
11
  import { tmpdir } from 'node:os';
12
12
  import { join } from 'node:path';
@@ -24,6 +24,56 @@ export function sttProvider(keys) {
24
24
  return null;
25
25
  }
26
26
 
27
+ // One Whisper worker, started on first use (or by warmStt) and kept: jobs go one at a time.
28
+ let worker = null;
29
+ let queue = Promise.resolve();
30
+ function startWorker() {
31
+ const p = spawn(LOCAL_PY(), [SCRIPT, process.env.SEVENOTS_STT_MODEL || ''], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
32
+ const w = { p, buf: '', waiting: null };
33
+ p.stdout.on('data', (d) => {
34
+ w.buf += d;
35
+ let i;
36
+ while ((i = w.buf.indexOf('\n')) >= 0) {
37
+ const line = w.buf.slice(0, i);
38
+ w.buf = w.buf.slice(i + 1);
39
+ let m = {};
40
+ try {
41
+ m = JSON.parse(line);
42
+ } catch {}
43
+ if (!m.ready) w.waiting?.(m);
44
+ }
45
+ });
46
+ p.on('exit', () => {
47
+ if (worker === w) worker = null;
48
+ w.waiting?.({ error: 'worker exited' });
49
+ });
50
+ p.unref();
51
+ return w;
52
+ }
53
+ function local(file, lang) {
54
+ const job = queue.then(
55
+ () =>
56
+ new Promise((res, rej) => {
57
+ worker ||= startWorker();
58
+ const w = worker;
59
+ const timer = setTimeout(() => (w.p.kill(), rej(Object.assign(new Error('local stt: timeout'), { status: 504 }))), 90000);
60
+ w.waiting = (m) => {
61
+ clearTimeout(timer);
62
+ w.waiting = null;
63
+ m.error === undefined ? res(String(m.text || '').trim()) : rej(Object.assign(new Error(`local stt: ${m.error}`), { status: 502 }));
64
+ };
65
+ w.p.stdin.write(JSON.stringify({ file, lang }) + '\n');
66
+ }),
67
+ );
68
+ queue = job.catch(() => {});
69
+ return job;
70
+ }
71
+
72
+ /** Loads the local model ahead of the first clip (the voice button, the wake word). */
73
+ export function warmStt() {
74
+ if (existsSync(LOCAL_PY())) worker ||= startWorker();
75
+ }
76
+
27
77
  /** → { text } ; throws with .status on provider errors. */
28
78
  export async function transcribe({ audio, contentType = 'audio/webm', lang = '', env = {} }) {
29
79
  const provider = sttProvider(env);
@@ -33,10 +83,7 @@ export async function transcribe({ audio, contentType = 'audio/webm', lang = '',
33
83
  const f = join(tmpdir(), `7ots-voice-${process.pid}-${Date.now()}.${EXT[type] || 'webm'}`);
34
84
  writeFileSync(f, audio, { mode: 0o600 });
35
85
  try {
36
- const text = await new Promise((res, rej) =>
37
- execFile(LOCAL_PY(), [SCRIPT, f, lang || ''], { timeout: 60000, windowsHide: true }, (e, out) => (e ? rej(Object.assign(new Error(`local stt: ${e.message.split('\n')[0]}`), { status: 502 })) : res(String(out).trim()))),
38
- );
39
- return { text, provider };
86
+ return { text: await local(f, lang), provider };
40
87
  } finally {
41
88
  try {
42
89
  unlinkSync(f);
@@ -0,0 +1,56 @@
1
+ /**
2
+ * What tools work for this ot (access.prowl, off by default): the host of each remote MCP server or API
3
+ * call, whether it worked and how long it took, summed in memory and sent every 10 minutes to the ot's
4
+ * account on 7ots.com (POST /api/device/plaza/tools). That feeds the plaza's trending tools and Prowl's
5
+ * ranking (server/platform/tooluse.mjs, docs/PLAZA-PROWL.md). Never the tool name, its arguments or its
6
+ * result; local servers (stdio commands, localhost, private IPs) are not counted.
7
+ */
8
+
9
+ import { env, loadConfig } from './config.mjs';
10
+ import { SEVENOTS_URL } from './account.mjs';
11
+
12
+ const buf = new Map();
13
+ let timer = null;
14
+
15
+ function hostOf(url) {
16
+ try {
17
+ const h = new URL(url).hostname.toLowerCase();
18
+ // the server drops private addresses too; this keeps them from leaving the computer at all
19
+ if (!h.includes('.') || /^(127|10|0)\.|^192\.168\.|^172\.(1[6-9]|2\d|3[01])\.|^169\.254\.|\.(local|localhost|internal|lan)$/.test(h) || h.startsWith('[')) return '';
20
+ return h;
21
+ } catch {
22
+ return '';
23
+ }
24
+ }
25
+
26
+ /** One call to an integration. Never throws. */
27
+ export function recordUse(url, ok, ms) {
28
+ try {
29
+ if (loadConfig().access?.prowl !== true) return;
30
+ const host = url ? hostOf(url) : '';
31
+ if (!host) return;
32
+ const r = buf.get(host) || { host, ok: 0, fail: 0, ms: 0 };
33
+ r[ok ? 'ok' : 'fail']++;
34
+ r.ms += Math.max(0, Math.round(ms) || 0);
35
+ buf.set(host, r);
36
+ if (!timer) (timer = setTimeout(flush, 10 * 60_000)), timer.unref?.();
37
+ } catch {
38
+ // counting never breaks the tool
39
+ }
40
+ }
41
+
42
+ export async function flush() {
43
+ timer = null;
44
+ const c = loadConfig();
45
+ const otsId = c.account?.otsId;
46
+ const token = env().SEVENOTS_TOKEN;
47
+ if (!buf.size || c.access?.prowl !== true || !otsId || !token) return buf.clear();
48
+ const uses = [...buf.values()].map((r) => ({ host: r.host, ok: r.ok, fail: r.fail, ms: Math.round(r.ms / (r.ok + r.fail)) }));
49
+ buf.clear();
50
+ await fetch(`${SEVENOTS_URL}/api/device/plaza/tools`, {
51
+ method: 'POST',
52
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
53
+ body: JSON.stringify({ ot: otsId, uses }),
54
+ signal: AbortSignal.timeout(15000),
55
+ }).catch(() => {});
56
+ }
package/cli/lib/vm.mjs CHANGED
@@ -284,7 +284,7 @@ async function deviceApi(otsId, path, o = {}) {
284
284
  }
285
285
 
286
286
  export const vmStatus = (otsId) => deviceApi(otsId, '');
287
- export const submitJob = (otsId, { kind, input, context }) => deviceApi(otsId, '/jobs', { method: 'POST', body: { kind, input, context } });
287
+ export const submitJob = (otsId, { kind, input, context }) => deviceApi(otsId, '/jobs', { method: 'POST', body: { kind, input, context }, timeout: 120000 }); // the first job may create the ot's microVM
288
288
  export const cancelJob = (otsId, jid) => deviceApi(otsId, `/jobs/${jid}/cancel`, { method: 'POST' });
289
289
 
290
290
  /** Follows a job until it ends; onEvent({kind,text,seq}) per event. Resolves {status, result?, error?}. */
@@ -0,0 +1,109 @@
1
+ """Wake word for the 7ots pet: python wake-local.py <model dir> <lang> <name> → listens to the default mic and prints
2
+ "wake" each time it hears "oye <name>" ("hey"/"ei" in en/pt). Runs in the venv ~/.7ots/stt (pip install vosk sounddevice).
3
+ Vosk runs on this computer and nothing is recorded or sent: it only reads the words to look for the trigger.
4
+ Free recognition of a whole room takes a full core, so it runs on a grammar: the trigger plus a few hundred common
5
+ words, which soak up everything else ("oye, dónde…" stays "oye donde", not "oye dobi") at ~10% of a core. A name the
6
+ model doesn't know (most invented ones) can't go in a grammar: then it's free recognition and a sounds-like match.
7
+ python wake-local.py --setup <model dir> <url> downloads and unzips the small model (~40-50 MB) once."""
8
+ import json
9
+ import os
10
+ import queue
11
+ import sys
12
+ import time
13
+ import unicodedata
14
+
15
+ if sys.argv[1] == '--setup':
16
+ import io
17
+ import shutil
18
+ import urllib.request
19
+ import zipfile
20
+ dest, url = sys.argv[2], sys.argv[3]
21
+ tmp = dest + '.part'
22
+ shutil.rmtree(tmp, ignore_errors=True)
23
+ with urllib.request.urlopen(url, timeout=120) as r:
24
+ z = zipfile.ZipFile(io.BytesIO(r.read()))
25
+ z.extractall(tmp)
26
+ inner = [d for d in os.listdir(tmp) if os.path.isdir(os.path.join(tmp, d))]
27
+ shutil.rmtree(dest, ignore_errors=True)
28
+ os.rename(os.path.join(tmp, inner[0]) if len(inner) == 1 else tmp, dest)
29
+ shutil.rmtree(tmp, ignore_errors=True)
30
+ print('ok')
31
+ sys.exit(0)
32
+
33
+ import sounddevice as sd
34
+ import vosk
35
+
36
+ vosk.SetLogLevel(-1)
37
+ model_dir, lang, name = sys.argv[1], sys.argv[2], sys.argv[3]
38
+ CALL = {'es': ['oye', 'hey', 'ey'], 'en': ['hey', 'hi', 'okay'], 'pt': ['ei', 'oi', 'hey']}.get(lang, ['hey', 'oye'])
39
+
40
+
41
+ def norm(s):
42
+ return ''.join(c for c in unicodedata.normalize('NFD', s.lower()) if unicodedata.category(c) != 'Mn')
43
+
44
+
45
+ def sound(s):
46
+ # spelled as it sounds, roughly: "toby" ≈ "dobi", "dovi" ≈ "dobi", "kai" ≈ "cai"
47
+ s = norm(s).replace('ll', 'y').replace('qu', 'k').replace('h', '')
48
+ s = ''.join({'v': 'b', 'c': 'k', 'z': 's', 'w': 'u', 't': 'd', 'p': 'b', 'g': 'k'}.get(c, c) for c in s)
49
+ s = s[:-1] + 'i' if s.endswith('y') else s
50
+ return ''.join(c for i, c in enumerate(s) if i == 0 or c != s[i - 1])
51
+
52
+
53
+ def dist(a, b):
54
+ row = list(range(len(b) + 1))
55
+ for i, ca in enumerate(a, 1):
56
+ prev, row[0] = row[0], i
57
+ for j, cb in enumerate(b, 1):
58
+ prev, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, prev + (ca != cb))
59
+ return row[-1]
60
+
61
+
62
+ target = norm(name).split()
63
+ key = sound(''.join(target))
64
+ slack = max(1, len(key) // 4)
65
+ calls = {sound(c) for c in CALL} | {sound('oi'), sound('ei')}
66
+
67
+
68
+ def hit(text):
69
+ w = norm(text).split()
70
+ n = len(target)
71
+ for i in range(1, len(w) - n + 1):
72
+ # "oye dobi", and the name split or glued the way the small model hears it ("do vi", "toby")
73
+ if sound(w[i - 1]) in calls and any(dist(sound(''.join(w[i:i + k])), key) <= slack for k in range(n, n + 2) if i + k <= len(w)):
74
+ return True
75
+ return False
76
+
77
+
78
+ COMMON = {
79
+ 'es': """a al algo ahi ahora alla aca asi aqui ayuda ayudas bien bueno buenos buenas cada casa como con cosa cual cuando cuanto de del dame decir dia dias dime donde dos el ella ellos en entonces era eres es esa ese eso esta este esto estas estoy favor frio fue gente gracias hace hacer hasta hay hola hora hoy ir la las le libro lo los luego mas me mi mio mira mucho muy nada no noche nos o otra otro para pero poco por porque pues puedes que quien quiero se si sin sobre son su tal tambien tan tarde te tengo tiempo tienes todo tu un una uno va vamos ve ven ver vez y ya yo""",
80
+ 'en': """a about all and are at be but by can come could do does done for from get go good have he hello her here hi his how i if in is it just know like look me my no not now of oh ok on one or out please right see she so some that the then there they this time to today up us want was we well what when where who why will with would yes you your""",
81
+ 'pt': """a ai agora aqui as assim bem boa bom casa com como de do da dia diz e ela ele em entao era esse essa esta este estou eu faz fazer hoje isso ja la mais me meu minha muito na nao no nos o obrigado olha onde os ou para pode por porque quando que quem se sei sim so sua tem tempo tudo um uma vai vamos ver voce""",
82
+ }.get(lang, '').split()
83
+ model = vosk.Model(model_dir)
84
+ has = lambda x: vosk._c.vosk_model_find_word(model._handle, x.encode()) >= 0
85
+ nm = ' '.join(target)
86
+ known = all(has(x) for x in target)
87
+ calls_k = [c for c in CALL if has(c)]
88
+ if known:
89
+ words = sorted({w for w in map(norm, COMMON) if has(w)} - set(target) - set(calls_k))
90
+ rec = vosk.KaldiRecognizer(model, 16000, json.dumps([f'{c} {nm}' for c in calls_k] + [nm] + calls_k + words + ['[unk]']))
91
+ else:
92
+ rec = vosk.KaldiRecognizer(model, 16000)
93
+ q = queue.Queue()
94
+ stream = sd.RawInputStream(samplerate=16000, blocksize=4000, dtype='int16', channels=1, callback=lambda d, *_: q.put(bytes(d)))
95
+ stream.start()
96
+ print('ready', flush=True)
97
+ quiet = 0
98
+ seen = 0
99
+ while True:
100
+ data = q.get()
101
+ final = rec.AcceptWaveform(data)
102
+ text = json.loads(rec.Result() if final else rec.PartialResult()).get('text' if final else 'partial', '')
103
+ # a partial can flicker to the name for a moment ("oye do…" → "oye dobi" → "oye donde"): twice in a row, or final
104
+ seen = seen + 1 if text and hit(text) else 0
105
+ if time.time() > quiet and (seen >= 2 or (final and seen)):
106
+ print('wake', flush=True)
107
+ quiet = time.time() + 3
108
+ seen = 0
109
+ rec.Reset()
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Wake word: "oye <name>" ("hey" / "ei") opens the mic like the 🎙️ button (voice.wake in config, off by default).
3
+ * Vosk in the venv ~/.7ots/stt (wake-local.py) reads the default microphone on this computer and only looks for the
4
+ * trigger: no audio is kept or sent. The first time it is turned on it adds vosk + sounddevice to the venv and the
5
+ * small model of the ot's language (~40-60 MB from alphacephei.com) into ~/.7ots/stt/vosk-<lang>.
6
+ */
7
+
8
+ import { execFile, spawn } from 'node:child_process';
9
+ import { existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { homeFile } from './paths.mjs';
12
+
13
+ const PY = () => homeFile(join('stt', 'bin', 'python'));
14
+ const SCRIPT = new URL('./wake-local.py', import.meta.url).pathname;
15
+ const MODELS = { es: 'vosk-model-small-es-0.42', en: 'vosk-model-small-en-us-0.15', pt: 'vosk-model-small-pt-0.3' };
16
+ const modelDir = (lang) => homeFile(join('stt', `vosk-${lang}`));
17
+
18
+ const run = (args, timeout) =>
19
+ new Promise((res, rej) => execFile(PY(), args, { timeout, windowsHide: true }, (e, out, err) => (e ? rej(new Error(String(err || e.message).trim().split('\n').pop())) : res(String(out)))));
20
+
21
+ /** → { set({ on, name, lang }), status(), stop() }; onWake() each time it hears the trigger. */
22
+ export function createWake({ log = () => {}, onWake = () => {}, onState = () => {} } = {}) {
23
+ let want = { on: false };
24
+ let proc = null;
25
+ let state = 'off';
26
+ let error = '';
27
+ let busy = null;
28
+ let fails = 0;
29
+ let retry = null;
30
+ const status = () => ({ on: want.on, state, ...(error ? { error } : {}) });
31
+ const to = (s, e = '') => (state !== s || error !== e) && ((state = s), (error = e), onState(status()));
32
+
33
+ async function ready(lang) {
34
+ if (!existsSync(PY())) throw new Error('no local voice venv (~/.7ots/stt)');
35
+ try {
36
+ await run(['-c', 'import vosk, sounddevice'], 20000);
37
+ } catch {
38
+ log('wake: installing vosk + sounddevice in the venv');
39
+ await run(['-m', 'pip', 'install', '-q', 'vosk', 'sounddevice'], 600000);
40
+ }
41
+ if (!existsSync(join(modelDir(lang), 'conf'))) {
42
+ log(`wake: downloading ${MODELS[lang]}`);
43
+ await run([SCRIPT, '--setup', modelDir(lang), `https://alphacephei.com/vosk/models/${MODELS[lang]}.zip`], 600000);
44
+ }
45
+ }
46
+
47
+ function kill() {
48
+ clearTimeout(retry);
49
+ if (proc) proc.removeAllListeners('exit'), proc.kill();
50
+ proc = null;
51
+ }
52
+
53
+ async function start() {
54
+ const { name, lang } = want;
55
+ to('setup');
56
+ busy = ready(lang);
57
+ try {
58
+ await busy;
59
+ } catch (e) {
60
+ busy = null;
61
+ return log(`wake: ${e.message}`), to('error', e.message);
62
+ }
63
+ busy = null;
64
+ if (!want.on || want.name !== name || want.lang !== lang) return want.on ? start() : to('off'); // changed meanwhile
65
+ const p = (proc = spawn(PY(), [SCRIPT, modelDir(lang), lang, name], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }));
66
+ let tail = '';
67
+ p.stderr.on('data', (d) => (tail = (tail + d).slice(-400)));
68
+ p.stdout.on('data', (d) => {
69
+ for (const line of String(d).split('\n')) {
70
+ if (line === 'ready') (fails = 0), to('on'), log(`wake: listening for "${name}" (${lang})`);
71
+ if (line === 'wake') log('wake: heard it'), onWake();
72
+ }
73
+ });
74
+ p.on('exit', (code) => {
75
+ proc = null;
76
+ const why = tail.trim().split('\n').pop() || `exit ${code}`;
77
+ log(`wake: stopped (${why})`);
78
+ if (!want.on) return to('off');
79
+ // a mic that went away, a crash: try again a few times, slower each time
80
+ if (++fails > 4) return to('error', why);
81
+ to('error', why);
82
+ retry = setTimeout(() => want.on && !proc && !busy && start(), 5000 * fails);
83
+ });
84
+ }
85
+
86
+ return {
87
+ set({ on, name, lang }) {
88
+ const next = { on: !!on && !!String(name || '').trim(), name: String(name || '').trim().slice(0, 40), lang: MODELS[lang] ? lang : 'en' };
89
+ if (next.on === want.on && next.name === want.name && next.lang === want.lang) return;
90
+ want = next;
91
+ kill();
92
+ fails = 0;
93
+ if (!want.on) return to('off');
94
+ if (!busy) start();
95
+ },
96
+ status,
97
+ stop() {
98
+ want = { on: false };
99
+ kill();
100
+ },
101
+ };
102
+ }
@@ -12,7 +12,7 @@
12
12
 
13
13
  const path = require('node:path');
14
14
  const { execFile } = require('node:child_process');
15
- const { app, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, screen, session, shell } = require('electron');
15
+ const { app, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, screen, session, shell, systemPreferences } = require('electron');
16
16
 
17
17
  const URL_ = process.env.SEVENOTS_PET_URL;
18
18
  const TOKEN = process.env.SEVENOTS_PET_TOKEN;
@@ -31,9 +31,9 @@ const MIN = { w: 288, h: 272 };
31
31
  const linux = process.platform === 'linux';
32
32
 
33
33
  const L = {
34
- en: { settings: '⚙️ Settings', talk: '💬 Talk', listen: '🎙️ Listen (Ctrl+Alt+Space)', show: 'Show pet', hide: 'Hide (keeps living)', feed: '🍎 Treat', play: '🎾 Play', byte: '🎮 Play on byte', watch: '📺 Watch the game', stopGame: '⏹ Stop the game', noGames: 'byte: no games (sign in to 7ots.com)', sleep: '💤 Sleep', wake: '☀️ Wake up', still: 'Stay still', quit: 'Quit pet' },
35
- es: { settings: '⚙️ Configuración', talk: '💬 Hablar', listen: '🎙️ Escúchame (Ctrl+Alt+Espacio)', show: 'Mostrar mascota', hide: 'Ocultar (sigue viva)', feed: '🍎 Mimar', play: '🎾 Jugar', byte: '🎮 Jugar en byte', watch: '📺 Ver la partida', stopGame: '⏹ Parar la partida', noGames: 'byte: sin juegos (entra a 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Despertar', still: 'Quedarse quieta', quit: 'Cerrar mascota' },
36
- pt: { settings: '⚙️ Configurações', talk: '💬 Falar', listen: '🎙️ Me escute (Ctrl+Alt+Espaço)', show: 'Mostrar bichinho', hide: 'Esconder (segue vivo)', feed: '🍎 Mimar', play: '🎾 Brincar', byte: '🎮 Jogar no byte', watch: '📺 Ver a partida', stopGame: '⏹ Parar a partida', noGames: 'byte: sem jogos (entre no 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Acordar', still: 'Ficar parado', quit: 'Fechar bichinho' },
34
+ en: { settings: '⚙️ Settings', talk: '💬 Talk', listen: '🎙️ Listen (Ctrl+Alt+Space)', show: 'Show pet', hide: 'Hide (keeps living)', feed: '🍎 Treat', play: '🎾 Play', byte: '🎮 Play on byte', watch: '📺 Watch the game', stopGame: '⏹ Stop the game', lastGame: 'Last played', moreGames: 'More games', noGames: 'byte: no games (sign in to 7ots.com)', sleep: '💤 Sleep', wake: '☀️ Wake up', still: 'Stay still', quit: 'Quit pet' },
35
+ es: { settings: '⚙️ Configuración', talk: '💬 Hablar', listen: '🎙️ Escúchame (Ctrl+Alt+Espacio)', show: 'Mostrar mascota', hide: 'Ocultar (sigue viva)', feed: '🍎 Mimar', play: '🎾 Jugar', byte: '🎮 Jugar en byte', watch: '📺 Ver la partida', stopGame: '⏹ Parar la partida', lastGame: 'Último jugado', moreGames: 'Más juegos', noGames: 'byte: sin juegos (entra a 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Despertar', still: 'Quedarse quieta', quit: 'Cerrar mascota' },
36
+ pt: { settings: '⚙️ Configurações', talk: '💬 Falar', listen: '🎙️ Me escute (Ctrl+Alt+Espaço)', show: 'Mostrar bichinho', hide: 'Esconder (segue vivo)', feed: '🍎 Mimar', play: '🎾 Brincar', byte: '🎮 Jogar no byte', watch: '📺 Ver a partida', stopGame: '⏹ Parar a partida', lastGame: 'Último jogado', moreGames: 'Mais jogos', noGames: 'byte: sem jogos (entre no 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Acordar', still: 'Ficar parado', quit: 'Fechar bichinho' },
37
37
  }[LANG] || {};
38
38
  const tr = (k) => L[k] || { listen: 'Listen', show: 'Show pet', hide: 'Hide', talk: 'Talk', settings: 'Settings', feed: 'Feed', play: 'Play', sleep: 'Sleep', wake: 'Wake up', still: 'Stay still', quit: 'Quit pet' }[k];
39
39
 
@@ -142,6 +142,32 @@ function start() {
142
142
  setTimeout(syncVisitors, 2500);
143
143
  setInterval(syncVisitors, 4000);
144
144
  require('./director.cjs').createDirector({ ots, lang: LANG, url: URL_, token: TOKEN });
145
+ setInterval(syncSenses, 5000);
146
+ setTimeout(syncSenses, 4000);
147
+ }
148
+
149
+ // The ot's eyes (settings → Senses → camera): /senses in a hidden window while the daemon wants the camera.
150
+ // Closing the window is what turns the camera off (its light goes out), so off and paused destroy it.
151
+ let sensesWin = null;
152
+ let askedCamera = false;
153
+ async function syncSenses() {
154
+ const st = await fetch(new URL('/senses/status', URL_), { headers: { 'X-7ots-Token': TOKEN } }).then((r) => (r.ok ? r.json() : null), () => null);
155
+ const want = Boolean(st?.wantCamera);
156
+ if (!want) {
157
+ if (sensesWin && !sensesWin.isDestroyed()) sensesWin.destroy();
158
+ sensesWin = null;
159
+ return;
160
+ }
161
+ if (sensesWin && !sensesWin.isDestroyed()) return;
162
+ if (process.platform === 'darwin' && !askedCamera) {
163
+ askedCamera = true;
164
+ if (systemPreferences.getMediaAccessStatus('camera') !== 'granted' && !(await systemPreferences.askForMediaAccess('camera').catch(() => false))) return;
165
+ }
166
+ sensesWin = new BrowserWindow({ show: false, width: 640, height: 480, skipTaskbar: true, webPreferences: { contextIsolation: true, sandbox: true, backgroundThrottling: false } });
167
+ sensesWin.webContents.on('will-navigate', (e) => e.preventDefault());
168
+ sensesWin.webContents.on('console-message', (e, level, msg) => ['warning', 'error', 2, 3].includes(e?.level ?? level) && console.log(`[7ots senses] ${msg ?? e?.message}`));
169
+ sensesWin.on('closed', () => (sensesWin = null));
170
+ sensesWin.loadURL(`${URL_}/senses?token=${encodeURIComponent(TOKEN)}`).catch(() => {});
145
171
  }
146
172
 
147
173
  // Settings in a window of our own (not a browser tab); links elsewhere open in the browser.
@@ -226,21 +252,39 @@ function makeOt(opt = {}) {
226
252
  // Only our own pet page may load (its reload after a settings change or another ot: Electron routes
227
253
  // location.reload() through will-navigate too, so blocking everything froze the old look until a restart).
228
254
  win.webContents.on('will-navigate', (e, url) => String(url || e?.url || '').startsWith(`${base}/pet?`) || e.preventDefault());
255
+ win.webContents.on('did-finish-load', () => ((offTold = ''), alive() && tellOff(win.getBounds()))); // a reload forgets it
229
256
  win.webContents.on('console-message', (e, level, msg) => /\[7ots/.test(msg ?? e?.message) && console.log(msg ?? e?.message)); // to ~/.7ots/electron.log
230
257
  // The microphone, only for our own page (voice control).
231
258
  const ours = (u) => /^http:\/\/127\.0\.0\.1:\d+\//.test(String(u || '')); // our daemons
232
259
  session.defaultSession.setPermissionRequestHandler((wc, perm, cb, d) => cb(perm === 'media' && ours(d?.requestingUrl || wc.getURL())));
233
260
  session.defaultSession.setPermissionCheckHandler((wc, perm, origin) => perm === 'media' && ours(origin));
234
261
  const alive = () => !win.isDestroyed();
235
- const page = (js) => alive() && win.webContents.executeJavaScript(js).catch(() => {});
262
+ // While the page loads (a reload after the settings, 2D ↔ 3D) executeJavaScript waits for it on a
263
+ // did-stop-loading listener of its own: the 60 ms timers piled them up (MaxListenersExceededWarning)
264
+ const ready = () => alive() && !win.webContents.isLoadingMainFrame();
265
+ const page = (js) => ready() && win.webContents.executeJavaScript(js).catch(() => {});
236
266
 
237
267
  let still = false;
238
268
  let lastBounds = null;
269
+ // How much of the window hangs off the screen it is on (a drag may leave it 40 px past the floor or the
270
+ // right edge, or over the taskbar): the page lifts the hover menu by that much, and moves it to the ot's
271
+ // left when the right side is cut, so the buttons are never off screen (QA BUG-015).
272
+ let offTold = '';
273
+ const tellOff = (b) => {
274
+ const wa = screen.getDisplayNearestPoint({ x: Math.round(b.x + b.width / 2), y: Math.round(b.y + b.height / 2) }).workArea;
275
+ const below = Math.max(0, b.y + b.height - (wa.y + wa.height));
276
+ const pastRight = Math.max(0, b.x + b.width - (wa.x + wa.width));
277
+ const key = `${below},${pastRight}`;
278
+ if (key === offTold) return;
279
+ offTold = key;
280
+ page(`document.documentElement.style.setProperty('--off-below', '${below}px'); document.body.classList.toggle('menu-left', ${pastRight > 0})`);
281
+ };
239
282
  const place = (lift = 0) => {
240
283
  const b = bounds(size, pos, lift);
241
284
  if (lastBounds && b.x === lastBounds.x && b.y === lastBounds.y && b.width === lastBounds.width && b.height === lastBounds.height) return;
242
285
  lastBounds = b;
243
286
  win.setBounds(b);
287
+ tellOff(b);
244
288
  };
245
289
  const show = () => {
246
290
  Object.assign(pos, homeAnchor());
@@ -293,7 +337,32 @@ function makeOt(opt = {}) {
293
337
  gameWin.once('ready-to-show', () => gameWin.showInactive());
294
338
  gameWin.on('closed', () => (gameWin = null));
295
339
  };
340
+ // what it saw when you asked it to look at you ("¿cómo me ves?"): a small window beside it, like the game's.
341
+ // The frame comes from the pet page (in memory) and is shown from a data: page; nothing is written to disk.
342
+ let photoWin = null;
343
+ const showPhoto = ({ photo }) => {
344
+ if (!/^data:image\/jpeg;base64,[\w+/=]+$/.test(String(photo || ''))) return;
345
+ const title = { es: 'Lo que vi', pt: 'O que eu vi' }[LANG] || 'What I saw';
346
+ const html = `<!doctype html><meta charset="utf-8"><title>${title}</title><style>html,body{margin:0;height:100%;background:#0b0b12;color:#e8e8f0;font:13px/1.4 system-ui,sans-serif}body{display:flex;flex-direction:column}img{flex:1;min-height:0;width:100%;object-fit:contain;background:#000}</style><img src="${photo}" alt="">`;
347
+ const url = `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
348
+ if (photoWin && !photoWin.isDestroyed()) return photoWin.loadURL(url), photoWin.showInactive();
349
+ const w = 400;
350
+ const h = 330;
351
+ 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));
354
+ 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
+ photoWin.removeMenu?.();
356
+ photoWin.setAlwaysOnTop(true, 'floating');
357
+ photoWin.webContents.on('will-navigate', (e) => e.preventDefault());
358
+ photoWin.loadURL(url);
359
+ photoWin.once('ready-to-show', () => photoWin.showInactive());
360
+ photoWin.on('closed', () => (photoWin = null));
361
+ };
296
362
  const playGame = async (game) => {
363
+ try {
364
+ require('node:fs').writeFileSync(path.join(process.env.SEVENOTS_HOME || path.join(require('node:os').homedir(), '.7ots'), 'byte-last.json'), JSON.stringify({ slug: game, at: Date.now() }));
365
+ } catch {}
297
366
  const r = await fetch(new URL('/byte/play', base), { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-7ots-Token': tok }, body: JSON.stringify({ game }) }).then((x) => x.json()).catch((e) => ({ error: e.message }));
298
367
  if (r.streamUrl) {
299
368
  watchGame(r.streamUrl);
@@ -311,17 +380,68 @@ function makeOt(opt = {}) {
311
380
  if (gameWin && !gameWin.isDestroyed()) gameWin.close();
312
381
  } else if (!st.moves && n < 12) watchStart(sid, n + 1);
313
382
  }, 4000);
383
+ // The 🎮 menu: only what the ot can play from here, with byte's covers as thumbnails: the last one it played,
384
+ // 3 at random, and "more games" with the rest. byte's covers are webp (a menu icon takes png/jpg), so the
385
+ // pet's own page decodes each one once into a small png, kept in ~/.7ots/byte-thumbs.
386
+ const fs = require('node:fs');
387
+ const SEVEN = process.env.SEVENOTS_HOME || path.join(require('node:os').homedir(), '.7ots');
388
+ const THUMBS = path.join(SEVEN, 'byte-thumbs');
389
+ const LAST_FILE = path.join(SEVEN, 'byte-last.json');
390
+ const thumbs = new Map(); // slug → nativeImage | null
391
+ const thumbOf = async (g) => {
392
+ if (thumbs.has(g.slug)) return thumbs.get(g.slug);
393
+ const file = path.join(THUMBS, `${String(g.slug).replace(/[^\w-]/g, '_')}.png`);
394
+ let img = null;
395
+ try {
396
+ if (fs.existsSync(file)) img = nativeImage.createFromPath(file);
397
+ else if (/^https:\/\//.test(g.cover || '')) {
398
+ 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)) {
401
+ const src = `data:${type};base64,${Buffer.from(await r.arrayBuffer()).toString('base64')}`;
402
+ const png = await win.webContents.executeJavaScript(`(async () => { const i = new Image(); i.src = ${JSON.stringify(src)}; await i.decode();
403
+ const h = 40, w = 30, c = document.createElement('canvas'); c.width = w * 2; c.height = h * 2; const x = c.getContext('2d');
404
+ const s = Math.max(c.width / i.naturalWidth, c.height / i.naturalHeight); x.drawImage(i, (c.width - i.naturalWidth * s) / 2, (c.height - i.naturalHeight * s) / 2, i.naturalWidth * s, i.naturalHeight * s);
405
+ return c.toDataURL('image/png'); })()`, true);
406
+ img = nativeImage.createFromDataURL(png);
407
+ fs.mkdirSync(THUMBS, { recursive: true });
408
+ fs.writeFileSync(file, img.toPNG());
409
+ }
410
+ }
411
+ } catch {}
412
+ img = img && !img.isEmpty() ? img.resize({ width: 30, height: 40, quality: 'best' }) : null;
413
+ thumbs.set(g.slug, img);
414
+ return img;
415
+ };
416
+ const lastPlayed = () => {
417
+ try {
418
+ return JSON.parse(fs.readFileSync(LAST_FILE, 'utf8')).slug || '';
419
+ } catch {
420
+ return '';
421
+ }
422
+ };
314
423
  const gameMenu = async () => {
315
424
  const [st, g] = await Promise.all([getOt('/byte'), getOt('/byte/games')]);
316
- const live = st.play?.status === 'running';
317
- const items = live
318
- ? [
319
- { label: `${st.play.game} · ${st.play.moves}`, enabled: false },
320
- { label: tr('watch'), click: () => watchGame(st.play.streamUrl) },
321
- { label: tr('stopGame'), click: () => postOt('/byte/stop').then(() => gameWin && !gameWin.isDestroyed() && gameWin.close()) },
322
- ]
323
- : (g.games || []).map((x) => ({ label: x.name || x.slug, click: () => playGame(x.slug) }));
324
- return Menu.buildFromTemplate(items.length ? items : [{ label: tr('noGames'), enabled: false }]);
425
+ if (st.play?.status === 'running') {
426
+ return Menu.buildFromTemplate([
427
+ { label: `${st.play.game} · ${st.play.moves}`, enabled: false },
428
+ { label: tr('watch'), click: () => watchGame(st.play.streamUrl) },
429
+ { label: tr('stopGame'), click: () => postOt('/byte/stop').then(() => gameWin && !gameWin.isDestroyed() && gameWin.close()) },
430
+ ]);
431
+ }
432
+ const games = (g.games || []).filter((x) => x.playable !== false && x.slug);
433
+ if (!games.length) return Menu.buildFromTemplate([{ label: tr('noGames'), enabled: false }]);
434
+ await Promise.all(games.map((x) => thumbOf(x).catch(() => null)));
435
+ const item = (x) => ({ label: x.name || x.slug, ...(thumbs.get(x.slug) ? { icon: thumbs.get(x.slug) } : {}), click: () => playGame(x.slug) });
436
+ const last = games.find((x) => x.slug === lastPlayed());
437
+ const rest = games.filter((x) => x !== last);
438
+ const pick = [...rest].sort(() => Math.random() - 0.5).slice(0, 3);
439
+ const more = rest.filter((x) => !pick.includes(x));
440
+ return Menu.buildFromTemplate([
441
+ ...(last ? [{ label: tr('lastGame'), enabled: false }, item(last), { type: 'separator' }] : []),
442
+ ...pick.map(item),
443
+ ...(more.length ? [{ type: 'separator' }, { label: tr('moreGames'), submenu: more.map(item) }] : []),
444
+ ]);
325
445
  };
326
446
  function listen() {
327
447
  if (!win.isVisible()) win.showInactive();
@@ -411,13 +531,15 @@ function makeOt(opt = {}) {
411
531
  window.__goal = null;
412
532
  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') };
413
533
  })()`;
534
+ let hitting = false; // one at a time: a busy renderer doesn't get a queue of them
414
535
  const hitTimer = setInterval(() => {
415
- if (!alive()) return;
536
+ if (!ready() || hitting) return;
537
+ hitting = true;
416
538
  win.webContents.executeJavaScript(HIT).then((r) => {
417
539
  ({ rects, busy, asleep } = r);
418
540
  need = r.need || null;
419
541
  if (r.goal) goTo(r.goal);
420
- }).catch(() => {});
542
+ }).catch(() => {}).finally(() => (hitting = false));
421
543
  }, 120);
422
544
 
423
545
  // Click-through: only the ot, its buttons and the talk box take the mouse; the transparent rest lets
@@ -516,6 +638,13 @@ function makeOt(opt = {}) {
516
638
  if (m.startsWith('\u00a77bye')) return HOST || dismiss();
517
639
  if (m.startsWith('\u00a77ctx')) return (FULL ? menu() : guestMenu()).popup({ window: win });
518
640
  if (m.startsWith('\u00a77game')) return FULL && gameMenu().then((mm) => mm.popup({ window: win }));
641
+ if (m.startsWith('\u00a77photo')) {
642
+ try {
643
+ return showPhoto(JSON.parse(m.slice(7)));
644
+ } catch {
645
+ return;
646
+ }
647
+ }
519
648
  if (m.startsWith('\u00a77view')) return setView(m.slice(6) === '3d');
520
649
  if (m.startsWith('\u00a77enter')) return enter();
521
650
  if (!m.startsWith('\u00a77need')) return;