vibedgames 0.6.2 → 0.7.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.
Files changed (140) hide show
  1. package/README.md +14 -9
  2. package/dist/THIRD_PARTY_NOTICES.txt +383 -0
  3. package/dist/chunk-2GL2WJZX.js +172 -0
  4. package/dist/chunk-2QBYTIMH.js +511 -0
  5. package/dist/chunk-34AHIMX7.js +466 -0
  6. package/dist/chunk-6FZPPUQH.js +107 -0
  7. package/dist/chunk-BVVYDSFJ.js +99 -0
  8. package/dist/chunk-CAKBGDCY.js +47 -0
  9. package/dist/chunk-CBKOPVU6.js +1780 -0
  10. package/dist/chunk-CU7UY5YJ.js +1108 -0
  11. package/dist/chunk-CZPKN32Z.js +257 -0
  12. package/dist/chunk-DHEXGWJY.js +111 -0
  13. package/dist/chunk-FL6IFBUF.js +22 -0
  14. package/dist/chunk-FLUXEHMU.js +1360 -0
  15. package/dist/chunk-FNYBZNW2.js +165 -0
  16. package/dist/chunk-G5FRIFA3.js +22 -0
  17. package/dist/chunk-HCMTSR7E.js +69 -0
  18. package/dist/chunk-HKA5LBYW.js +159 -0
  19. package/dist/chunk-I6O4HIDY.js +1063 -0
  20. package/dist/chunk-J6PKNPI2.js +26 -0
  21. package/dist/chunk-JT2AU24K.js +759 -0
  22. package/dist/chunk-MBXCVCC4.js +478 -0
  23. package/dist/chunk-MJQSHP3Y.js +415 -0
  24. package/dist/chunk-MYFLYNPO.js +68 -0
  25. package/dist/chunk-PEUP4MZR.js +59 -0
  26. package/dist/chunk-PHEDW6C7.js +32 -0
  27. package/dist/chunk-PQDBCZRT.js +2017 -0
  28. package/dist/chunk-QGEITHUP.js +395 -0
  29. package/dist/chunk-QIVCBUYD.js +273 -0
  30. package/dist/chunk-RYFO3ZPO.js +71 -0
  31. package/dist/chunk-RZ4DIJQW.js +68 -0
  32. package/dist/chunk-SAANBZ25.js +118 -0
  33. package/dist/chunk-VFFOT7KD.js +2980 -0
  34. package/dist/chunk-Y552BNFZ.js +41 -0
  35. package/dist/chunk-Z4Z24FWO.js +39 -0
  36. package/dist/chunk-ZI6PKVXG.js +64 -0
  37. package/dist/chunk-ZYCSYJWX.js +87 -0
  38. package/dist/index.js +67 -60
  39. package/package.json +13 -16
  40. package/templates/none/_gitignore +3 -0
  41. package/templates/none/index.html +29 -0
  42. package/templates/none/package.json +16 -0
  43. package/templates/none/src/main.ts +16 -0
  44. package/templates/none/tsconfig.json +18 -0
  45. package/templates/none/vite.config.ts +8 -0
  46. package/templates/phaser/_gitignore +3 -0
  47. package/templates/phaser/index.html +24 -0
  48. package/templates/phaser/package.json +19 -0
  49. package/templates/phaser/src/main.ts +16 -0
  50. package/templates/phaser/src/scenes/game-scene.ts +65 -0
  51. package/templates/phaser/tsconfig.json +18 -0
  52. package/templates/phaser/vite.config.ts +8 -0
  53. package/templates/react-r3f/_gitignore +3 -0
  54. package/templates/react-r3f/index.html +24 -0
  55. package/templates/react-r3f/package.json +27 -0
  56. package/templates/react-r3f/src/app.tsx +33 -0
  57. package/templates/react-r3f/src/main.tsx +15 -0
  58. package/templates/react-r3f/tsconfig.json +19 -0
  59. package/templates/react-r3f/vite.config.ts +10 -0
  60. package/templates/threejs/_gitignore +3 -0
  61. package/templates/threejs/index.html +36 -0
  62. package/templates/threejs/package.json +20 -0
  63. package/templates/threejs/src/main.ts +44 -0
  64. package/templates/threejs/tsconfig.json +18 -0
  65. package/templates/threejs/vite.config.ts +8 -0
  66. package/dist/commands/completions.d.ts +0 -7
  67. package/dist/commands/completions.js +0 -145
  68. package/dist/commands/credits.d.ts +0 -10
  69. package/dist/commands/credits.js +0 -136
  70. package/dist/commands/deploy.d.ts +0 -26
  71. package/dist/commands/deploy.js +0 -257
  72. package/dist/commands/factory.d.ts +0 -3
  73. package/dist/commands/factory.js +0 -73
  74. package/dist/commands/fork.d.ts +0 -29
  75. package/dist/commands/fork.js +0 -124
  76. package/dist/commands/generate.d.ts +0 -1
  77. package/dist/commands/generate.js +0 -565
  78. package/dist/commands/init.d.ts +0 -20
  79. package/dist/commands/init.js +0 -105
  80. package/dist/commands/login.d.ts +0 -1
  81. package/dist/commands/login.js +0 -45
  82. package/dist/commands/logout.d.ts +0 -1
  83. package/dist/commands/logout.js +0 -13
  84. package/dist/commands/new.d.ts +0 -26
  85. package/dist/commands/new.js +0 -318
  86. package/dist/commands/playtest-run.d.ts +0 -66
  87. package/dist/commands/playtest-run.js +0 -268
  88. package/dist/commands/playtest.d.ts +0 -76
  89. package/dist/commands/playtest.js +0 -372
  90. package/dist/commands/update.d.ts +0 -13
  91. package/dist/commands/update.js +0 -82
  92. package/dist/commands/whoami.d.ts +0 -10
  93. package/dist/commands/whoami.js +0 -44
  94. package/dist/index.d.ts +0 -2
  95. package/dist/lib/api.d.ts +0 -18
  96. package/dist/lib/api.js +0 -27
  97. package/dist/lib/archive.d.ts +0 -17
  98. package/dist/lib/archive.js +0 -228
  99. package/dist/lib/codex.d.ts +0 -117
  100. package/dist/lib/codex.js +0 -426
  101. package/dist/lib/config-file.d.ts +0 -16
  102. package/dist/lib/config-file.js +0 -54
  103. package/dist/lib/config.d.ts +0 -11
  104. package/dist/lib/config.js +0 -54
  105. package/dist/lib/manifest.d.ts +0 -10
  106. package/dist/lib/manifest.js +0 -91
  107. package/dist/lib/media-args.d.ts +0 -30
  108. package/dist/lib/media-args.js +0 -219
  109. package/dist/lib/media-download.d.ts +0 -37
  110. package/dist/lib/media-download.js +0 -268
  111. package/dist/lib/media-poll.d.ts +0 -18
  112. package/dist/lib/media-poll.js +0 -86
  113. package/dist/lib/media-upload.d.ts +0 -12
  114. package/dist/lib/media-upload.js +0 -52
  115. package/dist/lib/output.d.ts +0 -68
  116. package/dist/lib/output.js +0 -102
  117. package/dist/lib/package-manager.d.ts +0 -25
  118. package/dist/lib/package-manager.js +0 -77
  119. package/dist/lib/playtest/agent.d.ts +0 -192
  120. package/dist/lib/playtest/agent.js +0 -652
  121. package/dist/lib/playtest/browser.d.ts +0 -109
  122. package/dist/lib/playtest/browser.js +0 -219
  123. package/dist/lib/playtest/controls.d.ts +0 -47
  124. package/dist/lib/playtest/controls.js +0 -218
  125. package/dist/lib/playtest/errors.d.ts +0 -9
  126. package/dist/lib/playtest/errors.js +0 -12
  127. package/dist/lib/playtest/keys.d.ts +0 -41
  128. package/dist/lib/playtest/keys.js +0 -157
  129. package/dist/lib/playtest/run.d.ts +0 -195
  130. package/dist/lib/playtest/run.js +0 -409
  131. package/dist/lib/run.d.ts +0 -19
  132. package/dist/lib/run.js +0 -23
  133. package/dist/lib/strict-args.d.ts +0 -27
  134. package/dist/lib/strict-args.js +0 -78
  135. package/dist/lib/types.d.ts +0 -16
  136. package/dist/lib/types.js +0 -10
  137. package/dist/lib/update.d.ts +0 -10
  138. package/dist/lib/update.js +0 -110
  139. package/dist/lib/upload.d.ts +0 -16
  140. package/dist/lib/upload.js +0 -41
