@7ots/cli 0.1.17 → 0.1.19

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/README.md CHANGED
@@ -640,8 +640,19 @@ server/ proxy Node (sin frameworks): llm, tts, contact, demo
640
640
  examples/ sitio de demo "Nimbus" (index, docs, dashboard) e identidad.html
641
641
  site/ la web de 7ots.com (landing es/en/pt con demo, editor y agente en vivo)
642
642
  brand/ logo, favicon, tokens.css y la mascota Ots (ver docs/BRAND.md)
643
+ desktop/ la mascota como app de escritorio (electron-builder): AppImage/deb, dmg, Setup.exe
643
644
  ```
644
645
 
646
+ **Instaladores de la mascota.** `npm run build` en la raíz y luego, en `desktop/`, `npm ci && npm run dist:linux`
647
+ (o `dist:mac` / `dist:win`); salen en `desktop/release/`. La app arranca sola el daemon (su propio Electron en modo
648
+ node) y la ventana de `cli/pet/electron/main.cjs`, sin npx ni node global. En CI, un tag `v*` dispara
649
+ `.github/workflows/desktop-release.yml` (Linux, macOS universal y Windows en paralelo, release en borrador; los
650
+ secretos de firma están descritos en su cabecera). Luego `scripts/publish-desktop.sh <tag>` copia los instaladores al repo público `7ots/pet-releases` (de donde descargan los usuarios y se actualiza la app).
651
+
652
+ **Código abierto.** El cliente (CLI, mascota, `desktop/` y el server local que trae el paquete npm) se publica en
653
+ [github.com/7ots/pet](https://github.com/7ots/pet) bajo MIT, para que cualquiera pueda auditar lo que instala.
654
+ `scripts/publish-source.sh [--dry-run]` sube HEAD como un commit `sync <sha>`; ver [`docs/OPEN-SOURCE.md`](docs/OPEN-SOURCE.md).
655
+
645
656
  Detalles de diseño en [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md).
646
657
 
647
658
  ## Licencia
package/cli/7ots.mjs CHANGED
@@ -127,6 +127,7 @@ async function spawnDaemon() {
127
127
  const log = openSync(homeFile('pet.log'), 'a');
128
128
  const child = spawn(process.execPath, [join(PKG_ROOT, 'cli', '7ots.mjs'), 'pet', '--daemon'], {
129
129
  detached: true,
130
+ windowsHide: true,
130
131
  stdio: ['ignore', log, log],
131
132
  env: process.env,
132
133
  });
@@ -210,6 +211,7 @@ function openDesktop({ opaque = false, view3d = false } = {}) {
210
211
  const child = spawn(bin, [join(PKG_ROOT, 'cli', 'pet', 'electron', 'main.cjs'), ...electronSandboxArgs(bin)], {
211
212
  stdio: ['ignore', log, log],
212
213
  detached: true,
214
+ windowsHide: true,
213
215
  env: { ...process.env, SEVENOTS_PET_URL: `http://127.0.0.1:${PET_PORT}`, SEVENOTS_PET_TOKEN: petToken(), SEVENOTS_PET_OPAQUE: opaque ? '1' : '', SEVENOTS_PET_3D: view3d ? '1' : '', SEVENOTS_PET_LANG: menuLang() },
214
216
  });
