@7ots/cli 0.1.17 → 0.1.36

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 (107) hide show
  1. package/.env.example +14 -0
  2. package/README.md +11 -0
  3. package/brand/logos/base.svg +1 -0
  4. package/brand/logos/clawpump.png +0 -0
  5. package/brand/logos/conductors.svg +1 -0
  6. package/brand/logos/notlogin.svg +12 -0
  7. package/brand/logos/pumpfun.png +0 -0
  8. package/brand/logos/solana.png +0 -0
  9. package/brand/logos/spawnerbot.svg +1 -0
  10. package/brand/logos/virtuals.png +0 -0
  11. package/cli/7ots.mjs +61 -1
  12. package/cli/lib/account.mjs +23 -3
  13. package/cli/lib/assistant.mjs +92 -14
  14. package/cli/lib/brain.mjs +84 -11
  15. package/cli/lib/card-shot.mjs +1 -1
  16. package/cli/lib/config.mjs +14 -3
  17. package/cli/lib/desktop-sync.mjs +177 -0
  18. package/cli/lib/i18n.mjs +9 -0
  19. package/cli/lib/inferences.mjs +19 -2
  20. package/cli/lib/integrations.mjs +98 -13
  21. package/cli/lib/mcp.mjs +1 -1
  22. package/cli/lib/open.mjs +3 -1
  23. package/cli/lib/pet-server.mjs +352 -41
  24. package/cli/lib/prompts.mjs +1 -1
  25. package/cli/lib/screen.mjs +1 -1
  26. package/cli/lib/senses/gestures.mjs +121 -0
  27. package/cli/lib/senses/index.mjs +490 -0
  28. package/cli/lib/senses/rules.mjs +159 -0
  29. package/cli/lib/senses/sources/activity.mjs +95 -0
  30. package/cli/lib/senses/sources/calendar.mjs +75 -0
  31. package/cli/lib/senses/sources/index.mjs +17 -0
  32. package/cli/lib/senses/sources/mail.mjs +48 -0
  33. package/cli/lib/senses/sources/system.mjs +39 -0
  34. package/cli/lib/senses/util.mjs +41 -0
  35. package/cli/lib/senses/vendor.mjs +78 -0
  36. package/cli/lib/stt-local.py +16 -8
  37. package/cli/lib/stt.mjs +53 -6
  38. package/cli/lib/tooluse.mjs +56 -0
  39. package/cli/lib/tts-local.mjs +2 -2
  40. package/cli/lib/vm.mjs +2 -2
  41. package/cli/lib/wake-local.py +109 -0
  42. package/cli/lib/wake.mjs +102 -0
  43. package/cli/pet/electron/main.cjs +190 -8
  44. package/cli/pet/pet.html +153 -34
  45. package/cli/pet/senses.html +342 -0
  46. package/cli/pet/settings.html +815 -74
  47. package/dist/7ots.esm.js +373 -146
  48. package/dist/7ots.esm.js.map +4 -4
  49. package/dist/7ots.iife.js +373 -146
  50. package/dist/7ots.iife.js.map +4 -4
  51. package/llms.txt +27 -0
  52. package/package.json +5 -2
  53. package/server/channels/apuchat.mjs +18 -4
  54. package/server/errors.mjs +90 -0
  55. package/server/notify.mjs +78 -0
  56. package/server/server.mjs +84 -14
  57. package/server/settings.mjs +3 -0
  58. package/server/site.mjs +401 -0
  59. package/server/tts.mjs +29 -5
  60. package/src/avatar/AvatarStage.js +2 -2
  61. package/src/avatar/three.js +3 -2
  62. package/src/character/AvatarEditor.js +2 -1
  63. package/src/character/Character.js +38 -5
  64. package/src/character/TradingCard.js +2 -0
  65. package/src/character/beat.js +64 -2
  66. package/src/character/mods/orc.js +8 -1
  67. package/src/character/mods.js +104 -10
  68. package/src/character/motion.js +252 -1
  69. package/src/character/parts.js +40 -38
  70. package/src/character/styles.js +40 -38
  71. package/src/character3d/Character3D.js +26 -5
  72. package/src/character3d/body.js +14 -12
  73. package/src/character3d/export.js +693 -0
  74. package/src/character3d/fx.js +13 -0
  75. package/src/character3d/index.js +2 -0
  76. package/src/character3d/materials.js +106 -10
  77. package/src/character3d/room-themes.js +1184 -0
  78. package/src/character3d/room.js +487 -0
  79. package/src/character3d/stage.js +14 -2
  80. package/src/creator/StepCreator.js +316 -0
  81. package/src/i18n/index.js +3 -3
  82. package/src/i18n/messages/character.js +352 -4
  83. package/src/i18n/messages/creator.js +138 -0
  84. package/src/i18n/messages/identity.js +89 -1
  85. package/src/i18n/messages/platform.js +270 -4
  86. package/src/i18n/messages/server.js +443 -1
  87. package/src/i18n/messages/widget.js +233 -0
  88. package/src/identity/random.js +14 -2
  89. package/src/identity/schema.js +2 -1
  90. package/src/index.js +9 -2
  91. package/src/voice/tags.js +22 -0
  92. package/server/platform/apuchat.mjs +0 -266
  93. package/server/platform/auth.mjs +0 -319
  94. package/server/platform/connect.mjs +0 -387
  95. package/server/platform/crypto.mjs +0 -80
  96. package/server/platform/db.mjs +0 -275
  97. package/server/platform/device.mjs +0 -222
  98. package/server/platform/integrations.mjs +0 -169
  99. package/server/platform/look.mjs +0 -20
  100. package/server/platform/mods.mjs +0 -222
  101. package/server/platform/orquesta.mjs +0 -577
  102. package/server/platform/profile.mjs +0 -161
  103. package/server/platform/routes.mjs +0 -542
  104. package/server/platform/runtime.mjs +0 -242
  105. package/server/platform/sites.mjs +0 -146
  106. package/server/platform/store.mjs +0 -456
  107. package/server/platform/vm.mjs +0 -1057
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 }, (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
+ }
@@ -35,7 +35,7 @@ function guessLang(text, fallback) {
35
35
  let worker = null;
36
36
  let queue = Promise.resolve();
37
37
  function startWorker() {
38
- const p = spawn(PY(), [new URL('./tts-local.py', import.meta.url).pathname], { stdio: ['pipe', 'pipe', 'ignore'] });
38
+ const p = spawn(PY(), [new URL('./tts-local.py', import.meta.url).pathname], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
39
39
  const w = { p, buf: '', waiting: null };
40
40
  p.stdout.on('data', (d) => {
41
41
  w.buf += d;
@@ -84,7 +84,7 @@ export async function synthesizeLocal(text, { lang = 'en', pitch = 1.12 } = {})
84
84
  if (Math.abs(pitch - 1) < 0.01) return { audio: readFileSync(out), contentType: 'audio/wav' };
85
85
  // higher voice, same speed: resample up, then stretch the tempo back
86
86
  const audio = await new Promise((res, rej) =>
87
- execFile('ffmpeg', ['-nostdin', '-loglevel', 'error', '-i', out, '-af', `asetrate=22050*${pitch},aresample=22050,atempo=${(1 / pitch).toFixed(4)}`, '-f', 'wav', '-'], { encoding: 'buffer', maxBuffer: 32 << 20 }, (e, stdout) =>
87
+ execFile('ffmpeg', ['-nostdin', '-loglevel', 'error', '-i', out, '-af', `asetrate=22050*${pitch},aresample=22050,atempo=${(1 / pitch).toFixed(4)}`, '-f', 'wav', '-'], { encoding: 'buffer', maxBuffer: 32 << 20, windowsHide: true }, (e, stdout) =>
88
88
  {
89
89
  if (!e) return res(stdout);
90
90
  // ffmpeg failed: the plain voice, if there is one (a throw here would take the whole pet down)
package/cli/lib/vm.mjs CHANGED
@@ -110,7 +110,7 @@ function childEnv() {
110
110
 
111
111
  function run(cmd, args, { cwd, signal, timeout = 10 * 60 * 1000, input } = {}) {
112
112
  return new Promise((resolve) => {
113
- const p = spawn(cmd, args, { cwd, env: childEnv(), stdio: ['pipe', 'pipe', 'pipe'] });
113
+ const p = spawn(cmd, args, { cwd, windowsHide: true, env: childEnv(), stdio: ['pipe', 'pipe', 'pipe'] });
114
114
  let out = '';
115
115
  const add = (b) => {
116
116
  if (out.length < OUT_MAX * 2) out += b;
@@ -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
+ }