glitchless-playtest 0.1.1 → 0.3.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/src/roblox.js ADDED
@@ -0,0 +1,319 @@
1
+ // Roblox: a game has no command line, so its play tests run in the open Roblox Studio, driven over Studio's own MCP
2
+ // server (StudioMCP, the tools an agent uses there). Each scenario sets its params as attributes of Workspace, where
3
+ // the game's autoplay bot reads them, starts a play test, waits until done_when (Luau, on the server) is true or max_s
4
+ // passes, stops it and puts the attributes back. The SDK sends the play test's sessions to the game's intake as any
5
+ // Roblox server does, and the run is read back from that Glitchless server like a browser run: the players' sessions
6
+ // under the game's service, the server's own under <service>.server (its script errors are the game's too).
7
+ // Studio sessions are `tester` unless the game marks its bot's `synthetic`; the play test's window picks out its own.
8
+
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { spawn } from 'node:child_process';
12
+ import { fetchSummary, gitInfo, machineInfo } from './run.js';
13
+
14
+ export const DEFAULT_ROBLOX_SCENARIOS = [
15
+ { name: 'autoplay, seed 7', params: { autoplay: true, seed: 7 }, max_s: 90 },
16
+ { name: 'autoplay, seed 21', params: { autoplay: true, seed: 21 }, max_s: 90 },
17
+ ];
18
+
19
+ // Luau, on the play test's server: the run ends early once it is true.
20
+ export const ROBLOX_DONE_WHEN = 'workspace:GetAttribute("GlitchlessPlaytestDone") == true';
21
+
22
+ export const ROBLOX_AUTOPLAY =
23
+ 'On Roblox, read workspace:GetAttribute("autoplay") and workspace:GetAttribute("seed") in a server Script: when autoplay is set, let a bot play each player\'s character (Humanoid:MoveTo, the game\'s own actions, with Random.new(seed) so the same seed plays the same way), call Glitchless.levelStart(player, …) as it goes, set workspace:SetAttribute("GlitchlessPlaytestDone", true) when the run is over, and pass sessionType = if workspace:GetAttribute("autoplay") then "synthetic" else nil to Glitchless.init so its sessions stay out of player numbers.';
24
+
25
+ const NEEDS_STUDIO =
26
+ 'Roblox playtests run in Roblox Studio: open the game\'s place in Studio and turn on Assistant → … → Manage MCP Servers → Enable Studio as MCP server.';
27
+
28
+ /** The StudioMCP command: "studio_mcp" in glitchless.playtest.json, else where Studio installs it. */
29
+ export function studioMcpCommand(cfg) {
30
+ if (cfg.studio_mcp) return [].concat(cfg.studio_mcp).map(String);
31
+ if (process.platform === 'win32') return ['cmd.exe', '/c', path.join(process.env.LOCALAPPDATA || '', 'Roblox', 'mcp.bat')];
32
+ return ['/Applications/RobloxStudio.app/Contents/MacOS/StudioMCP'];
33
+ }
34
+
35
+ // A small MCP client over stdio, for StudioMCP.
36
+ export function connectStudio(argv) {
37
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'ignore'] });
38
+ const pending = new Map();
39
+ let buf = '';
40
+ let seq = 0;
41
+ let failed = null;
42
+ const fail = (err) => {
43
+ failed = err;
44
+ for (const done of pending.values()) done({ error: { message: err.message } });
45
+ };
46
+ child.on('error', (err) => fail(err.code === 'ENOENT' ? new Error(`Roblox Studio's MCP server isn't at ${argv[0]}. ${NEEDS_STUDIO} Or set "studio_mcp" in glitchless.playtest.json to its command.`) : err));
47
+ child.on('exit', () => fail(new Error(`Roblox Studio's MCP server (${argv.join(' ')}) stopped. ${NEEDS_STUDIO}`)));
48
+ child.stdout.on('data', (d) => {
49
+ buf += d;
50
+ for (let i; (i = buf.indexOf('\n')) >= 0; ) {
51
+ const line = buf.slice(0, i).trim();
52
+ buf = buf.slice(i + 1);
53
+ if (!line.startsWith('{')) continue;
54
+ try {
55
+ const msg = JSON.parse(line);
56
+ if (msg.id != null && pending.has(msg.id)) pending.get(msg.id)(msg);
57
+ } catch {}
58
+ }
59
+ });
60
+ child.stdin.on('error', () => {});
61
+ const request = (method, params, timeoutMs = 120_000) =>
62
+ new Promise((resolve, reject) => {
63
+ if (failed) return reject(failed);
64
+ const id = ++seq;
65
+ const timer = setTimeout(() => (pending.delete(id), reject(new Error(`Roblox Studio's MCP server didn't answer ${method} in ${timeoutMs / 1000} s`))), timeoutMs);
66
+ pending.set(id, (msg) => {
67
+ clearTimeout(timer);
68
+ pending.delete(id);
69
+ if (failed && !msg.result) reject(failed);
70
+ else resolve(msg);
71
+ });
72
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
73
+ });
74
+ const tool = async (name, args = {}) => {
75
+ const msg = await request('tools/call', { name, arguments: args });
76
+ const text = (msg.result?.content || []).map((c) => c.text ?? '').join('\n');
77
+ if (msg.error || msg.result?.isError) throw new Error(`Studio ${name}: ${msg.error?.message || text}`);
78
+ return text;
79
+ };
80
+ return {
81
+ tool,
82
+ async init() {
83
+ await request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'glitchless-playtest', version: '0' } }, 30_000);
84
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
85
+ },
86
+ close: () => child.kill(),
87
+ };
88
+ }
89
+
90
+ // Luau answers come back as text; a marker around JSON survives however the tool prints a returned string.
91
+ const MARK = (expr) => `"GLP<" .. game:GetService("HttpService"):JSONEncode(${expr}) .. ">GLP"`;
92
+ export function unmark(text) {
93
+ const m = String(text).match(/GLP<([\s\S]*?)>GLP/);
94
+ if (!m) return undefined;
95
+ try {
96
+ return JSON.parse(m[1]);
97
+ } catch {
98
+ return JSON.parse(JSON.parse(`"${m[1]}"`)); // printed inside a quoted string
99
+ }
100
+ }
101
+ // A Luau long string that holds `text` as it is.
102
+ export function longString(text) {
103
+ let eq = '=';
104
+ while (text.includes(`]${eq}]`)) eq += '=';
105
+ return `[${eq}[${text}]${eq}]`;
106
+ }
107
+
108
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
109
+ const luau = (mcp, id, code, type = 'Edit') => mcp.tool('execute_luau', { studio_id: id, datamodel_type: type, code });
110
+ const mode = async (mcp, id) => (await mcp.tool('get_studio_state', { studio_id: id })).match(/Mode:\s*(\w+)/i)?.[1] || null;
111
+
112
+ // The Studio to play in: "studio" (part of its name, or its ID), else the only one open.
113
+ async function pickStudio(mcp, want, waitS = 10) {
114
+ let studios = [];
115
+ for (let i = 0; i < waitS && !studios.length; i++) {
116
+ studios = JSON.parse((await mcp.tool('list_roblox_studios')) || '{}').studios || [];
117
+ if (!studios.length) await sleep(1000); // the server finds open Studios a moment after it starts
118
+ }
119
+ if (!studios.length) throw new Error(`No Roblox Studio answered. ${NEEDS_STUDIO}`);
120
+ const names = studios.map((s) => `"${s.name}"`).join(', ');
121
+ const match = want ? studios.filter((s) => s.id === want || String(s.name).toLowerCase().includes(String(want).toLowerCase())) : studios;
122
+ if (!match.length) throw new Error(`No open Roblox Studio is "${want}". Open: ${names}.`);
123
+ if (match.length > 1) throw new Error(`${match.length} Roblox Studios are open (${names}): set "studio" in glitchless.playtest.json to part of the game's place name, so the playtest never plays another place.`);
124
+ return match[0];
125
+ }
126
+
127
+ // What the place has: the Glitchless module, Allow HTTP Requests, and the service its Glitchless.init names.
128
+ const PROBE = `-- glitchless-playtest: probe
129
+ local HttpService = game:GetService("HttpService")
130
+ local module = game:GetService("ReplicatedStorage"):FindFirstChild("Glitchless", true)
131
+ local service
132
+ for _, root in { game:GetService("ServerScriptService"), game:GetService("ServerStorage"), game:GetService("ReplicatedStorage"), game:GetService("ReplicatedFirst") } do
133
+ for _, d in root:GetDescendants() do
134
+ if not service and d:IsA("LuaSourceContainer") and not (module and (d == module or d:IsDescendantOf(module))) then
135
+ local ok, src = pcall(function() return d.Source end)
136
+ if ok and type(src) == "string" and string.find(src, "Glitchless.init", 1, true) then
137
+ service = string.match(src, "Glitchless%.init%s*%(%s*{.-service%s*=%s*[\\"']([^\\"']+)[\\"']")
138
+ end
139
+ end
140
+ end
141
+ end
142
+ return ${MARK('{ module = module ~= nil, http = HttpService.HttpEnabled, service = service }')}`;
143
+
144
+ // Sets Workspace attributes and clears others, answering what they were before.
145
+ const attributes = (set, clear) => `-- glitchless-playtest: attributes
146
+ local HttpService = game:GetService("HttpService")
147
+ local set = HttpService:JSONDecode(${longString(JSON.stringify(set))})
148
+ local clear = HttpService:JSONDecode(${longString(JSON.stringify(clear))})
149
+ local before = {}
150
+ for k, v in set do
151
+ before[k] = workspace:GetAttribute(k)
152
+ workspace:SetAttribute(k, v)
153
+ end
154
+ for _, k in clear do
155
+ before[k] = workspace:GetAttribute(k)
156
+ workspace:SetAttribute(k, nil)
157
+ end
158
+ return ${MARK('before')}`;
159
+
160
+ const ATTRIBUTE = /^[A-Za-z0-9_]{1,100}$/;
161
+ function checkParams(sc) {
162
+ for (const [k, v] of Object.entries(sc.params || {})) {
163
+ if (!ATTRIBUTE.test(k) || k.startsWith('RBX')) throw new Error(`Scenario "${sc.name || k}": "${k}" can't be a Roblox attribute name (letters, digits and _, at most 100).`);
164
+ if (!['boolean', 'number', 'string'].includes(typeof v)) throw new Error(`Scenario "${sc.name || k}": "${k}" must be true or false, a number or a string to be a Workspace attribute.`);
165
+ }
166
+ }
167
+
168
+ const label = (sc) => sc.name || JSON.stringify(sc.params || {});
169
+
170
+ // One play test: attributes on, play until done or the cap, stop, attributes back as they were.
171
+ async function playOnce(mcp, studio, sc, cfg, log) {
172
+ const params = sc.params || {};
173
+ const before = unmark(await luau(mcp, studio.id, attributes(params, ['GlitchlessPlaytestDone']))) || {};
174
+ const restore = () => luau(mcp, studio.id, attributes(before, [...Object.keys(params), 'GlitchlessPlaytestDone'].filter((k) => !(k in before)))).catch(() => {});
175
+ const started = Date.now();
176
+ let finished = false;
177
+ try {
178
+ if (sc.luau || cfg.luau) await luau(mcp, studio.id, sc.luau || cfg.luau);
179
+ await mcp.tool('start_stop_play', { studio_id: studio.id, is_start: true });
180
+ const maxMs = (sc.max_s || 90) * 1000;
181
+ const done = `-- glitchless-playtest: done_when\nreturn if (${sc.done_when || cfg.done_when || ROBLOX_DONE_WHEN}) then ${MARK('true')} else ${MARK('false')}`;
182
+ while (Date.now() - started < maxMs) {
183
+ await sleep(1000);
184
+ finished = (await luau(mcp, studio.id, done, 'Server').then(unmark).catch(() => false)) === true;
185
+ if (finished) break;
186
+ }
187
+ } finally {
188
+ await mcp.tool('start_stop_play', { studio_id: studio.id, is_start: false }).catch(() => {});
189
+ for (let i = 0; i < 30 && (await mode(mcp, studio.id).catch(() => 'Edit')) !== 'Edit'; i++) await sleep(1000);
190
+ await restore();
191
+ }
192
+ // From the start of a play test, the Output holds that test's lines only: Glitchless's warnings are the clues.
193
+ const output = await mcp.tool('get_console_output', { studio_id: studio.id }).catch(() => '');
194
+ const glitchless = output.split('\n').filter((l) => l.includes('[glitchless]')).slice(0, 12);
195
+ const seconds = Math.round((Date.now() - started) / 1000);
196
+ log(` → ${seconds}s${finished ? '' : ' (hit the time cap)'}`);
197
+ return { scenario: sc.name || null, params, started, ended: Date.now(), seconds, finished, glitchless };
198
+ }
199
+
200
+ // The Studio sessions of a service (synthetic, or tester as Studio marks them) that started between two times.
201
+ async function sessionsOf(cfg, service, from, to) {
202
+ const base = cfg.server.replace(/\/$/, '');
203
+ const qs = new URLSearchParams({ service, from: String(from - 60_000), to: String(to + 60_000) });
204
+ const headers = { 'x-glitchless-client': 'playtest', ...(cfg.api_key ? { 'x-glitchless-api-key': cfg.api_key } : {}) };
205
+ const res = await fetch(`${base}/v1/query/sessions?${qs}`, { headers });
206
+ if (!res.ok) throw new Error(`Glitchless server ${base} answered HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
207
+ const body = await res.json();
208
+ return (body.sessions || []).filter((s) => (s.session_type === 'synthetic' || s.session_type === 'tester') && s.start >= from && s.start <= to);
209
+ }
210
+
211
+ // Each session belongs to the play test it started in: the play tests run one after another, and the SDK's clock is
212
+ // this machine's. A session that starts up to a second and a half early still counts, if it lasted into the test (one
213
+ // that ended before it began is the previous test's).
214
+ const SLACK_MS = 1500;
215
+ function assign(results, sessions, key) {
216
+ for (const r of results) r[key] = [];
217
+ for (const s of sessions) {
218
+ const lasted = (x) => s.start + (s.duration_s ?? 0) * 1000 >= x.started;
219
+ const within = (slack) => results.filter((x) => x.started - slack <= s.start && s.start <= x.ended && (!slack || lasted(x))).at(-1);
220
+ within(0)?.[key].push(s.session_id) ?? within(SLACK_MS)?.[key].push(s.session_id);
221
+ }
222
+ }
223
+
224
+ // One summary for the players' sessions, with the server's errors and crashes added: a script error on the server is
225
+ // the game's error too.
226
+ async function robloxSummary(cfg, service, players, servers, since, log) {
227
+ const summary = await fetchSummary(cfg, service, players, since, { log });
228
+ if (!servers.length || !summary) return summary;
229
+ const server = await fetchSummary(cfg, `${service}.server`, servers, since, { log, timeoutMs: 10_000 }).catch(() => null);
230
+ if (!server) return summary;
231
+ const errors = [...(summary.errors || [])];
232
+ for (const e of server.errors || []) if (!errors.some((x) => x.fingerprint === e.fingerprint)) errors.push({ ...e, server: true });
233
+ return { ...summary, errors, crashes: (summary.crashes || 0) + (server.crashes || 0), server_errors_per_session: server.errors_per_session ?? null };
234
+ }
235
+
236
+ /** Plays every scenario in Roblox Studio and returns a run record ready to save or compare. */
237
+ export async function robloxRun(cfg, { scenarios = cfg.scenarios, log = () => {} } = {}) {
238
+ for (const sc of scenarios) checkParams(sc);
239
+ const mcp = connectStudio(studioMcpCommand(cfg));
240
+ let studio;
241
+ let service = cfg.service;
242
+ const results = [];
243
+ try {
244
+ await mcp.init();
245
+ studio = await pickStudio(mcp, cfg.studio, cfg.studio_wait_s);
246
+ log(`Roblox Studio: ${studio.name}`);
247
+ const state = await mode(mcp, studio.id);
248
+ if (state && state !== 'Edit') throw new Error(`Roblox Studio ("${studio.name}") is in a play test (${state}): stop it, and run the playtest again.`);
249
+ const place = unmark(await luau(mcp, studio.id, PROBE)) || {};
250
+ if (!place.module) throw new Error(`"${studio.name}" has no Glitchless module in ReplicatedStorage: add Glitchless to the game first (the instrument skill's Roblox steps).`);
251
+ if (!place.http) throw new Error(`"${studio.name}" has Allow HTTP Requests off, so Glitchless can't send anything: turn it on in Game Settings → Security.`);
252
+ service ||= place.service;
253
+ if (!service) throw new Error('Could not tell which game this is from its Glitchless.init: set "service" in glitchless.playtest.json (or pass --service) to the service name it sends as.');
254
+ for (const [i, sc] of scenarios.entries()) {
255
+ log(`run ${i + 1}/${scenarios.length}: ${label(sc)} …`);
256
+ results.push(await playOnce(mcp, studio, sc, cfg, log));
257
+ }
258
+ } finally {
259
+ mcp.close();
260
+ }
261
+
262
+ // BindToClose sends the last batches as the play test's server closes: give them a moment to land.
263
+ log(`collecting the play tests' sessions from ${cfg.server} …`);
264
+ const from = results[0].started - SLACK_MS;
265
+ const to = results.at(-1).ended;
266
+ for (let i = 0; i < (cfg.sessions_wait_s ?? 30); i++) {
267
+ assign(results, await sessionsOf(cfg, service, from, to), 'session_ids');
268
+ if (results.every((r) => r.session_ids.length)) break;
269
+ await sleep(1000);
270
+ }
271
+ assign(results, await sessionsOf(cfg, `${service}.server`, from, to), 'server_session_ids');
272
+ for (const r of results) r.session_id = r.session_ids[0] || null;
273
+ const players = results.flatMap((r) => r.session_ids);
274
+ if (!players.length) {
275
+ const said = [...new Set(results.flatMap((r) => r.glitchless))];
276
+ throw new Error(`No session from "${service}" reached ${cfg.server} during the play tests. The game sends where its Glitchless.init intake says: read from that server (--server, or GLITCHLESS_URL), and check the service name.${said.length ? `\nStudio's Output said:\n${said.join('\n')}` : ''}`);
277
+ }
278
+ const servers = results.flatMap((r) => r.server_session_ids);
279
+ const started = Math.min(...results.map((r) => r.started));
280
+ const summary = await robloxSummary(cfg, service, players, servers, started, log);
281
+ const notes = [];
282
+ const noLevel = !Object.keys(summary?.levels || {}).length && !summary?.level_attempts;
283
+ if (noLevel && cfg.default_scenarios) throw new Error(`The play tests ran with the default scenarios (Workspace attributes autoplay = true, seed = 7) but no player started a level, so the game probably has no autoplay mode. ${ROBLOX_AUTOPLAY} Then list the runs in glitchless.playtest.json under "scenarios".`);
284
+ if (noLevel) notes.push(`No player started a level (Glitchless.levelStart), so the bot may not have played. If the game has no autoplay mode yet: ${ROBLOX_AUTOPLAY}`);
285
+ // A Studio window that is hidden or minimized runs the play test's client without drawing: no frames come back.
286
+ if (summary?.sessions && summary.frame_p95 == null) notes.push("No frames came from the players: Studio's window was probably hidden or minimized, so the play test's client drew nothing, and frame times can't be compared. Keep the place's Studio window in view while it plays.");
287
+ const many = results.filter((r) => r.server_session_ids.length > 1).length;
288
+ if (many) notes.push(`${many} play test window(s) held more than one Studio server session of "${service}": someone else's play test may be mixed in.`);
289
+ return {
290
+ created: new Date().toISOString(),
291
+ kind: 'roblox',
292
+ game: studio.name,
293
+ server: cfg.server,
294
+ service,
295
+ git: gitInfo(cfg.root),
296
+ machine: { ...machineInfo(summary, 'Roblox Studio'), browser: 'Roblox Studio', cpu: os.cpus()[0]?.model || null },
297
+ scenarios: results,
298
+ summary,
299
+ notes,
300
+ };
301
+ }
302
+
303
+ // A quick run plays fewer scenarios than a full baseline: ask the server for just the matching baseline sessions,
304
+ // the server's too, or keep the full baseline (compareRuns notes the mismatch).
305
+ export async function matchingRobloxBaseline(cfg, baseline, candidate, log) {
306
+ if (baseline.kind !== 'roblox') return baseline;
307
+ const key = (s) => JSON.stringify([s.scenario, s.params]);
308
+ const wanted = new Set((candidate.scenarios || []).map(key));
309
+ const have = baseline.scenarios || [];
310
+ const subset = have.filter((s) => wanted.has(key(s)) && s.session_ids?.length);
311
+ if (subset.length === have.length || subset.length !== wanted.size) return baseline;
312
+ try {
313
+ const since = Math.min(...subset.map((s) => s.started)) - 2 * 3600e3;
314
+ const summary = await robloxSummary(cfg, baseline.service, subset.flatMap((s) => s.session_ids), subset.flatMap((s) => s.server_session_ids || []), since, log);
315
+ return summary?.sessions ? { ...baseline, scenarios: subset, summary, name: `${baseline.name} (matching runs)` } : baseline;
316
+ } catch {
317
+ return baseline;
318
+ }
319
+ }