glitchless-playtest 0.2.0 → 0.4.0

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.
@@ -0,0 +1,465 @@
1
+ // The players of a game check: bots that play a web game with no help from it. The explorer clicks to start, tries
2
+ // the common controls in turn (arrow keys, WASD, Space and the usual action keys, the mouse, click and drag; taps,
3
+ // swipes and holds on a phone) and spends more of its time on whatever makes the screen change. With an Anthropic
4
+ // API key and `ai`, a Claude model looks at the screen every few seconds and picks the inputs instead. Either way,
5
+ // each step goes in a timeline, with the frames, memory and errors of that moment, so a report can say "after two
6
+ // minutes, frames took 80 ms".
7
+ //
8
+ // How much the screen changed is read from small PNG screenshots, compared pixel by pixel (decoded here with zlib).
9
+
10
+ import zlib from 'node:zlib';
11
+ import { createRequire } from 'node:module';
12
+ import path from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ // The two ways a check plays: desktop Chrome on this computer's own GPU, and a throttled phone: the same computer
16
+ // with its CPU slowed 4×, a phone's touch screen and a 4G-like connection. A phone is held the way the game wants:
17
+ // sideways for a game wider than it is tall.
18
+ export const PROFILES = {
19
+ desktop: { name: 'desktop', viewport: { width: 1280, height: 720 }, cpu: 1, network: null, touch: false },
20
+ phone: { name: 'phone', viewport: { width: 390, height: 844 }, deviceScaleFactor: 3, isMobile: true, touch: true, cpu: 4, network: { latency: 60, downloadThroughput: Math.round(9e6 / 8), uploadThroughput: Math.round(1.5e6 / 8) } },
21
+ };
22
+
23
+ export function profileWords(p) {
24
+ if (p.name === 'phone') return `a throttled phone: this computer with its CPU slowed ${p.cpu}×, a ${p.viewport.width}×${p.viewport.height} touch screen and a 4G-like connection (9 Mbps, 60 ms)`;
25
+ return `desktop Chrome on this computer's own GPU, at ${p.viewport.width}×${p.viewport.height}`;
26
+ }
27
+
28
+ // The inputs the explorer tries, and the words a report uses for each.
29
+ const DESKTOP_INPUTS = [
30
+ { name: 'arrows', words: 'the arrow keys and Space', run: (io) => io.keys([['ArrowRight', 900], ['Space', 0], ['ArrowUp', 300], ['ArrowLeft', 700], ['Space', 0], ['ArrowDown', 300], ['ArrowRight', 600]]) },
31
+ { name: 'wasd', words: 'W, A, S, D and Space', run: (io) => io.keys([['d', 900], ['Space', 0], ['w', 300], ['a', 700], ['Space', 0], ['s', 300], ['d', 600]]) },
32
+ { name: 'mouse', words: 'moving the mouse and clicking', run: (io) => io.mouse(6) },
33
+ { name: 'drag', words: 'clicking and dragging', run: (io) => io.drags(3) },
34
+ { name: 'actions', words: 'Z, X, C, J, K, E, F, Tab, Shift and Enter', run: (io) => io.keys([['z', 0], ['x', 0], ['c', 0], ['j', 0], ['k', 0], ['e', 0], ['f', 0], ['Tab', 0], ['Shift', 300], ['Enter', 0]]) },
35
+ ];
36
+ const PHONE_INPUTS = [
37
+ { name: 'taps', words: 'tapping around the screen', run: (io) => io.taps(8) },
38
+ { name: 'holds', words: 'holding the left and right of the screen', run: (io) => io.holds() },
39
+ { name: 'swipes', words: 'swiping left, right, up and down', run: (io) => io.swipes() },
40
+ { name: 'drag', words: 'touching and dragging', run: (io) => io.drags(3) },
41
+ ];
42
+
43
+ // Below this share of pixels changed, a step's screen counts as still (0.1%: a blinking cursor, a clock).
44
+ const STILL = 0.001;
45
+
46
+ // Words on buttons that start a game or carry on after it ends, in the order they're tried.
47
+ const START = /^(play|play now|start|start game|new game|begin|go|let'?s go|continue|tap to (play|start)|click to (play|start)|press (any key|start)|ok|okay|got it|i understand|accept|enter|resume|retry|try again|play again|restart|next)!?$/i;
48
+
49
+ // A small random generator, so a check of the same game tries the same points.
50
+ function random(seed) {
51
+ let a = seed >>> 0;
52
+ return () => {
53
+ a = (a + 0x6d2b79f5) >>> 0;
54
+ let t = a;
55
+ t = Math.imul(t ^ (t >>> 15), t | 1);
56
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
57
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
58
+ };
59
+ }
60
+
61
+ // ───────────────────────────── screen changes ─────────────────────────────
62
+
63
+ // A PNG (8-bit gray, RGB, gray with alpha or RGBA, not interlaced: what Chrome's screenshots are) → { width, height,
64
+ // gray: Uint8Array }, or null for anything else.
65
+ export function decodePng(buf) {
66
+ if (!Buffer.isBuffer(buf) || buf.readUInt32BE(0) !== 0x89504e47) return null;
67
+ let off = 8;
68
+ let width = 0;
69
+ let height = 0;
70
+ let depth = 0;
71
+ let type = 0;
72
+ let interlace = 0;
73
+ const idat = [];
74
+ while (off + 8 <= buf.length) {
75
+ const len = buf.readUInt32BE(off);
76
+ const kind = buf.toString('ascii', off + 4, off + 8);
77
+ const data = buf.subarray(off + 8, off + 8 + len);
78
+ if (kind === 'IHDR') [width, height, depth, type, interlace] = [data.readUInt32BE(0), data.readUInt32BE(4), data[8], data[9], data[12]];
79
+ else if (kind === 'IDAT') idat.push(data);
80
+ else if (kind === 'IEND') break;
81
+ off += 12 + len;
82
+ }
83
+ const channels = { 0: 1, 2: 3, 4: 2, 6: 4 }[type];
84
+ if (!width || !height || depth !== 8 || !channels || interlace) return null;
85
+ const raw = zlib.inflateSync(Buffer.concat(idat));
86
+ const stride = width * channels;
87
+ const out = Buffer.alloc(stride * height);
88
+ for (let y = 0; y < height; y++) {
89
+ const filter = raw[y * (stride + 1)];
90
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
91
+ for (let x = 0; x < stride; x++) {
92
+ const a = x >= channels ? out[y * stride + x - channels] : 0;
93
+ const b = y ? out[(y - 1) * stride + x] : 0;
94
+ const c = x >= channels && y ? out[(y - 1) * stride + x - channels] : 0;
95
+ let v = line[x];
96
+ if (filter === 1) v += a;
97
+ else if (filter === 2) v += b;
98
+ else if (filter === 3) v += (a + b) >> 1;
99
+ else if (filter === 4) {
100
+ const p = a + b - c;
101
+ const [pa, pb, pc] = [Math.abs(p - a), Math.abs(p - b), Math.abs(p - c)];
102
+ v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
103
+ }
104
+ out[y * stride + x] = v & 255;
105
+ }
106
+ }
107
+ const gray = new Uint8Array(width * height);
108
+ for (let i = 0; i < width * height; i++) {
109
+ const p = i * channels;
110
+ gray[i] = channels >= 3 ? (out[p] * 3 + out[p + 1] * 6 + out[p + 2]) / 10 : out[p];
111
+ }
112
+ return { width, height, gray };
113
+ }
114
+
115
+ // How different two small screenshots are: the share of their pixels that clearly changed (by more than 12 of 255
116
+ // levels of gray), 0 (the same) to 1. A share, not a mean, so one small character walking across a still background
117
+ // counts as much as it looks.
118
+ export function screenChange(a, b) {
119
+ if (!a || !b || a.width !== b.width || a.height !== b.height) return null;
120
+ let changed = 0;
121
+ for (let i = 0; i < a.gray.length; i++) if (Math.abs(a.gray[i] - b.gray[i]) > 12) changed++;
122
+ return Math.round((changed / a.gray.length) * 10000) / 10000;
123
+ }
124
+
125
+ // ───────────────────────────── playing ─────────────────────────────
126
+
127
+ // Plays the page for `seconds`, already loaded, as `profile`. → { steps, inputs, labels, shots, notes }.
128
+ // area() → the game's rectangle in the page (its canvas, or the whole viewport)
129
+ // shot(name) → saves a JPEG of the screen for the report, → its path
130
+ export async function explore(page, { profile, seconds, cdp, area, shot, ai = null, seed = 7, log = () => {} }) {
131
+ const rand = random(seed);
132
+ const touch = !!profile.touch;
133
+ const inputs = touch ? PHONE_INPUTS : DESKTOP_INPUTS;
134
+ const t0 = Date.now();
135
+ const elapsed = () => Math.round((Date.now() - t0) / 100) / 10;
136
+ const steps = [];
137
+ const notes = [];
138
+ const shots = [];
139
+ const tried = new Map(inputs.map((i) => [i.name, { tries: 0, moved: 0, change: 0 }]));
140
+
141
+ const small = async () => {
142
+ const r = await area();
143
+ if (!r || r.width < 4 || r.height < 4) return null;
144
+ const scale = Math.min(1, 192 / (r.width * (profile.deviceScaleFactor || 1)));
145
+ const { data } = await cdp.send('Page.captureScreenshot', { format: 'png', clip: { x: r.x, y: r.y, width: r.width, height: r.height, scale }, captureBeyondViewport: false }).catch(() => ({}));
146
+ return data ? decodePng(Buffer.from(data, 'base64')) : null;
147
+ };
148
+ const point = async (fx, fy) => {
149
+ const r = await area();
150
+ return { x: r.x + r.width * Math.min(0.97, Math.max(0.03, fx)), y: r.y + r.height * Math.min(0.97, Math.max(0.03, fy)) };
151
+ };
152
+ const tapAt = async (p) => (touch ? page.touchscreen.tap(p.x, p.y) : page.mouse.click(p.x, p.y));
153
+ // A touch drag, as CDP touch events (Playwright's touchscreen only taps).
154
+ const touchDrag = async (a, b, ms) => {
155
+ const n = 8;
156
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: a.x, y: a.y }] });
157
+ for (let i = 1; i <= n; i++) {
158
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }] });
159
+ await page.waitForTimeout(ms / n);
160
+ }
161
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
162
+ };
163
+ const io = {
164
+ keys: async (seq) => {
165
+ for (const [key, ms] of seq) {
166
+ if (ms) {
167
+ await page.keyboard.down(key);
168
+ await page.waitForTimeout(ms);
169
+ await page.keyboard.up(key);
170
+ } else await page.keyboard.press(key);
171
+ await page.waitForTimeout(120);
172
+ }
173
+ },
174
+ mouse: async (n) => {
175
+ for (let i = 0; i < n; i++) {
176
+ const p = await point(rand(), rand());
177
+ await page.mouse.move(p.x, p.y, { steps: 6 });
178
+ await page.mouse.click(p.x, p.y);
179
+ await page.waitForTimeout(250);
180
+ }
181
+ },
182
+ drags: async (n) => {
183
+ for (let i = 0; i < n; i++) {
184
+ const a = await point(0.3 + rand() * 0.4, 0.4 + rand() * 0.3);
185
+ const b = await point(rand(), rand());
186
+ if (touch) await touchDrag(a, b, 500);
187
+ else {
188
+ await page.mouse.move(a.x, a.y);
189
+ await page.mouse.down();
190
+ await page.mouse.move(b.x, b.y, { steps: 12 });
191
+ await page.mouse.up();
192
+ }
193
+ await page.waitForTimeout(200);
194
+ }
195
+ },
196
+ taps: async (n) => {
197
+ for (let i = 0; i < n; i++) {
198
+ await tapAt(await point(rand(), rand()));
199
+ await page.waitForTimeout(200);
200
+ }
201
+ },
202
+ holds: async () => {
203
+ for (const fx of [0.15, 0.85, 0.15, 0.85]) {
204
+ const p = await point(fx, 0.7);
205
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: p.x, y: p.y }] });
206
+ await page.waitForTimeout(600);
207
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
208
+ await page.waitForTimeout(100);
209
+ }
210
+ },
211
+ swipes: async () => {
212
+ for (const [a, b] of [[[0.5, 0.5], [0.1, 0.5]], [[0.5, 0.5], [0.9, 0.5]], [[0.5, 0.6], [0.5, 0.2]], [[0.5, 0.4], [0.5, 0.8]]]) {
213
+ await touchDrag(await point(...a), await point(...b), 250);
214
+ await page.waitForTimeout(150);
215
+ }
216
+ },
217
+ };
218
+
219
+ // Start the game, or carry on after it stops: a button that says Play (or Retry…), a click on the game, Enter, Space.
220
+ const start = async (why) => {
221
+ const button = await page
222
+ .evaluate((source) => {
223
+ const re = new RegExp(source, 'i');
224
+ const shown = (el) => {
225
+ const r = el.getBoundingClientRect();
226
+ return r.width > 4 && r.height > 4 && r.top < innerHeight && r.left < innerWidth && r.bottom > 0 && getComputedStyle(el).visibility !== 'hidden';
227
+ };
228
+ for (const el of document.querySelectorAll('button, [role=button], input[type=button], input[type=submit], a, div, span')) {
229
+ const t = (el.innerText || el.value || '').trim().replace(/\s+/g, ' ');
230
+ if (!t || t.length > 24 || !re.test(t) || !shown(el)) continue;
231
+ if (el.tagName === 'A' && el.href && new URL(el.href, location.href).origin !== location.origin) continue; // never off the game's site
232
+ if (el.children.length > 2) continue; // a container that merely holds the word
233
+ const r = el.getBoundingClientRect();
234
+ return { text: t, x: r.left + r.width / 2, y: r.top + r.height / 2 };
235
+ }
236
+ return null;
237
+ }, START.source)
238
+ .catch(() => null);
239
+ const did = [];
240
+ if (button) {
241
+ await tapAt(button);
242
+ did.push(`pressed "${button.text}"`);
243
+ await page.waitForTimeout(600);
244
+ }
245
+ await tapAt(await point(0.5, 0.5));
246
+ did.push(touch ? 'tapped the game' : 'clicked the game');
247
+ if (!touch) {
248
+ await page.keyboard.press('Enter');
249
+ await page.waitForTimeout(300);
250
+ await page.keyboard.press('Space');
251
+ did.push('pressed Enter and Space');
252
+ }
253
+ await page.waitForTimeout(800);
254
+ log(` ${why}: ${did.join(', ')}`);
255
+ return did.join(', ');
256
+ };
257
+
258
+ // How much the screen changes by itself (an animated title screen changes a little): the bar for "an input did something".
259
+ const idle = async () => {
260
+ const a = await small();
261
+ await page.waitForTimeout(700);
262
+ return screenChange(a, await small()) ?? 0;
263
+ };
264
+
265
+ // One step: an input (or the AI's choice), with the screen watched while it runs, then the frames and memory.
266
+ const step = async (input, run, extra = {}) => {
267
+ const before = await small();
268
+ const t = elapsed();
269
+ await run();
270
+ const after = await small();
271
+ const change = screenChange(before, after);
272
+ const stats = await page.evaluate(() => ({ frames: window.__GLITCHLESS_CHECK__?.take(), page: window.__GLITCHLESS_CHECK__?.read() })).catch(() => ({}));
273
+ const label = extra.label || stats.page?.screen_labels?.[0] || null;
274
+ const s = { t, input: input.name, words: input.words, change, frames: stats.frames || null, heap_mb: stats.page?.heap_mb ?? null, level: stats.page?.level ?? null, ...extra, label };
275
+ steps.push(s);
276
+ const screen = change == null ? 'unknown' : change < STILL ? 'still' : change < 0.4 ? 'moving' : 'new screen';
277
+ await page.evaluate((a) => window.__GLITCHLESS_CHECK__?.step(a), { profile: profile.name, step: steps.length, input: input.words.slice(0, 48), screen, ...(label ? { label: String(label).slice(0, 40) } : {}) }).catch(() => {});
278
+ return s;
279
+ };
280
+
281
+ // A step with no input at all, the same length as an input's: what the screen does by itself (an animated title,
282
+ // enemies moving). An input "did something" when the screen changed clearly more than that.
283
+ const rest = { name: 'idle', words: 'nothing (the bot waited)', run: () => page.waitForTimeout(3000) };
284
+ let base = await idle();
285
+ shots.push(await shot('loaded'));
286
+ const started = await start('starting');
287
+ notes.push(`To start, the bot ${started}.`);
288
+ let calm = (await step(rest, rest.run)).change ?? 0;
289
+ let still = 0;
290
+ let next = 0;
291
+ const end = t0 + seconds * 1000;
292
+ let shotMid = false;
293
+
294
+ while (Date.now() < end) {
295
+ if (!shotMid && Date.now() > t0 + seconds * 500) {
296
+ shots.push(await shot('playing'));
297
+ shotMid = true;
298
+ }
299
+ let s;
300
+ if (ai) {
301
+ const choice = await ai.choose(page, { area: await area(), touch, recent: steps.slice(-3) }).catch((err) => {
302
+ notes.push(`The AI player stopped (${err.message.split('\n')[0]}); the explorer carried on.`);
303
+ return null;
304
+ });
305
+ if (!choice) {
306
+ ai = null; // out of calls, or it failed: the explorer plays the rest
307
+ continue;
308
+ }
309
+ s = await step({ name: 'ai', words: choice.words }, () => ai.act(page, choice, { point, touch, touchDrag }), { screen: choice.screen, kind: choice.kind, label: choice.label || null });
310
+ } else {
311
+ // First every input once, then mostly the ones that moved the screen most, and now and then the others again.
312
+ const ranked = [...tried.entries()].sort((a, b) => b[1].change / Math.max(1, b[1].tries) - a[1].change / Math.max(1, a[1].tries));
313
+ const untried = inputs.find((i) => !tried.get(i.name).tries);
314
+ const pick = untried || (next++ % 4 === 3 ? inputs[Math.floor(rand() * inputs.length)] : inputs.find((i) => i.name === ranked[next % 2]?.[0]) || inputs[0]);
315
+ s = await step(pick, () => pick.run(io));
316
+ const st = tried.get(pick.name);
317
+ st.tries++;
318
+ st.change += s.change ?? 0;
319
+ if ((s.change ?? 0) > calm * 1.3 + 0.002) st.moved++;
320
+ }
321
+ // The screen stopped changing: a game over, a menu, or a stall. Try to carry on, and say so.
322
+ if ((s.change ?? 1) < STILL) still++;
323
+ else still = 0;
324
+ if (still >= 2) {
325
+ s.carried_on = await start('the screen stopped changing');
326
+ still = 0;
327
+ calm = (await step(rest, rest.run)).change ?? calm;
328
+ }
329
+ }
330
+ shots.push(await shot('end'));
331
+ // The inputs that moved the screen more than waiting did, most first.
332
+ const worked = [...tried.entries()].filter(([, st]) => st.moved).sort((a, b) => b[1].change / b[1].tries - a[1].change / a[1].tries).map(([name]) => inputs.find((i) => i.name === name).words);
333
+ return { steps, notes, shots: shots.filter(Boolean), inputs: { tried: [...tried.entries()].filter(([, st]) => st.tries).map(([name]) => inputs.find((i) => i.name === name).words), worked }, idle_change: base, calm_change: calm, elapsed_s: elapsed() };
334
+ }
335
+
336
+ // ───────────────────────────── the AI player ─────────────────────────────
337
+
338
+ export const AI_MODEL = 'claude-haiku-5-5';
339
+
340
+ const AI_SCHEMA = {
341
+ type: 'object',
342
+ additionalProperties: false,
343
+ required: ['screen', 'kind', 'label', 'actions'],
344
+ properties: {
345
+ screen: { type: 'string', description: 'What is on screen now, in under 15 words' },
346
+ kind: { type: 'string', enum: ['loading', 'title', 'menu', 'playing', 'paused', 'game_over', 'other'] },
347
+ label: { type: 'string', description: 'The level, wave, stage or mode the screen shows (e.g. "Wave 3"), or ""' },
348
+ actions: {
349
+ type: 'array',
350
+ items: {
351
+ type: 'object',
352
+ additionalProperties: false,
353
+ required: ['do', 'key', 'ms', 'x', 'y', 'x2', 'y2'],
354
+ properties: {
355
+ do: { type: 'string', enum: ['press', 'hold', 'click', 'drag', 'wait'] },
356
+ key: { type: 'string', description: 'For press and hold: ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Space, Enter, Escape, Shift or one letter or digit; else ""' },
357
+ ms: { type: 'integer', description: 'How long to hold or wait, 0 to 2000' },
358
+ x: { type: 'number', description: 'Where to click or start a drag, 0 (left) to 1 (right) across the game' },
359
+ y: { type: 'number', description: '0 (top) to 1 (bottom)' },
360
+ x2: { type: 'number', description: 'Where a drag ends; else 0' },
361
+ y2: { type: 'number' },
362
+ },
363
+ },
364
+ },
365
+ },
366
+ };
367
+
368
+ const KEYS = /^(Arrow(Up|Down|Left|Right)|Space|Enter|Escape|Shift|[a-z0-9])$/;
369
+
370
+ // Resolve the Anthropic SDK from the project first, then from here, as Playwright is (an optional peer dependency).
371
+ async function loadAnthropic(cwd = process.cwd()) {
372
+ const unwrap = (mod) => mod?.default ?? mod;
373
+ for (const from of [path.join(cwd, 'noop.js'), import.meta.url]) {
374
+ try {
375
+ const req = createRequire(from);
376
+ return unwrap(await import(pathToFileURL(req.resolve('@anthropic-ai/sdk')).href));
377
+ } catch {}
378
+ }
379
+ throw new Error('The AI player needs the Anthropic SDK: npm install @anthropic-ai/sdk (and ANTHROPIC_API_KEY set)');
380
+ }
381
+
382
+ // An AI player: a Claude model (Haiku by default, for cost) that sees the game every few seconds and picks the inputs.
383
+ // The key comes from the environment (ANTHROPIC_API_KEY, or an `ant auth login` profile) and is never printed.
384
+ export async function aiPlayer({ model = AI_MODEL, maxCalls = 40, cwd, client = null } = {}) {
385
+ client ||= new (await loadAnthropic(cwd))();
386
+ let calls = 0;
387
+ return {
388
+ model,
389
+ get calls() {
390
+ return calls;
391
+ },
392
+ async choose(page, { area, touch, recent }) {
393
+ if (calls >= maxCalls) return null;
394
+ calls++;
395
+ const scale = Math.min(1, 768 / area.width);
396
+ const jpeg = await page.screenshot({ type: 'jpeg', quality: 60, clip: area, scale: 'css' });
397
+ const context = recent.map((s) => `t=${s.t}s ${s.screen ? `screen: ${s.screen}` : ''} did: ${s.words}${s.change != null ? ` (screen change ${s.change})` : ''}`).join('\n');
398
+ const res = await client.messages.create({
399
+ model,
400
+ max_tokens: 1024,
401
+ thinking: { type: 'disabled' },
402
+ output_config: { effort: 'low', format: { type: 'json_schema', schema: AI_SCHEMA } },
403
+ system:
404
+ 'You are playtesting a web game for its developer, to see how it runs. Play it like a new player would: get past menus and title screens, then keep playing and moving, and try what the game offers. ' +
405
+ `The game is played with ${touch ? 'a touch screen (use click for a tap and drag for a swipe; no keys)' : 'a keyboard and mouse'}. ` +
406
+ 'Never buy anything, sign in, type personal details, open links or leave the game. Answer with what is on screen and up to 6 inputs for the next 3 seconds.',
407
+ messages: [
408
+ {
409
+ role: 'user',
410
+ content: [
411
+ { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: jpeg.toString('base64') } },
412
+ { type: 'text', text: `The game's screen now (${Math.round(area.width * scale)} px wide).${context ? `\nThe last steps:\n${context}` : ''}` },
413
+ ],
414
+ },
415
+ ],
416
+ });
417
+ if (res.stop_reason === 'refusal') throw new Error('the model declined to play this game');
418
+ const text = res.content.find((b) => b.type === 'text')?.text;
419
+ const out = JSON.parse(text);
420
+ const actions = (out.actions || []).slice(0, 6).filter((a) => a.do !== 'press' && a.do !== 'hold' ? true : KEYS.test(normalKey(a.key)) && !touch);
421
+ return { screen: String(out.screen || '').slice(0, 120), kind: out.kind, label: String(out.label || '').slice(0, 40), actions, words: describe(actions) };
422
+ },
423
+ async act(page, choice, { point, touch, touchDrag }) {
424
+ for (const a of choice.actions) {
425
+ const ms = Math.max(0, Math.min(2000, a.ms | 0));
426
+ if (a.do === 'press') await page.keyboard.press(normalKey(a.key));
427
+ else if (a.do === 'hold') {
428
+ await page.keyboard.down(normalKey(a.key));
429
+ await page.waitForTimeout(ms || 400);
430
+ await page.keyboard.up(normalKey(a.key));
431
+ } else if (a.do === 'click') {
432
+ const p = await point(a.x, a.y);
433
+ if (touch) await page.touchscreen.tap(p.x, p.y);
434
+ else await page.mouse.click(p.x, p.y);
435
+ } else if (a.do === 'drag') {
436
+ const [p, q] = [await point(a.x, a.y), await point(a.x2, a.y2)];
437
+ if (touch) await touchDrag(p, q, 400);
438
+ else {
439
+ await page.mouse.move(p.x, p.y);
440
+ await page.mouse.down();
441
+ await page.mouse.move(q.x, q.y, { steps: 10 });
442
+ await page.mouse.up();
443
+ }
444
+ } else await page.waitForTimeout(Math.min(ms, 1500));
445
+ await page.waitForTimeout(120);
446
+ }
447
+ },
448
+ };
449
+ }
450
+
451
+ function normalKey(k) {
452
+ const s = String(k || '').trim();
453
+ if (/^space$/i.test(s) || s === ' ') return 'Space';
454
+ if (/^(enter|return)$/i.test(s)) return 'Enter';
455
+ if (/^(esc|escape)$/i.test(s)) return 'Escape';
456
+ if (/^shift$/i.test(s)) return 'Shift';
457
+ if (/^(left|right|up|down)$/i.test(s)) return `Arrow${s[0].toUpperCase()}${s.slice(1).toLowerCase()}`;
458
+ if (/^arrow(up|down|left|right)$/i.test(s)) return `Arrow${s.slice(5, 6).toUpperCase()}${s.slice(6).toLowerCase()}`;
459
+ return s.length === 1 ? s.toLowerCase() : s;
460
+ }
461
+
462
+ function describe(actions) {
463
+ const words = actions.map((a) => (a.do === 'press' ? `pressed ${normalKey(a.key)}` : a.do === 'hold' ? `held ${normalKey(a.key)}` : a.do === 'click' ? 'clicked' : a.do === 'drag' ? 'dragged' : 'waited'));
464
+ return [...new Set(words)].join(', ') || 'waited';
465
+ }