glitchless-playtest 0.3.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.
- package/README.md +58 -3
- package/bin/glitchless-playtest.js +33 -1
- package/package.json +1 -1
- package/src/check-bot.js +465 -0
- package/src/check-page.js +252 -0
- package/src/check-report.js +327 -0
- package/src/check-site.js +158 -0
- package/src/check.js +532 -0
- package/src/index.js +6 -1
- package/src/run.js +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# glitchless-playtest
|
|
2
2
|
|
|
3
|
-
Playtest every change. Your game's autoplay bot plays it on a saved baseline and on the current code, and
|
|
3
|
+
Playtest every change, and check any web game. Your game's autoplay bot plays it on a saved baseline and on the current code, and
|
|
4
4
|
[Glitchless](https://github.com/glitchless-gg/glitchless) compares the two: slow frames, frame time, render and
|
|
5
5
|
update time, draw calls, hitches, errors and crashes. A regression exits with code 1, so it can gate a pull request.
|
|
6
6
|
It plays Unity, Godot, Unreal and GameMaker builds from their command line ([engine builds](#engine-builds)), Roblox
|
|
@@ -12,6 +12,12 @@ npx glitchless-playtest --save baseline # before changing the code
|
|
|
12
12
|
npx glitchless-playtest # after: compares with "baseline"
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
+
It also checks any web game someone posted, with nothing installed in it ([game checks](#game-checks)):
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npx glitchless-playtest --check https://someone.itch.io/their-game
|
|
19
|
+
```
|
|
20
|
+
|
|
15
21
|
## Engine builds
|
|
16
22
|
|
|
17
23
|
A Unity, Godot, Unreal or GameMaker build with the Glitchless SDK measures itself: started with
|
|
@@ -110,6 +116,44 @@ hide it, so they fail a run on their own: update CPU is the game's update code,
|
|
|
110
116
|
where the engine lets it (Phaser's scene updates and physics). The Phaser demo in the Glitchless repo,
|
|
111
117
|
`apps/phaser-demo`, has a working `glitchless.playtest.json`.
|
|
112
118
|
|
|
119
|
+
## Game checks
|
|
120
|
+
|
|
121
|
+
A game check shows a game's maker what Glitchless would do for their game, before they install anything. Glitchless's
|
|
122
|
+
bots play any web game, an itch.io page, a github.io, Vercel or Netlify page or any address, and make a report in
|
|
123
|
+
plain words, a dashboard made for that game and, on Glitchless Cloud, an unlisted link to it, with three sentences to
|
|
124
|
+
send its maker.
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
GLITCHLESS_URL=https://api.glitchless.gg GLITCHLESS_API_KEY=gl_ws_… npx glitchless-playtest --check https://someone.itch.io/their-game
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- **Nothing in the game.** The browser SDK is added to the page before it runs, its sessions marked as bots
|
|
131
|
+
(synthetic), so they never count as players. The engine is named where it can be (Three.js, Phaser, Babylon.js,
|
|
132
|
+
PlayCanvas, Unity, Godot, GameMaker, Construct, GDevelop, Defold, PixiJS and others, or plain canvas and WebGL), and
|
|
133
|
+
Three.js, Phaser, Babylon.js and PlayCanvas are handed to their Glitchless adapters, as installing it would.
|
|
134
|
+
- **Two ways of playing**, one after the other, in real Chrome: desktop on this computer's GPU (90 s by default,
|
|
135
|
+
`--seconds`, at most 240), then a throttled phone: the same computer with its CPU slowed 4×, a phone's touch screen
|
|
136
|
+
(sideways for a wide game) and a 4G-like connection, for two thirds as long. With loading, 3 to 6 minutes.
|
|
137
|
+
- **A player that needs no help.** It clicks Play, then tries the arrow keys, WASD, the mouse, click and drag and the
|
|
138
|
+
usual action keys (taps, holds and swipes on the phone), and spends its time on what changes the screen. With
|
|
139
|
+
`--ai` and an `ANTHROPIC_API_KEY`, a Claude model (Haiku) picks the inputs from screenshots instead
|
|
140
|
+
(`npm install @anthropic-ai/sdk`; at most 40 screenshots a profile). Each step is kept with the frames, memory,
|
|
141
|
+
errors and level of that moment, so the report can say when a freeze came.
|
|
142
|
+
- **Where it goes.** With a workspace key (`gl_ws_…`, from `npx glitchless-mcp login`) on Glitchless Cloud, it makes a
|
|
143
|
+
game named after the page (`--name` to choose; an existing game by that name is reused), its dashboard and a share
|
|
144
|
+
link that shows the check's bot runs, for 30 days. On the open-source server it saves the dashboard there, with no
|
|
145
|
+
link. The report, `message.txt` (the link and three sentences), `check.json` and screenshots go in
|
|
146
|
+
`.glitchless/checks/<game>-<time>/`. Check a game on a public site against a public server: Chrome keeps a public
|
|
147
|
+
page from sending to a server on your own computer or network, and the report says so when that happens.
|
|
148
|
+
- **It asks first.** It reads the site's robots.txt (as `GlitchlessCheck`) and stops where bots are asked to stay out,
|
|
149
|
+
stops on a 401, 403 or 429 or a page that checks for a human, never plays more than a few minutes from one computer,
|
|
150
|
+
closes popups and comes back from links that leave the game. A game that already sends to Glitchless has its own
|
|
151
|
+
sends held back during the check.
|
|
152
|
+
- **Private.** The check's game and board are in your workspace. Don't use it to rank games.
|
|
153
|
+
|
|
154
|
+
The numbers come from this computer, not from the game's players, and the report says so. Running checks for anyone
|
|
155
|
+
on the web would need a GPU machine in the cloud; this runs where you run it.
|
|
156
|
+
|
|
113
157
|
## Options
|
|
114
158
|
|
|
115
159
|
```
|
|
@@ -132,6 +176,16 @@ where the engine lets it (Phaser's scene updates and physics). The Phaser demo i
|
|
|
132
176
|
--channel NAME browser: chrome (default) or chromium
|
|
133
177
|
--headed show the browser windows
|
|
134
178
|
--json print the full result as JSON instead of markdown
|
|
179
|
+
|
|
180
|
+
Game check (any web game, with nothing installed in it):
|
|
181
|
+
--check URL play the game at URL on a desktop and a throttled phone, then make its
|
|
182
|
+
report, dashboard and (Glitchless Cloud) share link
|
|
183
|
+
--name NAME the game's name in Glitchless (default: its page's title)
|
|
184
|
+
--seconds N seconds of desktop play (default 90, at most 240; the phone plays 2/3 as long)
|
|
185
|
+
--profiles LIST desktop, phone or desktop,phone (default)
|
|
186
|
+
--ai a Claude model picks the inputs (ANTHROPIC_API_KEY, @anthropic-ai/sdk)
|
|
187
|
+
--out DIR where the report goes (default .glitchless/checks/<game>-<time>)
|
|
188
|
+
--no-share no share link
|
|
135
189
|
```
|
|
136
190
|
|
|
137
191
|
Saved runs go in `.glitchless/playtest/` (add it to `.gitignore`).
|
|
@@ -158,12 +212,13 @@ on a fast machine doesn't fail a build.
|
|
|
158
212
|
## From code or an agent
|
|
159
213
|
|
|
160
214
|
```js
|
|
161
|
-
import { playtest } from 'glitchless-playtest';
|
|
215
|
+
import { playtest, gameCheck } from 'glitchless-playtest';
|
|
162
216
|
const result = await playtest({ saveAs: 'baseline' }); // later: playtest({ compareTo: 'baseline' })
|
|
217
|
+
const check = await gameCheck({ url: 'https://someone.itch.io/their-game', server, apiKey }); // → { report, dm, share, files }
|
|
163
218
|
```
|
|
164
219
|
|
|
165
220
|
The [glitchless-mcp](https://www.npmjs.com/package/glitchless-mcp) server exposes the same thing to
|
|
166
|
-
coding agents as the `glitchless_playtest` tool
|
|
221
|
+
coding agents as the `glitchless_playtest` tool, and a game check as its `check_url`.
|
|
167
222
|
|
|
168
223
|
## License
|
|
169
224
|
|
|
@@ -7,12 +7,15 @@
|
|
|
7
7
|
// glitchless-playtest --baseline-url http://localhost:5174/ # CI: main build vs this branch's build
|
|
8
8
|
// glitchless-playtest --command "godot --path ." --save baseline # an engine build instead of a web game
|
|
9
9
|
// glitchless-playtest --engine roblox --studio "My Obby" --save baseline # a play test in Roblox Studio
|
|
10
|
+
// glitchless-playtest --check https://someone.itch.io/their-game # a game check: any web game, nothing installed
|
|
10
11
|
//
|
|
11
12
|
// A web game needs the game and a Glitchless server running, and Playwright installed in the game project.
|
|
12
13
|
// An engine build (Unity, Godot, Unreal, GameMaker) needs only the build, with the Glitchless SDK in it.
|
|
13
14
|
// A Roblox game needs its place open in Roblox Studio with Studio's MCP server on, and the Glitchless server it sends to.
|
|
15
|
+
// A game check needs Playwright and a Glitchless server; with a workspace key (gl_ws_…) on Glitchless Cloud it also makes
|
|
16
|
+
// the game and an unlisted share link.
|
|
14
17
|
|
|
15
|
-
import { playtest, compareSaved } from '../src/index.js';
|
|
18
|
+
import { playtest, compareSaved, gameCheck } from '../src/index.js';
|
|
16
19
|
|
|
17
20
|
const HELP = `Usage: glitchless-playtest [options]
|
|
18
21
|
|
|
@@ -36,6 +39,16 @@ const HELP = `Usage: glitchless-playtest [options]
|
|
|
36
39
|
--headed show the browser windows
|
|
37
40
|
--json print the full result as JSON instead of markdown
|
|
38
41
|
|
|
42
|
+
Game check (any web game, with nothing installed in it):
|
|
43
|
+
--check URL play the game at URL (an itch.io page, github.io, Vercel, Netlify…) on a
|
|
44
|
+
desktop and a throttled phone, then make its report, dashboard and share link
|
|
45
|
+
--name NAME the game's name in Glitchless (default: its page's title)
|
|
46
|
+
--seconds N seconds of desktop play (default 90, at most 240; the phone plays 2/3 as long)
|
|
47
|
+
--profiles LIST desktop, phone or desktop,phone (default)
|
|
48
|
+
--ai a Claude model picks the inputs from screenshots (ANTHROPIC_API_KEY, @anthropic-ai/sdk)
|
|
49
|
+
--out DIR where the report and screenshots go (default .glitchless/checks/<game>-<time>)
|
|
50
|
+
--no-share no share link
|
|
51
|
+
|
|
39
52
|
Scenarios, thresholds, URLs and the command can also be set in glitchless.playtest.json.
|
|
40
53
|
Exit code: 0 pass (or nothing to compare), 1 regression, 2 error.`;
|
|
41
54
|
|
|
@@ -57,6 +70,25 @@ const config = { game: val('game'), command: val('command'), engine: val('engine
|
|
|
57
70
|
try {
|
|
58
71
|
let result;
|
|
59
72
|
const only = argv.indexOf('--compare-only');
|
|
73
|
+
if (val('check')) {
|
|
74
|
+
const r = await gameCheck({
|
|
75
|
+
url: val('check'),
|
|
76
|
+
server: config.server,
|
|
77
|
+
apiKey: config.api_key,
|
|
78
|
+
name: val('name'),
|
|
79
|
+
seconds: val('seconds') ? Number(val('seconds')) : undefined,
|
|
80
|
+
profiles: val('profiles') ? val('profiles').split(',').map((s) => s.trim()) : undefined,
|
|
81
|
+
ai: has('ai'),
|
|
82
|
+
outDir: val('out'),
|
|
83
|
+
share: !has('no-share'),
|
|
84
|
+
channel: config.channel,
|
|
85
|
+
headed: config.headed,
|
|
86
|
+
log,
|
|
87
|
+
});
|
|
88
|
+
if (has('json')) console.log(JSON.stringify(r, null, 2));
|
|
89
|
+
else console.log(`${r.report}\n\n---\nTo send its maker:\n\n${r.dm}\n\nSaved in ${r.dir}`);
|
|
90
|
+
process.exit(0);
|
|
91
|
+
}
|
|
60
92
|
if (only >= 0) {
|
|
61
93
|
const [a, b] = argv.slice(only + 1, only + 3);
|
|
62
94
|
if (!a || !b) throw new Error('--compare-only needs two saved run names, e.g. --compare-only baseline latest');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glitchless-playtest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Playtest bots for game observability: your game's autoplay bot plays a Unity, Godot, Unreal or GameMaker build, a Roblox game in Roblox Studio, or a web game (Three.js, Phaser, Babylon.js, PlayCanvas) in Chrome, on the current code and on a saved baseline, and Glitchless flags what got slower or started breaking.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"playtesting",
|
package/src/check-bot.js
ADDED
|
@@ -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
|
+
}
|