@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.
- package/cli/lib/assistant.mjs +17 -7
- package/cli/lib/assistant.test.mjs +159 -0
- package/cli/lib/brain.mjs +6 -2
- package/cli/lib/config.mjs +5 -1
- package/cli/lib/control.mjs +408 -0
- package/cli/lib/control.test.mjs +141 -0
- package/cli/lib/pet-server.mjs +54 -1
- package/cli/lib/vm.mjs +62 -3
- package/cli/pet/electron/main.cjs +19 -7
- package/cli/pet/pet.html +2 -0
- package/cli/pet/settings.html +22 -8
- package/package.json +1 -1
- package/server/llm.mjs +4 -1
- package/server/server.mjs +2 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uses the computer for you (access.control, off by default): it looks at the screen, moves the mouse, clicks,
|
|
3
|
+
* types and presses keys until the goal you gave it is done.
|
|
4
|
+
*
|
|
5
|
+
* loop: screenshot (scaled to ≤1280 px) → the brain answers ONE JSON action → it runs → again
|
|
6
|
+
* actions: click · move · drag · type · key · scroll · open · wait · done · ask
|
|
7
|
+
*
|
|
8
|
+
* Backends: X11 → xdotool (+ ImageMagick `import` for the screenshot) · macOS → cliclick + screencapture/sips.
|
|
9
|
+
* Wayland has no portable way to inject input or grab the screen without a portal prompt: it says so.
|
|
10
|
+
*
|
|
11
|
+
* Safety:
|
|
12
|
+
* · at most config.control.maxSteps steps (default 25) and one goal at a time; stop() (POST /control/stop,
|
|
13
|
+
* the tray, Esc on the pet) ends it at the next step;
|
|
14
|
+
* · you take over = it stops: if the mouse is not where it left it, it ends ("you moved the mouse");
|
|
15
|
+
* · Enter in a terminal, and text that looks destructive (sudo, rm -rf, mkfs, dd, curl | sh…), need your OK
|
|
16
|
+
* in its bubble (confirm); text that looks like a secret is never typed;
|
|
17
|
+
* · the screenshot lives only while the step runs (~/.7ots/screen/control.jpg, 0600 dir) and is then deleted.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { execFile } from 'node:child_process';
|
|
21
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { homeFile } from './paths.mjs';
|
|
24
|
+
|
|
25
|
+
const exec = (cmd, args, ms = 5000, env = undefined) =>
|
|
26
|
+
new Promise((res) => execFile(cmd, args, { timeout: ms, windowsHide: true, env }, (e, out, err) => res({ ok: !e, out: String(out || '').trim(), err: String(err || e?.message || '').trim() })));
|
|
27
|
+
|
|
28
|
+
const TERM = /terminal|kitty|alacritty|konsole|tilix|wezterm|xterm|ghostty|warp|terminator|urxvt|st-256color|iterm/i;
|
|
29
|
+
const DANGER = /\b(sudo|su\s+-|rm\s+-[a-z]*[rf]|mkfs|dd\s+if=|shutdown|reboot|poweroff|chmod\s+-R|chown\s+-R|git\s+push\s+.*--force|drop\s+(table|database))\b|curl[^|\n]*\|\s*(ba|z)?sh|wget[^|\n]*\|\s*(ba|z)?sh|:\(\)\s*\{/i;
|
|
30
|
+
const SECRET = /\b(sk-[\w-]{16,}|sk_live_\w+|ghp_\w{20,}|gho_\w{20,}|xox[abp]-[\w-]+|AKIA[0-9A-Z]{16}|eyJ[\w-]{20,}\.[\w-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY)/;
|
|
31
|
+
const KEYS = /^[A-Za-z0-9_]+(\+[A-Za-z0-9_]+){0,4}$/;
|
|
32
|
+
const ACTIONS = ['click', 'move', 'drag', 'type', 'key', 'scroll', 'open', 'wait', 'done', 'ask'];
|
|
33
|
+
export const CONTROL_MAX_STEPS = 60;
|
|
34
|
+
|
|
35
|
+
/** Width × height of a JPEG or PNG (no dependency). */
|
|
36
|
+
export function imageSize(buf) {
|
|
37
|
+
if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
|
|
38
|
+
let i = 2;
|
|
39
|
+
while (i + 9 < buf.length && buf[0] === 0xff && buf[1] === 0xd8) {
|
|
40
|
+
if (buf[i] !== 0xff) return null;
|
|
41
|
+
const m = buf[i + 1];
|
|
42
|
+
if (m >= 0xc0 && m <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(m)) return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5) };
|
|
43
|
+
i += 2 + buf.readUInt16BE(i + 2);
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The brain's answer → one checked action, or { error }. Coordinates stay in screenshot pixels here. */
|
|
49
|
+
export function parseControl(raw, { w = 1280, h = 800 } = {}) {
|
|
50
|
+
let j;
|
|
51
|
+
try {
|
|
52
|
+
j = JSON.parse(String(raw).match(/\{[\s\S]*\}/)?.[0] || '');
|
|
53
|
+
} catch {
|
|
54
|
+
return { error: 'not JSON' };
|
|
55
|
+
}
|
|
56
|
+
const type = String(j.action || j.type || '').toLowerCase();
|
|
57
|
+
if (!ACTIONS.includes(type)) return { error: `unknown action "${type}"` };
|
|
58
|
+
const say = String(j.say || '').slice(0, 160);
|
|
59
|
+
const num = (v) => (Number.isFinite(Number(v)) ? Math.round(Number(v)) : NaN);
|
|
60
|
+
const pt = (x, y) => {
|
|
61
|
+
const p = { x: num(x), y: num(y) };
|
|
62
|
+
return p.x >= 0 && p.y >= 0 && p.x <= w && p.y <= h ? p : null;
|
|
63
|
+
};
|
|
64
|
+
const a = { type, say };
|
|
65
|
+
if (['click', 'move', 'drag', 'scroll'].includes(type)) {
|
|
66
|
+
const p = pt(j.x, j.y);
|
|
67
|
+
if (!p && type !== 'scroll') return { error: `${type} needs x,y inside the ${w}x${h} screenshot` };
|
|
68
|
+
Object.assign(a, p || {});
|
|
69
|
+
}
|
|
70
|
+
if (type === 'click') {
|
|
71
|
+
a.button = ['left', 'right', 'middle'].includes(j.button) ? j.button : 'left';
|
|
72
|
+
a.double = j.double === true;
|
|
73
|
+
}
|
|
74
|
+
if (type === 'drag') {
|
|
75
|
+
const to = pt(j.to_x ?? j.toX, j.to_y ?? j.toY);
|
|
76
|
+
if (!to) return { error: 'drag needs to_x,to_y' };
|
|
77
|
+
a.to = to;
|
|
78
|
+
}
|
|
79
|
+
if (type === 'type') {
|
|
80
|
+
a.text = String(j.text ?? '').slice(0, 2000);
|
|
81
|
+
if (!a.text) return { error: 'type needs text' };
|
|
82
|
+
}
|
|
83
|
+
if (type === 'key') {
|
|
84
|
+
a.keys = String(j.keys || j.key || '').trim().replace(/\s*\+\s*/g, '+');
|
|
85
|
+
if (!KEYS.test(a.keys)) return { error: `bad keys "${a.keys}" (e.g. "ctrl+alt+t", "Return")` };
|
|
86
|
+
}
|
|
87
|
+
if (type === 'scroll') {
|
|
88
|
+
a.dir = ['up', 'down', 'left', 'right'].includes(j.dir || j.direction) ? j.dir || j.direction : 'down';
|
|
89
|
+
a.amount = Math.max(1, Math.min(15, num(j.amount) || 3));
|
|
90
|
+
}
|
|
91
|
+
if (type === 'open') {
|
|
92
|
+
a.url = String(j.url || '').trim();
|
|
93
|
+
if (!/^https?:\/\/[^\s"'<>]{1,500}$/i.test(a.url)) return { error: 'open needs an http(s) url' };
|
|
94
|
+
}
|
|
95
|
+
if (type === 'wait') a.seconds = Math.max(0.2, Math.min(10, Number(j.seconds) || 1));
|
|
96
|
+
if (type === 'done' || type === 'ask') a.say = String(j.say || j.question || j.text || '').slice(0, 300);
|
|
97
|
+
return a;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Screenshot pixels → screen pixels. */
|
|
101
|
+
export const toScreen = (p, scale) => (p ? { x: Math.round(p.x / scale), y: Math.round(p.y / scale) } : null);
|
|
102
|
+
|
|
103
|
+
/** Why an action needs your OK first (or null). */
|
|
104
|
+
export function risk(a, app = '') {
|
|
105
|
+
if (a.type === 'type' && DANGER.test(a.text)) return 'danger';
|
|
106
|
+
if (a.type === 'type' && /\n/.test(a.text) && TERM.test(app)) return 'enter';
|
|
107
|
+
if (a.type === 'key' && /^(Return|KP_Enter|enter)$/i.test(a.keys.split('+').pop()) && TERM.test(app)) return 'enter';
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── backends ──
|
|
112
|
+
function backend() {
|
|
113
|
+
if (process.platform === 'darwin') return 'mac';
|
|
114
|
+
if (process.platform === 'linux' && process.env.WAYLAND_DISPLAY && !process.env.DISPLAY) return 'wayland';
|
|
115
|
+
if (process.platform === 'linux' && process.env.DISPLAY) return 'x11';
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const BTN = { left: '1', middle: '2', right: '3' };
|
|
119
|
+
// xdotool key names ← what models tend to write
|
|
120
|
+
const KEYNAME = { enter: 'Return', return: 'Return', esc: 'Escape', escape: 'Escape', tab: 'Tab', backspace: 'BackSpace', delete: 'Delete', del: 'Delete', space: 'space', up: 'Up', down: 'Down', left: 'Left', right: 'Right', home: 'Home', end: 'End', pageup: 'Page_Up', pagedown: 'Page_Down', win: 'super', cmd: 'super', meta: 'super', control: 'ctrl' };
|
|
121
|
+
const xKeys = (k) => k.split('+').map((p) => KEYNAME[p.toLowerCase()] || p).join('+');
|
|
122
|
+
// Wayland: ydotool speaks Linux input event codes (/usr/include/linux/input-event-codes.h)
|
|
123
|
+
const EVCODE = { escape: 1, backspace: 14, tab: 15, return: 28, ctrl: 29, shift: 42, alt: 56, space: 57, home: 102, up: 103, page_up: 104, left: 105, right: 106, end: 107, down: 108, page_down: 109, insert: 110, delete: 111, super: 125, minus: 12, equal: 13, period: 52, comma: 51, slash: 53 };
|
|
124
|
+
[...'qwertyuiop'].forEach((c, i) => (EVCODE[c] = 16 + i));
|
|
125
|
+
[...'asdfghjkl'].forEach((c, i) => (EVCODE[c] = 30 + i));
|
|
126
|
+
[...'zxcvbnm'].forEach((c, i) => (EVCODE[c] = 44 + i));
|
|
127
|
+
[...'1234567890'].forEach((c, i) => (EVCODE[c] = 2 + i));
|
|
128
|
+
for (let i = 1; i <= 10; i++) EVCODE[`f${i}`] = 58 + i;
|
|
129
|
+
Object.assign(EVCODE, { f11: 87, f12: 88 });
|
|
130
|
+
/** "ctrl+alt+t" → ["29:1","56:1","20:1","20:0","56:0","29:0"], or null for an unknown key. */
|
|
131
|
+
export function evKeys(k) {
|
|
132
|
+
const codes = xKeys(k).split('+').map((p) => EVCODE[p.toLowerCase()]);
|
|
133
|
+
if (codes.some((c) => c == null)) return null;
|
|
134
|
+
return [...codes.map((c) => `${c}:1`), ...codes.reverse().map((c) => `${c}:0`)];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** display: an X display of its own (":99", the worker's Xvfb); the tools run there instead of on yours. */
|
|
138
|
+
export function createDesktop({ kind = backend(), display = null, dir = null, run = display ? (c, a, ms) => exec(c, a, ms, { ...process.env, DISPLAY: display }) : exec } = {}) {
|
|
139
|
+
if (display) kind = 'x11';
|
|
140
|
+
const shot = dir || homeFile('screen');
|
|
141
|
+
const file = join(shot, 'control.jpg');
|
|
142
|
+
const tools = { x11: ['xdotool', 'import'], mac: ['cliclick'], wayland: ['ydotool', 'convert'] }[kind] || [];
|
|
143
|
+
// Wayland: grim on wlroots compositors, gnome-screenshot on GNOME; the full-size capture gives the screen size
|
|
144
|
+
const raw = join(shot, 'control-raw.png');
|
|
145
|
+
const grab = async () => {
|
|
146
|
+
mkdirSync(shot, { recursive: true, mode: 0o700 });
|
|
147
|
+
for (const [cmd, args] of [['grim', [raw]], ['gnome-screenshot', ['-f', raw]], ['spectacle', ['-b', '-n', '-f', '-o', raw]]]) if ((await run(cmd, args, 8000)).ok && existsSync(raw)) return raw;
|
|
148
|
+
return null;
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
kind,
|
|
152
|
+
/** null when it can work here, else what is missing. */
|
|
153
|
+
async missing() {
|
|
154
|
+
if (!kind) return 'no desktop here';
|
|
155
|
+
if (kind === 'wayland' && !(await run('sh', ['-c', 'command -v grim || command -v gnome-screenshot || command -v spectacle'])).ok) return 'grim';
|
|
156
|
+
for (const t of tools) if (!(await run(kind === 'mac' ? 'which' : 'sh', kind === 'mac' ? [t] : ['-c', `command -v ${t}`])).ok) return t;
|
|
157
|
+
return null;
|
|
158
|
+
},
|
|
159
|
+
async size() {
|
|
160
|
+
if (kind === 'x11') {
|
|
161
|
+
const m = (await run('xdotool', ['getdisplaygeometry'])).out.match(/(\d+)\s+(\d+)/);
|
|
162
|
+
return m ? { w: +m[1], h: +m[2] } : null;
|
|
163
|
+
}
|
|
164
|
+
if (kind === 'mac') {
|
|
165
|
+
const m = (await run('osascript', ['-e', 'tell application "Finder" to get bounds of window of desktop'])).out.match(/(-?\d+),\s*(-?\d+),\s*(\d+),\s*(\d+)/);
|
|
166
|
+
return m ? { w: +m[3], h: +m[4] } : null;
|
|
167
|
+
}
|
|
168
|
+
if (kind === 'wayland') {
|
|
169
|
+
const f = await grab();
|
|
170
|
+
const d = f && imageSize(readFileSync(f));
|
|
171
|
+
try {
|
|
172
|
+
unlinkSync(raw);
|
|
173
|
+
} catch {}
|
|
174
|
+
return d || null;
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
},
|
|
178
|
+
async screenshot() {
|
|
179
|
+
mkdirSync(shot, { recursive: true, mode: 0o700 });
|
|
180
|
+
try {
|
|
181
|
+
unlinkSync(file);
|
|
182
|
+
} catch {}
|
|
183
|
+
if (kind === 'x11') await run('import', ['-silent', '-window', 'root', '-resize', '1280x1280>', '-quality', '70', file], 8000);
|
|
184
|
+
else if (kind === 'mac') {
|
|
185
|
+
await run('screencapture', ['-x', '-C', '-t', 'jpg', file], 8000);
|
|
186
|
+
if (existsSync(file)) await run('sips', ['-Z', '1280', file], 8000);
|
|
187
|
+
} else if (kind === 'wayland' && (await grab())) {
|
|
188
|
+
await run('convert', [raw, '-resize', '1280x1280>', '-quality', '70', file], 8000);
|
|
189
|
+
try {
|
|
190
|
+
unlinkSync(raw);
|
|
191
|
+
} catch {}
|
|
192
|
+
}
|
|
193
|
+
return existsSync(file) ? file : null;
|
|
194
|
+
},
|
|
195
|
+
drop() {
|
|
196
|
+
try {
|
|
197
|
+
unlinkSync(file);
|
|
198
|
+
} catch {}
|
|
199
|
+
},
|
|
200
|
+
async mouse() {
|
|
201
|
+
if (kind === 'x11') {
|
|
202
|
+
const m = (await run('xdotool', ['getmouselocation'])).out.match(/x:(\d+)\s+y:(\d+)/);
|
|
203
|
+
return m ? { x: +m[1], y: +m[2] } : null;
|
|
204
|
+
}
|
|
205
|
+
if (kind === 'mac') {
|
|
206
|
+
const m = (await run('cliclick', ['p:.'])).out.match(/(\d+),(\d+)/);
|
|
207
|
+
return m ? { x: +m[1], y: +m[2] } : null;
|
|
208
|
+
}
|
|
209
|
+
return null;
|
|
210
|
+
},
|
|
211
|
+
async activeApp() {
|
|
212
|
+
if (kind === 'x11') {
|
|
213
|
+
const id = (await run('xdotool', ['getactivewindow'])).out;
|
|
214
|
+
if (!id) return '';
|
|
215
|
+
const [t, c] = await Promise.all([run('xdotool', ['getwindowname', id]), run('xprop', ['-id', id, 'WM_CLASS'])]);
|
|
216
|
+
return `${c.out.match(/"([^"]*)"\s*$/)?.[1] || ''} — ${t.out}`.slice(0, 200);
|
|
217
|
+
}
|
|
218
|
+
if (kind === 'mac') return (await run('osascript', ['-e', 'tell application "System Events" to get name of first process whose frontmost is true'])).out;
|
|
219
|
+
// Wayland does not say which window has focus: assume a terminal, so Enter always asks first
|
|
220
|
+
if (kind === 'wayland') return 'unknown window (Wayland: treated as a terminal)';
|
|
221
|
+
return '';
|
|
222
|
+
},
|
|
223
|
+
/** Runs one action (screen pixels). → { ok, err } */
|
|
224
|
+
async act(a) {
|
|
225
|
+
if (kind === 'x11') {
|
|
226
|
+
const xy = (p) => ['mousemove', String(p.x), String(p.y), 'sleep', '0.05'];
|
|
227
|
+
if (a.type === 'move') return run('xdotool', xy(a));
|
|
228
|
+
if (a.type === 'click') return run('xdotool', [...xy(a), 'click', ...(a.double ? ['--repeat', '2', '--delay', '80'] : []), BTN[a.button]]);
|
|
229
|
+
if (a.type === 'drag') return run('xdotool', [...xy(a), 'mousedown', '1', 'sleep', '0.15', ...xy(a.to), 'sleep', '0.15', 'mouseup', '1']);
|
|
230
|
+
if (a.type === 'scroll') {
|
|
231
|
+
const b = { up: '4', down: '5', left: '6', right: '7' }[a.dir];
|
|
232
|
+
return run('xdotool', [...(a.x != null ? xy(a) : []), 'click', '--repeat', String(a.amount), '--delay', '40', b]);
|
|
233
|
+
}
|
|
234
|
+
if (a.type === 'type') return run('xdotool', ['type', '--delay', '12', '--', a.text], 60000);
|
|
235
|
+
if (a.type === 'key') return run('xdotool', ['key', '--clearmodifiers', '--', xKeys(a.keys)]);
|
|
236
|
+
}
|
|
237
|
+
if (kind === 'mac') {
|
|
238
|
+
const xy = (p) => `${p.x},${p.y}`;
|
|
239
|
+
if (a.type === 'move') return run('cliclick', [`m:${xy(a)}`]);
|
|
240
|
+
if (a.type === 'click') return run('cliclick', [`${a.button === 'right' ? 'rc' : a.double ? 'dc' : 'c'}:${xy(a)}`]);
|
|
241
|
+
if (a.type === 'drag') return run('cliclick', [`dd:${xy(a)}`, `du:${xy(a.to)}`]);
|
|
242
|
+
if (a.type === 'type') return run('cliclick', [`t:${a.text}`], 60000);
|
|
243
|
+
if (a.type === 'key') {
|
|
244
|
+
const parts = a.keys.toLowerCase().split('+');
|
|
245
|
+
const mods = parts.slice(0, -1).map((m) => ({ ctrl: 'ctrl', control: 'ctrl', alt: 'alt', option: 'alt', shift: 'shift', cmd: 'cmd', super: 'cmd', meta: 'cmd' })[m]).filter(Boolean);
|
|
246
|
+
const k = parts.at(-1);
|
|
247
|
+
const named = { enter: 'return', return: 'return', esc: 'esc', escape: 'esc', tab: 'tab', backspace: 'delete', delete: 'fwd-delete', space: 'space', up: 'arrow-up', down: 'arrow-down', left: 'arrow-left', right: 'arrow-right', home: 'home', end: 'end', pageup: 'page-up', pagedown: 'page-down' }[k];
|
|
248
|
+
const press = named ? `kp:${named}` : `t:${k}`;
|
|
249
|
+
return run('cliclick', mods.length ? [`kd:${mods.join(',')}`, press, `ku:${mods.join(',')}`] : [press]);
|
|
250
|
+
}
|
|
251
|
+
if (a.type === 'scroll') return { ok: false, err: 'scroll is not supported on macOS yet: use keys (Page_Down, space)' };
|
|
252
|
+
}
|
|
253
|
+
if (kind === 'wayland') {
|
|
254
|
+
// ydotool ≥1.0 (ydotoold running, /dev/uinput): absolute moves, button codes 0xC0 = left down+up
|
|
255
|
+
const xy = (p) => ['mousemove', '--absolute', '-x', String(p.x), '-y', String(p.y)];
|
|
256
|
+
const BT = { left: 0, right: 1, middle: 2 };
|
|
257
|
+
const yd = (args, ms) => run('ydotool', args, ms);
|
|
258
|
+
if (a.type === 'move') return yd(xy(a));
|
|
259
|
+
if (a.type === 'click') {
|
|
260
|
+
await yd(xy(a));
|
|
261
|
+
return yd(['click', ...(a.double ? ['-r', '2', '-D', '80'] : []), `0x${(0xc0 + BT[a.button]).toString(16)}`]);
|
|
262
|
+
}
|
|
263
|
+
if (a.type === 'drag') {
|
|
264
|
+
await yd(xy(a));
|
|
265
|
+
await yd(['click', '0x40']);
|
|
266
|
+
await yd(xy(a.to));
|
|
267
|
+
return yd(['click', '0x80']);
|
|
268
|
+
}
|
|
269
|
+
if (a.type === 'scroll') {
|
|
270
|
+
if (a.x != null) await yd(xy(a));
|
|
271
|
+
const n = a.amount * (a.dir === 'up' || a.dir === 'left' ? 1 : -1);
|
|
272
|
+
return yd(['mousemove', '-w', ...(a.dir === 'left' || a.dir === 'right' ? ['-x', String(n), '-y', '0'] : ['-x', '0', '-y', String(n)])]);
|
|
273
|
+
}
|
|
274
|
+
if (a.type === 'type') return yd(['type', '-d', '12', '--', a.text], 60000);
|
|
275
|
+
if (a.type === 'key') {
|
|
276
|
+
const codes = evKeys(a.keys);
|
|
277
|
+
return codes ? yd(['key', ...codes]) : { ok: false, err: `unknown key on Wayland: ${a.keys}` };
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return { ok: false, err: `${a.type}: not supported on ${kind}` };
|
|
281
|
+
},
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const SYSTEM = (name, lang) => `You are ${name}, a little desktop pet that is now using your human's computer for them, like a careful assistant with a mouse and keyboard.
|
|
286
|
+
Each turn you get a screenshot of the whole screen (its size is given) and what you did so far. Answer with ONE action as JSON, nothing else:
|
|
287
|
+
{"action":"click","x":0,"y":0,"button":"left|right|middle","double":false,"say":"…"}
|
|
288
|
+
{"action":"move","x":0,"y":0,"say":"…"}
|
|
289
|
+
{"action":"drag","x":0,"y":0,"to_x":0,"to_y":0,"say":"…"}
|
|
290
|
+
{"action":"type","text":"…","say":"…"} (types into the focused field; "\\n" = Enter)
|
|
291
|
+
{"action":"key","keys":"ctrl+alt+t","say":"…"} (xdotool names: Return, Escape, Tab, BackSpace, super, ctrl+l, alt+F4…)
|
|
292
|
+
{"action":"scroll","x":0,"y":0,"dir":"down|up","amount":3,"say":"…"}
|
|
293
|
+
{"action":"open","url":"https://…","say":"…"} (opens it in the default browser)
|
|
294
|
+
{"action":"wait","seconds":1,"say":"…"}
|
|
295
|
+
{"action":"done","say":"what you did, for your human"}
|
|
296
|
+
{"action":"ask","say":"a question when you are stuck or need them (a login, a password, a choice)"}
|
|
297
|
+
Rules: x,y are pixels IN THE SCREENSHOT. Click the center of things. After a click or typing, check the next screenshot before going on.
|
|
298
|
+
The small cute creature on the screen is you: never click it. Never type passwords, keys or payment details, never buy or send money, never delete files or send messages on their behalf unless the goal says so exactly: "ask" instead.
|
|
299
|
+
Keep "say" to a few words in ${lang} (it shows in your bubble). Finish with "done" as soon as the goal is reached.`;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* One goal at a time. brain: needs vision (createBrain → .vision). confirm(text) → Promise<boolean>.
|
|
303
|
+
* onStep({ step, action, point, say }) is called before each action (point in screen pixels, to walk there).
|
|
304
|
+
*/
|
|
305
|
+
export function createControl({ brain, desktop = createDesktop(), name = 'ot', lang = () => 'en', maxSteps = () => 25, confirm = async () => false, onStep = () => {}, openUrl = null, log = () => {}, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
|
|
306
|
+
let job = null; // { goal, step, stop, history }
|
|
307
|
+
|
|
308
|
+
async function run(goal) {
|
|
309
|
+
goal = String(goal || '').trim().slice(0, 600);
|
|
310
|
+
if (!goal) return { ok: false, error: 'goal' };
|
|
311
|
+
if (job) return { ok: false, error: 'busy', goal: job.goal };
|
|
312
|
+
if (!brain.vision) return { ok: false, error: 'no_vision' };
|
|
313
|
+
const miss = await desktop.missing();
|
|
314
|
+
if (miss) return { ok: false, error: miss === 'wayland' ? 'wayland' : 'missing', missing: miss };
|
|
315
|
+
const me = (job = { goal, step: 0, stop: false, history: [] });
|
|
316
|
+
const limit = Math.max(1, Math.min(CONTROL_MAX_STEPS, Number(maxSteps()) || 25));
|
|
317
|
+
let left = null; // where it left the mouse: if it moved, you took over
|
|
318
|
+
let result = { ok: false, error: 'steps', said: '' };
|
|
319
|
+
try {
|
|
320
|
+
const screen = await desktop.size();
|
|
321
|
+
if (!screen) return (result = { ok: false, error: 'screen' });
|
|
322
|
+
for (; me.step < limit; me.step++) {
|
|
323
|
+
if (me.stop) return (result = { ok: false, error: 'stopped' });
|
|
324
|
+
if (left) {
|
|
325
|
+
const m = await desktop.mouse();
|
|
326
|
+
if (m && Math.hypot(m.x - left.x, m.y - left.y) > 40) return (result = { ok: false, error: 'taken' });
|
|
327
|
+
}
|
|
328
|
+
const f = await desktop.screenshot();
|
|
329
|
+
if (!f) return (result = { ok: false, error: 'screenshot' });
|
|
330
|
+
const img = imageSize(readFileSync(f)) || { w: screen.w, h: screen.h };
|
|
331
|
+
const scale = img.w / screen.w;
|
|
332
|
+
const app = await desktop.activeApp();
|
|
333
|
+
const past = me.history.slice(-12).map((h, i) => `${i + 1}. ${h}`).join('\n');
|
|
334
|
+
let raw = '';
|
|
335
|
+
try {
|
|
336
|
+
raw = await brain.think({
|
|
337
|
+
purpose: 'control',
|
|
338
|
+
system: SYSTEM(name, lang()),
|
|
339
|
+
messages: [{ role: 'user', content: `Goal: «${goal}»\nScreenshot: ${img.w}x${img.h} px (file ${f}). Focused window: ${app || '?'}\nStep ${me.step + 1} of ${limit}. Done so far:\n${past || '(nothing yet)'}\n\nYour next action (JSON):` }],
|
|
340
|
+
files: [f],
|
|
341
|
+
timeoutMs: 90000,
|
|
342
|
+
raw: true,
|
|
343
|
+
});
|
|
344
|
+
} finally {
|
|
345
|
+
desktop.drop();
|
|
346
|
+
}
|
|
347
|
+
if (me.stop) return (result = { ok: false, error: 'stopped' });
|
|
348
|
+
const a = parseControl(raw, img);
|
|
349
|
+
if (a.error) {
|
|
350
|
+
me.history.push(`(invalid answer: ${a.error})`);
|
|
351
|
+
log(`control: ${a.error}`);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (a.type === 'done') return (result = { ok: true, said: a.say });
|
|
355
|
+
if (a.type === 'ask') return (result = { ok: false, error: 'ask', said: a.say });
|
|
356
|
+
const real = { ...a, ...toScreen(a.x != null ? a : null, scale), ...(a.to ? { to: toScreen(a.to, scale) } : {}) };
|
|
357
|
+
onStep({ step: me.step + 1, action: real, point: real.x != null ? { x: real.x, y: real.y } : null, say: a.say });
|
|
358
|
+
if (a.type === 'type' && SECRET.test(a.text)) {
|
|
359
|
+
me.history.push('type: refused (looks like a secret)');
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
const why = risk(a, app);
|
|
363
|
+
if (why && !(await confirm(why === 'danger' ? `${name} wants to type: ${a.text.slice(0, 200)}` : `${name} wants to press Enter in ${app.slice(0, 60)}${a.text ? `: ${a.text.slice(0, 160)}` : ''}`, why))) return (result = { ok: false, error: 'rejected' });
|
|
364
|
+
if (me.stop) return (result = { ok: false, error: 'stopped' });
|
|
365
|
+
let r;
|
|
366
|
+
if (a.type === 'wait') (await sleep(a.seconds * 1000)), (r = { ok: true });
|
|
367
|
+
else if (a.type === 'open') r = openUrl ? (openUrl(a.url), { ok: true }) : await desktop.act(a);
|
|
368
|
+
else r = await desktop.act(real);
|
|
369
|
+
me.history.push(`${describe(a)}${r.ok ? '' : ` → failed: ${String(r.err).slice(0, 120)}`}`);
|
|
370
|
+
if (['click', 'move', 'drag', 'scroll'].includes(a.type) && r.ok) left = (await desktop.mouse()) || (real.to ?? real);
|
|
371
|
+
await sleep(a.type === 'open' ? 1800 : a.type === 'key' || a.type === 'click' ? 700 : 350); // let the screen catch up
|
|
372
|
+
}
|
|
373
|
+
return result;
|
|
374
|
+
} catch (e) {
|
|
375
|
+
log(`control: ${e.message}`);
|
|
376
|
+
return (result = { ok: false, error: 'error', said: e.message });
|
|
377
|
+
} finally {
|
|
378
|
+
result.steps = me.step;
|
|
379
|
+
result.log = me.history.slice(-30);
|
|
380
|
+
if (job === me) job = null;
|
|
381
|
+
log(`control: ${result.ok ? 'done' : result.error} after ${me.step} steps — ${goal.slice(0, 80)}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
return {
|
|
386
|
+
run,
|
|
387
|
+
/** Ends the goal running now at its next step. */
|
|
388
|
+
stop() {
|
|
389
|
+
if (!job) return false;
|
|
390
|
+
job.stop = true;
|
|
391
|
+
return true;
|
|
392
|
+
},
|
|
393
|
+
get status() {
|
|
394
|
+
return job ? { goal: job.goal, step: job.step, last: job.history.at(-1) || '' } : null;
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function describe(a) {
|
|
400
|
+
if (a.type === 'click') return `${a.double ? 'double-' : ''}${a.button} click at ${a.x},${a.y}`;
|
|
401
|
+
if (a.type === 'move') return `move to ${a.x},${a.y}`;
|
|
402
|
+
if (a.type === 'drag') return `drag ${a.x},${a.y} → ${a.to.x},${a.to.y}`;
|
|
403
|
+
if (a.type === 'type') return `type «${a.text.slice(0, 80)}»`;
|
|
404
|
+
if (a.type === 'key') return `key ${a.keys}`;
|
|
405
|
+
if (a.type === 'scroll') return `scroll ${a.dir} ×${a.amount}`;
|
|
406
|
+
if (a.type === 'open') return `open ${a.url}`;
|
|
407
|
+
return `wait ${a.seconds}s`;
|
|
408
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* control.mjs: the brain's actions are checked, scaled to the real screen and run in order; it stops when
|
|
3
|
+
* you move the mouse, asks before Enter in a terminal, never types secrets, and keeps to its step limit.
|
|
4
|
+
* The desktop and the brain are fakes: nothing moves the real mouse.
|
|
5
|
+
*/
|
|
6
|
+
import { test } from 'node:test';
|
|
7
|
+
import assert from 'node:assert/strict';
|
|
8
|
+
import { mkdtempSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { createControl, evKeys, imageSize, parseControl, risk, toScreen } from './control.mjs';
|
|
12
|
+
|
|
13
|
+
const dir = mkdtempSync(join(tmpdir(), '7ots-control-'));
|
|
14
|
+
// a 1280×720 JPEG header (SOI + SOF0), enough for imageSize
|
|
15
|
+
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x02, 0xd0, 0x05, 0x00, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
|
16
|
+
const shot = join(dir, 'shot.jpg');
|
|
17
|
+
writeFileSync(shot, jpeg);
|
|
18
|
+
|
|
19
|
+
function fakeDesktop({ app = 'Firefox — page', mouseMoves = null } = {}) {
|
|
20
|
+
const acts = [];
|
|
21
|
+
let mouse = { x: 0, y: 0 };
|
|
22
|
+
let n = 0;
|
|
23
|
+
return {
|
|
24
|
+
acts,
|
|
25
|
+
kind: 'x11',
|
|
26
|
+
missing: async () => null,
|
|
27
|
+
size: async () => ({ w: 2560, h: 1440 }),
|
|
28
|
+
screenshot: async () => shot,
|
|
29
|
+
drop() {},
|
|
30
|
+
activeApp: async () => app,
|
|
31
|
+
mouse: async () => (mouseMoves && ++n === mouseMoves ? { x: mouse.x + 300, y: mouse.y } : mouse),
|
|
32
|
+
act: async (a) => {
|
|
33
|
+
acts.push(a);
|
|
34
|
+
if (a.x != null) mouse = a.to || { x: a.x, y: a.y };
|
|
35
|
+
return { ok: true };
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const brainSaying = (...answers) => ({ vision: true, kind: 'api', calls: 0, async think() { return JSON.stringify(answers[this.calls++] || { action: 'done', say: 'ok' }); } });
|
|
40
|
+
const opts = { sleep: async () => {}, maxSteps: () => 10 };
|
|
41
|
+
|
|
42
|
+
test('imageSize reads JPEG and PNG headers', () => {
|
|
43
|
+
assert.deepEqual(imageSize(jpeg), { w: 1280, h: 720 });
|
|
44
|
+
const png = Buffer.alloc(24);
|
|
45
|
+
png.writeUInt32BE(0x89504e47, 0);
|
|
46
|
+
png.writeUInt32BE(640, 16);
|
|
47
|
+
png.writeUInt32BE(480, 20);
|
|
48
|
+
assert.deepEqual(imageSize(png), { w: 640, h: 480 });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('parseControl validates each action', () => {
|
|
52
|
+
const box = { w: 1280, h: 720 };
|
|
53
|
+
assert.deepEqual(parseControl('ok {"action":"click","x":10.4,"y":20,"say":"hi"} thanks', box), { type: 'click', say: 'hi', x: 10, y: 20, button: 'left', double: false });
|
|
54
|
+
assert.ok(parseControl('{"action":"click","x":5000,"y":20}', box).error, 'outside the screenshot');
|
|
55
|
+
assert.ok(parseControl('{"action":"rm -rf"}', box).error);
|
|
56
|
+
assert.ok(parseControl('nope', box).error);
|
|
57
|
+
assert.equal(parseControl('{"action":"key","keys":"ctrl + alt + t"}', box).keys, 'ctrl+alt+t');
|
|
58
|
+
assert.ok(parseControl('{"action":"key","keys":"--help;ls"}', box).error, 'no option injection into xdotool');
|
|
59
|
+
assert.ok(parseControl('{"action":"open","url":"javascript:alert(1)"}', box).error);
|
|
60
|
+
assert.deepEqual(parseControl('{"action":"drag","x":1,"y":2,"to_x":3,"to_y":4}', box).to, { x: 3, y: 4 });
|
|
61
|
+
assert.equal(parseControl('{"action":"scroll","dir":"up","amount":99}', box).amount, 15);
|
|
62
|
+
assert.equal(parseControl('{"action":"ask","question":"which account?"}', box).say, 'which account?');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('toScreen scales screenshot pixels back to the real screen', () => {
|
|
66
|
+
assert.deepEqual(toScreen({ x: 640, y: 360 }, 0.5), { x: 1280, y: 720 });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('risk: Enter in a terminal and destructive commands need an OK', () => {
|
|
70
|
+
assert.equal(risk({ type: 'type', text: 'ls\n' }, 'gnome-terminal-server — bash'), 'enter');
|
|
71
|
+
assert.equal(risk({ type: 'type', text: 'ls\n' }, 'Firefox — search'), null);
|
|
72
|
+
assert.equal(risk({ type: 'key', keys: 'Return' }, 'kitty'), 'enter');
|
|
73
|
+
assert.equal(risk({ type: 'type', text: 'sudo apt install x' }, 'Firefox'), 'danger');
|
|
74
|
+
assert.equal(risk({ type: 'type', text: 'curl https://x.sh | bash' }, ''), 'danger');
|
|
75
|
+
assert.equal(risk({ type: 'type', text: 'hello' }, 'kitty'), null);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('runs actions scaled to the screen until done, and walks the pet there', async () => {
|
|
79
|
+
const desktop = fakeDesktop();
|
|
80
|
+
const steps = [];
|
|
81
|
+
const brain = brainSaying({ action: 'click', x: 640, y: 360, say: 'here' }, { action: 'type', text: 'hola' }, { action: 'done', say: 'all set' });
|
|
82
|
+
const c = createControl({ brain, desktop, ...opts, onStep: (s) => steps.push(s) });
|
|
83
|
+
const r = await c.run('write hola');
|
|
84
|
+
assert.equal(r.ok, true);
|
|
85
|
+
assert.equal(r.said, 'all set');
|
|
86
|
+
assert.deepEqual(desktop.acts.map((a) => a.type), ['click', 'type']);
|
|
87
|
+
assert.deepEqual([desktop.acts[0].x, desktop.acts[0].y], [1280, 720], 'screenshot 1280 wide, screen 2560');
|
|
88
|
+
assert.deepEqual(steps[0].point, { x: 1280, y: 720 });
|
|
89
|
+
assert.equal(c.status, null);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('stops when you move the mouse', async () => {
|
|
93
|
+
const desktop = fakeDesktop({ mouseMoves: 2 });
|
|
94
|
+
const brain = brainSaying({ action: 'click', x: 10, y: 10 }, { action: 'click', x: 20, y: 20 }, { action: 'click', x: 30, y: 30 });
|
|
95
|
+
const r = await createControl({ brain, desktop, ...opts }).run('click around');
|
|
96
|
+
assert.equal(r.error, 'taken');
|
|
97
|
+
assert.equal(desktop.acts.length, 1);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('asks before Enter in a terminal; a no ends it', async () => {
|
|
101
|
+
const desktop = fakeDesktop({ app: 'gnome-terminal-server — bash' });
|
|
102
|
+
const asked = [];
|
|
103
|
+
const brain = brainSaying({ action: 'type', text: 'ls -la\n' });
|
|
104
|
+
const r = await createControl({ brain, desktop, ...opts, confirm: async (t) => (asked.push(t), false) }).run('list files');
|
|
105
|
+
assert.equal(r.error, 'rejected');
|
|
106
|
+
assert.equal(asked.length, 1);
|
|
107
|
+
assert.equal(desktop.acts.length, 0);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('never types secrets, and keeps to the step limit', async () => {
|
|
111
|
+
const desktop = fakeDesktop();
|
|
112
|
+
const brain = { vision: true, kind: 'api', think: async () => '{"action":"type","text":"sk-abcdefghijklmnopqrstuvwxyz"}' };
|
|
113
|
+
const r = await createControl({ brain, desktop, ...opts, maxSteps: () => 3 }).run('paste my key');
|
|
114
|
+
assert.equal(r.error, 'steps');
|
|
115
|
+
assert.equal(r.steps, 3);
|
|
116
|
+
assert.equal(desktop.acts.length, 0);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('refuses without a vision brain or while busy, and stop() ends it', async () => {
|
|
120
|
+
assert.equal((await createControl({ brain: { vision: false }, desktop: fakeDesktop(), ...opts }).run('x')).error, 'no_vision');
|
|
121
|
+
let release;
|
|
122
|
+
const gate = new Promise((r) => (release = r));
|
|
123
|
+
const brain = { vision: true, kind: 'api', think: async () => (await gate, '{"action":"wait","seconds":1}') };
|
|
124
|
+
const c = createControl({ brain, desktop: fakeDesktop(), ...opts });
|
|
125
|
+
const first = c.run('wait');
|
|
126
|
+
await new Promise((r) => setImmediate(r));
|
|
127
|
+
assert.equal((await c.run('another')).error, 'busy');
|
|
128
|
+
assert.equal(c.stop(), true);
|
|
129
|
+
release();
|
|
130
|
+
assert.equal((await first).error, 'stopped');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('evKeys: Wayland (ydotool) key codes, pressed in order and released in reverse', () => {
|
|
134
|
+
assert.deepEqual(evKeys('ctrl+alt+t'), ['29:1', '56:1', '20:1', '20:0', '56:0', '29:0']);
|
|
135
|
+
assert.deepEqual(evKeys('Return'), ['28:1', '28:0']);
|
|
136
|
+
assert.equal(evKeys('ctrl+ñ'), null);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('Wayland treats the focused window as a terminal, so Enter always asks', () => {
|
|
140
|
+
assert.equal(risk({ type: 'key', keys: 'Return' }, 'unknown window (Wayland: treated as a terminal)'), 'enter');
|
|
141
|
+
});
|