@7ots/cli 0.1.42 → 0.1.43

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.
@@ -53,6 +53,7 @@ const T = {
53
53
  opening: (s) => `Opening ${s}.`,
54
54
  fire: (r) => `Reminder: ${r.text}!`,
55
55
  offload: (k) => `On it: I sent it to my server (${k}). I'll tell you how it goes.`,
56
+ control: () => `On it: I'm taking the mouse. Move it to stop me.`,
56
57
  offloadQueued: 'Queued: my server is offline right now, it will start when it is back.',
57
58
  offloadStep: (s) => `Still working: ${s}`,
58
59
  offloadDone: (r) => `Done: ${r}`,
@@ -74,6 +75,7 @@ const T = {
74
75
  opening: (s) => `Abriendo ${s}.`,
75
76
  fire: (r) => `¡Recordatorio: ${r.text}!`,
76
77
  offload: (k) => `Voy: se lo mandé a mi servidor (${k}). Te cuento cómo va.`,
78
+ control: () => `Voy: tomo el mouse. Muévelo si quieres que pare.`,
77
79
  offloadQueued: 'En cola: mi servidor está apagado ahora, empieza cuando vuelva.',
78
80
  // what the 7ots server says about the microVM (server/platform/vm.mjs), in your language
79
81
  server: { 'Starting the microVM…': 'prendiendo la microVM…', 'The microVM is slow to start; Orquesta keeps trying…': 'la microVM tarda en arrancar; Orquesta sigue intentando…', 'The microVM is working on it…': 'la microVM está trabajando en eso…', 'The microVM did not start in time': 'la microVM no arrancó a tiempo', 'The task no longer exists in Orquesta': 'la tarea ya no existe en Orquesta' },
@@ -97,6 +99,7 @@ const T = {
97
99
  opening: (s) => `Abrindo ${s}.`,
98
100
  fire: (r) => `Lembrete: ${r.text}!`,
99
101
  offload: (k) => `Já vou: mandei para o meu servidor (${k}). Te conto como vai.`,
102
+ control: () => `Já vou: pego o mouse. Mexa nele se quiser que eu pare.`,
100
103
  offloadQueued: 'Na fila: meu servidor está desligado agora, começa quando voltar.',
101
104
  server: { 'Starting the microVM…': 'ligando a microVM…', 'The microVM is slow to start; Orquesta keeps trying…': 'a microVM está demorando para iniciar; a Orquesta continua tentando…', 'The microVM is working on it…': 'a microVM está trabalhando nisso…', 'The microVM did not start in time': 'a microVM não iniciou a tempo', 'The task no longer exists in Orquesta': 'a tarefa não existe mais na Orquesta' },
102
105
  offloadStep: (s) => `Ainda trabalhando: ${s}`,
@@ -227,7 +230,7 @@ export function parseLocal(text, now = Date.now()) {
227
230
 
228
231
  // ── AI understanding ──
229
232
 
230
- function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', more = '', conv = '', vmKinds = [], work = '', now }) {
233
+ function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', more = '', conv = '', vmKinds = [], work = '', control = false, now }) {
231
234
  return [
232
235
  // the conversation goes first, right above the new message: a short «ok», «prueba», «dale» answers your last line
233
236
  conv,
@@ -245,7 +248,8 @@ function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', mor
245
248
  `{"type":"watch_price","coin":"bitcoin|ethereum|solana|… (CoinGecko id) or ticker","op":">=|<=","value":N,"vs":"usd|clp|eur|…","text":"what to tell them"} (crypto price alert; checked every minute)`,
246
249
  `{"type":"watch_process","match":"part of the command line, e.g. 'npm run build'","until":"exit|start","text":"what to tell them"} (tell them when a program on their computer finishes or starts)`,
247
250
  work,
248
- vmKinds.length ? `{"type":"offload","kind":"${vmKinds.join('|')}","text":"the full request, self-contained (dates, places, budget…)"} (hand long work to your worker: research = think it through, browse = read the URLs in text, long = multi-step work${vmKinds.includes('code') ? ', code = programming task' : ''}${vmKinds.includes('shell') ? ', shell = one bash command' : ''}; you will report back when it is done)` : '',
251
+ control ? `{"type":"control","goal":"the full task, self-contained"} (use their computer yourself: you see the screen and move the mouse, click and type, e.g. open a terminal and run something, open an app, fill a form; only when they ask you to do it on their computer)` : '',
252
+ vmKinds.length ? `{"type":"offload","kind":"${vmKinds.join('|')}","text":"the full request, self-contained (dates, places, budget…)"} (hand long work to your worker: research = think it through, browse = read the URLs in text, long = multi-step work${vmKinds.includes('code') ? ', code = programming task' : ''}${vmKinds.includes('shell') ? ', shell = one bash command' : ''}${vmKinds.includes('desktop') ? ', desktop = do it with a mouse and keyboard on a desktop and browser of its own on the server (not this computer)' : ''}; you will report back when it is done)` : '',
249
253
  more,
250
254
  `Use the watch actions for "alert me / let me know if/when …" about a price or a program. Never say you cannot do something these actions can do.`,
251
255
  `When a reminder is about a website (email → https://mail.google.com, calendar → https://calendar.google.com, etc.) set "open" so it opens when due.`,
@@ -256,7 +260,7 @@ function aiPrompt(text, { lang, notes, reminders, watchers = [], procs = '', mor
256
260
  .join('\n');
257
261
  }
258
262
 
259
- function parseAi(raw, now, extra = null, vmKinds = []) {
263
+ function parseAi(raw, now, extra = null, vmKinds = [], control = false) {
260
264
  const m = String(raw || '').match(/\{[\s\S]*\}/);
261
265
  if (!m) return null;
262
266
  let j;
@@ -275,6 +279,7 @@ function parseAi(raw, now, extra = null, vmKinds = []) {
275
279
  else if (['cancel', 'list'].includes(a?.type)) actions.push({ type: a.type });
276
280
  else if (a?.type === 'watch_price' && a.coin && Number.isFinite(Number(a.value))) actions.push({ type: 'watch_price', coin: String(a.coin), op: ['<=', '<'].includes(a.op) ? '<=' : '>=', value: Number(a.value), vs: String(a.vs || 'usd').toLowerCase().slice(0, 6), text: String(a.text || '').slice(0, 200) });
277
281
  else if (a?.type === 'watch_process' && a.match) actions.push({ type: 'watch_process', match: String(a.match).slice(0, 120), until: a.until === 'start' ? 'start' : 'exit', text: String(a.text || '').slice(0, 200) });
282
+ else if (a?.type === 'control' && control && a.goal) actions.push({ type: 'control', goal: String(a.goal).slice(0, 600) });
278
283
  else if (a?.type === 'offload' && vmKinds.includes(a.kind) && a.text) actions.push({ type: 'offload', kind: a.kind, text: String(a.text).slice(0, 8000) });
279
284
  else {
280
285
  const x = extra?.parse(a);
@@ -308,9 +313,9 @@ export function notify(title, body) {
308
313
  * vm + vmKinds (offload to the ot's cloud worker; off unless explicitly true)
309
314
  * cloud() the ot id of this computer (signed in to 7ots.com) or null · say(line) speaks later
310
315
  */
311
- export function createAssistant({ brain, system, lang, name, onFire, watchers = null, procs = async () => '', access = () => ({}), memoryTokens = () => 20000, extra = null, sites = null, cloud = () => null, say = () => {}, context = () => '', log = () => {} }) {
316
+ export function createAssistant({ brain, system, lang, name, onFire, watchers = null, procs = async () => '', access = () => ({}), memoryTokens = () => 20000, extra = null, sites = null, cloud = () => null, control = null, say = () => {}, context = () => '', log = () => {} }) {
312
317
  const may = (k) => access()[k] !== false;
313
- // the owner's own AI CLI (brain.work) does research/browse/long here; code/shell stay on the server
318
+ // the owner's own AI CLI (brain.work) does research/browse/long here; code/shell/desktop stay on the server
314
319
  const local = () => typeof brain.work === 'function';
315
320
  const vmKinds = () => {
316
321
  const kinds = (access().vmKinds || []).filter(Boolean);
@@ -498,6 +503,11 @@ export function createAssistant({ brain, system, lang, name, onFire, watchers =
498
503
  if (!vmKinds().includes(a.kind)) continue;
499
504
  offload(a, L);
500
505
  out.push(local() ? L.offloadLocal(a.kind) : L.offload(a.kind));
506
+ } else if (a.type === 'control') {
507
+ // control: { on(), start(goal) } (pet-server → control.mjs); it reports back by itself when done
508
+ if (!control?.on()) continue;
509
+ control.start(a.goal, L === T.es ? 'es' : L === T.pt ? 'pt' : 'en');
510
+ out.push(L.control());
501
511
  } else if (a.type === 'list') out.push(reminders.length ? L.list(reminders) : L.none, ...(watchers?.list || []).map((w) => L.watch(w)));
502
512
  else if (a.type === 'know') out.push(L.know(may('memory') ? notes.slice(-12) : []));
503
513
  else if (a.type === 'ask_when') out.push(L.when);
@@ -521,8 +531,8 @@ export function createAssistant({ brain, system, lang, name, onFire, watchers =
521
531
  // Prowl.world guides for the sites in play (access.sites; untrusted reference), fetched alongside the processes
522
532
  const [running, siteRef] = await Promise.all([may('processes') ? procs().catch(() => '') : '', sites ? sites.prompt(text).catch(() => '') : '']);
523
533
  const more = [extra?.prompt() || '', context() || '', siteRef].filter(Boolean).join('\n');
524
- 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(), work: workLine(), now }) }], timeoutMs: 45000, raw: true });
525
- ai = parseAi(raw, now, extra, vmKinds());
534
+ 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(), work: workLine(), control: Boolean(control?.on()), now }) }], timeoutMs: 45000, raw: true });
535
+ ai = parseAi(raw, now, extra, vmKinds(), Boolean(control?.on()));
526
536
  } catch (e) {
527
537
  log(`assistant: ${e.message}`);
528
538
  }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * BUG-07 regression: reminders must fire onFire even when the Electron window
3
+ * is hidden (backgroundThrottling: false) and the daemon is the only process
4
+ * keeping the event loop alive.
5
+ *
6
+ * BUG-02 regression: help text in assistant.mjs and usage.ask in i18n.mjs must
7
+ * NOT say "coming soon" / "muy pronto" / "em breve" for the screen feature —
8
+ * the feature is live and users should be directed to Settings.
9
+ *
10
+ * BUG-13 regression: stop(then) in pet-server.mjs must ref its exit timer when
11
+ * a restart callback is provided so the new daemon is always spawned; and
12
+ * main.cjs must adopt a new daemon PID instead of quitting.
13
+ */
14
+ import { test } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import { mkdtempSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { dirname, resolve } from 'node:path';
21
+
22
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
23
+
24
+ // ── BUG-07: Electron shell configuration ─────────────────────────────────────
25
+
26
+ test('BUG-07: main.cjs disables backgroundThrottling on the pet window', () => {
27
+ const src = readFileSync(join(ROOT, 'cli/pet/electron/main.cjs'), 'utf8');
28
+ // The pet window must NOT be throttled when hidden, so SSE reminder events are
29
+ // processed immediately and TTS plays even if the user clicked "Hide".
30
+ assert.ok(
31
+ src.includes('backgroundThrottling: false'),
32
+ 'pet BrowserWindow must set backgroundThrottling: false',
33
+ );
34
+ });
35
+
36
+ test('BUG-07: pet.html sends §7show to the shell when a reminder fires', () => {
37
+ const src = readFileSync(join(ROOT, 'cli/pet/pet.html'), 'utf8');
38
+ assert.ok(
39
+ src.includes('m.reminder') && src.includes('§7show'),
40
+ 'pet.html must send §7show console message on reminder so the hidden window reappears',
41
+ );
42
+ });
43
+
44
+ test('BUG-07: main.cjs handles §7show by calling show() on the hidden window', () => {
45
+ const src = readFileSync(join(ROOT, 'cli/pet/electron/main.cjs'), 'utf8');
46
+ // The source stores it as the §7 Unicode escape (§ = U+00A7, then '7').
47
+ assert.ok(
48
+ (src.includes("'§7show'") || src.includes("'\\u00a77show'")) && src.includes('show()'),
49
+ 'main.cjs must handle §7show and call show() to un-hide the window',
50
+ );
51
+ });
52
+
53
+ // ── BUG-07: Assistant reminder-timer fires past-due reminders ─────────────────
54
+
55
+ test('BUG-07: past-due reminder fires onFire within one interval tick', async (t) => {
56
+ // MockTimers replaces setInterval globally; clearInterval is not a separate mock API.
57
+ t.mock.timers.enable({ apis: ['setInterval'] });
58
+
59
+ // SEVENOTS_HOME must be set before paths.mjs is evaluated; since it was already
60
+ // imported above, patch via a temp dir written to the real ~/.7ots path only if
61
+ // needed — or write to a unique temp location and import assistant freshly.
62
+ // Simplest: write the reminder to the real home dir with a unique id and clean up.
63
+ const { HOME, ensureHome } = await import('./paths.mjs');
64
+ ensureHome();
65
+ const remFile = join(HOME, 'reminders.json');
66
+ let original;
67
+ try { original = readFileSync(remFile, 'utf8'); } catch { original = null; }
68
+
69
+ const rem = { id: 'bug07-test', at: Date.now() - 500, text: 'check email', done: false };
70
+ const existing = original ? JSON.parse(original) : [];
71
+ writeFileSync(remFile, JSON.stringify([...existing, rem]));
72
+
73
+ const { createAssistant } = await import('./assistant.mjs');
74
+
75
+ let fired = null;
76
+ const a = createAssistant({
77
+ brain: { kind: 'mock', think: async () => '' },
78
+ system: () => '',
79
+ lang: 'en',
80
+ name: 'TestPet',
81
+ onFire: (r, line) => { if (r.id === 'bug07-test') fired = { r, line }; },
82
+ access: () => ({ notify: false, open: false }), // skip OS notification in test
83
+ });
84
+
85
+ // The interval is 5 000 ms; tick past it once.
86
+ t.mock.timers.tick(5001);
87
+ a.stop();
88
+
89
+ // Restore original reminders.json
90
+ if (original === null) {
91
+ try { rmSync(remFile); } catch {}
92
+ } else {
93
+ writeFileSync(remFile, original);
94
+ }
95
+
96
+ assert.ok(fired, 'onFire should have been called for the past-due reminder');
97
+ assert.equal(fired.r.id, 'bug07-test', 'correct reminder was fired');
98
+ assert.match(fired.line, /check email/i, 'fire line contains reminder text');
99
+ });
100
+
101
+ // ── BUG-02: no "coming soon" for screen feature ───────────────────────────────
102
+
103
+ test('BUG-02: assistant.mjs help text does not say "coming soon" for screen', () => {
104
+ const src = readFileSync(join(ROOT, 'cli/lib/assistant.mjs'), 'utf8');
105
+ // Extract all three help strings (EN / ES / PT) — they appear as `help: '...'` entries in the T object.
106
+ const helpStrings = [...src.matchAll(/\bhelp:\s*'([^']+)'/g)].map((m) => m[1]);
107
+ assert.ok(helpStrings.length >= 3, 'expected EN + ES + PT help strings in assistant.mjs');
108
+ for (const s of helpStrings) {
109
+ assert.ok(
110
+ !/coming soon|muy pronto|em breve/i.test(s),
111
+ `assistant.mjs help string says "coming soon": ${s.slice(0, 120)}`,
112
+ );
113
+ }
114
+ });
115
+
116
+ test('BUG-02: i18n.mjs usage.ask does not say "coming soon" for screen or processes', () => {
117
+ const src = readFileSync(join(ROOT, 'cli/lib/i18n.mjs'), 'utf8');
118
+ const usageAskStrings = [...src.matchAll(/'usage\.ask':\s*'([^']+(?:\\'[^']+)*)'/g)].map((m) =>
119
+ m[1],
120
+ );
121
+ assert.ok(usageAskStrings.length >= 3, 'expected EN + ES + PT usage.ask strings in i18n.mjs');
122
+ for (const s of usageAskStrings) {
123
+ assert.ok(
124
+ !/coming soon|muy pronto|em breve/i.test(s),
125
+ `i18n.mjs usage.ask says "coming soon": ${s.slice(0, 120)}`,
126
+ );
127
+ }
128
+ });
129
+
130
+ // ── BUG-13: stop() refs timer on restart; shell adopts new PID ────────────────
131
+
132
+ test('BUG-13: pet-server.mjs stop() only unref()s timer when there is no callback', () => {
133
+ const src = readFileSync(join(ROOT, 'cli/lib/pet-server.mjs'), 'utf8');
134
+ // The fix: `const _t = setTimeout(...); if (!then) _t.unref();`
135
+ // The broken form was: `setTimeout(...).unref()` unconditionally.
136
+ assert.ok(
137
+ src.includes('if (!then) _t.unref()'),
138
+ "stop() must unref timer only when there is no callback (restart path keeps it ref'd)",
139
+ );
140
+ assert.ok(
141
+ !src.match(/setTimeout\([^)]+\)\.unref\(\)/),
142
+ 'stop() must not unconditionally unref the exit timer',
143
+ );
144
+ });
145
+
146
+ test('BUG-13: main.cjs adopts a new daemon PID instead of quitting', () => {
147
+ const src = readFileSync(join(ROOT, 'cli/pet/electron/main.cjs'), 'utf8');
148
+ // The fix: `if (h.pid !== pid) pid = h.pid;` (always adopt)
149
+ // The broken form was: `if (h.pid !== pid) process.env.SEVENOTS_PET_APP ? (pid = h.pid) : app.quit();`
150
+ assert.ok(
151
+ src.includes('if (h.pid !== pid) pid = h.pid'),
152
+ 'health check must adopt a new daemon PID in all modes, not quit',
153
+ );
154
+ assert.ok(
155
+ !src.includes('app.quit()') || !src.match(/h\.pid !== pid[\s\S]{0,60}app\.quit\(\)/),
156
+ 'health check must not quit when daemon PID changes',
157
+ );
158
+ });
159
+
package/cli/lib/brain.mjs CHANGED
@@ -224,11 +224,15 @@ export function createBrain(brain = { kind: 'lines' }, home = {}) {
224
224
  const llm = createLLM(llmEnv);
225
225
  return {
226
226
  kind: brain.kind,
227
- async think({ system, messages, raw = false, onUsage }) {
227
+ // files: images (the screen) go inline with the last user message; Batuta routes to models that may not see
228
+ vision: brain.kind === 'api',
229
+ async think({ system, messages, raw = false, files = null, onUsage }) {
228
230
  if (brain.kind === 'batuta' && !keys.ORQUESTA_TOKEN) throw Object.assign(new Error('batuta: no Orquesta token'), { code: 'batuta_no_token' });
229
231
  let r;
230
232
  try {
231
- r = await llm.step({ system, messages, tools: [] });
233
+ const images = (files || []).filter((f) => /\.(jpe?g|png)$/i.test(f) && existsSync(f)).map((f) => ({ mediaType: /\.png$/i.test(f) ? 'image/png' : 'image/jpeg', data: readFileSync(f).toString('base64') }));
234
+ const msgs = images.length ? messages.map((m, i) => (i === messages.length - 1 && m.role === 'user' ? { ...m, images } : m)) : messages;
235
+ r = await llm.step({ system, messages: msgs, tools: [] });
232
236
  } catch (e) {
233
237
  throw brain.kind === 'batuta' ? batutaError(e, keys.ORQUESTA_TOKEN) : e;
234
238
  }
@@ -23,6 +23,7 @@
23
23
  * prowl: false, share which tools work: host, ok and latency of remote integrations go to your 7ots.com ot
24
24
  * and from there to Prowl's ranking (tooluse.mjs; never the tool, its arguments or results)
25
25
  * screen: false, it looks at the active window and, every screen.every minutes, a screenshot (screen.mjs)
26
+ * control: false, it may use the mouse and keyboard to do what you ask (control.mjs; steps ≤ control.maxSteps)
26
27
  * processes: false, it sees which programs run (name, cpu, memory) and can wait for one to finish
27
28
  * logs: false, it may read the logs of running processes (journal, pm2, docker, a log file) when asked
28
29
  * inbox: false, it may read your email (apumail inbox) when asked
@@ -41,6 +42,7 @@
41
42
  * character { backstory, style, quirks, examples, scenario, greeting, the character sheet (chara_card_v2)
42
43
  * letta?: { on, agentId } } persona memory on Letta (LETTA_API_KEY)
43
44
  * screen { every: 5 } minutes between screenshots
45
+ * control { maxSteps: 25 } most actions one goal may take while it uses the computer (≤ 60)
44
46
  *
45
47
  * ~/.7ots/keys.json (0600) keeps the keys typed in the wizard under their usual env-var names
46
48
  * (and, on a server enrolled with `7ots vm enroll`, its worker token SEVENOTS_VM_TOKEN).
@@ -58,9 +60,10 @@ export const CONFIG_DEFAULTS = Object.freeze({
58
60
  brain: { kind: 'lines' },
59
61
  voice: { kind: 'browser' },
60
62
  pet: { mode: 'ask', annoy: 2, music: 'synth', musicVol: 0.5, entrance: { onStart: false, kind: 'wwe', dance: '' } },
61
- access: { agent: true, memory: true, open: true, notify: true, sites: true, prowl: false, screen: false, processes: false, logs: false, inbox: false, vm: false, vmKinds: ['research', 'browse', 'long'], camera: false, activity: false, mail: false, calendar: false, whatsapp: false },
63
+ access: { agent: true, memory: true, open: true, notify: true, sites: true, prowl: false, screen: false, control: false, processes: false, logs: false, inbox: false, vm: false, vmKinds: ['research', 'browse', 'long'], camera: false, activity: false, mail: false, calendar: false, whatsapp: false },
62
64
  senses: { arm: true, holdMs: 600, fps: 5, reflect: true },
63
65
  screen: { every: 5 },
66
+ control: { maxSteps: 25 },
64
67
  // conversation memory: recent turns up to `tokens` (≈chars/4), older ones compacted into a summary; 0 = off
65
68
  memory: { tokens: 20000 },
66
69
  integrations: { orquesta: { on: false }, apumail: { on: false, inbox: '' }, custom: [] },
@@ -78,6 +81,7 @@ export function loadConfig() {
78
81
  pet: { ...CONFIG_DEFAULTS.pet, ...c.pet },
79
82
  access: { ...CONFIG_DEFAULTS.access, ...c.access },
80
83
  screen: { ...CONFIG_DEFAULTS.screen, ...c.screen },
84
+ control: { ...CONFIG_DEFAULTS.control, ...c.control },
81
85
  senses: { ...CONFIG_DEFAULTS.senses, ...c.senses },
82
86
  memory: { ...CONFIG_DEFAULTS.memory, ...c.memory },
83
87
  integrations: {