215
217
  return new Promise((resolve) => {
@@ -206,9 +206,12 @@ export function parseLocal(text, now = Date.now()) {
206
206
 
207
207
  // ── AI understanding ──
208
208
 
209
- function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', more = '', vmKinds = [], now }) {
209
+ function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', more = '', conv = '', vmKinds = [], now }) {
210
210
  return [
211
+ // the conversation goes first, right above the new message: a short «ok», «prueba», «dale» answers your last line
212
+ conv,
211
213
  `Your human wrote to you: """${String(text).slice(0, 800)}"""`,
214
+ conv ? `Read it as the next turn of that conversation: if it is short ("yes", "go", "try it", "ok"), it answers or continues your last message, so do what you offered or asked there.` : '',
212
215
  `Now it is ${new Date(now).toString()}.`,
213
216
  notes.length ? `What you know about them: ${notes.map((n) => `- ${n.text}`).join('\n')}` : '',
214
217
  reminders.length ? `Pending reminders: ${reminders.map((r) => `${new Date(r.at).toString()}: ${r.text}`).join('; ')}` : '',
@@ -273,7 +276,7 @@ export function notify(title, body) {
273
276
  : ['notify-send', ['-a', '7ots', '-u', 'critical', title, body]];
274
277
  if (!cmd) return;
275
278
  try {
276
- spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
279
+ spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }).on('error', () => {}).unref();
277
280
  } catch {}
278
281
  }
279
282
 
@@ -444,8 +447,8 @@ export function createAssistant({ brain, system, lang, name, onFire, watchers =
444
447
  try {
445
448
  // Prowl.world guides for the sites in play (access.sites; untrusted reference), fetched alongside the processes
446
449
  const [running, siteRef] = await Promise.all([may('processes') ? procs().catch(() => '') : '', sites ? sites.prompt(text).catch(() => '') : '']);
447
- const more = [extra?.prompt() || '', siteRef, convBlock()].filter(Boolean).join('\n');
448
- const raw = await brain.think({ purpose: 'assistant', system: system(detected), messages: [{ role: 'user', content: aiPrompt(text, { lang: detected, notes: may('memory') ? notes.slice(-30) : [], reminders, watchers: watchers?.list || [], procs: running, more, vmKinds: vmKinds(), now }) }], timeoutMs: 45000, raw: true });
450
+ const more = [extra?.prompt() || '', siteRef].filter(Boolean).join('\n');
451
+ const raw = await brain.think({ purpose: 'assistant', system: system(detected), messages: [{ role: 'user', content: aiPrompt(text, { lang: detected, notes: may('memory') ? notes.slice(-30) : [], reminders, watchers: watchers?.list || [], procs: running, more, conv: convBlock(), vmKinds: vmKinds(), now }) }], timeoutMs: 45000, raw: true });
449
452
  ai = parseAi(raw, now, extra, vmKinds());
450
453
  } catch (e) {
451
454
  log(`assistant: ${e.message}`);
package/cli/lib/brain.mjs CHANGED
@@ -39,12 +39,16 @@ export const AI_CLIS = {
39
39
 
40
40
  const LANG_NAME = { en: 'English', es: 'Spanish', pt: 'Portuguese' };
41
41
 
42
- /** Which AI CLIs are installed (for the wizard and `--mode auto`). */
42
+ /** Which AI CLIs are installed (for the wizard and `--mode auto`). Cached a minute: settings polls it. */
43
+ let clisSeen = null;
43
44
  export function detectClis() {
44
- return Object.keys(AI_CLIS).filter((k) => {
45
- const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [AI_CLIS[k].bin], { stdio: 'ignore' });
45
+ if (clisSeen && Date.now() - clisSeen.at < 60000) return clisSeen.list;
46
+ const list = Object.keys(AI_CLIS).filter((k) => {
47
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [AI_CLIS[k].bin], { stdio: 'ignore', windowsHide: true });
46
48
  return r.status === 0;
47
49
  });
50
+ clisSeen = { at: Date.now(), list };
51
+ return list;
48
52
  }
49
53
 
50
54
  /** System prompt shared by every brain. */
@@ -79,6 +83,7 @@ function runCli({ cli, model, command }, prompt, timeoutMs, files) {
79
83
  return new Promise((resolve, reject) => {
80
84
  const child = spawn(spec.bin, spec.args(prompt, model, files), {
81
85
  cwd: ensureHome(),
86
+ windowsHide: true,
82
87
  env: { ...process.env, SEVENOTS_PET_BRAIN: '1', NO_COLOR: '1' },
83
88
  stdio: ['ignore', 'pipe', 'ignore'],
84
89
  });
@@ -23,7 +23,7 @@ export async function cardShot(url, { scale = 4, gl = false, timeout = 45000 } =
23
23
  const dir = mkdtempSync(join(tmpdir(), '7ots-card-'));
24
24
  const args = ['--headless=new', '--remote-debugging-pipe', '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', `--user-data-dir=${dir}`,
25
25
  ...(gl ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--disable-gpu']), 'about:blank'];
26
- const p = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
26
+ const p = spawn(chrome, args, { windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
27
27
  const [toChrome, fromChrome] = [p.stdio[3], p.stdio[4]];
28
28
  let seq = 0;
29
29
  const waiting = new Map();
@@ -143,7 +143,7 @@ function exec(bin, args, { timeoutMs = 10000, max = 64000 } = {}) {
143
143
  let out = '';
144
144
  let child;
145
145
  try {
146
- child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NO_COLOR: '1', PAGER: 'cat' } });
146
+ child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, env: { ...process.env, NO_COLOR: '1', PAGER: 'cat' } });
147
147
  } catch (e) {
148
148
  return resolve({ ok: false, out: e.message });
149
149
  }
@@ -219,16 +219,20 @@ export async function readLogs({ source, target }) {
219
219
 
220
220
  // ── email (apumail) ──
221
221
 
222
+ const isAcctToken = (t) => typeof t === 'string' && t.startsWith('acct_');
223
+
224
+ /** An inbox token reads that inbox; an account token (`acct_…`) reads that inbox, or all of the account's when none is set. */
222
225
  export async function readMail(inbox, { n = 8 } = {}) {
223
226
  const token = env().APUMAIL_TOKEN;
224
- if (!token || !inbox) throw new Error('email is not connected');
225
- const res = await fetch(`${APUMAIL_API}/api/v1/inbox/${encodeURIComponent(inbox)}/wait?timeout=1`, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15000) });
227
+ const all = !inbox && isAcctToken(token);
228
+ if (!token || (!inbox && !all)) throw new Error('email is not connected');
229
+ const url = all ? `${APUMAIL_API}/api/v1/account/all-mail?limit=${n}` : `${APUMAIL_API}/api/v1/inbox/${encodeURIComponent(inbox)}/wait?timeout=1`;
230
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15000) });
226
231
  if (!res.ok) throw new Error(`apumail ${res.status}`);
227
232
  const { messages = [] } = await res.json();
228
- return messages
229
- .slice(-n)
230
- .reverse()
231
- .map((m) => `- ${new Date(Number(m.received_at) || m.received_at).toLocaleString()} · ${str(m.from, 120)} · ${str(m.subject, 160) || '(no subject)'}\n ${str(m.text, 300).replace(/\s+/g, ' ')}`)
233
+ // all-mail comes newest first; an inbox's wait, oldest first.
234
+ return (all ? messages.slice(0, n) : messages.slice(-n).reverse())
235
+ .map((m) => `- ${new Date(Number(m.received_at) || m.received_at).toLocaleString()} · ${all && m._addr ? `${m._addr} ← ` : ''}${str(m.from, 120)} · ${str(m.subject, 160) || '(no subject)'}\n ${str(m.text, 300).replace(/\s+/g, ' ')}`)
232
236
  .join('\n');
233
237
  }
234
238
 
@@ -303,6 +307,32 @@ export async function cloudStatus(config = loadConfig()) {
303
307
  return out;
304
308
  }
305
309
 
310
+ /** The twin ot's Notlogin subwallet on 7ots.com (device token): addresses, balances, payments. Read only. */
311
+ export async function cloudWallet(config = loadConfig()) {
312
+ const id = config.account?.otsId;
313
+ if (!signedIn() || !id) return { available: false };
314
+ const res = await fetch(`${SEVENOTS_URL}/api/device/ots/${encodeURIComponent(id)}/wallet`, { headers: { Authorization: `Bearer ${env().SEVENOTS_TOKEN}` }, signal: AbortSignal.timeout(20000) });
315
+ if (res.status === 404) return { available: false };
316
+ if (!res.ok) throw Object.assign(new Error(`7ots.com ${res.status}`), { status: res.status });
317
+ return { available: true, ...(await res.json()) };
318
+ }
319
+
320
+ /** The twin ot's byte arena account on 7ots.com (device token): games, play { game }, status, stop. */
321
+ export async function cloudByte(config = loadConfig(), sub = '', { method = 'GET', body } = {}) {
322
+ const id = config.account?.otsId;
323
+ if (!signedIn() || !id) return { available: false };
324
+ const res = await fetch(`${SEVENOTS_URL}/api/device/ots/${encodeURIComponent(id)}/byte${sub}`, {
325
+ method,
326
+ headers: { Authorization: `Bearer ${env().SEVENOTS_TOKEN}`, ...(body ? { 'Content-Type': 'application/json' } : {}) },
327
+ body: body ? JSON.stringify(body) : undefined,
328
+ signal: AbortSignal.timeout(90000),
329
+ });
330
+ if (res.status === 404) return { available: false };
331
+ const data = await res.json().catch(() => ({}));
332
+ if (!res.ok) throw Object.assign(new Error(data.error || `7ots.com ${res.status}`), { status: res.status });
333
+ return { available: true, ...data };
334
+ }
335
+
306
336
  // ── Letta (persona memory) ──
307
337
  // Contract (docs.letta.com): Bearer LETTA_API_KEY
308
338
  // POST /v1/agents { name, memory_blocks: [{ label, value }], model, embedding } → { id }
@@ -373,7 +403,7 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
373
403
  const o = config().integrations?.orquesta || {};
374
404
  return o.projectId ? { id: o.projectId, name: o.projectName } : cloudOrq.project ? { id: cloudOrq.project, name: cloudOrq.projectName } : null;
375
405
  };
376
- const mailOn = () => config().access?.inbox === true && config().integrations?.apumail?.on && config().integrations.apumail.inbox && Boolean(env().APUMAIL_TOKEN);
406
+ const mailOn = () => config().access?.inbox === true && config().integrations?.apumail?.on && Boolean(env().APUMAIL_TOKEN) && Boolean(config().integrations.apumail.inbox || isAcctToken(env().APUMAIL_TOKEN));
377
407
  const cloudId = () => (env().SEVENOTS_TOKEN && config().account?.otsId) || null;
378
408
  const customs = () => (config().integrations?.custom || []).filter((c) => c.on !== false && customKind(c) !== 'note' && (c.url || c.command));
379
409
  const toolsLine = (x) => {
@@ -425,7 +455,7 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
425
455
  const lines = [];
426
456
  checkCloud();
427
457
  if (c.access?.logs === true) lines.push(`{"type":"read_logs","source":"journal|pm2|docker|file|process","target":"unit / pm2 app / container / path to a .log file / part of a running command"} (read the last lines of a program's logs, then you explain them)`);
428
- if (mailOn()) lines.push(`{"type":"read_mail"} (read the latest emails in their inbox ${c.integrations.apumail.inbox}, then you sum them up)`);
458
+ if (mailOn()) lines.push(`{"type":"read_mail"} (read the latest emails in ${c.integrations.apumail.inbox ? `their inbox ${c.integrations.apumail.inbox}` : 'all their apumail inboxes'}, then you sum them up)`);
429
459
  if (orqOn()) {
430
460
  const def = defProject()?.name ? ` (default project: "${defProject().name}")` : '';
431
461
  lines.push(`{"type":"orquesta_list"} (list their Orquesta projects and whether each agent is online) · {"type":"orquesta","project":"name or id, or null for the default","text":"the message for that project's coding agent"}${def} (send a task or question to one of their Orquesta agents; you tell them the answer when it finishes)`);
package/cli/lib/mcp.mjs CHANGED
@@ -61,7 +61,7 @@ async function httpSession(url, token) {
61
61
 
62
62
  // ── stdio ──
63
63
  async function stdioSession(command, extraEnv) {
64
- const child = spawn('/bin/sh', ['-c', command], { stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env, ...extraEnv } });
64
+ const child = spawn('/bin/sh', ['-c', command], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env, ...extraEnv } });
65
65
  const waiting = new Map();
66
66
  let buf = '';
67
67
  let dead = null;
package/cli/lib/open.mjs CHANGED
@@ -6,7 +6,9 @@ export function openUrl(url) {
6
6
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
7
7
  const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
8
8
  try {
9
- const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
9
+ // The desktop app runs the daemon as Electron-in-node-mode; a browser or app opened from here must not inherit that.
10
+ const { ELECTRON_RUN_AS_NODE, ...env } = process.env;
11
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true, env });
10
12
  child.on('error', () => {});
11
13
  child.unref();
12
14
  return true;
@@ -10,6 +10,7 @@
10
10
  * POST /tts X-7ots-Token { text } → audio with the configured voice
11
11
  * POST /ask X-7ots-Token { text } → { reply, actions } reminders, notes, open a site (assistant.mjs)
12
12
  * POST /stt X-7ots-Token raw audio (webm/ogg) → { text } voice control (stt.mjs)
13
+ * POST /log X-7ots-Token { page, msg } → pet.log «audio[page]: msg» (what each page did with its audio)
13
14
  * GET /reminders?token=… { reminders, notes }
14
15
  * GET /inferences?token=… the brain's history: what was sent (the data it used) and what came back
15
16
  * GET /memory?token=… everything it keeps about you: notes, what it saw, what it said, its state
@@ -20,6 +21,8 @@
20
21
  * POST /watchers/cancel { id | 'all' }
21
22
  * GET /cloud 7ots.com link + the cloud assistant's VM status (integrations.mjs)
22
23
  * POST /integrations/test { integration } → { ok, tools? (MCP), text?, error? } (a draft, not saved)
24
+ * GET /byte · /byte/games · /byte/status · POST /byte/play { game } · /byte/stop the twin ot plays byte arena (7ots.com)
25
+ * GET /wallet the twin ot's wallet on 7ots.com (read only): addresses, balances, payments + tx links
23
26
  * GET /orquesta/projects · POST /orquesta/send { projectId, text } · GET /orquesta/prompt?id= your Orquesta agents
24
27
  * POST /character/letta write the character sheet into a Letta agent's persona (LETTA_API_KEY)
25
28
  * GET /settings?token=… the settings page: brain, what it may see and do, notes, reminders
@@ -58,7 +61,7 @@ import { createSiteContext } from './prowl.mjs';
58
61
  import { SEVENOTS_URL, community, sync as syncOt, logout as accountLogout, me as accountMe, pull as pullOt, signedIn, startLogin, use as useOt } from './account.mjs';
59
62
  import { openUrl } from './open.mjs';
60
63
  import { VM_KINDS } from './vm.mjs';
61
- import { cloudStatus, createExtras, lettaSync, normalizeCharacter, normalizeIntegrations, redact, testCustom } from './integrations.mjs';
64
+ import { cloudByte, cloudStatus, cloudWallet, createExtras, lettaSync, normalizeCharacter, normalizeIntegrations, redact, testCustom } from './integrations.mjs';
62
65
  import { spawn } from 'node:child_process';
63
66
  import { openSync } from 'node:fs';
64
67
  import { line } from './lines.mjs';
@@ -185,6 +188,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
185
188
 
186
189
  const broadcast = (msg) => {
187
190
  const data = `data: ${JSON.stringify({ state: view(pet), ...msg })}\n\n`;
191
+ if (msg.say) log(`audio: say → ${clients.size} page(s) «${String(msg.say).slice(0, 60)}»${msg.ambient ? ' (ambient)' : ''}`); // to debug a voice heard twice
188
192
  for (const res of clients) res.write(data);
189
193
  };
190
194
 
@@ -506,6 +510,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
506
510
  spawn(process.execPath, [join(PKG_ROOT, 'cli', '7ots.mjs'), 'pet', '--daemon'], {
507
511
  cwd: c.dir, // never pick up a project's .7ots/identity.json
508
512
  detached: true,
513
+ windowsHide: true,
509
514
  stdio: ['ignore', out, out],
510
515
  env: { ...process.env, SEVENOTS_COMPANION: '1', SEVENOTS_HOME: c.dir, SEVENOTS_PET_PORT: String(port + 1), SEVENOTS_PORT_WAIT: '1' },
511
516
  }).unref();
@@ -635,11 +640,36 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
635
640
  });
636
641
  if (req.method === 'GET' && p === '/reminders') return json(200, { reminders: assistant.reminders, notes: assistant.notes });
637
642
  if (req.method === 'GET' && p === '/cloud') return json(200, await cloudStatus(config));
643
+ const bm = /^\/byte(\/(?:games|status|play|stop))?$/.exec(p);
644
+ if (bm && (req.method === 'GET' || req.method === 'POST')) {
645
+ try {
646
+ let body;
647
+ if (req.method === 'POST') {
648
+ let raw = '';
649
+ for await (const c of req) if ((raw += c).length > 4096) break;
650
+ try {
651
+ body = JSON.parse(raw || '{}');
652
+ } catch {
653
+ body = {};
654
+ }
655
+ }
656
+ return json(200, await cloudByte(config, bm[1] || '', { method: req.method, body }));
657
+ } catch (e) {
658
+ return json(e.status === 401 ? 200 : 502, e.status === 401 ? { available: false } : { error: e.message });
659
+ }
660
+ }
661
+ if (req.method === 'GET' && p === '/wallet') {
662
+ try {
663
+ return json(200, await cloudWallet(config));
664
+ } catch (e) {
665
+ return json(e.status === 401 ? 200 : 502, e.status === 401 ? { available: false } : { error: e.message });
666
+ }
667
+ }
638
668
  if (req.method === 'GET' && (p === '/orquesta/projects' || p === '/orquesta/prompt')) {
639
669
  const o = await import('./orquesta.mjs');
640
670
  if (!o.via()) return json(200, { connected: false });
641
671
  try {
642
- if (p === '/orquesta/projects') return json(200, { connected: true, projects: await o.agentProjects() });
672
+ if (p === '/orquesta/projects') return json(200, { connected: true, via: o.via(), projects: await o.agentProjects() });
643
673
  return json(200, { connected: true, ...(await o.agentTask(String(url.searchParams.get('id') || '').slice(0, 80))) });
644
674
  } catch (e) {
645
675
  const off = [401, 409].includes(e.status); // no token / not connected on 7ots.com
@@ -695,8 +725,14 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
695
725
  savePet(pet);
696
726
  return json(200, { ok: true, state: view(pet) });
697
727
  }
728
+ // what each page did with its audio (say, tts, play, cut, music): pet.log, to debug voices heard twice
729
+ if (p === '/log') {
730
+ log(`audio[${String(data.page || '?').slice(0, 8)}]: ${String(data.msg || '').replace(/\s+/g, ' ').slice(0, 200)}`);
731
+ return json(200, { ok: true });
732
+ }
698
733
  if (p === '/tts') {
699
734
  const kind = config.voice.kind;
735
+ log(`audio: tts ${kind} «${String(data.text || '').slice(0, 60)}»`);
700
736
  if (['none', 'browser'].includes(kind)) return json(501, { error: 'browser voice' });
701
737
  try {
702
738
  if (kind === 'local') {
@@ -1161,7 +1197,7 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
1161
1197
  // The new one retries the port while this one lets go of it.
1162
1198
  stop(() => {
1163
1199
  const out = openSync(homeFile('pet.log'), 'a');
1164
- spawn(process.execPath, [join(PKG_ROOT, 'cli', '7ots.mjs'), 'pet', '--daemon'], { detached: true, stdio: ['ignore', out, out], env: { ...process.env, SEVENOTS_PORT_WAIT: '1' } }).unref();
1200
+ spawn(process.execPath, [join(PKG_ROOT, 'cli', '7ots.mjs'), 'pet', '--daemon'], { detached: true, windowsHide: true, stdio: ['ignore', out, out], env: { ...process.env, SEVENOTS_PORT_WAIT: '1' } }).unref();
1165
1201
  });
1166
1202
  }
1167
1203
 
@@ -12,7 +12,7 @@ import { existsSync, mkdirSync, unlinkSync } from 'node:fs';
12
12
  import { join } from 'node:path';
13
13
  import { homeFile, readJson, writeJson } from './paths.mjs';
14
14
 
15
- const run = (cmd, args, ms = 4000) => new Promise((res) => execFile(cmd, args, { timeout: ms }, (e, out) => res(e ? '' : String(out).trim())));
15
+ const run = (cmd, args, ms = 4000) => new Promise((res) => execFile(cmd, args, { timeout: ms, windowsHide: true }, (e, out) => res(e ? '' : String(out).trim())));
16
16
  const MAX = 60;
17
17
 
18
18
  export function createScreenWatcher({ brain, enabled, every = () => 5, lang = 'en', log = () => {}, onSeen = () => {} }) {
package/cli/lib/stt.mjs CHANGED
@@ -34,7 +34,7 @@ export async function transcribe({ audio, contentType = 'audio/webm', lang = '',
34
34
  writeFileSync(f, audio, { mode: 0o600 });
35
35
  try {
36
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()))),
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
38
  );
39
39
  return { text, provider };
40
40
  } finally {
@@ -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;
@@ -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', 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', 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', 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', 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' },
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
 
@@ -47,7 +47,8 @@ if (linux && !OPAQUE) {
47
47
  const post = (p, body) =>
48
48
  fetch(new URL(p, URL_), { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-7ots-Token': TOKEN }, body: JSON.stringify(body || {}) }).catch(() => {});
49
49
 
50
- app.whenReady().then(() => setTimeout(start, linux ? 400 : 0)); // Linux: the compositor needs a moment
50
+ // The packaged desktop app (desktop/launcher.cjs) starts the daemon itself and sets sevenotsReady: wait for it.
51
+ app.whenReady().then(() => globalThis.sevenotsReady).then(() => setTimeout(start, linux ? 400 : 0)); // Linux: the compositor needs a moment
51
52
 
52
53
  // The shell lives as long as the daemon that started it: when that one stops (7ots stop) or another takes
53
54
  // its place (a relaunch), this shell leaves too, so there are never two shells (and two directors) at once.
@@ -59,7 +60,8 @@ app.whenReady().then(() => setTimeout(start, linux ? 400 : 0)); // Linux: the co
59
60
  if (!h?.pid) return ++misses > 4 && app.quit(); // gone for ~25 s
60
61
  misses = 0;
61
62
  pid ||= h.pid;
62
- if (h.pid !== pid) app.quit();
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
65
  }, 5000);
64
66
  }
65
67
 
@@ -89,7 +91,7 @@ function watchX11Cursor() {
89
91
  ].join('\n');
90
92
  let child;
91
93
  try {
92
- child = require('node:child_process').spawn('python3', ['-c', py], { stdio: ['ignore', 'pipe', 'ignore'] });
94
+ child = require('node:child_process').spawn('python3', ['-c', py], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
93
95
  } catch {
94
96
  return;
95
97
  }
@@ -169,6 +171,8 @@ function makeOt(opt = {}) {
169
171
  const FULL = HOST || !!opt.url;
170
172
  const postOt = (p, body) =>
171
173
  fetch(new URL(p, base), { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-7ots-Token': tok }, body: JSON.stringify(body || {}) }).catch(() => {});
174
+ const getOt = (p) =>
175
+ fetch(new URL(p, base), { headers: { 'X-7ots-Token': tok } }).then((r) => r.json()).catch(() => ({}));
172
176
  const area = screen.getPrimaryDisplay().workArea;
173
177
  const right = area.x + area.width;
174
178
  const floor = area.y + area.height;
@@ -261,11 +265,64 @@ function makeOt(opt = {}) {
261
265
  { label: tr('feed'), click: () => postOt('/event', { type: 'feed' }) },
262
266
  { label: tr('sleep'), click: () => postOt('/event', { type: 'sleep' }) },
263
267
  { label: tr('wake'), click: () => postOt('/event', { type: 'wake' }) },
268
+ { label: tr('byte'), click: () => gameMenu().then((m) => m.popup({ window: win })) },
264
269
  { type: 'separator' },
265
270
  { label: tr('settings'), click: () => openSettings(base, tok) },
266
271
  { label: tr('still'), type: 'checkbox', checked: still, click: (i) => (still = i.checked) },
267
272
  HOST ? { label: tr('quit'), click: () => post('/quit').finally(() => app.quit()) } : { label: { es: '👋 Despedir', pt: '👋 Mandar embora' }[LANG] || '👋 Send home', click: dismiss },
268
273
  ]);
274
+ // ── byte arena: the ot plays a game live (7ots.com runs its moves) and a small window shows it, beside it ──
275
+ let gameWin = null;
276
+ const watchGame = (url) => {
277
+ if (!/^https:\/\/[^/]+\/stream\/s_[a-z0-9]+$/i.test(String(url || ''))) return;
278
+ if (gameWin && !gameWin.isDestroyed()) return gameWin.loadURL(url), gameWin.showInactive();
279
+ const w = 480;
280
+ const h = 300;
281
+ const [wx, wy] = win.getPosition();
282
+ const x = Math.max(area.x, Math.min(right - w, wx + size.w / 2 - w - 40));
283
+ const y = Math.max(area.y, Math.min(floor - h, wy + size.h - h));
284
+ 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 } });
285
+ gameWin.removeMenu?.();
286
+ gameWin.setAlwaysOnTop(true, 'floating');
287
+ gameWin.webContents.setAudioMuted(false);
288
+ // the page stays on byte's stream; any other link goes to the browser
289
+ const origin = new URL(url).origin;
290
+ gameWin.webContents.setWindowOpenHandler(({ url: u }) => (shell.openExternal(u).catch(() => {}), { action: 'deny' }));
291
+ gameWin.webContents.on('will-navigate', (e, u) => String(u).startsWith(`${origin}/stream/`) || (e.preventDefault(), shell.openExternal(u).catch(() => {})));
292
+ gameWin.loadURL(url);
293
+ gameWin.once('ready-to-show', () => gameWin.showInactive());
294
+ gameWin.on('closed', () => (gameWin = null));
295
+ };
296
+ const playGame = async (game) => {
297
+ 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
+ if (r.streamUrl) {
299
+ watchGame(r.streamUrl);
300
+ postOt('/event', { type: 'say', text: `🎮 ${r.game}` });
301
+ watchStart(r.sessionId);
302
+ } else postOt('/event', { type: 'say', text: `byte: ${r.error || 'no'}` });
303
+ };
304
+ // a game that dies before its first move leaves the stream black: say why and close the window
305
+ const watchStart = (sid, n = 0) =>
306
+ setTimeout(async () => {
307
+ const st = await getOt('/byte/status').catch(() => ({}));
308
+ if (st.sessionId !== sid) return;
309
+ if (st.status === 'error' || ((st.status === 'finished' || st.status === 'stopped') && !st.moves)) {
310
+ postOt('/event', { type: 'say', text: `byte: ${st.error || st.status}` });
311
+ if (gameWin && !gameWin.isDestroyed()) gameWin.close();
312
+ } else if (!st.moves && n < 12) watchStart(sid, n + 1);
313
+ }, 4000);
314
+ const gameMenu = async () => {
315
+ 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 }]);
325
+ };
269
326
  function listen() {
270
327
  if (!win.isVisible()) win.showInactive();
271
328
  page('postMessage({ listen: true })');
@@ -458,6 +515,7 @@ function makeOt(opt = {}) {
458
515
  }
459
516
  if (m.startsWith('\u00a77bye')) return HOST || dismiss();
460
517
  if (m.startsWith('\u00a77ctx')) return (FULL ? menu() : guestMenu()).popup({ window: win });
518
+ if (m.startsWith('\u00a77game')) return FULL && gameMenu().then((mm) => mm.popup({ window: win }));
461
519
  if (m.startsWith('\u00a77view')) return setView(m.slice(6) === '3d');
462
520
  if (m.startsWith('\u00a77enter')) return enter();
463
521
  if (!m.startsWith('\u00a77need')) return;
@@ -594,7 +652,7 @@ function makeOt(opt = {}) {
594
652
  const minY = area.y + BIG.h;
595
653
  const TERM = /terminal|kitty|alacritty|konsole|tilix|wezterm|xterm|ghostty|warp|terminator|code|cursor|windsurf|zed|jetbrains|idea|pycharm|webstorm/i;
596
654
  const BROWSER = /chrom|firefox|brave|vivaldi|opera|edge|epiphany|librewolf|zen/i;
597
- const run = (cmd, args) => new Promise((res) => execFile(cmd, args, { timeout: 1500 }, (e, out) => res(e ? '' : String(out))));
655
+ const run = (cmd, args) => new Promise((res) => execFile(cmd, args, { timeout: 1500, windowsHide: true }, (e, out) => res(e ? '' : String(out))));
598
656
  // The top-most visible window whose class matches, if it is not mostly covered by others (no use pointing
599
657
  // at a terminal hidden behind the browser: then it comes to the cursor instead).
600
658
  async function findWindow(re) {