@@ -0,0 +1,1780 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ ensureAgentBrowser,
9
+ projectSessionId,
10
+ resolveGameUrl
11
+ } from "./chunk-CZPKN32Z.js";
12
+ import "./chunk-2QBYTIMH.js";
13
+ import "./chunk-SAANBZ25.js";
14
+ import "./chunk-6FZPPUQH.js";
15
+ import "./chunk-ZI6PKVXG.js";
16
+ import {
17
+ authErrorCode,
18
+ createClient
19
+ } from "./chunk-PQDBCZRT.js";
20
+ import "./chunk-Z4Z24FWO.js";
21
+ import "./chunk-PEUP4MZR.js";
22
+ import {
23
+ outputArgs,
24
+ writeStructured
25
+ } from "./chunk-ZYCSYJWX.js";
26
+ import {
27
+ assertKnownFlags
28
+ } from "./chunk-RZ4DIJQW.js";
29
+ import {
30
+ getBaseUrl,
31
+ getToken
32
+ } from "./chunk-RYFO3ZPO.js";
33
+ import {
34
+ consola
35
+ } from "./chunk-CU7UY5YJ.js";
36
+ import {
37
+ isJsonObject,
38
+ isJsonString
39
+ } from "./chunk-J6PKNPI2.js";
40
+ import {
41
+ defineCommand
42
+ } from "./chunk-MBXCVCC4.js";
43
+ import "./chunk-CAKBGDCY.js";
44
+
45
+ // src/lib/playtest/browser.ts
46
+ import { spawnSync } from "node:child_process";
47
+
48
+ // src/lib/playtest/errors.ts
49
+ var HarnessError = class extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = "HarnessError";
53
+ }
54
+ };
55
+
56
+ // src/lib/playtest/browser.ts
57
+ var READ_FN = `const __botRead = () => {
58
+ const d = window.__GAME_DIAGNOSTICS__, p = (d && d.player) || {};
59
+ return { x: p.x ?? 0, y: p.y ?? 0, z: p.z ?? 0, frame: (d && d.frame) ?? 0, score: (d && d.score) ?? 0, complete: !!(d && d.complete) };
60
+ };
61
+ const __botDist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);`;
62
+ var CONTRACT_READY = "window.__GAME_DIAGNOSTICS__ !== undefined && window.__GAME_TEST_HOOKS__ !== undefined";
63
+ var num = (value) => Number.isFinite(value) ? Number(value) : 0;
64
+ var GameBrowser = class {
65
+ bin;
66
+ session;
67
+ constructor(bin, session) {
68
+ this.bin = bin;
69
+ this.session = session;
70
+ }
71
+ /** Run one agent-browser command in this session. */
72
+ run(args) {
73
+ const res = spawnSync(this.bin, ["--session", this.session, ...args], {
74
+ encoding: "utf-8",
75
+ timeout: 12e4
76
+ });
77
+ if (res.error) {
78
+ throw new HarnessError(`couldn't run the playtest browser (${res.error.message}).`);
79
+ }
80
+ return { status: res.status ?? 1, stderr: res.stderr ?? "", stdout: res.stdout ?? "" };
81
+ }
82
+ /**
83
+ * Read the payload of a `--json` command. agent-browser wraps every JSON
84
+ * response as `{ success, data, error }`, with the command's payload under
85
+ * `data` — `data.result` for `eval`, `data.messages` for `console`.
86
+ * Verified against agent-browser 0.34. A shape this doesn't recognize is a
87
+ * harness failure, not something to guess around.
88
+ */
89
+ payload(args, key) {
90
+ const { status, stdout, stderr } = this.run([...args, "--json"]);
91
+ const text = stdout.trim();
92
+ if (status !== 0) {
93
+ throw new HarnessError(`\`${args[0]}\` failed: ${stderr.trim() || text}`);
94
+ }
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(text);
98
+ } catch {
99
+ throw new HarnessError(`\`${args[0]} --json\` did not return JSON: ${text.slice(0, 200)}`);
100
+ }
101
+ if (!isJsonObject(parsed)) {
102
+ throw new HarnessError(`unexpected response for \`${args[0]}\`: ${text.slice(0, 200)}`);
103
+ }
104
+ if (parsed.success === false) {
105
+ throw new HarnessError(`\`${args[0]}\` failed: ${JSON.stringify(parsed.error)}`);
106
+ }
107
+ const { data } = parsed;
108
+ if (!isJsonObject(data) || !(key in data)) {
109
+ throw new HarnessError(
110
+ `unexpected agent-browser response for \`${args[0]}\` (no data.${key}): ${text.slice(0, 200)}`
111
+ );
112
+ }
113
+ return data[key] ?? null;
114
+ }
115
+ evaluate(expression) {
116
+ return this.payload(["eval", expression], "result");
117
+ }
118
+ /**
119
+ * Navigate and wait for the diagnostics contract. Logs are cleared BEFORE
120
+ * navigating so boot errors belong to this run. Waits for the CONTRACT,
121
+ * not for frames: most games boot into a menu where the loop hasn't
122
+ * started, so frames only advance once setState('active-play') has run.
123
+ */
124
+ boot(url, headed, whenAbsent) {
125
+ this.run(["console", "--clear"]);
126
+ this.run(["errors", "--clear"]);
127
+ const open = this.run(["open", url, ...headed ? ["--headed"] : []]);
128
+ if (open.status !== 0) {
129
+ throw new HarnessError(`couldn't open the game: ${open.stderr.trim() || open.stdout.trim()}`);
130
+ }
131
+ if (this.run(["wait", "--fn", CONTRACT_READY]).status !== 0) {
132
+ throw new HarnessError(whenAbsent);
133
+ }
134
+ }
135
+ /**
136
+ * Two ways a game can honour a seed: a `seed()` hook that restarts the run,
137
+ * or a `?seed=` boot param for games whose scene is single-start. Calling
138
+ * an absent hook would leave the run unseeded while the report still
139
+ * claimed the seed, so detect which one this game implements.
140
+ */
141
+ applySeed(seed, headed) {
142
+ const probe = this.evaluate(
143
+ "({ hasSeedHook: typeof window.__GAME_TEST_HOOKS__?.seed === 'function', href: location.href })"
144
+ );
145
+ if (isJsonObject(probe) && probe.hasSeedHook === true) {
146
+ return "hook";
147
+ }
148
+ const href = isJsonObject(probe) ? probe.href : void 0;
149
+ if (!isJsonString(href)) {
150
+ throw new HarnessError("couldn't read location.href to apply the seed.");
151
+ }
152
+ const url = new URL(href);
153
+ url.searchParams.set("seed", String(seed));
154
+ this.boot(
155
+ url.toString(),
156
+ headed,
157
+ "the game stopped publishing diagnostics after the seeded reload."
158
+ );
159
+ return "boot-param";
160
+ }
161
+ /** Open the game, seed it, start a run and wait for the loop to be live. */
162
+ launch({ url, seed, headed }) {
163
+ this.boot(
164
+ url,
165
+ headed,
166
+ "the game never published window.__GAME_DIAGNOSTICS__ / window.__GAME_TEST_HOOKS__. Either it crashed on boot, or it doesn't implement the diagnostics contract (see the playtest skill's references/autonomous-playtest.md)."
167
+ );
168
+ const seedApplied = this.applySeed(seed, headed);
169
+ const ack = this.evaluate(
170
+ `(async () => { const h = window.__GAME_TEST_HOOKS__; h.seed?.(${seed}); const ack = await h.setState?.('active-play'); window.__BOT_F0__ = h && window.__GAME_DIAGNOSTICS__.frame; return ack === undefined ? null : ack; })()`
171
+ );
172
+ if (ack !== null && (!isJsonObject(ack) || ack.state !== "active-play")) {
173
+ throw new HarnessError(
174
+ `setState('active-play') acknowledged ${JSON.stringify(ack)} instead of { state: 'active-play' } \u2014 the hook applied a different state or is a no-op.`
175
+ );
176
+ }
177
+ const live = this.run([
178
+ "wait",
179
+ "--fn",
180
+ "(window.__GAME_DIAGNOSTICS__?.frame ?? 0) > 10 && window.__GAME_DIAGNOSTICS__.frame !== window.__BOT_F0__"
181
+ ]);
182
+ if (live.status !== 0) {
183
+ throw new HarnessError(
184
+ "diagnostics are published but the loop never advanced after seed()/setState('active-play') \u2014 check they aren't no-ops."
185
+ );
186
+ }
187
+ const sample = this.evaluate(`(() => { ${READ_FN} return __botRead(); })()`);
188
+ const before = isJsonObject(sample) ? { complete: sample.complete === true, frame: num(sample.frame), score: num(sample.score) } : { complete: false, frame: 0, score: 0 };
189
+ const manifest = this.evaluate(
190
+ "(() => { try { return JSON.parse(JSON.stringify(window.__GAME_PLAYTEST__ ?? null, (key, value) => (key === 'reflex' && typeof value === 'function' ? true : value))); } catch { return null; } })()"
191
+ );
192
+ return { before, manifest, seedApplied };
193
+ }
194
+ /** Evaluate the injected agent's source in the page. */
195
+ inject(source) {
196
+ this.evaluate(source);
197
+ }
198
+ /** Whether the agent has finished, and why if it stopped early. Null if the page lost it. */
199
+ agentStatus() {
200
+ const status = this.evaluate(
201
+ "(() => { const a = window.__PLAYTEST_AGENT__; return a ? { done: a.done === true, error: a.error ?? null } : null; })()"
202
+ );
203
+ if (!isJsonObject(status)) {
204
+ return null;
205
+ }
206
+ return { done: status.done === true, error: isJsonString(status.error) ? status.error : null };
207
+ }
208
+ /** The agent's published result, as JSON. */
209
+ agentResult() {
210
+ return this.evaluate(
211
+ "(() => { try { return JSON.parse(JSON.stringify(window.__PLAYTEST_AGENT__ ?? null)); } catch { return null; } })()"
212
+ );
213
+ }
214
+ /**
215
+ * Best-effort stop on the failure path: raw spawn, no throw. The agent
216
+ * releases whatever it holds and cancels its frame loop.
217
+ */
218
+ stopAgent() {
219
+ spawnSync(
220
+ this.bin,
221
+ [
222
+ "--session",
223
+ this.session,
224
+ "eval",
225
+ "(() => { window.__PLAYTEST_AGENT__?.stop?.(); return true; })()"
226
+ ],
227
+ { encoding: "utf-8", timeout: 3e4 }
228
+ );
229
+ }
230
+ /** Console messages at error level — `console` returns every level. */
231
+ consoleErrors() {
232
+ const entries = this.payload(["console"], "messages");
233
+ if (!Array.isArray(entries)) {
234
+ throw new HarnessError("`console` returned a non-array `messages`.");
235
+ }
236
+ return entries.filter((entry) => isJsonObject(entry) && entry.type === "error").map(
237
+ (entry) => isJsonObject(entry) && isJsonString(entry.text) ? entry.text : JSON.stringify(entry)
238
+ );
239
+ }
240
+ /** Uncaught page errors. */
241
+ pageErrors() {
242
+ const errors = this.payload(["errors"], "errors");
243
+ if (!Array.isArray(errors)) {
244
+ throw new HarnessError("`errors` returned a non-array `errors`.");
245
+ }
246
+ return errors;
247
+ }
248
+ /**
249
+ * Renderer string of the game's own WebGL context, so a SwiftShader run
250
+ * can't pass as performance evidence.
251
+ */
252
+ gpuInfo() {
253
+ const info = this.evaluate(
254
+ `(() => {
255
+ const canvas = document.querySelector("canvas");
256
+ let gl = null;
257
+ try { gl = canvas?.getContext("webgl2") ?? canvas?.getContext("webgl") ?? null; } catch { gl = null; }
258
+ if (!gl) { return null; }
259
+ const debug = gl.getExtension("WEBGL_debug_renderer_info");
260
+ return {
261
+ renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER),
262
+ vendor: debug ? gl.getParameter(debug.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR),
263
+ };
264
+ })()`
265
+ );
266
+ if (!isJsonObject(info) || !isJsonString(info.renderer)) {
267
+ return { renderer: null, softwareRendered: null, vendor: null };
268
+ }
269
+ return {
270
+ renderer: info.renderer,
271
+ softwareRendered: /swiftshader|llvmpipe|software|basic render/iu.test(info.renderer),
272
+ vendor: isJsonString(info.vendor) ? info.vendor : null
273
+ };
274
+ }
275
+ close() {
276
+ this.run(["close"]);
277
+ }
278
+ };
279
+
280
+ // src/lib/playtest/controls.ts
281
+ import { readFileSync } from "node:fs";
282
+
283
+ // src/lib/playtest/keys.ts
284
+ var NAMED_KEYS = /* @__PURE__ */ new Map([
285
+ ["AltLeft", 18],
286
+ ["AltRight", 18],
287
+ ["ArrowDown", 40],
288
+ ["ArrowLeft", 37],
289
+ ["ArrowRight", 39],
290
+ ["ArrowUp", 38],
291
+ ["Backquote", 192],
292
+ ["Backslash", 220],
293
+ ["Backspace", 8],
294
+ ["BracketLeft", 219],
295
+ ["BracketRight", 221],
296
+ ["Comma", 188],
297
+ ["ControlLeft", 17],
298
+ ["ControlRight", 17],
299
+ ["Delete", 46],
300
+ ["Enter", 13],
301
+ ["Equal", 187],
302
+ ["Escape", 27],
303
+ ["Minus", 189],
304
+ ["Period", 190],
305
+ ["Quote", 222],
306
+ ["Semicolon", 186],
307
+ ["ShiftLeft", 16],
308
+ ["ShiftRight", 16],
309
+ ["Slash", 191],
310
+ ["Space", 32],
311
+ ["Tab", 9]
312
+ ]);
313
+ var NAMED_VALUES = /* @__PURE__ */ new Map([
314
+ ["AltLeft", "Alt"],
315
+ ["AltRight", "Alt"],
316
+ ["Backquote", "`"],
317
+ ["Backslash", "\\"],
318
+ ["BracketLeft", "["],
319
+ ["BracketRight", "]"],
320
+ ["Comma", ","],
321
+ ["ControlLeft", "Control"],
322
+ ["ControlRight", "Control"],
323
+ ["Equal", "="],
324
+ ["Minus", "-"],
325
+ ["Period", "."],
326
+ ["Quote", "'"],
327
+ ["Semicolon", ";"],
328
+ ["ShiftLeft", "Shift"],
329
+ ["ShiftRight", "Shift"],
330
+ ["Slash", "/"],
331
+ ["Space", " "]
332
+ ]);
333
+ var SHIFTED = /* @__PURE__ */ new Map([
334
+ ["Backquote", "~"],
335
+ ["Backslash", "|"],
336
+ ["BracketLeft", "{"],
337
+ ["BracketRight", "}"],
338
+ ["Comma", "<"],
339
+ ["Digit0", ")"],
340
+ ["Digit1", "!"],
341
+ ["Digit2", "@"],
342
+ ["Digit3", "#"],
343
+ ["Digit4", "$"],
344
+ ["Digit5", "%"],
345
+ ["Digit6", "^"],
346
+ ["Digit7", "&"],
347
+ ["Digit8", "*"],
348
+ ["Digit9", "("],
349
+ ["Equal", "+"],
350
+ ["Minus", "_"],
351
+ ["Period", ">"],
352
+ ["Quote", '"'],
353
+ ["Semicolon", ":"],
354
+ ["Slash", "?"]
355
+ ]);
356
+ var SUPPORTED_KEYS_HINT = `Key<A-Z>, Digit<0-9>, and ${[...NAMED_KEYS.keys()].join(", ")}`;
357
+ var shiftedKey = (code, key) => {
358
+ if (/^Key[A-Z]$/u.test(code)) {
359
+ return key.toUpperCase();
360
+ }
361
+ return SHIFTED.get(code) ?? key;
362
+ };
363
+ var keyFields = (code) => {
364
+ const letter = /^Key(?<letter>[A-Z])$/u.exec(code)?.groups?.letter;
365
+ if (letter) {
366
+ return [letter.codePointAt(0) ?? 0, letter.toLowerCase()];
367
+ }
368
+ const digit = /^Digit(?<digit>[0-9])$/u.exec(code)?.groups?.digit;
369
+ if (digit) {
370
+ return [48 + Number(digit), digit];
371
+ }
372
+ const keyCode = NAMED_KEYS.get(code);
373
+ if (keyCode !== void 0) {
374
+ return [keyCode, NAMED_VALUES.get(code) ?? code];
375
+ }
376
+ throw new HarnessError(`unsupported key code "${code}". Supported: ${SUPPORTED_KEYS_HINT}.`);
377
+ };
378
+ var modifiersOf = (codes) => ({
379
+ altKey: codes.some((c) => c === "AltLeft" || c === "AltRight"),
380
+ ctrlKey: codes.some((c) => c === "ControlLeft" || c === "ControlRight"),
381
+ shiftKey: codes.some((c) => c === "ShiftLeft" || c === "ShiftRight")
382
+ });
383
+ var keyInitsFor = (codes) => {
384
+ const modifiers = modifiersOf(codes);
385
+ return codes.map((code) => {
386
+ const [keyCode, key] = keyFields(code);
387
+ return {
388
+ bubbles: true,
389
+ code,
390
+ key: modifiers.shiftKey ? shiftedKey(code, key) : key,
391
+ keyCode,
392
+ which: keyCode,
393
+ ...modifiers
394
+ };
395
+ });
396
+ };
397
+ var keyTable = () => {
398
+ const codes = [
399
+ ...Array.from({ length: 26 }, (_, i) => `Key${String.fromCodePoint(65 + i)}`),
400
+ ...Array.from({ length: 10 }, (_, i) => `Digit${i}`),
401
+ ...NAMED_KEYS.keys()
402
+ ];
403
+ const table = {};
404
+ for (const code of codes) {
405
+ const [init] = keyInitsFor([code]);
406
+ if (init) {
407
+ table[code] = init;
408
+ }
409
+ }
410
+ return table;
411
+ };
412
+
413
+ // src/lib/playtest/controls.ts
414
+ var DEFAULT_GOAL = "Play the game well: stay alive, keep moving through the level, raise the score, and avoid whatever the state marks as hazards, enemies or damage.";
415
+ var NONE = {
416
+ description: "Hold no movement input \u2014 stay still",
417
+ keys: [],
418
+ pointer: null,
419
+ reflex: false
420
+ };
421
+ var move = (description, keys) => ({
422
+ description,
423
+ keys,
424
+ pointer: null,
425
+ reflex: false
426
+ });
427
+ var directions = (up, down, left, right) => ({
428
+ down: move("Move down / backward", [down]),
429
+ down_left: move("Move diagonally down and left", [down, left]),
430
+ down_right: move("Move diagonally down and right", [down, right]),
431
+ left: move("Move left", [left]),
432
+ none: NONE,
433
+ right: move("Move right", [right]),
434
+ up: move("Move up / forward", [up]),
435
+ up_left: move("Move diagonally up and left", [up, left]),
436
+ up_right: move("Move diagonally up and right", [up, right])
437
+ });
438
+ var ACTION_PRESET = {
439
+ action: { description: "press the action key (jump, fire or confirm)", keys: ["Space"] }
440
+ };
441
+ var PRESETS = /* @__PURE__ */ new Map([
442
+ [
443
+ "arrows",
444
+ {
445
+ actions: ACTION_PRESET,
446
+ goal: DEFAULT_GOAL,
447
+ minDisplacement: null,
448
+ move: directions("ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight")
449
+ }
450
+ ],
451
+ [
452
+ "wasd",
453
+ {
454
+ actions: ACTION_PRESET,
455
+ goal: DEFAULT_GOAL,
456
+ minDisplacement: null,
457
+ move: directions("KeyW", "KeyS", "KeyA", "KeyD")
458
+ }
459
+ ]
460
+ ]);
461
+ var DEFAULT_PRESET = "wasd";
462
+ var PRESET_NAMES = [...PRESETS.keys()];
463
+ var fail = (message) => {
464
+ throw new HarnessError(message);
465
+ };
466
+ var nonEmptyString = (value) => isJsonString(value) && value.trim() !== "";
467
+ var readKeys = (value, where) => {
468
+ if (value === void 0) {
469
+ return [];
470
+ }
471
+ if (!Array.isArray(value) || !value.every(isJsonString)) {
472
+ fail(`${where}: \`keys\` must be an array of KeyboardEvent codes.`);
473
+ }
474
+ for (const code of value) {
475
+ try {
476
+ keyFields(code);
477
+ } catch (error) {
478
+ fail(`${where}: ${error instanceof Error ? error.message : String(error)}`);
479
+ }
480
+ }
481
+ return value;
482
+ };
483
+ var readPointer = (value, where) => {
484
+ if (value === void 0) {
485
+ return null;
486
+ }
487
+ if (!isJsonObject(value)) {
488
+ fail(`${where}: \`pointer\` must be an object { x, y, down? }.`);
489
+ }
490
+ const { x, y, down } = value;
491
+ for (const [name, axis] of [
492
+ ["x", x],
493
+ ["y", y]
494
+ ]) {
495
+ if (!Number.isFinite(axis) || Number(axis) < 0 || Number(axis) > 1) {
496
+ fail(`${where}: \`pointer.${name}\` must be a viewport fraction between 0 and 1.`);
497
+ }
498
+ }
499
+ if (down !== void 0 && down !== true && down !== false) {
500
+ fail(`${where}: \`pointer.down\` must be a boolean.`);
501
+ }
502
+ return { down: down === true, x: Number(x), y: Number(y) };
503
+ };
504
+ var readDescription = (option, where) => {
505
+ if (!nonEmptyString(option.description)) {
506
+ fail(`${where} needs a non-empty \`description\` \u2014 that is what the model decides from.`);
507
+ }
508
+ return option.description;
509
+ };
510
+ var readMoveOption = (value, where) => {
511
+ if (!isJsonObject(value)) {
512
+ fail(`${where} must be an object with a \`description\`.`);
513
+ }
514
+ return {
515
+ description: readDescription(value, where),
516
+ keys: readKeys(value.keys, where),
517
+ pointer: readPointer(value.pointer, where),
518
+ reflex: value.reflex === true
519
+ };
520
+ };
521
+ var readActionOption = (value, where) => {
522
+ if (!isJsonObject(value)) {
523
+ fail(`${where} must be an object with a \`description\`.`);
524
+ }
525
+ if (value.pointer !== void 0) {
526
+ fail(
527
+ `${where}: actions are keys only. A pointer belongs in a \`move\` option (aim-and-thrust games put \`down: true\` there).`
528
+ );
529
+ }
530
+ const keys = readKeys(value.keys, where);
531
+ if (keys.length === 0) {
532
+ fail(`${where} needs a non-empty \`keys\` array.`);
533
+ }
534
+ return { description: readDescription(value, where), keys };
535
+ };
536
+ var parseControls = (raw, source) => {
537
+ if (!isJsonObject(raw)) {
538
+ fail(`${source} must be a JSON object with \`move\` (and optionally \`actions\`, \`goal\`).`);
539
+ }
540
+ if (raw.goal !== void 0 && !nonEmptyString(raw.goal)) {
541
+ fail(`${source}: \`goal\` must be a non-empty string.`);
542
+ }
543
+ if (!isJsonObject(raw.move) || Object.keys(raw.move).length === 0) {
544
+ fail(
545
+ `${source}: \`move\` must map at least one option label to { description, keys | pointer }.`
546
+ );
547
+ }
548
+ const moves = {};
549
+ for (const [label, option] of Object.entries(raw.move)) {
550
+ moves[label] = readMoveOption(option, `${source} move.${label}`);
551
+ }
552
+ if (!Object.values(moves).some(
553
+ (option) => option.keys.length > 0 || option.pointer || option.reflex
554
+ )) {
555
+ fail(`${source}: no \`move\` option holds any input, so the playtester could never move.`);
556
+ }
557
+ if (Object.keys(moves).length < 2 && !Object.hasOwn(moves, "none")) {
558
+ moves.none = NONE;
559
+ }
560
+ const actions = {};
561
+ if (raw.actions !== void 0) {
562
+ if (!isJsonObject(raw.actions)) {
563
+ fail(`${source}: \`actions\` must map option labels to { description, keys }.`);
564
+ }
565
+ for (const [label, option] of Object.entries(raw.actions)) {
566
+ actions[label] = readActionOption(option, `${source} actions.${label}`);
567
+ }
568
+ }
569
+ const { minDisplacement } = raw;
570
+ if (minDisplacement !== void 0 && (!Number.isFinite(minDisplacement) || Number(minDisplacement) <= 0)) {
571
+ fail(`${source}: \`minDisplacement\` must be a positive number, in the units of player.x/y.`);
572
+ }
573
+ return {
574
+ actions,
575
+ goal: nonEmptyString(raw.goal) ? raw.goal : DEFAULT_GOAL,
576
+ minDisplacement: minDisplacement === void 0 ? null : Number(minDisplacement),
577
+ move: moves
578
+ };
579
+ };
580
+ var readControlsArg = (value) => {
581
+ const preset = PRESETS.get(value);
582
+ if (preset) {
583
+ return preset;
584
+ }
585
+ let text;
586
+ try {
587
+ text = readFileSync(value, "utf-8");
588
+ } catch {
589
+ fail(
590
+ `couldn't read --controls ${value} (not a preset \u2014 those are ${PRESET_NAMES.join(", ")} \u2014 and not a readable file).`
591
+ );
592
+ }
593
+ let raw;
594
+ try {
595
+ raw = JSON.parse(text);
596
+ } catch (error) {
597
+ fail(
598
+ `--controls ${value} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}`
599
+ );
600
+ }
601
+ return parseControls(raw, `--controls ${value}`);
602
+ };
603
+
604
+ // src/lib/playtest/run.ts
605
+ import { setTimeout as delay } from "node:timers/promises";
606
+
607
+ // src/lib/playtest/agent.ts
608
+ var browserEnv = () => {
609
+ const read = () => {
610
+ const d = window.__GAME_DIAGNOSTICS__;
611
+ const p = d?.player ?? {};
612
+ return {
613
+ complete: d?.complete === true,
614
+ frame: d?.frame ?? 0,
615
+ score: d?.score ?? 0,
616
+ x: p.x ?? 0,
617
+ y: p.y ?? 0,
618
+ z: p.z ?? 0
619
+ };
620
+ };
621
+ const pointerTarget = (cx, cy) => document.elementFromPoint(cx, cy) ?? document.querySelector("canvas") ?? window;
622
+ const mouseType = (type) => {
623
+ if (type === "pointermove") {
624
+ return "mousemove";
625
+ }
626
+ return type === "pointerdown" ? "mousedown" : "mouseup";
627
+ };
628
+ let lastPointer = null;
629
+ const isFunction = (value) => Object.prototype.toString.call(value) === "[object Function]";
630
+ return {
631
+ caf: (id) => window.cancelAnimationFrame(id),
632
+ delay: (ms) => (
633
+ // oxlint-disable-next-line promise/avoid-new -- the page has no timers/promises; wrapping setTimeout is the only way to await a delay there
634
+ new Promise((resolve) => {
635
+ window.setTimeout(resolve, ms);
636
+ })
637
+ ),
638
+ dispatchKey: (type, init) => {
639
+ const target = document.activeElement ?? document.body ?? window;
640
+ target.dispatchEvent(new KeyboardEvent(type, init));
641
+ },
642
+ dispatchPointer: (pointer, type) => {
643
+ const cx = Math.round(window.innerWidth * pointer.x);
644
+ const cy = Math.round(window.innerHeight * pointer.y);
645
+ const pressed = type === "pointerdown" || type === "pointermove" && pointer.down;
646
+ const moved = type === "pointermove" && lastPointer !== null;
647
+ const movementX = moved && lastPointer ? cx - lastPointer.x : 0;
648
+ const movementY = moved && lastPointer ? cy - lastPointer.y : 0;
649
+ if (type === "pointermove") {
650
+ lastPointer = { x: cx, y: cy };
651
+ }
652
+ const init = {
653
+ bubbles: true,
654
+ button: 0,
655
+ buttons: pressed ? 1 : 0,
656
+ cancelable: true,
657
+ clientX: cx,
658
+ clientY: cy,
659
+ composed: true,
660
+ isPrimary: true,
661
+ movementX,
662
+ movementY,
663
+ pointerId: 1,
664
+ pointerType: "mouse",
665
+ screenX: cx,
666
+ screenY: cy
667
+ };
668
+ const target = pointerTarget(cx, cy);
669
+ target.dispatchEvent(new PointerEvent(type, init));
670
+ target.dispatchEvent(new MouseEvent(mouseType(type), init));
671
+ },
672
+ fetch: (url, init) => window.fetch(url, init),
673
+ live: () => window.__GAME_DIAGNOSTICS__ ?? null,
674
+ now: () => Date.now(),
675
+ publish: (result) => {
676
+ window.__PLAYTEST_AGENT__ = result;
677
+ },
678
+ raf: (frame) => window.requestAnimationFrame(frame),
679
+ read,
680
+ reflexFor: (label) => {
681
+ const reflex = window.__GAME_PLAYTEST__?.move?.[label]?.reflex;
682
+ return isFunction(reflex) ? reflex : null;
683
+ },
684
+ snapshot: () => {
685
+ try {
686
+ return JSON.parse(JSON.stringify(window.__GAME_DIAGNOSTICS__ ?? null));
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+ };
692
+ };
693
+ var inPageAgent = (config, env) => {
694
+ const isObject = (value) => Object(value) === value && !Array.isArray(value);
695
+ const round2 = (value) => Number(value.toFixed(2));
696
+ const started = env.now();
697
+ const usage = {
698
+ calls: 0,
699
+ inputTokens: 0,
700
+ maxDecisionMs: 0,
701
+ outputTokens: 0,
702
+ totalDecisionMs: 0
703
+ };
704
+ let stopped = false;
705
+ let rafId = 0;
706
+ let heldKeys = [];
707
+ let heldPointer = null;
708
+ const samePointer = (a, b) => a === b || a !== null && b !== null && a.x === b.x && a.y === b.y && a.down === b.down;
709
+ const hold = (next) => {
710
+ if (!samePointer(heldPointer, next.pointer)) {
711
+ const wasDown = heldPointer?.down === true;
712
+ const staysDown = wasDown && next.pointer?.down === true;
713
+ if (heldPointer && wasDown && !staysDown) {
714
+ env.dispatchPointer(heldPointer, "pointerup");
715
+ }
716
+ if (next.pointer) {
717
+ env.dispatchPointer(next.pointer, "pointermove");
718
+ if (next.pointer.down && !staysDown) {
719
+ env.dispatchPointer(next.pointer, "pointerdown");
720
+ }
721
+ }
722
+ heldPointer = next.pointer;
723
+ }
724
+ const wanted = new Set(next.keys.map((init) => init.code));
725
+ const have = new Set(heldKeys.map((init) => init.code));
726
+ for (const init of heldKeys) {
727
+ if (!wanted.has(init.code)) {
728
+ env.dispatchKey("keyup", init);
729
+ }
730
+ }
731
+ for (const init of next.keys) {
732
+ if (!have.has(init.code)) {
733
+ env.dispatchKey("keydown", init);
734
+ }
735
+ }
736
+ heldKeys = next.keys;
737
+ };
738
+ const release = (inits) => {
739
+ const codes = new Set(inits.map((init) => init.code));
740
+ for (const init of heldKeys) {
741
+ if (codes.has(init.code)) {
742
+ env.dispatchKey("keyup", init);
743
+ }
744
+ }
745
+ heldKeys = heldKeys.filter((init) => !codes.has(init.code));
746
+ };
747
+ const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
748
+ let trackStart = env.read();
749
+ let trackLast = trackStart;
750
+ let trackPath = 0;
751
+ let trackPeak = 0;
752
+ let trackScore = trackStart.score;
753
+ const sample = () => {
754
+ const c = env.read();
755
+ trackPath += dist(c, trackLast);
756
+ trackPeak = Math.max(trackPeak, dist(c, trackStart));
757
+ trackLast = c;
758
+ trackScore = Math.max(trackScore, c.score);
759
+ };
760
+ const flush = () => {
761
+ sample();
762
+ const c = trackLast;
763
+ const measured = {
764
+ complete: c.complete,
765
+ frame: c.frame,
766
+ frameBefore: trackStart.frame,
767
+ path: Number(trackPath.toFixed(3)),
768
+ peak: Number(Math.max(trackPeak, dist(c, trackStart)).toFixed(3)),
769
+ score: Math.max(trackScore, c.score),
770
+ scoreBefore: trackStart.score,
771
+ x: c.x,
772
+ y: c.y,
773
+ z: c.z
774
+ };
775
+ trackStart = c;
776
+ trackPath = 0;
777
+ trackPeak = 0;
778
+ trackScore = c.score;
779
+ return measured;
780
+ };
781
+ const PROGRESS_LEVELS = [
782
+ "No progress: the player is not moving towards the goal, or is losing (dying, falling behind)",
783
+ "Barely started: moving, but the goal is far off or the player is in trouble",
784
+ "Halfway: clear progress towards the goal and out of immediate danger",
785
+ "Nearly there: the goal is close, or the score is rising steadily",
786
+ "Achieved, or about to be"
787
+ ];
788
+ let pending = null;
789
+ let blocked = [];
790
+ let stuckRun = 0;
791
+ let idleRun = 0;
792
+ let rested = null;
793
+ const trail = [];
794
+ let lastWindow = null;
795
+ const result = {
796
+ completedAtTick: null,
797
+ done: false,
798
+ error: null,
799
+ records: [],
800
+ stop: () => {
801
+ stopped = true;
802
+ },
803
+ usage,
804
+ wallMs: 0
805
+ };
806
+ env.publish(result);
807
+ const offeredMoves = (tick) => {
808
+ const resting = rested !== null && tick < rested.untilTick ? rested.label : null;
809
+ const criteria = {};
810
+ for (const [label, option] of Object.entries(config.move)) {
811
+ if (!blocked.includes(label) && label !== resting) {
812
+ criteria[label] = option.description;
813
+ }
814
+ }
815
+ if (resting !== null && Object.keys(criteria).length < 2) {
816
+ criteria[resting] = config.move[resting]?.description ?? resting;
817
+ }
818
+ return criteria;
819
+ };
820
+ const questions = (criteria) => {
821
+ const out = {
822
+ move: {
823
+ criteria,
824
+ instructions: "Which movement input should the player hold next to pursue `goal`? Decide from `game` (the live state) and `recent` (what the last inputs achieved). Options that recently produced no movement have been removed.",
825
+ type: "choice"
826
+ },
827
+ progress: {
828
+ criteria: PROGRESS_LEVELS,
829
+ instructions: "How close is the player to achieving `goal` right now, judging from `game` and `recent`?",
830
+ type: "score"
831
+ }
832
+ };
833
+ for (const [label, action] of Object.entries(config.actions)) {
834
+ out[`act:${label}`] = {
835
+ criteria: { false: "Not now", true: "Yes, do it now" },
836
+ instructions: `Given \`game\` and \`goal\`, should the player ${action.description} right now?`,
837
+ type: "noul"
838
+ };
839
+ }
840
+ return out;
841
+ };
842
+ const answerFor = (answers, key) => {
843
+ const answer = answers[key];
844
+ return isObject(answer) ? answer : {};
845
+ };
846
+ const parseDecision = (text, offered) => {
847
+ let body;
848
+ try {
849
+ body = JSON.parse(text);
850
+ } catch {
851
+ throw new Error(`decision response was not JSON: ${text.slice(0, 200)}`);
852
+ }
853
+ const answers = isObject(body) ? body.answers : void 0;
854
+ if (!isObject(answers)) {
855
+ throw new Error(`decision response had no answers: ${text.slice(0, 200)}`);
856
+ }
857
+ const move2 = answerFor(answers, "move");
858
+ const choice = String(move2.choice ?? "");
859
+ if (!Object.hasOwn(offered, choice)) {
860
+ throw new Error(`decision model answered \`move\` outside the offered options: ${choice}`);
861
+ }
862
+ const actions = [];
863
+ const actionProbabilities = {};
864
+ for (const label of Object.keys(config.actions)) {
865
+ const probability = Number(answerFor(answers, `act:${label}`).noul);
866
+ if (!Number.isFinite(probability)) {
867
+ throw new TypeError(`decision model answered \`${label}\` without a probability`);
868
+ }
869
+ actionProbabilities[label] = Number(probability.toFixed(3));
870
+ if (probability >= config.actionThreshold) {
871
+ actions.push(label);
872
+ }
873
+ }
874
+ const usageBody = isObject(body) && isObject(body.usage) ? body.usage : {};
875
+ const confidence = Number(move2.confidence);
876
+ const scored = Number(answerFor(answers, "progress").score);
877
+ const progress = Number.isFinite(scored) ? Number(Math.min(1, Math.max(0, scored / (PROGRESS_LEVELS.length - 1))).toFixed(3)) : null;
878
+ return {
879
+ actionProbabilities,
880
+ actions,
881
+ confidence: Number.isFinite(confidence) ? Number(confidence.toFixed(3)) : null,
882
+ inputTokens: Number(usageBody.input_tokens) || 0,
883
+ move: choice,
884
+ outputTokens: Number(usageBody.output_tokens) || 0,
885
+ progress
886
+ };
887
+ };
888
+ const timeout = async () => {
889
+ await env.delay(config.decisionTimeoutMs);
890
+ throw new Error(`no answer within ${config.decisionTimeoutMs} ms`);
891
+ };
892
+ const decide = async (state) => {
893
+ if (config.pinMove !== null) {
894
+ await env.delay(0);
895
+ return {
896
+ actionProbabilities: {},
897
+ actions: [],
898
+ confidence: null,
899
+ inputTokens: 0,
900
+ move: config.pinMove,
901
+ outputTokens: 0,
902
+ progress: null
903
+ };
904
+ }
905
+ const offered = offeredMoves(state.tick.index);
906
+ const body = JSON.stringify({ model: config.model, questions: questions(offered), state });
907
+ for (let attempt = 0; ; attempt += 1) {
908
+ let response = null;
909
+ let failure = "";
910
+ try {
911
+ response = await Promise.race([
912
+ env.fetch(config.decideUrl, {
913
+ body,
914
+ headers: {
915
+ authorization: `Bearer ${config.token}`,
916
+ "content-type": "application/json"
917
+ },
918
+ method: "POST"
919
+ }),
920
+ timeout()
921
+ ]);
922
+ } catch (error) {
923
+ failure = error instanceof Error ? error.message : String(error);
924
+ }
925
+ if (response?.ok) {
926
+ const text = await response.text();
927
+ return parseDecision(text, offered);
928
+ }
929
+ if (response !== null && response.status !== 429 && response.status < 500) {
930
+ const text = await response.text();
931
+ throw new Error(`decision failed (HTTP ${response.status}): ${text.slice(0, 300)}`);
932
+ }
933
+ const reason = response === null ? failure : `HTTP ${response.status}`;
934
+ if (attempt >= config.decisionRetries) {
935
+ throw new Error(`decision failed after ${attempt + 1} attempts: ${reason}`);
936
+ }
937
+ await env.delay(500 * 2 ** attempt);
938
+ }
939
+ };
940
+ const pointerFrom = (input) => {
941
+ if (!input) {
942
+ return null;
943
+ }
944
+ const x = Number(input.x);
945
+ const y = Number(input.y);
946
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
947
+ return null;
948
+ }
949
+ return {
950
+ down: input.down === true,
951
+ x: Math.min(1, Math.max(0, x)),
952
+ y: Math.min(1, Math.max(0, y))
953
+ };
954
+ };
955
+ const keysFrom = (codes) => {
956
+ const inits = [];
957
+ for (const code of codes ?? []) {
958
+ const init = config.keyTable[code];
959
+ if (init) {
960
+ inits.push(init);
961
+ }
962
+ }
963
+ return inits;
964
+ };
965
+ const withActions = (base, decision) => {
966
+ const keys = [...base];
967
+ const seen = new Set(keys.map((init) => init.code));
968
+ for (const label of decision.actions) {
969
+ for (const init of config.actions[label]?.inits ?? []) {
970
+ if (!seen.has(init.code)) {
971
+ seen.add(init.code);
972
+ keys.push(init);
973
+ }
974
+ }
975
+ }
976
+ return keys;
977
+ };
978
+ const staticInputs = (decision) => {
979
+ const option = config.move[decision.move];
980
+ return { keys: withActions(option?.inits ?? [], decision), pointer: option?.pointer ?? null };
981
+ };
982
+ const runReflex = (current) => {
983
+ if (!current.reflex) {
984
+ return;
985
+ }
986
+ let inputs = null;
987
+ try {
988
+ inputs = current.reflex(env.live());
989
+ } catch {
990
+ inputs = null;
991
+ }
992
+ hold({
993
+ keys: withActions(keysFrom(inputs?.keys), current.decision),
994
+ pointer: pointerFrom(inputs?.pointer)
995
+ });
996
+ if (inputs) {
997
+ current.reflexFrames += 1;
998
+ current.reflexStuck ||= inputs.stuck === true;
999
+ }
1000
+ };
1001
+ const frame = () => {
1002
+ if (stopped) {
1003
+ return;
1004
+ }
1005
+ sample();
1006
+ if (pending) {
1007
+ runReflex(pending);
1008
+ }
1009
+ rafId = env.raf(frame);
1010
+ };
1011
+ const canWithdraw = () => Object.keys(config.move).length - blocked.length - 1 >= 2;
1012
+ const withdrawIfStuck = (move2, stuck, still) => {
1013
+ if (!still) {
1014
+ blocked = [];
1015
+ } else if (stuck && stuckRun >= config.stuckRun && move2 !== "none" && !blocked.includes(move2) && canWithdraw()) {
1016
+ blocked = [...blocked, move2];
1017
+ }
1018
+ };
1019
+ const restIfIdle = (done, still) => {
1020
+ const option = config.move[done.decision.move];
1021
+ const idle = done.reflex === null && option !== void 0 && option.inits.length === 0 && option.pointer === null;
1022
+ idleRun = idle && still ? idleRun + 1 : 0;
1023
+ if (idleRun >= config.idleRun && canWithdraw()) {
1024
+ rested = { label: done.decision.move, untilTick: done.tick + 1 + config.idleRestTicks };
1025
+ idleRun = 0;
1026
+ }
1027
+ };
1028
+ const settle = (done, measured) => {
1029
+ const option = config.move[done.decision.move];
1030
+ const askedToMove = done.reflex ? done.reflexStuck : option !== void 0 && (option.inits.length > 0 || option.pointer?.down === true);
1031
+ const progressed = measured.score > measured.scoreBefore;
1032
+ let stuck = false;
1033
+ if (askedToMove) {
1034
+ stuck = measured.frame > measured.frameBefore && measured.peak < config.motionEpsilon && !progressed;
1035
+ stuckRun = stuck ? stuckRun + 1 : 0;
1036
+ }
1037
+ const still = measured.peak < config.motionEpsilon && !progressed;
1038
+ withdrawIfStuck(done.decision.move, stuck, still);
1039
+ restIfIdle(done, still);
1040
+ trail.push({ x: round2(measured.x), y: round2(measured.y), z: round2(measured.z) });
1041
+ if (trail.length > config.trailLength) {
1042
+ trail.shift();
1043
+ }
1044
+ lastWindow = measured;
1045
+ result.records.push({
1046
+ actionProbabilities: done.decision.actionProbabilities,
1047
+ actions: done.decision.actions,
1048
+ askedToMove,
1049
+ confidence: done.decision.confidence,
1050
+ decisionMs: done.decisionMs,
1051
+ inputTokens: done.decision.inputTokens,
1052
+ move: done.decision.move,
1053
+ outputTokens: done.decision.outputTokens,
1054
+ progress: done.decision.progress,
1055
+ reflexFrames: done.reflexFrames,
1056
+ tick: done.tick,
1057
+ window: measured
1058
+ });
1059
+ };
1060
+ const stateFor = (game, tick) => ({
1061
+ game,
1062
+ goal: config.goal,
1063
+ recent: {
1064
+ blockedMoves: blocked,
1065
+ held: pending ? { actions: pending.decision.actions, move: pending.decision.move } : null,
1066
+ movedLastTick: lastWindow ? lastWindow.peak : null,
1067
+ scoreDeltaLastTick: lastWindow ? lastWindow.score - lastWindow.scoreBefore : null,
1068
+ stuckTicksInARow: stuckRun,
1069
+ trail
1070
+ },
1071
+ tick: { index: tick, of: config.ticks }
1072
+ });
1073
+ const record = (decision, decisionMs) => {
1074
+ usage.calls += 1;
1075
+ usage.inputTokens += decision.inputTokens;
1076
+ usage.outputTokens += decision.outputTokens;
1077
+ usage.totalDecisionMs += decisionMs;
1078
+ usage.maxDecisionMs = Math.max(usage.maxDecisionMs, decisionMs);
1079
+ };
1080
+ const run = async () => {
1081
+ rafId = env.raf(frame);
1082
+ let game = env.snapshot();
1083
+ for (let tick = 0; tick < config.ticks; tick += 1) {
1084
+ if (stopped) {
1085
+ break;
1086
+ }
1087
+ const t0 = env.now();
1088
+ const decision = await decide(stateFor(game, tick));
1089
+ const decisionMs = env.now() - t0;
1090
+ record(decision, decisionMs);
1091
+ if (stopped) {
1092
+ break;
1093
+ }
1094
+ if (pending) {
1095
+ const remaining = config.tickMs - (env.now() - pending.appliedAt);
1096
+ if (remaining > 0) {
1097
+ await env.delay(remaining);
1098
+ }
1099
+ }
1100
+ const reflex = env.reflexFor(decision.move);
1101
+ release(decision.actions.flatMap((label) => config.actions[label]?.inits ?? []));
1102
+ if (!reflex) {
1103
+ hold(staticInputs(decision));
1104
+ }
1105
+ const measured = flush();
1106
+ if (pending) {
1107
+ settle(pending, measured);
1108
+ }
1109
+ pending = {
1110
+ appliedAt: env.now(),
1111
+ decision,
1112
+ decisionMs,
1113
+ reflex,
1114
+ reflexFrames: 0,
1115
+ reflexStuck: false,
1116
+ tick
1117
+ };
1118
+ game = env.snapshot();
1119
+ if (measured.complete) {
1120
+ result.completedAtTick = Math.max(0, tick - 1);
1121
+ pending = null;
1122
+ break;
1123
+ }
1124
+ }
1125
+ if (pending && !stopped) {
1126
+ await env.delay(Math.max(config.tickMs, config.finalHoldMs));
1127
+ const measured = flush();
1128
+ settle(pending, measured);
1129
+ if (measured.complete && result.completedAtTick === null) {
1130
+ result.completedAtTick = pending.tick;
1131
+ }
1132
+ pending = null;
1133
+ }
1134
+ };
1135
+ const finish = (error) => {
1136
+ stopped = true;
1137
+ env.caf(rafId);
1138
+ hold({ keys: [], pointer: null });
1139
+ result.error = error;
1140
+ result.wallMs = env.now() - started;
1141
+ result.done = true;
1142
+ };
1143
+ const main = async () => {
1144
+ try {
1145
+ await run();
1146
+ finish(null);
1147
+ } catch (error) {
1148
+ finish(error instanceof Error ? error.message : String(error));
1149
+ }
1150
+ };
1151
+ void main();
1152
+ return result;
1153
+ };
1154
+
1155
+ // src/lib/playtest/run.ts
1156
+ var THRESHOLDS = {
1157
+ /** Mean `move` confidence below which the state is probably too thin to decide from. */
1158
+ confidence: 0.3,
1159
+ displacement: 5,
1160
+ /**
1161
+ * Frames a run must advance to count as alive — the bot's gate — capped by
1162
+ * `minFps` × the run's wall time, because a model run can legitimately be
1163
+ * a couple of seconds long where the scripted sweep is twelve.
1164
+ */
1165
+ framesAdvanced: 100,
1166
+ /** Decisions a rested no-input option stays out of the question. */
1167
+ idleRestTicks: 8,
1168
+ /** Idle decisions in a row (holding nothing, going nowhere) before the no-input option is rested. */
1169
+ idleRun: 3,
1170
+ minFps: 10,
1171
+ /**
1172
+ * A window counts as "didn't move" below this fraction of the displacement
1173
+ * gate, so both scale together when a game measures in world units.
1174
+ */
1175
+ motionEpsilonRatio: 0.04,
1176
+ /** Stuck ticks in a row after which the agent withdraws the move. */
1177
+ stuckRun: 2,
1178
+ /**
1179
+ * Stuck ticks in a row that fail the run. The decision after a withdrawal
1180
+ * was already in flight when it landed, so `stuckRun + 1` is what hitting
1181
+ * one wall costs; past that the alternatives went nowhere too.
1182
+ */
1183
+ wedgedRun: 5
1184
+ };
1185
+ var displacementGate = (controls) => controls.minDisplacement ?? THRESHOLDS.displacement;
1186
+ var motionEpsilon = (controls) => displacementGate(controls) * THRESHOLDS.motionEpsilonRatio;
1187
+ var ACTION_THRESHOLD = 0.5;
1188
+ var TRAIL_LENGTH = 6;
1189
+ var FINAL_HOLD_MS = 250;
1190
+ var DECISION_RETRIES = 2;
1191
+ var DECISION_TIMEOUT_MS = 1e4;
1192
+ var POLL_MS = 250;
1193
+ var round = (value) => Number(value.toFixed(2));
1194
+ var agentConfig = (opts, session) => {
1195
+ const move2 = {};
1196
+ for (const [label, option] of Object.entries(opts.controls.move)) {
1197
+ move2[label] = {
1198
+ description: option.description,
1199
+ inits: keyInitsFor(option.keys),
1200
+ pointer: option.pointer ? { down: option.pointer.down === true, x: option.pointer.x, y: option.pointer.y } : null
1201
+ };
1202
+ }
1203
+ const actions = {};
1204
+ for (const [label, action] of Object.entries(opts.controls.actions)) {
1205
+ actions[label] = { description: action.description, inits: keyInitsFor(action.keys) };
1206
+ }
1207
+ return {
1208
+ actionThreshold: ACTION_THRESHOLD,
1209
+ actions,
1210
+ decideUrl: session.decideUrl,
1211
+ decisionRetries: DECISION_RETRIES,
1212
+ decisionTimeoutMs: DECISION_TIMEOUT_MS,
1213
+ finalHoldMs: FINAL_HOLD_MS,
1214
+ goal: opts.controls.goal,
1215
+ idleRestTicks: THRESHOLDS.idleRestTicks,
1216
+ idleRun: THRESHOLDS.idleRun,
1217
+ keyTable: keyTable(),
1218
+ model: opts.model,
1219
+ motionEpsilon: motionEpsilon(opts.controls),
1220
+ move: move2,
1221
+ pinMove: opts.pinMove,
1222
+ stuckRun: THRESHOLDS.stuckRun,
1223
+ tickMs: opts.tickMs,
1224
+ ticks: opts.ticks,
1225
+ token: session.token,
1226
+ trailLength: TRAIL_LENGTH
1227
+ };
1228
+ };
1229
+ var agentSource = (config) => `(${inPageAgent.toString()})(${JSON.stringify(config)}, (${browserEnv.toString()})())`;
1230
+ var budgetMs = (opts) => opts.ticks * (Math.max(opts.tickMs, 150) + DECISION_TIMEOUT_MS + 3500) + FINAL_HOLD_MS + 15e3;
1231
+ var measure = (metrics, window2, askedToMove, index, epsilon) => {
1232
+ metrics.distance += window2.path;
1233
+ metrics.maxTickDisplacement = Math.max(metrics.maxTickDisplacement, window2.peak);
1234
+ const progressed = window2.score > window2.scoreBefore;
1235
+ if (progressed && metrics.tickOfFirstScore === null) {
1236
+ metrics.tickOfFirstScore = index;
1237
+ }
1238
+ let stuck = false;
1239
+ if (askedToMove) {
1240
+ stuck = window2.frame > window2.frameBefore && window2.peak < epsilon && !progressed;
1241
+ if (stuck) {
1242
+ metrics.stuckTicks += 1;
1243
+ metrics.stuckRun += 1;
1244
+ metrics.longestStuckRun = Math.max(metrics.longestStuckRun, metrics.stuckRun);
1245
+ } else {
1246
+ metrics.stuckRun = 0;
1247
+ }
1248
+ }
1249
+ return { progressed, stuck };
1250
+ };
1251
+ var timelineEntry = (record, progressed, stuck) => ({
1252
+ actionProbabilities: record.actionProbabilities,
1253
+ actions: record.actions,
1254
+ confidence: record.confidence,
1255
+ decisionMs: record.decisionMs,
1256
+ frames: record.window.frame - record.window.frameBefore,
1257
+ move: record.move,
1258
+ path: record.window.path,
1259
+ peak: record.window.peak,
1260
+ progress: record.progress,
1261
+ progressed,
1262
+ reflexFrames: record.reflexFrames,
1263
+ scoreDelta: record.window.score - record.window.scoreBefore,
1264
+ stuck,
1265
+ tick: record.tick
1266
+ });
1267
+ var num2 = (value) => Number.isFinite(value) ? Number(value) : 0;
1268
+ var readWindow = (value) => {
1269
+ if (!isJsonObject(value)) {
1270
+ return null;
1271
+ }
1272
+ return {
1273
+ complete: value.complete === true,
1274
+ frame: num2(value.frame),
1275
+ frameBefore: num2(value.frameBefore),
1276
+ path: num2(value.path),
1277
+ peak: num2(value.peak),
1278
+ score: num2(value.score),
1279
+ scoreBefore: num2(value.scoreBefore),
1280
+ x: num2(value.x),
1281
+ y: num2(value.y),
1282
+ z: num2(value.z)
1283
+ };
1284
+ };
1285
+ var readRecord = (value) => {
1286
+ const window2 = isJsonObject(value) ? readWindow(value.window) : null;
1287
+ if (!isJsonObject(value) || !window2 || !isJsonString(value.move)) {
1288
+ throw new HarnessError(
1289
+ `the agent published a malformed record: ${JSON.stringify(value).slice(0, 200)}`
1290
+ );
1291
+ }
1292
+ const probabilities = {};
1293
+ if (isJsonObject(value.actionProbabilities)) {
1294
+ for (const [label, probability] of Object.entries(value.actionProbabilities)) {
1295
+ probabilities[label] = num2(probability);
1296
+ }
1297
+ }
1298
+ return {
1299
+ actionProbabilities: probabilities,
1300
+ actions: Array.isArray(value.actions) ? value.actions.filter(isJsonString) : [],
1301
+ askedToMove: value.askedToMove === true,
1302
+ confidence: Number.isFinite(value.confidence) ? Number(value.confidence) : null,
1303
+ decisionMs: num2(value.decisionMs),
1304
+ inputTokens: num2(value.inputTokens),
1305
+ move: value.move,
1306
+ outputTokens: num2(value.outputTokens),
1307
+ progress: Number.isFinite(value.progress) ? Number(value.progress) : null,
1308
+ reflexFrames: num2(value.reflexFrames),
1309
+ tick: num2(value.tick),
1310
+ window: window2
1311
+ };
1312
+ };
1313
+ var resultFromAgent = (published, epsilon = THRESHOLDS.displacement * THRESHOLDS.motionEpsilonRatio) => {
1314
+ if (!isJsonObject(published)) {
1315
+ throw new HarnessError("the page lost the agent before its result could be read.");
1316
+ }
1317
+ if (isJsonString(published.error)) {
1318
+ throw new HarnessError(published.error);
1319
+ }
1320
+ const records = Array.isArray(published.records) ? published.records.map(readRecord) : [];
1321
+ const metrics = {
1322
+ distance: 0,
1323
+ longestStuckRun: 0,
1324
+ maxTickDisplacement: 0,
1325
+ stuckRun: 0,
1326
+ stuckTicks: 0,
1327
+ tickOfFirstScore: null
1328
+ };
1329
+ const timeline = [];
1330
+ const usage = { calls: 0, inputTokens: 0, maxDecisionMs: 0, outputTokens: 0, totalDecisionMs: 0 };
1331
+ let lastWindow = null;
1332
+ for (const record of records) {
1333
+ const { progressed, stuck } = measure(
1334
+ metrics,
1335
+ record.window,
1336
+ record.askedToMove,
1337
+ record.tick,
1338
+ epsilon
1339
+ );
1340
+ timeline.push(timelineEntry(record, progressed, stuck));
1341
+ usage.calls += 1;
1342
+ usage.inputTokens += record.inputTokens;
1343
+ usage.outputTokens += record.outputTokens;
1344
+ usage.totalDecisionMs += record.decisionMs;
1345
+ usage.maxDecisionMs = Math.max(usage.maxDecisionMs, record.decisionMs);
1346
+ lastWindow = record.window;
1347
+ }
1348
+ return {
1349
+ completedAtTick: Number.isFinite(published.completedAtTick) ? Number(published.completedAtTick) : null,
1350
+ lastWindow,
1351
+ metrics,
1352
+ timeline,
1353
+ usage,
1354
+ wallMs: num2(published.wallMs)
1355
+ };
1356
+ };
1357
+ var runInPage = async (browser, opts, session) => {
1358
+ browser.inject(agentSource(agentConfig(opts, session)));
1359
+ const deadline = Date.now() + budgetMs(opts);
1360
+ for (; ; ) {
1361
+ const status = browser.agentStatus();
1362
+ if (!status) {
1363
+ throw new HarnessError("the page lost the agent; it probably navigated mid-run.");
1364
+ }
1365
+ if (status.done) {
1366
+ break;
1367
+ }
1368
+ if (Date.now() > deadline) {
1369
+ browser.stopAgent();
1370
+ throw new HarnessError(
1371
+ `the run did not finish within ${Math.round(budgetMs(opts) / 1e3)} s.`
1372
+ );
1373
+ }
1374
+ await delay(POLL_MS);
1375
+ }
1376
+ return resultFromAgent(browser.agentResult(), motionEpsilon(opts.controls));
1377
+ };
1378
+ var summarizeProgress = (timeline) => {
1379
+ const scored = timeline.map((entry) => entry.progress).filter((p) => p !== null);
1380
+ const [first] = scored;
1381
+ const last = scored.at(-1);
1382
+ if (first === void 0 || last === void 0) {
1383
+ return null;
1384
+ }
1385
+ let sum = 0;
1386
+ let max = 0;
1387
+ for (const value of scored) {
1388
+ sum += value;
1389
+ max = Math.max(max, value);
1390
+ }
1391
+ return {
1392
+ first: round(first),
1393
+ last: round(last),
1394
+ max: round(max),
1395
+ mean: round(sum / scored.length)
1396
+ };
1397
+ };
1398
+ var summarizeDecisions = (timeline) => {
1399
+ const moves = {};
1400
+ const actions = {};
1401
+ let confidenceSum = 0;
1402
+ let confidenceCount = 0;
1403
+ let reflexFrames = 0;
1404
+ for (const entry of timeline) {
1405
+ moves[entry.move] = (moves[entry.move] ?? 0) + 1;
1406
+ for (const label of entry.actions) {
1407
+ actions[label] = (actions[label] ?? 0) + 1;
1408
+ }
1409
+ if (entry.confidence !== null) {
1410
+ confidenceSum += entry.confidence;
1411
+ confidenceCount += 1;
1412
+ }
1413
+ reflexFrames += entry.reflexFrames;
1414
+ }
1415
+ return {
1416
+ actions,
1417
+ meanConfidence: confidenceCount > 0 ? round(confidenceSum / confidenceCount) : null,
1418
+ moves,
1419
+ progress: summarizeProgress(timeline),
1420
+ reflexFrames
1421
+ };
1422
+ };
1423
+ var buildReport = (opts, input) => {
1424
+ const { before, run } = input;
1425
+ const last = run.lastWindow;
1426
+ const seconds = run.wallMs / 1e3;
1427
+ return {
1428
+ complete: last ? last.complete : before.complete,
1429
+ completedAtTick: run.completedAtTick,
1430
+ consoleErrors: input.consoleErrors,
1431
+ decisions: summarizeDecisions(run.timeline),
1432
+ decisionsPerSecond: seconds > 0 ? round(run.timeline.length / seconds) : null,
1433
+ distanceTravelled: round(run.metrics.distance),
1434
+ framesAdvanced: (last ? last.frame : before.frame) - before.frame,
1435
+ goal: opts.controls.goal,
1436
+ // Which GPU rasterized the run. Under software rendering the functional
1437
+ // checks still hold; any frame-rate read from the run does not.
1438
+ gpu: input.gpu,
1439
+ longestStuckRun: run.metrics.longestStuckRun,
1440
+ maxTickDisplacement: round(run.metrics.maxTickDisplacement),
1441
+ // The gate `maxTickDisplacement` was held to, so the number reads in context.
1442
+ minDisplacement: displacementGate(opts.controls),
1443
+ model: {
1444
+ calls: run.usage.calls,
1445
+ id: opts.model,
1446
+ inputTokens: run.usage.inputTokens,
1447
+ maxDecisionMs: run.usage.maxDecisionMs,
1448
+ meanDecisionMs: run.usage.calls > 0 ? Math.round(run.usage.totalDecisionMs / run.usage.calls) : null,
1449
+ outputTokens: run.usage.outputTokens
1450
+ },
1451
+ pageErrors: input.pageErrors,
1452
+ scoreAfter: last ? last.score : before.score,
1453
+ scoreBefore: before.score,
1454
+ seed: input.seed,
1455
+ // How the seed actually landed, so a reader can tell a real seeded run
1456
+ // from one where the hook quietly did nothing.
1457
+ seedApplied: input.seedApplied,
1458
+ stuckTicks: run.metrics.stuckTicks,
1459
+ target: input.target,
1460
+ tickMs: opts.tickMs,
1461
+ tickOfFirstScore: run.metrics.tickOfFirstScore,
1462
+ ticks: opts.ticks,
1463
+ ticksRun: run.timeline.length,
1464
+ timeline: run.timeline,
1465
+ wallMs: run.wallMs
1466
+ };
1467
+ };
1468
+ var verdict = (report, opts) => {
1469
+ const failures = [];
1470
+ const warnings = [];
1471
+ const framesRequired = Math.min(
1472
+ THRESHOLDS.framesAdvanced,
1473
+ Math.round(report.wallMs / 1e3 * THRESHOLDS.minFps)
1474
+ );
1475
+ if (report.framesAdvanced <= framesRequired) {
1476
+ failures.push(
1477
+ `game loop stalled (framesAdvanced ${report.framesAdvanced} over ${report.wallMs} ms)`
1478
+ );
1479
+ }
1480
+ const gate = displacementGate(opts.controls);
1481
+ const holdsInput = (label) => {
1482
+ const option = opts.controls.move[label];
1483
+ return option !== void 0 && (option.keys.length > 0 || option.pointer !== null || option.reflex);
1484
+ };
1485
+ const triedToMove = report.timeline.some((entry) => holdsInput(entry.move));
1486
+ if (!triedToMove && report.timeline.length > 0) {
1487
+ failures.push(
1488
+ "the model never chose a movement \u2014 every decision held nothing. The diagnostics gave it no reason to go anywhere: expose where the goal, threats and pickups are (dx/dy from the player) in __GAME_DIAGNOSTICS__, and say which way progress is in the goal"
1489
+ );
1490
+ } else if (report.maxTickDisplacement <= gate) {
1491
+ failures.push(
1492
+ `player did not respond to input (maxTickDisplacement ${report.maxTickDisplacement}, needs > ${gate}) \u2014 if this game steers with the mouse, give it pointer moves in __GAME_PLAYTEST__ or --controls; if \`player\` is in world units rather than pixels, set \`minDisplacement\` in __GAME_PLAYTEST__ or pass --min-displacement`
1493
+ );
1494
+ }
1495
+ if (report.longestStuckRun >= THRESHOLDS.wedgedRun) {
1496
+ failures.push(
1497
+ `player wedged for ${report.longestStuckRun} consecutive movement ticks (longestStuckRun) \u2014 the model kept choosing moves that went nowhere`
1498
+ );
1499
+ }
1500
+ if (report.scoreAfter <= report.scoreBefore) {
1501
+ const { progress } = report.decisions;
1502
+ let judged = "";
1503
+ if (progress !== null) {
1504
+ const trend = `progress ${progress.first} \u2192 ${progress.last}`;
1505
+ judged = progress.last > progress.first ? ` (though the model judged the player closer to the goal by the end: ${trend})` : ` (and the model agreed: ${trend})`;
1506
+ }
1507
+ const message = `the run never progressed the objective${judged}`;
1508
+ if (opts.expectProgress) {
1509
+ failures.push(message);
1510
+ } else {
1511
+ warnings.push(
1512
+ `${message} \u2014 pass --expect-progress once the controls express this game's scoring verb, to make that an assertion`
1513
+ );
1514
+ }
1515
+ }
1516
+ if (report.completedAtTick !== null) {
1517
+ warnings.push(
1518
+ `the run ended at tick ${report.completedAtTick} of ${opts.ticks} (complete became true) \u2014 a win, or a fail state the playtester couldn't avoid; read the timeline to tell which`
1519
+ );
1520
+ }
1521
+ const { meanConfidence } = report.decisions;
1522
+ if (meanConfidence !== null && meanConfidence < THRESHOLDS.confidence) {
1523
+ warnings.push(
1524
+ `the model was rarely sure which way to move (mean confidence ${meanConfidence}) \u2014 the diagnostics probably don't expose what a player sees; add hazards, goals and nearby entities with positions to __GAME_DIAGNOSTICS__`
1525
+ );
1526
+ }
1527
+ if (report.consoleErrors.length > 0) {
1528
+ failures.push(`${report.consoleErrors.length} console error(s)`);
1529
+ }
1530
+ if (report.pageErrors.length > 0) {
1531
+ failures.push(`${report.pageErrors.length} uncaught page error(s)`);
1532
+ }
1533
+ return { failures, warnings };
1534
+ };
1535
+
1536
+ // src/commands/playtest-run.ts
1537
+ var HARNESS_FAILURE = 2;
1538
+ var DEFAULT_TICK_MS = 150;
1539
+ var runArgs = {
1540
+ controls: {
1541
+ description: `Control scheme: a preset (${PRESET_NAMES.join(", ")}) or a JSON file. Default: the game's window.__GAME_PLAYTEST__ if it publishes one, else ${DEFAULT_PRESET}.`,
1542
+ type: "string"
1543
+ },
1544
+ expectProgress: {
1545
+ description: "Assert the objective advances (score rises) during the run.",
1546
+ type: "boolean"
1547
+ },
1548
+ game: {
1549
+ description: "Deployed game slug to playtest (mutually exclusive with --url).",
1550
+ type: "string"
1551
+ },
1552
+ goal: {
1553
+ description: "What the playtester is trying to do \u2014 what wins, what kills, which way is progress. Overrides the scheme's goal.",
1554
+ type: "string"
1555
+ },
1556
+ headed: { description: "Show the browser.", type: "boolean" },
1557
+ keepOpen: { description: "Leave the page open afterwards.", type: "boolean" },
1558
+ minDisplacement: {
1559
+ description: "Per-decision movement that proves input works, in the units of the game's player.x/y (default 5 \u2014 pixels; a game in world units needs far less). Overrides the scheme's.",
1560
+ type: "string"
1561
+ },
1562
+ model: { default: "jev-latest", description: "Decision model id.", type: "string" },
1563
+ pinMove: {
1564
+ description: "Hold this one move for the whole run and never call the model \u2014 for tuning a reflex deterministically, for free. The report's decisions are then yours, not the model's.",
1565
+ type: "string"
1566
+ },
1567
+ seed: { default: "12345", description: "Seed for the game's RNG.", type: "string" },
1568
+ tickMs: {
1569
+ default: String(DEFAULT_TICK_MS),
1570
+ description: `Minimum time each decision's inputs stay held (ms). The default caps the playtester near a fast player's cadence; 0 = as fast as decisions arrive.`,
1571
+ type: "string"
1572
+ },
1573
+ ticks: { default: "60", description: "Decisions to make.", type: "string" },
1574
+ url: {
1575
+ description: "Where the game is served (mutually exclusive with --game).",
1576
+ type: "string"
1577
+ },
1578
+ ...outputArgs
1579
+ };
1580
+ var numberArg = (raw, flag, check, hint) => {
1581
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
1582
+ if (!check(value)) {
1583
+ throw new HarnessError(`\`${flag}\` must be ${hint}.`);
1584
+ }
1585
+ return value;
1586
+ };
1587
+ var settingsFrom = (args) => {
1588
+ if (!args.url && !args.game) {
1589
+ throw new HarnessError("Pass --url <url> or --game <slug>.");
1590
+ }
1591
+ if (args.url && args.game) {
1592
+ throw new HarnessError("Pass either --url or --game, not both.");
1593
+ }
1594
+ if (args.goal !== void 0 && args.goal.trim() === "") {
1595
+ throw new HarnessError("`--goal` must not be empty.");
1596
+ }
1597
+ if (args.model.trim() === "") {
1598
+ throw new HarnessError("`--model` must not be empty.");
1599
+ }
1600
+ return {
1601
+ expectProgress: args.expectProgress === true,
1602
+ explicitControls: args.controls === void 0 ? null : readControlsArg(args.controls),
1603
+ goal: args.goal ?? null,
1604
+ headed: args.headed === true,
1605
+ keepOpen: args.keepOpen === true,
1606
+ minDisplacement: args.minDisplacement === void 0 ? null : numberArg(
1607
+ args.minDisplacement,
1608
+ "--min-displacement",
1609
+ (n) => Number.isFinite(n) && n > 0,
1610
+ "a positive number"
1611
+ ),
1612
+ model: args.model,
1613
+ pinMove: args.pinMove ?? null,
1614
+ seed: numberArg(args.seed, "--seed", Number.isFinite, "a finite number"),
1615
+ target: args.game ? `game:${args.game}` : args.url ?? "",
1616
+ tickMs: numberArg(
1617
+ args.tickMs,
1618
+ "--tick-ms",
1619
+ (n) => Number.isFinite(n) && n >= 0 && n <= 5e3,
1620
+ "between 0 and 5000 milliseconds"
1621
+ ),
1622
+ ticks: numberArg(
1623
+ args.ticks,
1624
+ "--ticks",
1625
+ (n) => Number.isInteger(n) && n > 0,
1626
+ "a positive integer"
1627
+ ),
1628
+ url: args.url ?? resolveGameUrl(args.game ?? null)
1629
+ };
1630
+ };
1631
+ var chooseControls = (settings, manifest) => {
1632
+ let controls = settings.explicitControls;
1633
+ if (!controls) {
1634
+ controls = manifest === null ? PRESETS.get(DEFAULT_PRESET) : parseControls(manifest, "window.__GAME_PLAYTEST__");
1635
+ }
1636
+ if (!controls) {
1637
+ throw new HarnessError("no control scheme available.");
1638
+ }
1639
+ return {
1640
+ ...controls,
1641
+ goal: settings.goal ?? controls.goal,
1642
+ minDisplacement: settings.minDisplacement ?? controls.minDisplacement
1643
+ };
1644
+ };
1645
+ var isLoopback = (url) => {
1646
+ const host = URL.canParse(url) ? new URL(url).hostname : null;
1647
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
1648
+ };
1649
+ var assertReachable = (gameUrl) => {
1650
+ if (isLoopback(getBaseUrl()) && !isLoopback(gameUrl)) {
1651
+ throw new HarnessError(
1652
+ `the game at ${gameUrl} is a public page and the API (${getBaseUrl()}) is on localhost \u2014 the browser blocks that request. Serve the game locally, or point VG_API_URL at a deployed API.`
1653
+ );
1654
+ }
1655
+ };
1656
+ var mintSession = async (client) => {
1657
+ try {
1658
+ const { token } = await client.playtest.session();
1659
+ return { decideUrl: new URL("/api/playtest/decide", getBaseUrl()).toString(), token };
1660
+ } catch (error) {
1661
+ const code = authErrorCode(error);
1662
+ if (code === "UNAUTHORIZED" || code === "FORBIDDEN") {
1663
+ throw new HarnessError(
1664
+ "Not authenticated. Run `vg login`, or check your VG_TOKEN / API key."
1665
+ );
1666
+ }
1667
+ throw new HarnessError(
1668
+ `couldn't start a playtest session: ${error instanceof Error ? error.message : String(error)}`
1669
+ );
1670
+ }
1671
+ };
1672
+ var summarize = (report, failures, warnings) => {
1673
+ const rate = report.decisionsPerSecond === null ? "" : ` at ${report.decisionsPerSecond}/s`;
1674
+ consola.log(
1675
+ `The model made ${report.ticksRun} decisions${rate} (mean ${report.model.meanDecisionMs ?? "?"} ms each) on ${report.target}`
1676
+ );
1677
+ consola.log(
1678
+ ` frames +${report.framesAdvanced} moved ${report.distanceTravelled} (peak ${report.maxTickDisplacement}/tick) score ${report.scoreBefore} \u2192 ${report.scoreAfter} stuck ${report.stuckTicks} (longest run ${report.longestStuckRun})`
1679
+ );
1680
+ const moves = Object.entries(report.decisions.moves).map(([label, count]) => `${label}\xD7${count}`).join(" ");
1681
+ const { progress } = report.decisions;
1682
+ const judged = progress === null ? "n/a" : `${progress.first} \u2192 ${progress.last}`;
1683
+ consola.log(
1684
+ ` moves: ${moves || "none"} confidence ${report.decisions.meanConfidence ?? "n/a"} progress ${judged} tokens ${report.model.inputTokens}`
1685
+ );
1686
+ for (const warning of warnings) {
1687
+ consola.warn(warning);
1688
+ }
1689
+ if (failures.length > 0) {
1690
+ consola.error(`FAILED \u2014 ${failures.join("; ")}`);
1691
+ } else {
1692
+ consola.success("PASSED");
1693
+ }
1694
+ };
1695
+ var playtestRunCommand = defineCommand({
1696
+ args: runArgs,
1697
+ meta: {
1698
+ description: "Let a model play the game and report how it went \u2014 reads the game's diagnostics each tick, decides what to hold, drives real input. Needs the diagnostics contract (see the playtest skill).",
1699
+ name: "run"
1700
+ },
1701
+ run: async ({ args, rawArgs }) => {
1702
+ assertKnownFlags(rawArgs, runArgs);
1703
+ let settings;
1704
+ try {
1705
+ settings = settingsFrom(args);
1706
+ } catch (error) {
1707
+ consola.error(error instanceof Error ? error.message : String(error));
1708
+ process.exit(HARNESS_FAILURE);
1709
+ }
1710
+ if (!getToken()) {
1711
+ consola.warn("Not logged in. Run `vg login` to authenticate.");
1712
+ process.exit(1);
1713
+ }
1714
+ const client = createClient();
1715
+ const { bin } = ensureAgentBrowser();
1716
+ const browser = new GameBrowser(bin, process.env.AGENT_BROWSER_SESSION ?? projectSessionId());
1717
+ for (const signal of ["SIGINT", "SIGTERM"]) {
1718
+ process.on(signal, () => {
1719
+ browser.stopAgent();
1720
+ process.exit(HARNESS_FAILURE);
1721
+ });
1722
+ }
1723
+ let opts;
1724
+ let payload;
1725
+ try {
1726
+ assertReachable(settings.url);
1727
+ const session = await mintSession(client);
1728
+ const launched = browser.launch({
1729
+ headed: settings.headed,
1730
+ seed: settings.seed,
1731
+ url: settings.url
1732
+ });
1733
+ const controls = chooseControls(settings, launched.manifest);
1734
+ if (settings.pinMove !== null && !Object.hasOwn(controls.move, settings.pinMove)) {
1735
+ throw new HarnessError(
1736
+ `--pin-move ${settings.pinMove} is not a move in this scheme \u2014 those are ${Object.keys(controls.move).join(", ")}.`
1737
+ );
1738
+ }
1739
+ opts = {
1740
+ controls,
1741
+ expectProgress: settings.expectProgress,
1742
+ model: settings.model,
1743
+ pinMove: settings.pinMove,
1744
+ tickMs: settings.tickMs,
1745
+ ticks: settings.ticks
1746
+ };
1747
+ const run = await runInPage(browser, opts, session);
1748
+ const report = buildReport(opts, {
1749
+ before: launched.before,
1750
+ consoleErrors: browser.consoleErrors(),
1751
+ gpu: browser.gpuInfo(),
1752
+ pageErrors: browser.pageErrors(),
1753
+ run,
1754
+ seed: settings.seed,
1755
+ seedApplied: launched.seedApplied,
1756
+ target: settings.target
1757
+ });
1758
+ payload = { ...report, ...verdict(report, opts) };
1759
+ } catch (error) {
1760
+ browser.stopAgent();
1761
+ const message = error instanceof Error ? error.message : String(error);
1762
+ consola.error(
1763
+ error instanceof HarnessError ? message : `playtest harness failed: ${message}`
1764
+ );
1765
+ process.exit(HARNESS_FAILURE);
1766
+ }
1767
+ if (!settings.keepOpen) {
1768
+ browser.close();
1769
+ }
1770
+ if (!writeStructured(payload, args)) {
1771
+ summarize(payload, payload.failures, payload.warnings);
1772
+ }
1773
+ if (payload.failures.length > 0) {
1774
+ process.exit(1);
1775
+ }
1776
+ }
1777
+ });
1778
+ export {
1779
+ playtestRunCommand
1780
+ };