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/src/check.js
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
// A game check: Glitchless's bots play any web game someone posted, with nothing installed in it, and make a report
|
|
2
|
+
// and a dashboard for it, so its maker can see what Glitchless would do for their game. Used by
|
|
3
|
+
// `glitchless-playtest --check URL` and the glitchless_playtest MCP tool's `check_url`.
|
|
4
|
+
//
|
|
5
|
+
// 1. Find the game behind the address (an itch.io page's frame: check-site.js) and ask the site's robots.txt.
|
|
6
|
+
// 2. Make a game for it in Glitchless (with a workspace key on Glitchless Cloud; an open server takes any name).
|
|
7
|
+
// 3. Play it in real Chrome twice: desktop on this computer's GPU, then a throttled phone (check-bot.js), with the
|
|
8
|
+
// browser SDK added to the page before it runs (check-page.js), its sessions synthetic.
|
|
9
|
+
// 4. Read back what Glitchless made of it (the playtest summary and findings), design the game's dashboard, put a
|
|
10
|
+
// picture of the game on it, and on Glitchless Cloud make an unlisted share link to it.
|
|
11
|
+
// 5. Write the report and the three sentences to send its maker (check-report.js).
|
|
12
|
+
//
|
|
13
|
+
// A check is private: its game, board and link are in the checker's own workspace, and nothing ranks games. It plays
|
|
14
|
+
// for a few minutes from one computer, and stops where the site asks bots to stay out or checks for a human.
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import os from 'node:os';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { createRequire } from 'node:module';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { loadPlaywright, CHROME_ARGS } from './run.js';
|
|
22
|
+
import { checkInitScript } from './check-page.js';
|
|
23
|
+
import { resolveGame, robotsCheck, refusal, CHECK_UA_SUFFIX } from './check-site.js';
|
|
24
|
+
import { PROFILES, explore, aiPlayer, profileWords, AI_MODEL } from './check-bot.js';
|
|
25
|
+
import { checkReport, checkDm, checkDashboard, CHECK_PAGE } from './check-report.js';
|
|
26
|
+
|
|
27
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
28
|
+
// Seconds of play per profile by default; the phone plays two thirds as long. A check never plays past MAX_PLAY_S.
|
|
29
|
+
export const CHECK_SECONDS = 90;
|
|
30
|
+
const MAX_PLAY_S = 240;
|
|
31
|
+
const LOAD_CAP_S = { desktop: 60, phone: 120 };
|
|
32
|
+
|
|
33
|
+
export function slugify(s) {
|
|
34
|
+
return (
|
|
35
|
+
String(s || '')
|
|
36
|
+
.normalize('NFKD')
|
|
37
|
+
.replace(/[̀-ͯ]/g, '')
|
|
38
|
+
.toLowerCase()
|
|
39
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
40
|
+
.replace(/^-+|-+$/g, '')
|
|
41
|
+
.slice(0, 48) || 'game'
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {object} o
|
|
47
|
+
* @param {string} o.url the game's address: an itch.io page, a github.io, Vercel or Netlify page, any web game
|
|
48
|
+
* @param {string} [o.server] Glitchless server (default $GLITCHLESS_URL or http://localhost:7777)
|
|
49
|
+
* @param {string} [o.apiKey] a workspace key (gl_ws_…) on Glitchless Cloud: makes the game and the share link
|
|
50
|
+
* @param {string} [o.name] the game's name in Glitchless (default: its page's title)
|
|
51
|
+
* @param {number} [o.seconds] seconds of desktop play (default 90; the phone plays two thirds as long)
|
|
52
|
+
* @param {string[]} [o.profiles] 'desktop', 'phone' or both (default both)
|
|
53
|
+
* @param {boolean} [o.ai] let a Claude model pick the inputs (needs ANTHROPIC_API_KEY and @anthropic-ai/sdk)
|
|
54
|
+
* @param {string} [o.outDir] where the report and screenshots go (default .glitchless/checks/<game>-<time>)
|
|
55
|
+
*/
|
|
56
|
+
export async function gameCheck({ url, server = process.env.GLITCHLESS_URL || 'http://localhost:7777', apiKey = process.env.GLITCHLESS_API_KEY || '', name, seconds = CHECK_SECONDS, profiles = ['desktop', 'phone'], ai = false, aiModel, headed = false, channel = 'chrome', adapters = true, outDir, cwd = process.cwd(), share = true, log = () => {} } = {}) {
|
|
57
|
+
if (!url) throw new Error('A game check needs the game\'s address (url).');
|
|
58
|
+
const base = String(server).replace(/\/$/, '');
|
|
59
|
+
const want = profiles.filter((p) => PROFILES[p]);
|
|
60
|
+
if (!want.length) throw new Error(`profiles are ${Object.keys(PROFILES).join(' and ')}`);
|
|
61
|
+
const desktopS = Math.max(15, Math.min(MAX_PLAY_S, Number(seconds) || CHECK_SECONDS));
|
|
62
|
+
const playS = { desktop: desktopS, phone: Math.max(15, Math.round((desktopS * 2) / 3)) };
|
|
63
|
+
const notes = [];
|
|
64
|
+
|
|
65
|
+
const { chromium } = await loadPlaywright(cwd);
|
|
66
|
+
const launch = (ch) => chromium.launch({ headless: !headed, channel: ch, args: [...CHROME_ARGS, '--mute-audio', '--autoplay-policy=no-user-gesture-required'] });
|
|
67
|
+
const browser = await launch(channel === 'chromium' ? undefined : channel).catch((err) => {
|
|
68
|
+
if (channel === 'chromium') throw err;
|
|
69
|
+
log(`Could not launch ${channel} (${err.message.split('\n')[0]}); using Playwright's Chromium.`);
|
|
70
|
+
return launch(undefined);
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
// The browser's own User-Agent, with the check named at its end, so a site can tell this visit apart.
|
|
74
|
+
const probe = await browser.newPage();
|
|
75
|
+
const chromeUa = (await probe.evaluate(() => navigator.userAgent)).replace('HeadlessChrome', 'Chrome');
|
|
76
|
+
await probe.close();
|
|
77
|
+
const major = chromeUa.match(/Chrome\/(\d+)/)?.[1] || '140';
|
|
78
|
+
const ua = { desktop: `${chromeUa} ${CHECK_UA_SUFFIX}`, phone: `Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Mobile Safari/537.36 ${CHECK_UA_SUFFIX}` };
|
|
79
|
+
|
|
80
|
+
const robots = new Map();
|
|
81
|
+
const target = await resolveGame(url, { ua: ua.desktop, log, robots });
|
|
82
|
+
if (!target.title) target.title = await pageTitle(target.play_url, ua.desktop);
|
|
83
|
+
const gameName = String(name || target.title || new URL(target.page_url).hostname).trim().slice(0, 80);
|
|
84
|
+
log(`Game check: ${gameName} (${target.play_url})`);
|
|
85
|
+
|
|
86
|
+
const dest = await checkDestination({ base, apiKey, name: gameName, log });
|
|
87
|
+
const sdk = await sdkScript(base, cwd);
|
|
88
|
+
const version = `check-${new Date().toISOString().slice(0, 10)}`;
|
|
89
|
+
const dir = outDir ? path.resolve(cwd, outDir) : path.join(cwd, '.glitchless', 'checks', `${slugify(gameName)}-${new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '')}`);
|
|
90
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
91
|
+
const player = ai ? await aiPlayer({ model: aiModel || AI_MODEL, cwd }) : null;
|
|
92
|
+
|
|
93
|
+
const started = Date.now();
|
|
94
|
+
const runs = [];
|
|
95
|
+
let landscape = target.size ? target.size.width > target.size.height * 1.1 : null;
|
|
96
|
+
for (const p of want) {
|
|
97
|
+
const profile = { ...PROFILES[p] };
|
|
98
|
+
if (p === 'desktop' && target.size) profile.viewport = { width: target.size.width, height: target.size.height };
|
|
99
|
+
if (p === 'phone' && landscape) profile.viewport = { width: profile.viewport.height, height: profile.viewport.width };
|
|
100
|
+
log(`${p}: ${profileWords(profile)}`);
|
|
101
|
+
const run = await playProfile(browser, { profile, target, dest, sdk, version, seconds: playS[p], ua: ua[p], dir, adapters, ai: player, robots, log });
|
|
102
|
+
runs.push(run);
|
|
103
|
+
if (run.stopped) {
|
|
104
|
+
notes.push(run.stopped);
|
|
105
|
+
if (run.refused) break; // the site doesn't want bots: no second visit
|
|
106
|
+
}
|
|
107
|
+
if (landscape == null && run.page?.canvas) landscape = run.page.canvas.width > run.page.canvas.height * 1.1;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const ids = runs.map((r) => r.session_id).filter(Boolean);
|
|
111
|
+
const read = readerFor(base, apiKey, dest);
|
|
112
|
+
let summary = null;
|
|
113
|
+
let findings = [];
|
|
114
|
+
if (ids.length) {
|
|
115
|
+
log(`reading what Glitchless made of ${ids.length} run(s) …`);
|
|
116
|
+
summary = await waitForSummary(read, dest.service, ids, started, { log, timeoutMs: dest.cloud ? 180_000 : 30_000 }).catch((err) => {
|
|
117
|
+
notes.push(`Glitchless's summary of the runs couldn't be read: ${err.message}`);
|
|
118
|
+
return null;
|
|
119
|
+
});
|
|
120
|
+
findings = await read('findings', { service: dest.service, sessions: ids.join(','), from: started - 60_000, to: Date.now() + 60_000 })
|
|
121
|
+
.then((b) => b.findings || [])
|
|
122
|
+
.catch(() => []);
|
|
123
|
+
// Chrome keeps a public page from reaching a server on this computer or its network (Local Network Access).
|
|
124
|
+
const localHost = (u) => /^(localhost|127\.|\[::1\]|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)|\.local(host)?(:\d+)?$/.test(safeHost(u) || '');
|
|
125
|
+
if (!summary?.runs?.length && localHost(base) && !localHost(target.play_url)) notes.push(`Nothing the bots measured reached ${base}: Chrome keeps a public page like this one from sending to a server on this computer (Local Network Access). Check public games against Glitchless Cloud; the numbers below are the bots' own.`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const result = {
|
|
129
|
+
checked_at: new Date(started).toISOString(),
|
|
130
|
+
url,
|
|
131
|
+
target,
|
|
132
|
+
game: { name: gameName, in_glitchless: dest.name || gameName, id: dest.game_id, service: dest.service, cloud: dest.cloud, version },
|
|
133
|
+
machine: { os: `${os.type()} ${os.release()}`, cpu: os.cpus()[0]?.model || null, gpu: summary?.runs?.find((r) => r.gpu)?.gpu || null, browser: `Chrome ${browser.version()}` },
|
|
134
|
+
ai: player ? { model: player.model, calls: player.calls } : null,
|
|
135
|
+
profiles: runs,
|
|
136
|
+
summary,
|
|
137
|
+
findings,
|
|
138
|
+
notes,
|
|
139
|
+
dir,
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// The game's dashboard, a picture of it as the board's banner, and an unlisted link to the check's page: only when
|
|
143
|
+
// what the bots measured reached Glitchless, or the board and its link would show nothing.
|
|
144
|
+
if (ids.length && !summary?.runs?.length) notes.push(`No dashboard or share link: ${summary ? 'nothing the bots measured reached Glitchless' : "Glitchless's summary of the runs couldn't be read"}, so they would show nothing.`);
|
|
145
|
+
if (summary?.runs?.length) {
|
|
146
|
+
const pages = checkDashboard(result);
|
|
147
|
+
await write(base, apiKey, dest, 'PUT', `/v1/dashboard?service=${encodeURIComponent(dest.service)}`, { pages })
|
|
148
|
+
.then(() => (result.dashboard = { pages: pages.map((p) => p.title) }))
|
|
149
|
+
.catch((err) => notes.push(`The dashboard wasn't saved: ${err.message}`));
|
|
150
|
+
const picture = runs.find((r) => r.profile === 'desktop')?.shots?.find((s) => /playing/.test(s)) || runs.flatMap((r) => r.shots || []).find((s) => /playing|end/.test(s));
|
|
151
|
+
if (picture && fs.statSync(picture).size <= 300_000) {
|
|
152
|
+
await upload(base, apiKey, dest, `/v1/brand/banner?service=${encodeURIComponent(dest.service)}`, fs.readFileSync(picture), 'image/jpeg').catch((err) => notes.push(`The board's banner wasn't set: ${err.message}`));
|
|
153
|
+
}
|
|
154
|
+
result.dashboard_url = dest.dashboard ? `${dest.dashboard}#/${CHECK_PAGE}` : `${base}/?service=${encodeURIComponent(dest.service)}#/${CHECK_PAGE}`;
|
|
155
|
+
if (share && dest.cloud) {
|
|
156
|
+
result.share = await shareLink(base, apiKey, dest, { from: started - 60_000, to: Date.now() + 120_000 }).catch((err) => {
|
|
157
|
+
notes.push(`No share link: ${err.message}`);
|
|
158
|
+
return null;
|
|
159
|
+
});
|
|
160
|
+
} else if (share) notes.push('No share link: share links are a Glitchless Cloud feature (sign in with a workspace key, gl_ws_…). The dashboard is on this server.');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
result.report = checkReport(result);
|
|
164
|
+
result.dm = checkDm(result);
|
|
165
|
+
const files = { report: path.join(dir, 'report.md'), dm: path.join(dir, 'message.txt'), json: path.join(dir, 'check.json') };
|
|
166
|
+
fs.writeFileSync(files.report, `${result.report}\n`);
|
|
167
|
+
fs.writeFileSync(files.dm, `${result.dm}\n`);
|
|
168
|
+
fs.writeFileSync(files.json, `${JSON.stringify({ ...result, report: undefined, dm: undefined }, null, 2)}\n`);
|
|
169
|
+
result.files = { ...files, shots: runs.flatMap((r) => r.shots || []) };
|
|
170
|
+
return result;
|
|
171
|
+
} finally {
|
|
172
|
+
await browser.close();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ───────────────────────────── playing one profile ─────────────────────────────
|
|
177
|
+
|
|
178
|
+
async function playProfile(browser, { profile, target, dest, sdk, version, seconds, ua, dir, adapters, ai, robots, log }) {
|
|
179
|
+
const ctx = await browser.newContext({
|
|
180
|
+
viewport: profile.viewport,
|
|
181
|
+
deviceScaleFactor: profile.deviceScaleFactor || 1,
|
|
182
|
+
isMobile: !!profile.isMobile,
|
|
183
|
+
hasTouch: !!profile.touch,
|
|
184
|
+
userAgent: ua,
|
|
185
|
+
// The SDK sends to Glitchless from inside the game's page: a page whose CSP lists only its own hosts would block it.
|
|
186
|
+
bypassCSP: true,
|
|
187
|
+
});
|
|
188
|
+
const run = { profile: profile.name, words: profileWords(profile), viewport: profile.viewport, url: target.play_url, load: null, errors: [], shots: [], steps: [], notes: [], held_back: 0 };
|
|
189
|
+
const intakeHost = safeHost(dest.intake);
|
|
190
|
+
const ours = (u) => safeHost(u) === intakeHost && /\/v1\//.test(u);
|
|
191
|
+
// A game with Glitchless already in it would send the bots' play to its own game as players' sessions: every send
|
|
192
|
+
// to a Glitchless intake (any SDK: /v1/intake?token=…) with another token than the check's is held back.
|
|
193
|
+
await ctx.route(/\/v1\/intake(\?|$)/, (route) => {
|
|
194
|
+
let token = null;
|
|
195
|
+
try {
|
|
196
|
+
token = new URL(route.request().url()).searchParams.get('token');
|
|
197
|
+
} catch {}
|
|
198
|
+
if (token === dest.client_token) return route.continue();
|
|
199
|
+
run.held_back++;
|
|
200
|
+
return route.abort('blockedbyclient');
|
|
201
|
+
});
|
|
202
|
+
const page = await ctx.newPage();
|
|
203
|
+
// Popups and new tabs the game opens (ads, links) are closed: the check stays on the game.
|
|
204
|
+
ctx.on('page', (p) => p !== page && p.close().catch(() => {}));
|
|
205
|
+
page.on('dialog', (d) => d.dismiss().catch(() => {}));
|
|
206
|
+
const cdp = await ctx.newCDPSession(page);
|
|
207
|
+
if (profile.cpu > 1) await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu });
|
|
208
|
+
if (profile.network) {
|
|
209
|
+
await cdp.send('Network.enable');
|
|
210
|
+
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network });
|
|
211
|
+
}
|
|
212
|
+
await page.addInitScript({
|
|
213
|
+
content: checkInitScript({
|
|
214
|
+
sdk,
|
|
215
|
+
init: {
|
|
216
|
+
adapters,
|
|
217
|
+
glitchless: { service: dest.service, version, env: 'check', intake: dest.intake, clientToken: dest.client_token, sessionType: 'synthetic', overlay: false, webmcp: false, privacy: 'anonymous', properties: { profile: profile.name } },
|
|
218
|
+
},
|
|
219
|
+
}),
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// What loading costs: bytes, requests, what's missing (4xx) or failed, and requests still in flight.
|
|
223
|
+
const net = { bytes: 0, requests: 0, missing: new Map(), failed: new Map(), inflight: new Set(), lastActivity: Date.now() };
|
|
224
|
+
page.on('request', (r) => {
|
|
225
|
+
if (ours(r.url())) return;
|
|
226
|
+
net.requests++;
|
|
227
|
+
net.inflight.add(r);
|
|
228
|
+
net.lastActivity = Date.now();
|
|
229
|
+
});
|
|
230
|
+
const done = (r) => {
|
|
231
|
+
net.inflight.delete(r);
|
|
232
|
+
net.lastActivity = Date.now();
|
|
233
|
+
};
|
|
234
|
+
page.on('requestfinished', (r) => {
|
|
235
|
+
done(r);
|
|
236
|
+
if (ours(r.url())) return;
|
|
237
|
+
r.sizes()
|
|
238
|
+
.then((s) => (net.bytes += s.responseBodySize + s.responseHeadersSize))
|
|
239
|
+
.catch(() => {});
|
|
240
|
+
});
|
|
241
|
+
page.on('requestfailed', (r) => {
|
|
242
|
+
done(r);
|
|
243
|
+
if (/BLOCKED_BY_CLIENT/.test(r.failure()?.errorText || '')) return; // a send held back above
|
|
244
|
+
if (ours(r.url())) {
|
|
245
|
+
run.failed_sends = (run.failed_sends || 0) + 1;
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const why = r.failure()?.errorText || 'failed';
|
|
249
|
+
if (!/ERR_ABORTED/.test(why)) net.failed.set(shortUrl(r.url()), why);
|
|
250
|
+
});
|
|
251
|
+
page.on('response', (res) => {
|
|
252
|
+
if (res.status() >= 400 && !ours(res.url())) net.missing.set(shortUrl(res.url()), res.status());
|
|
253
|
+
});
|
|
254
|
+
page.on('pageerror', (err) => run.errors.length < 50 && run.errors.push(String(err?.message || err).split('\n')[0].slice(0, 300)));
|
|
255
|
+
// The browser's own complaints about the check's sends to Glitchless (CORS, a blocked address) aren't the game's.
|
|
256
|
+
const aboutUs = (t) => (intakeHost && t.includes(intakeHost) && /\/v1\//.test(t)) || /\/v1\/intake\?token=/.test(t);
|
|
257
|
+
page.on('console', (m) => m.type() === 'error' && run.errors.length < 50 && !/Failed to load resource/.test(m.text()) && !aboutUs(m.text()) && run.errors.push(`console: ${m.text().split('\n')[0].slice(0, 300)}`));
|
|
258
|
+
|
|
259
|
+
// A click that leaves the game's site is undone.
|
|
260
|
+
const origin = new URL(target.play_url).origin;
|
|
261
|
+
let wentAway = null;
|
|
262
|
+
page.on('framenavigated', (f) => {
|
|
263
|
+
if (f === page.mainFrame() && f.url() !== 'about:blank' && safeOrigin(f.url()) !== origin) wentAway = f.url();
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
const t0 = Date.now();
|
|
267
|
+
try {
|
|
268
|
+
let res;
|
|
269
|
+
try {
|
|
270
|
+
res = await page.goto(target.play_url, { waitUntil: 'commit', referer: target.referer || undefined, timeout: 60_000 });
|
|
271
|
+
} catch (err) {
|
|
272
|
+
run.stopped = `${profile.name}: the game didn't load (${err.message.split('\n')[0]})`;
|
|
273
|
+
return run;
|
|
274
|
+
}
|
|
275
|
+
await page.waitForLoadState('domcontentloaded', { timeout: 60_000 }).catch(() => {});
|
|
276
|
+
const refused = refusal({ status: res?.status(), headers: res ? await res.allHeaders().catch(() => ({})) : {}, title: await page.title().catch(() => ''), body: await page.evaluate(() => document.body?.innerText?.slice(0, 4000) || '').catch(() => '') });
|
|
277
|
+
if (refused) {
|
|
278
|
+
run.stopped = `${target.play_url}: ${refused}, so the check stopped without playing`;
|
|
279
|
+
run.refused = true;
|
|
280
|
+
return run;
|
|
281
|
+
}
|
|
282
|
+
if (res && res.status() >= 400) {
|
|
283
|
+
run.stopped = `${target.play_url} answered HTTP ${res.status()}`;
|
|
284
|
+
return run;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Loaded: the load event, then the network quiet for 2 s (a game that streams while it plays is cut off at the cap).
|
|
288
|
+
const cap = (LOAD_CAP_S[profile.name] || 60) * 1000;
|
|
289
|
+
await page.waitForLoadState('load', { timeout: cap }).catch(() => {});
|
|
290
|
+
while (Date.now() - t0 < cap && (net.inflight.size > 0 || Date.now() - net.lastActivity < 2000)) await page.waitForTimeout(250);
|
|
291
|
+
let info = await readPage(page);
|
|
292
|
+
// The game in a frame of its own (a page that embeds it): play the frame itself, as for itch.io.
|
|
293
|
+
if (!info?.canvas && info?.frame?.src && /^https?:/.test(info.frame.src) && safeOrigin(info.frame.src) !== origin) {
|
|
294
|
+
const robotsFrame = await robotsCheck(info.frame.src, { ua, cache: robots });
|
|
295
|
+
if (robotsFrame.allowed) {
|
|
296
|
+
run.notes.push(`The game runs in a frame from ${safeHost(info.frame.src)}: the check played that frame.`);
|
|
297
|
+
run.url = info.frame.src;
|
|
298
|
+
await page.goto(info.frame.src, { waitUntil: 'load', referer: target.play_url, timeout: cap }).catch(() => {});
|
|
299
|
+
while (Date.now() - t0 < cap && (net.inflight.size > 0 || Date.now() - net.lastActivity < 2000)) await page.waitForTimeout(250);
|
|
300
|
+
info = await readPage(page);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
run.load = { ready_s: round1((net.lastActivity - t0) / 1000), timed_out: Date.now() - t0 >= cap, bytes: net.bytes, requests: net.requests };
|
|
304
|
+
run.page_start = info;
|
|
305
|
+
if (!info) {
|
|
306
|
+
run.stopped = `${profile.name}: the page never answered`;
|
|
307
|
+
return run;
|
|
308
|
+
}
|
|
309
|
+
if (info.init_error || !info.session) {
|
|
310
|
+
run.stopped = `${profile.name}: Glitchless didn't start in the page (${info.init_error || 'no session'})`;
|
|
311
|
+
return run;
|
|
312
|
+
}
|
|
313
|
+
run.session_id = info.session;
|
|
314
|
+
log(` loaded in ${run.load.ready_s} s, ${mb(net.bytes)} MB${info.engines.length ? `, ${info.engines.map((e) => e.name).join(' + ')}` : ''}`);
|
|
315
|
+
|
|
316
|
+
const area = async () => {
|
|
317
|
+
const r = await page.evaluate(() => window.__GLITCHLESS_CHECK__?.area?.() ?? null).catch(() => null);
|
|
318
|
+
if (r && r.width >= 40 && r.height >= 40) return { x: Math.max(0, r.x), y: Math.max(0, r.y), width: Math.min(r.width, profile.viewport.width), height: Math.min(r.height, profile.viewport.height) };
|
|
319
|
+
return { x: 0, y: 0, width: profile.viewport.width, height: profile.viewport.height };
|
|
320
|
+
};
|
|
321
|
+
const shot = async (name) => {
|
|
322
|
+
const file = path.join(dir, `${profile.name}-${name}.jpg`);
|
|
323
|
+
await page.screenshot({ path: file, type: 'jpeg', quality: 70 }).catch(() => null);
|
|
324
|
+
return fs.existsSync(file) ? file : null;
|
|
325
|
+
};
|
|
326
|
+
const guard = setInterval(() => {
|
|
327
|
+
if (!wentAway) return;
|
|
328
|
+
run.notes.push(`A click led away from the game (${safeHost(wentAway)}); the bot went back.`);
|
|
329
|
+
wentAway = null;
|
|
330
|
+
page.goto(run.url, { waitUntil: 'load', timeout: 30_000 }).catch(() => {});
|
|
331
|
+
}, 500);
|
|
332
|
+
try {
|
|
333
|
+
const played = await explore(page, { profile, seconds, cdp, area, shot, ai, log });
|
|
334
|
+
Object.assign(run, { steps: played.steps, inputs: played.inputs, shots: played.shots, idle_change: played.idle_change, seconds_played: played.elapsed_s });
|
|
335
|
+
run.notes.push(...played.notes);
|
|
336
|
+
} finally {
|
|
337
|
+
clearInterval(guard);
|
|
338
|
+
}
|
|
339
|
+
run.page = await readPage(page);
|
|
340
|
+
// Ending the page makes the SDK send session_end and whatever it still holds.
|
|
341
|
+
await page.evaluate(() => window.dispatchEvent(new Event('pagehide'))).catch(() => {});
|
|
342
|
+
await page.waitForTimeout(1500);
|
|
343
|
+
} finally {
|
|
344
|
+
run.load ||= { ready_s: null, bytes: net.bytes, requests: net.requests };
|
|
345
|
+
run.load.missing = [...net.missing].slice(0, 12).map(([url, status]) => ({ url, status }));
|
|
346
|
+
run.load.failed = [...net.failed].filter(([url]) => !/\/v1\/intake/.test(url)).slice(0, 12).map(([url, why]) => ({ url, why }));
|
|
347
|
+
if (run.failed_sends) run.notes.push(`${run.failed_sends} of the check's sends to Glitchless failed.`);
|
|
348
|
+
if (run.held_back) run.notes.push(`The game already sends to Glitchless itself: its ${run.held_back} send${run.held_back === 1 ? ' was' : 's were'} held back during the check, so the bots never counted as its players.`);
|
|
349
|
+
run.errors = [...new Set(run.errors)];
|
|
350
|
+
await ctx.close().catch(() => {});
|
|
351
|
+
}
|
|
352
|
+
return run;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const readPage = (page) => page.evaluate(() => window.__GLITCHLESS_CHECK__?.read?.() ?? null).catch(() => null);
|
|
356
|
+
const round1 = (v) => Math.round(v * 10) / 10;
|
|
357
|
+
const mb = (b) => Math.round((b / 1048576) * 10) / 10;
|
|
358
|
+
const safeHost = (u) => {
|
|
359
|
+
try {
|
|
360
|
+
return new URL(u).host;
|
|
361
|
+
} catch {
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
const safeOrigin = (u) => {
|
|
366
|
+
try {
|
|
367
|
+
return new URL(u).origin;
|
|
368
|
+
} catch {
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
const shortUrl = (u) => {
|
|
373
|
+
try {
|
|
374
|
+
const x = new URL(u);
|
|
375
|
+
return `${x.host}${x.pathname}`.slice(0, 120);
|
|
376
|
+
} catch {
|
|
377
|
+
return String(u).slice(0, 120);
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
// The page's own title, for the game's name when the address doesn't give one.
|
|
382
|
+
async function pageTitle(url, ua) {
|
|
383
|
+
try {
|
|
384
|
+
const html = await fetch(url, { headers: { 'user-agent': ua }, signal: AbortSignal.timeout(15_000) }).then((r) => r.text());
|
|
385
|
+
const t = html.match(/<title[^>]*>([^<]{1,120})<\/title>/i)?.[1]?.trim();
|
|
386
|
+
return t ? t.replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/g, '"') : null;
|
|
387
|
+
} catch {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ───────────────────────────── Glitchless ─────────────────────────────
|
|
393
|
+
|
|
394
|
+
// The game the check sends to. With a workspace key (Glitchless Cloud), a game by this name, made if there's none, and
|
|
395
|
+
// its client token; on an open server (the open-source one), a service by this name with its development token. A
|
|
396
|
+
// check saves its own dashboard and banner, so it only reuses a game an earlier check made (its dashboard opens on the
|
|
397
|
+
// check page) or one that never sent anything: a real game by the same name is left alone, and the check goes to
|
|
398
|
+
// "<name> (game check)" instead.
|
|
399
|
+
export async function checkDestination({ base, apiKey, name, log = () => {}, fetchImpl = fetch }) {
|
|
400
|
+
// Whether `service` (of game `project`) belongs to a real game: a dashboard that isn't a check's, or data without one.
|
|
401
|
+
const taken = async (service, project, hasData) => {
|
|
402
|
+
const headers = { 'x-glitchless-client': 'game-check', ...(apiKey ? { 'x-glitchless-api-key': apiKey } : {}), ...(project ? { 'x-glitchless-project': project } : {}) };
|
|
403
|
+
const saved = await fetchImpl(`${base}/v1/dashboard?service=${encodeURIComponent(service)}`, { headers })
|
|
404
|
+
.then((r) => (r.ok ? r.json() : null))
|
|
405
|
+
.catch(() => null);
|
|
406
|
+
const pages = saved?.dashboard?.pages;
|
|
407
|
+
return pages?.length ? pages[0].id !== CHECK_PAGE : hasData;
|
|
408
|
+
};
|
|
409
|
+
if (apiKey?.startsWith('gl_ws_')) {
|
|
410
|
+
const agent = async (method, p, body) => {
|
|
411
|
+
const res = await fetchImpl(`${base}/v1/agent${p}`, { method, headers: { 'x-glitchless-api-key': apiKey, ...(body ? { 'content-type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
|
412
|
+
const data = await res.json().catch(() => ({}));
|
|
413
|
+
if (!res.ok) throw new Error(`Glitchless ${method} /v1/agent${p}: ${data.error || `HTTP ${res.status}`}`);
|
|
414
|
+
return data;
|
|
415
|
+
};
|
|
416
|
+
const { games, intake } = await agent('GET', '/games');
|
|
417
|
+
const find = (n) => games.find((g) => g.name.toLowerCase() === n.toLowerCase());
|
|
418
|
+
const serviceOf = (g, n) => g?.services?.find((s) => !s.server_of)?.service || slugify(n);
|
|
419
|
+
let gameName = name;
|
|
420
|
+
let game = find(gameName);
|
|
421
|
+
if (game && (await taken(serviceOf(game, gameName), game.id, !!game.services?.length))) {
|
|
422
|
+
log(`"${game.name}" is a game of its own in your workspace, with its own data: the check goes to "${name} (game check)"`);
|
|
423
|
+
gameName = `${name} (game check)`;
|
|
424
|
+
game = find(gameName);
|
|
425
|
+
}
|
|
426
|
+
let token = game?.client_token;
|
|
427
|
+
let dashboard = game?.dashboard;
|
|
428
|
+
if (!game) {
|
|
429
|
+
log(`making the game "${gameName}" in your workspace`);
|
|
430
|
+
const made = await agent('POST', '/games', { name: gameName }).catch((err) => {
|
|
431
|
+
throw new Error(`${err.message} A check makes a game of its own: make room in the workspace, or check into a game an earlier check made, by its name (check_name, or --name).`);
|
|
432
|
+
});
|
|
433
|
+
game = made.game;
|
|
434
|
+
token = made.client_token;
|
|
435
|
+
dashboard = made.dashboard;
|
|
436
|
+
} else log(`using the game "${game.name}" an earlier check made`);
|
|
437
|
+
return { cloud: true, game_id: game.id, name: game.name, service: serviceOf(game, gameName), client_token: token, intake: intake || base, dashboard };
|
|
438
|
+
}
|
|
439
|
+
const services = await fetchImpl(`${base}/v1/query/services`, { headers: { 'x-glitchless-client': 'game-check', ...(apiKey ? { 'x-glitchless-api-key': apiKey } : {}) } })
|
|
440
|
+
.then((r) => (r.ok ? r.json() : null))
|
|
441
|
+
.then((b) => new Set((b?.services || []).map((x) => x.service)))
|
|
442
|
+
.catch(() => new Set());
|
|
443
|
+
let service = slugify(name);
|
|
444
|
+
let gameName = name;
|
|
445
|
+
if (await taken(service, null, services.has(service))) {
|
|
446
|
+
log(`"${service}" is a game of its own on this server: the check goes to "${service}-check"`);
|
|
447
|
+
service = `${service}-check`;
|
|
448
|
+
gameName = `${name} (game check)`;
|
|
449
|
+
}
|
|
450
|
+
return { cloud: false, game_id: null, name: gameName, service, client_token: process.env.GLITCHLESS_CLIENT_TOKEN || 'gl_pub_dev', intake: base, dashboard: null };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function headersFor(apiKey, dest) {
|
|
454
|
+
return { 'x-glitchless-client': 'game-check', ...(apiKey ? { 'x-glitchless-api-key': apiKey } : {}), ...(apiKey?.startsWith('gl_ws_') && dest.game_id ? { 'x-glitchless-project': dest.game_id } : {}) };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function readerFor(base, apiKey, dest) {
|
|
458
|
+
return async (name, params) => {
|
|
459
|
+
const qs = new URLSearchParams(Object.entries(params).map(([k, v]) => [k, String(v)]));
|
|
460
|
+
const res = await fetch(`${base}/v1/query/${name}?${qs}`, { headers: headersFor(apiKey, dest) });
|
|
461
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} on ${name}: ${(await res.text()).slice(0, 200)}`);
|
|
462
|
+
const body = await res.json();
|
|
463
|
+
if (body.error) throw new Error(body.error);
|
|
464
|
+
return body;
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async function write(base, apiKey, dest, method, p, body) {
|
|
469
|
+
const res = await fetch(`${base}${p}`, { method, headers: { ...headersFor(apiKey, dest), 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
|
470
|
+
const data = await res.json().catch(() => ({}));
|
|
471
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
472
|
+
return data;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async function upload(base, apiKey, dest, p, bytes, type) {
|
|
476
|
+
const res = await fetch(`${base}${p}`, { method: 'PUT', headers: { ...headersFor(apiKey, dest), 'content-type': type }, body: bytes });
|
|
477
|
+
const data = await res.json().catch(() => ({}));
|
|
478
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
479
|
+
return data;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// The summary of the check's sessions, once each has ended (Glitchless Cloud's lake can take a minute or two).
|
|
483
|
+
async function waitForSummary(read, service, ids, started, { log, timeoutMs }) {
|
|
484
|
+
const deadline = Date.now() + timeoutMs;
|
|
485
|
+
let last = null;
|
|
486
|
+
while (true) {
|
|
487
|
+
const body = await read('playtest', { service, sessions: ids.join(','), from: started - 60_000, to: Date.now() + 60_000 });
|
|
488
|
+
last = body.summary;
|
|
489
|
+
const ended = new Set((last?.runs || []).filter((r) => r.ended).map((r) => r.session_id));
|
|
490
|
+
if (ids.every((id) => ended.has(id))) return last;
|
|
491
|
+
if (Date.now() > deadline) {
|
|
492
|
+
log(` ${ids.filter((id) => !ended.has(id)).length} run(s) not complete in Glitchless yet; using what arrived`);
|
|
493
|
+
return last;
|
|
494
|
+
}
|
|
495
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// An unlisted link to the check's page that shows the check's bot runs (bots: true), for 30 days.
|
|
500
|
+
async function shareLink(base, apiKey, dest, { from, to }) {
|
|
501
|
+
const res = await fetch(`${base}/v1/agent/games/${dest.game_id}/shares`, {
|
|
502
|
+
method: 'POST',
|
|
503
|
+
headers: { 'x-glitchless-api-key': apiKey, 'content-type': 'application/json' },
|
|
504
|
+
body: JSON.stringify({ service: dest.service, page: CHECK_PAGE, name: 'Game check', days: 30, from, to, bots: true }),
|
|
505
|
+
});
|
|
506
|
+
const data = await res.json().catch(() => ({}));
|
|
507
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
508
|
+
// A server from before share links could show bot runs would make a link that shows nothing: take it back.
|
|
509
|
+
if (data.share?.bots !== true) {
|
|
510
|
+
await fetch(`${base}/v1/agent/games/${dest.game_id}/shares/${data.share?.id}`, { method: 'DELETE', headers: { 'x-glitchless-api-key': apiKey } }).catch(() => {});
|
|
511
|
+
throw new Error('this Glitchless server makes share links that show players only, so a link would show an empty board (it needs the share links that show a game check\'s bot runs)');
|
|
512
|
+
}
|
|
513
|
+
return { url: data.url, id: data.share.id, expires_at: data.share.expiresAt };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// The browser SDK's <script> build: the copy the Glitchless server serves (it matches what that server reads), else
|
|
517
|
+
// one built in this checkout or installed with the glitchless package.
|
|
518
|
+
export async function sdkScript(base, cwd = process.cwd()) {
|
|
519
|
+
try {
|
|
520
|
+
const res = await fetch(`${base}/sdk/glitchless.js`, { signal: AbortSignal.timeout(15_000) });
|
|
521
|
+
if (res.ok && /javascript/.test(res.headers.get('content-type') || '')) return await res.text();
|
|
522
|
+
} catch {}
|
|
523
|
+
const candidates = [path.resolve(HERE, '../../sdk/dist/glitchless.js')];
|
|
524
|
+
for (const from of [path.join(cwd, 'noop.js'), import.meta.url]) {
|
|
525
|
+
try {
|
|
526
|
+
candidates.push(path.resolve(path.dirname(createRequire(from).resolve('glitchless')), '../dist/glitchless.js'));
|
|
527
|
+
} catch {}
|
|
528
|
+
}
|
|
529
|
+
const found = candidates.find((f) => fs.existsSync(f));
|
|
530
|
+
if (found) return fs.readFileSync(found, 'utf8');
|
|
531
|
+
throw new Error(`No Glitchless browser SDK to add to the page: ${base}/sdk/glitchless.js didn't answer and no built copy was found (in the Glitchless repo: npm run build -w glitchless).`);
|
|
532
|
+
}
|
package/src/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// a saved baseline. Used by the glitchless-playtest CLI and the glitchless_playtest MCP tool. A web game
|
|
3
3
|
// plays in Chrome (run.js); an engine build (Unity, Godot, Unreal, GameMaker) runs from its command with
|
|
4
4
|
// the SDK's --glitchless-measure (engine.js); a Roblox game plays in the open Roblox Studio over Studio's MCP
|
|
5
|
-
// server (roblox.js).
|
|
5
|
+
// server (roblox.js). A game check (check.js) plays any web game with nothing installed in it, and makes a report and a
|
|
6
|
+
// dashboard for its maker.
|
|
6
7
|
//
|
|
7
8
|
// await playtest({ saveAs: 'baseline' }) // before a change
|
|
8
9
|
// await playtest({ compareTo: 'baseline' }) // after it → { verdict, report, ... }
|
|
@@ -22,6 +23,10 @@ export { saveRun, loadRun, listRuns } from './runs.js';
|
|
|
22
23
|
export { playtestRun, loadPlaywright } from './run.js';
|
|
23
24
|
export { engineRun, measureSummary, parseMeasure, detectEngine, splitCommand, ENGINES } from './engine.js';
|
|
24
25
|
export { robloxRun } from './roblox.js';
|
|
26
|
+
// A game check: any web game, nothing installed in it (check.js).
|
|
27
|
+
export { gameCheck, CHECK_SECONDS } from './check.js';
|
|
28
|
+
export { checkReport, checkDm, checkDashboard, headlines, engineWords } from './check-report.js';
|
|
29
|
+
export { itchFrame, robotsAllow, refusal, siteOf } from './check-site.js';
|
|
25
30
|
|
|
26
31
|
/**
|
|
27
32
|
* @param {object} o
|
package/src/run.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createRequire } from 'node:module';
|
|
|
9
9
|
import { pathToFileURL } from 'node:url';
|
|
10
10
|
|
|
11
11
|
// Real GPU (Metal via ANGLE on macOS) and no background throttling, same as scripts/bots.js.
|
|
12
|
-
const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
|
|
12
|
+
export const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
|
|
13
13
|
|
|
14
14
|
// Resolve Playwright from the game project first (where people install it), then from here.
|
|
15
15
|
export async function loadPlaywright(cwd = process.cwd()) {
|