vibedgames 0.5.0 → 0.6.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/dist/commands/completions.d.ts +1 -1
  3. package/dist/commands/completions.js +21 -20
  4. package/dist/commands/credits.d.ts +5 -5
  5. package/dist/commands/credits.js +43 -33
  6. package/dist/commands/deploy.d.ts +10 -10
  7. package/dist/commands/deploy.js +155 -139
  8. package/dist/commands/factory.d.ts +1 -1
  9. package/dist/commands/factory.js +18 -15
  10. package/dist/commands/fork.d.ts +14 -14
  11. package/dist/commands/fork.js +51 -46
  12. package/dist/commands/generate.js +318 -264
  13. package/dist/commands/init.d.ts +8 -8
  14. package/dist/commands/init.js +31 -24
  15. package/dist/commands/login.js +12 -12
  16. package/dist/commands/logout.js +2 -2
  17. package/dist/commands/new.d.ts +16 -16
  18. package/dist/commands/new.js +153 -142
  19. package/dist/commands/playtest-run.d.ts +62 -0
  20. package/dist/commands/playtest-run.js +258 -0
  21. package/dist/commands/playtest.d.ts +41 -6
  22. package/dist/commands/playtest.js +114 -101
  23. package/dist/commands/update.d.ts +7 -7
  24. package/dist/commands/update.js +20 -17
  25. package/dist/commands/whoami.d.ts +5 -5
  26. package/dist/commands/whoami.js +8 -7
  27. package/dist/index.js +21 -11
  28. package/dist/lib/api.d.ts +4 -4
  29. package/dist/lib/api.js +6 -12
  30. package/dist/lib/archive.d.ts +4 -4
  31. package/dist/lib/archive.js +121 -104
  32. package/dist/lib/codex.d.ts +45 -15
  33. package/dist/lib/codex.js +175 -106
  34. package/dist/lib/config-file.d.ts +6 -6
  35. package/dist/lib/config-file.js +28 -26
  36. package/dist/lib/config.d.ts +8 -8
  37. package/dist/lib/config.js +31 -33
  38. package/dist/lib/manifest.d.ts +3 -3
  39. package/dist/lib/manifest.js +42 -38
  40. package/dist/lib/media-args.d.ts +7 -7
  41. package/dist/lib/media-args.js +113 -95
  42. package/dist/lib/media-download.d.ts +9 -9
  43. package/dist/lib/media-download.js +148 -134
  44. package/dist/lib/media-poll.d.ts +8 -8
  45. package/dist/lib/media-poll.js +32 -27
  46. package/dist/lib/media-upload.d.ts +2 -2
  47. package/dist/lib/media-upload.js +27 -27
  48. package/dist/lib/output.d.ts +27 -12
  49. package/dist/lib/output.js +26 -26
  50. package/dist/lib/package-manager.d.ts +3 -3
  51. package/dist/lib/package-manager.js +27 -22
  52. package/dist/lib/playtest/agent.d.ts +188 -0
  53. package/dist/lib/playtest/agent.js +610 -0
  54. package/dist/lib/playtest/browser.d.ts +109 -0
  55. package/dist/lib/playtest/browser.js +219 -0
  56. package/dist/lib/playtest/controls.d.ts +47 -0
  57. package/dist/lib/playtest/controls.js +218 -0
  58. package/dist/lib/playtest/errors.d.ts +9 -0
  59. package/dist/lib/playtest/errors.js +12 -0
  60. package/dist/lib/playtest/keys.d.ts +41 -0
  61. package/dist/lib/playtest/keys.js +157 -0
  62. package/dist/lib/playtest/run.d.ts +193 -0
  63. package/dist/lib/playtest/run.js +408 -0
  64. package/dist/lib/run.d.ts +4 -4
  65. package/dist/lib/run.js +7 -4
  66. package/dist/lib/strict-args.d.ts +4 -4
  67. package/dist/lib/strict-args.js +28 -18
  68. package/dist/lib/types.d.ts +5 -5
  69. package/dist/lib/types.js +9 -12
  70. package/dist/lib/update.d.ts +4 -4
  71. package/dist/lib/update.js +41 -32
  72. package/dist/lib/upload.d.ts +4 -4
  73. package/dist/lib/upload.js +14 -9
  74. package/package.json +16 -16
@@ -0,0 +1,610 @@
1
+ /**
2
+ * The in-page playtester.
3
+ *
4
+ * `vg playtest run` injects this function's SOURCE into the game's page and
5
+ * calls it there, so the whole decide → apply → measure loop runs inside the
6
+ * browser: no CLI round trip per decision, and a per-frame reflex layer that
7
+ * a subprocess could never keep up with. The CLI's only jobs are to mint the
8
+ * token, inject, poll `window.__PLAYTEST_AGENT__.done`, and read the
9
+ * records back.
10
+ *
11
+ * Rules that follow from being stringified: `inPageAgent` and `browserEnv`
12
+ * must be entirely self-contained — no imports, no module-scope references
13
+ * (the `declare`d globals below are erased and resolve to the page's own) —
14
+ * which is why every helper lives inside them. The agent talks to the page
15
+ * only through `env`, the real browser in production and a fake in tests.
16
+ *
17
+ * The decision is the hold: the previous inputs stay down while the model
18
+ * answers, so the game runs continuously and the loop decides at the
19
+ * model's latency, with `tickMs` as a floor. A move option in the game's
20
+ * `__GAME_PLAYTEST__` may carry a `reflex(game)` function; while that option
21
+ * is the current intent, the reflex runs every frame and its returned inputs
22
+ * are what is held — the model sets intent a few times a second, the reflex
23
+ * turns it into input at 60 fps.
24
+ */
25
+ /** The real page as an AgentEnv. Only ever runs in the browser; injected beside the agent. */
26
+ export const browserEnv = () => {
27
+ const read = () => {
28
+ const d = window.__GAME_DIAGNOSTICS__;
29
+ const p = d?.player ?? {};
30
+ return {
31
+ complete: d?.complete === true,
32
+ frame: d?.frame ?? 0,
33
+ score: d?.score ?? 0,
34
+ x: p.x ?? 0,
35
+ y: p.y ?? 0,
36
+ z: p.z ?? 0,
37
+ };
38
+ };
39
+ const pointerTarget = (cx, cy) => document.elementFromPoint(cx, cy) ?? document.querySelector("canvas") ?? window;
40
+ const mouseType = (type) => {
41
+ if (type === "pointermove") {
42
+ return "mousemove";
43
+ }
44
+ return type === "pointerdown" ? "mousedown" : "mouseup";
45
+ };
46
+ const isFunction = (value) => Object.prototype.toString.call(value) === "[object Function]";
47
+ return {
48
+ caf: (id) => window.cancelAnimationFrame(id),
49
+ delay: (ms) =>
50
+ // oxlint-disable-next-line promise/avoid-new -- the page has no timers/promises; wrapping setTimeout is the only way to await a delay there
51
+ new Promise((resolve) => {
52
+ window.setTimeout(resolve, ms);
53
+ }),
54
+ dispatchKey: (type, init) => {
55
+ // At the focused element, not `window`: a real keypress starts there
56
+ // and bubbles up, so listeners on element, document and window all fire.
57
+ const target = document.activeElement ?? document.body ?? window;
58
+ target.dispatchEvent(new KeyboardEvent(type, init));
59
+ },
60
+ dispatchPointer: (pointer, type) => {
61
+ const cx = Math.round(window.innerWidth * pointer.x);
62
+ const cy = Math.round(window.innerHeight * pointer.y);
63
+ const pressed = type === "pointerdown" || (type === "pointermove" && pointer.down);
64
+ const init = {
65
+ bubbles: true,
66
+ button: 0,
67
+ buttons: pressed ? 1 : 0,
68
+ cancelable: true,
69
+ clientX: cx,
70
+ clientY: cy,
71
+ composed: true,
72
+ isPrimary: true,
73
+ pointerId: 1,
74
+ pointerType: "mouse",
75
+ screenX: cx,
76
+ screenY: cy,
77
+ };
78
+ const target = pointerTarget(cx, cy);
79
+ target.dispatchEvent(new PointerEvent(type, init));
80
+ target.dispatchEvent(new MouseEvent(mouseType(type), init));
81
+ },
82
+ fetch: (url, init) => window.fetch(url, init),
83
+ live: () => window.__GAME_DIAGNOSTICS__ ?? null,
84
+ now: () => Date.now(),
85
+ publish: (result) => {
86
+ window.__PLAYTEST_AGENT__ = result;
87
+ },
88
+ raf: (frame) => window.requestAnimationFrame(frame),
89
+ read,
90
+ reflexFor: (label) => {
91
+ const reflex = window.__GAME_PLAYTEST__?.move?.[label]?.reflex;
92
+ return isFunction(reflex) ? reflex : null;
93
+ },
94
+ snapshot: () => {
95
+ try {
96
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- structuredClone throws on a function-valued field; JSON drops it, and the contract is JSON anyway
97
+ return JSON.parse(JSON.stringify(window.__GAME_DIAGNOSTICS__ ?? null));
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ },
103
+ };
104
+ };
105
+ /**
106
+ * Run the playtest inside the page. Returns the live result object, which is
107
+ * also published as `window.__PLAYTEST_AGENT__`; `done` flips when the run
108
+ * ends, `error` says why if it ended early.
109
+ */
110
+ export const inPageAgent = (config, env) => {
111
+ // Object() is the identity only on objects; arrays are split off explicitly.
112
+ const isObject = (value) => Object(value) === value && !Array.isArray(value);
113
+ const round = (value) => Number(value.toFixed(2));
114
+ const started = env.now();
115
+ const usage = {
116
+ calls: 0,
117
+ inputTokens: 0,
118
+ maxDecisionMs: 0,
119
+ outputTokens: 0,
120
+ totalDecisionMs: 0,
121
+ };
122
+ let stopped = false;
123
+ let rafId = 0;
124
+ let heldKeys = [];
125
+ let heldPointer = null;
126
+ const samePointer = (a, b) => a === b || (a !== null && b !== null && a.x === b.x && a.y === b.y && a.down === b.down);
127
+ /** Switch the held inputs, dispatching only the changes. */
128
+ const hold = (next) => {
129
+ if (!samePointer(heldPointer, next.pointer)) {
130
+ if (heldPointer?.down) {
131
+ env.dispatchPointer(heldPointer, "pointerup");
132
+ }
133
+ if (next.pointer) {
134
+ env.dispatchPointer(next.pointer, "pointermove");
135
+ if (next.pointer.down) {
136
+ env.dispatchPointer(next.pointer, "pointerdown");
137
+ }
138
+ }
139
+ heldPointer = next.pointer;
140
+ }
141
+ const wanted = new Set(next.keys.map((init) => init.code));
142
+ const have = new Set(heldKeys.map((init) => init.code));
143
+ for (const init of heldKeys) {
144
+ if (!wanted.has(init.code)) {
145
+ env.dispatchKey("keyup", init);
146
+ }
147
+ }
148
+ for (const init of next.keys) {
149
+ if (!have.has(init.code)) {
150
+ env.dispatchKey("keydown", init);
151
+ }
152
+ }
153
+ heldKeys = next.keys;
154
+ };
155
+ /**
156
+ * Release these keys if held, so the next `hold` presses them again. An
157
+ * action the model picks on consecutive decisions would otherwise stay down
158
+ * as one long press, and a game that acts on the keydown edge — jump, fire,
159
+ * drop a bomb — would see the first of them and none of the rest.
160
+ */
161
+ const release = (inits) => {
162
+ const codes = new Set(inits.map((init) => init.code));
163
+ for (const init of heldKeys) {
164
+ if (codes.has(init.code)) {
165
+ env.dispatchKey("keyup", init);
166
+ }
167
+ }
168
+ heldKeys = heldKeys.filter((init) => !codes.has(init.code));
169
+ };
170
+ // ---- motion tracker ----------------------------------------------------
171
+ const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
172
+ let trackStart = env.read();
173
+ let trackLast = trackStart;
174
+ let trackPath = 0;
175
+ let trackPeak = 0;
176
+ let trackScore = trackStart.score;
177
+ const sample = () => {
178
+ const c = env.read();
179
+ trackPath += dist(c, trackLast);
180
+ trackPeak = Math.max(trackPeak, dist(c, trackStart));
181
+ trackLast = c;
182
+ trackScore = Math.max(trackScore, c.score);
183
+ };
184
+ /** The window since the last flush; the next window starts now. */
185
+ const flush = () => {
186
+ sample();
187
+ const c = trackLast;
188
+ const measured = {
189
+ complete: c.complete,
190
+ frame: c.frame,
191
+ frameBefore: trackStart.frame,
192
+ path: Number(trackPath.toFixed(3)),
193
+ peak: Number(Math.max(trackPeak, dist(c, trackStart)).toFixed(3)),
194
+ score: Math.max(trackScore, c.score),
195
+ scoreBefore: trackStart.score,
196
+ x: c.x,
197
+ y: c.y,
198
+ z: c.z,
199
+ };
200
+ trackStart = c;
201
+ trackPath = 0;
202
+ trackPeak = 0;
203
+ trackScore = c.score;
204
+ return measured;
205
+ };
206
+ // Ordered lowest to highest; the answer is a probability-weighted position
207
+ // along them, which the agent normalises to 0–1. The model reads the same
208
+ // state it moves from, so this is its judgment of the run, not a metric —
209
+ // useful because it is the one signal that tracks the GOAL rather than the
210
+ // game's score field, which a goal like "survive" never raises.
211
+ const PROGRESS_LEVELS = [
212
+ "No progress: the player is not moving towards the goal, or is losing (dying, falling behind)",
213
+ "Barely started: moving, but the goal is far off or the player is in trouble",
214
+ "Halfway: clear progress towards the goal and out of immediate danger",
215
+ "Nearly there: the goal is close, or the score is rising steadily",
216
+ "Achieved, or about to be",
217
+ ];
218
+ let pending = null;
219
+ let blocked = [];
220
+ let stuckRun = 0;
221
+ let idleRun = 0;
222
+ let rested = null;
223
+ const trail = [];
224
+ let lastWindow = null;
225
+ const result = {
226
+ completedAtTick: null,
227
+ done: false,
228
+ error: null,
229
+ records: [],
230
+ stop: () => {
231
+ stopped = true;
232
+ },
233
+ usage,
234
+ wallMs: 0,
235
+ };
236
+ env.publish(result);
237
+ /** The move options on offer this tick: everything the reflex hasn't withdrawn. */
238
+ const offeredMoves = (tick) => {
239
+ const resting = rested !== null && tick < rested.untilTick ? rested.label : null;
240
+ const criteria = {};
241
+ for (const [label, option] of Object.entries(config.move)) {
242
+ if (!blocked.includes(label) && label !== resting) {
243
+ criteria[label] = option.description;
244
+ }
245
+ }
246
+ // A choice needs two options; the rested one comes back before that breaks.
247
+ if (resting !== null && Object.keys(criteria).length < 2) {
248
+ criteria[resting] = config.move[resting]?.description ?? resting;
249
+ }
250
+ return criteria;
251
+ };
252
+ const questions = (criteria) => {
253
+ const out = {
254
+ move: {
255
+ criteria,
256
+ 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.",
257
+ type: "choice",
258
+ },
259
+ progress: {
260
+ criteria: PROGRESS_LEVELS,
261
+ instructions: "How close is the player to achieving `goal` right now, judging from `game` and `recent`?",
262
+ type: "score",
263
+ },
264
+ };
265
+ for (const [label, action] of Object.entries(config.actions)) {
266
+ out[`act:${label}`] = {
267
+ criteria: { false: "Not now", true: "Yes, do it now" },
268
+ instructions: `Given \`game\` and \`goal\`, should the player ${action.description} right now?`,
269
+ type: "noul",
270
+ };
271
+ }
272
+ return out;
273
+ };
274
+ const answerFor = (answers, key) => {
275
+ const answer = answers[key];
276
+ return isObject(answer) ? answer : {};
277
+ };
278
+ const parseDecision = (text, offered) => {
279
+ let body;
280
+ try {
281
+ body = JSON.parse(text);
282
+ }
283
+ catch {
284
+ throw new Error(`decision response was not JSON: ${text.slice(0, 200)}`);
285
+ }
286
+ const answers = isObject(body) ? body.answers : undefined;
287
+ if (!isObject(answers)) {
288
+ throw new Error(`decision response had no answers: ${text.slice(0, 200)}`);
289
+ }
290
+ const move = answerFor(answers, "move");
291
+ const choice = String(move.choice ?? "");
292
+ if (!Object.hasOwn(offered, choice)) {
293
+ throw new Error(`decision model answered \`move\` outside the offered options: ${choice}`);
294
+ }
295
+ const actions = [];
296
+ const actionProbabilities = {};
297
+ for (const label of Object.keys(config.actions)) {
298
+ const probability = Number(answerFor(answers, `act:${label}`).noul);
299
+ if (!Number.isFinite(probability)) {
300
+ throw new TypeError(`decision model answered \`${label}\` without a probability`);
301
+ }
302
+ actionProbabilities[label] = Number(probability.toFixed(3));
303
+ if (probability >= config.actionThreshold) {
304
+ actions.push(label);
305
+ }
306
+ }
307
+ const usageBody = isObject(body) && isObject(body.usage) ? body.usage : {};
308
+ const confidence = Number(move.confidence);
309
+ // Advisory, so a missing or malformed score never fails the run.
310
+ const scored = Number(answerFor(answers, "progress").score);
311
+ const progress = Number.isFinite(scored)
312
+ ? Number(Math.min(1, Math.max(0, scored / (PROGRESS_LEVELS.length - 1))).toFixed(3))
313
+ : null;
314
+ return {
315
+ actionProbabilities,
316
+ actions,
317
+ confidence: Number.isFinite(confidence) ? Number(confidence.toFixed(3)) : null,
318
+ inputTokens: Number(usageBody.input_tokens) || 0,
319
+ move: choice,
320
+ outputTokens: Number(usageBody.output_tokens) || 0,
321
+ progress,
322
+ };
323
+ };
324
+ // A hung request would otherwise hold the last inputs down until the CLI's
325
+ // whole-run budget expired; a timed-out attempt is retried like a dropped one.
326
+ const timeout = async () => {
327
+ await env.delay(config.decisionTimeoutMs);
328
+ throw new Error(`no answer within ${config.decisionTimeoutMs} ms`);
329
+ };
330
+ /** One decision, with a short backoff on a rate limit, an upstream fault or a dropped connection. */
331
+ const decide = async (state) => {
332
+ const offered = offeredMoves(state.tick.index);
333
+ const body = JSON.stringify({ model: config.model, questions: questions(offered), state });
334
+ for (let attempt = 0;; attempt += 1) {
335
+ let response = null;
336
+ let failure = "";
337
+ try {
338
+ response = await Promise.race([
339
+ env.fetch(config.decideUrl, {
340
+ body,
341
+ headers: {
342
+ authorization: `Bearer ${config.token}`,
343
+ "content-type": "application/json",
344
+ },
345
+ method: "POST",
346
+ }),
347
+ timeout(),
348
+ ]);
349
+ }
350
+ catch (error) {
351
+ failure = error instanceof Error ? error.message : String(error);
352
+ }
353
+ if (response?.ok) {
354
+ const text = await response.text();
355
+ return parseDecision(text, offered);
356
+ }
357
+ if (response !== null && response.status !== 429 && response.status < 500) {
358
+ const text = await response.text();
359
+ throw new Error(`decision failed (HTTP ${response.status}): ${text.slice(0, 300)}`);
360
+ }
361
+ const reason = response === null ? failure : `HTTP ${response.status}`;
362
+ if (attempt >= config.decisionRetries) {
363
+ throw new Error(`decision failed after ${attempt + 1} attempts: ${reason}`);
364
+ }
365
+ await env.delay(500 * 2 ** attempt);
366
+ }
367
+ };
368
+ // ---- reflex + frame loop -----------------------------------------------
369
+ const pointerFrom = (input) => {
370
+ if (!input) {
371
+ return null;
372
+ }
373
+ const x = Number(input.x);
374
+ const y = Number(input.y);
375
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
376
+ return null;
377
+ }
378
+ return {
379
+ down: input.down === true,
380
+ x: Math.min(1, Math.max(0, x)),
381
+ y: Math.min(1, Math.max(0, y)),
382
+ };
383
+ };
384
+ const keysFrom = (codes) => {
385
+ const inits = [];
386
+ for (const code of codes ?? []) {
387
+ const init = config.keyTable[code];
388
+ if (init) {
389
+ inits.push(init);
390
+ }
391
+ }
392
+ return inits;
393
+ };
394
+ /** The keys of the chosen actions, deduplicated against `base`. */
395
+ const withActions = (base, decision) => {
396
+ const keys = [...base];
397
+ const seen = new Set(keys.map((init) => init.code));
398
+ for (const label of decision.actions) {
399
+ for (const init of config.actions[label]?.inits ?? []) {
400
+ if (!seen.has(init.code)) {
401
+ seen.add(init.code);
402
+ keys.push(init);
403
+ }
404
+ }
405
+ }
406
+ return keys;
407
+ };
408
+ const staticInputs = (decision) => {
409
+ const option = config.move[decision.move];
410
+ return { keys: withActions(option?.inits ?? [], decision), pointer: option?.pointer ?? null };
411
+ };
412
+ const runReflex = (current) => {
413
+ if (!current.reflex) {
414
+ return;
415
+ }
416
+ let inputs = null;
417
+ try {
418
+ inputs = current.reflex(env.live());
419
+ }
420
+ catch {
421
+ inputs = null;
422
+ }
423
+ if (!inputs) {
424
+ return;
425
+ }
426
+ // Actions the model chose stay held alongside whatever the reflex wants.
427
+ hold({
428
+ keys: withActions(keysFrom(inputs.keys), current.decision),
429
+ pointer: pointerFrom(inputs.pointer),
430
+ });
431
+ current.reflexFrames += 1;
432
+ };
433
+ const frame = () => {
434
+ if (stopped) {
435
+ return;
436
+ }
437
+ sample();
438
+ if (pending) {
439
+ runReflex(pending);
440
+ }
441
+ rafId = env.raf(frame);
442
+ };
443
+ // ---- the run -----------------------------------------------------------
444
+ /** At least two options have to survive any withdrawal: a choice needs them. */
445
+ const canWithdraw = () => Object.keys(config.move).length - blocked.length - 1 >= 2;
446
+ // The reflex layer for the model: a move that produced nothing for two
447
+ // ticks running is withdrawn from the question. Withdrawals accumulate
448
+ // while the player stays stuck — with a single slot the model alternates
449
+ // between the same two walls — and clear the moment it moves.
450
+ const withdrawIfStuck = (move, stuck, still) => {
451
+ if (!still) {
452
+ blocked = [];
453
+ }
454
+ else if (stuck &&
455
+ stuckRun >= config.stuckRun &&
456
+ move !== "none" &&
457
+ !blocked.includes(move) &&
458
+ canWithdraw()) {
459
+ blocked = [...blocked, move];
460
+ }
461
+ };
462
+ // Given a state that points nowhere, the model's safe answer is the option
463
+ // that holds nothing — confidently, every tick, and a playtester standing
464
+ // still learns nothing about the game. A few idle decisions in a row rest
465
+ // that option for a while, so the model has to commit to a direction; its
466
+ // confidence then says honestly how little the state told it.
467
+ const restIfIdle = (done, still) => {
468
+ const option = config.move[done.decision.move];
469
+ const idle = done.reflex === null &&
470
+ option !== undefined &&
471
+ option.inits.length === 0 &&
472
+ option.pointer === null;
473
+ idleRun = idle && still ? idleRun + 1 : 0;
474
+ if (idleRun >= config.idleRun && canWithdraw()) {
475
+ rested = { label: done.decision.move, untilTick: done.tick + 1 + config.idleRestTicks };
476
+ idleRun = 0;
477
+ }
478
+ };
479
+ const settle = (done, measured) => {
480
+ const option = config.move[done.decision.move];
481
+ // Only a held direction can be "stuck". A parked pointer that has arrived
482
+ // and a reflex that has converged are both still because they worked.
483
+ const askedToMove = done.reflex === null &&
484
+ option !== undefined &&
485
+ (option.inits.length > 0 || option.pointer?.down === true);
486
+ const progressed = measured.score > measured.scoreBefore;
487
+ let stuck = false;
488
+ if (askedToMove) {
489
+ stuck =
490
+ measured.frame > measured.frameBefore &&
491
+ measured.peak < config.motionEpsilon &&
492
+ !progressed;
493
+ stuckRun = stuck ? stuckRun + 1 : 0;
494
+ }
495
+ const still = measured.peak < config.motionEpsilon && !progressed;
496
+ withdrawIfStuck(done.decision.move, stuck, still);
497
+ restIfIdle(done, still);
498
+ trail.push({ x: round(measured.x), y: round(measured.y), z: round(measured.z) });
499
+ if (trail.length > config.trailLength) {
500
+ trail.shift();
501
+ }
502
+ lastWindow = measured;
503
+ result.records.push({
504
+ actionProbabilities: done.decision.actionProbabilities,
505
+ actions: done.decision.actions,
506
+ askedToMove,
507
+ confidence: done.decision.confidence,
508
+ decisionMs: done.decisionMs,
509
+ inputTokens: done.decision.inputTokens,
510
+ move: done.decision.move,
511
+ outputTokens: done.decision.outputTokens,
512
+ progress: done.decision.progress,
513
+ reflexFrames: done.reflexFrames,
514
+ tick: done.tick,
515
+ window: measured,
516
+ });
517
+ };
518
+ const stateFor = (game, tick) => ({
519
+ game,
520
+ goal: config.goal,
521
+ recent: {
522
+ blockedMoves: blocked,
523
+ held: pending ? { actions: pending.decision.actions, move: pending.decision.move } : null,
524
+ movedLastTick: lastWindow ? lastWindow.peak : null,
525
+ scoreDeltaLastTick: lastWindow ? lastWindow.score - lastWindow.scoreBefore : null,
526
+ stuckTicksInARow: stuckRun,
527
+ trail,
528
+ },
529
+ tick: { index: tick, of: config.ticks },
530
+ });
531
+ const record = (decision, decisionMs) => {
532
+ usage.calls += 1;
533
+ usage.inputTokens += decision.inputTokens;
534
+ usage.outputTokens += decision.outputTokens;
535
+ usage.totalDecisionMs += decisionMs;
536
+ usage.maxDecisionMs = Math.max(usage.maxDecisionMs, decisionMs);
537
+ };
538
+ const run = async () => {
539
+ rafId = env.raf(frame);
540
+ let game = env.snapshot();
541
+ for (let tick = 0; tick < config.ticks; tick += 1) {
542
+ if (stopped) {
543
+ break;
544
+ }
545
+ const t0 = env.now();
546
+ const decision = await decide(stateFor(game, tick));
547
+ const decisionMs = env.now() - t0;
548
+ record(decision, decisionMs);
549
+ if (stopped) {
550
+ break;
551
+ }
552
+ // A floor on how long the previous inputs stay down, for a slower player.
553
+ if (pending) {
554
+ const remaining = config.tickMs - (env.now() - pending.appliedAt);
555
+ if (remaining > 0) {
556
+ await env.delay(remaining);
557
+ }
558
+ }
559
+ // An option with a reflex takes over on the next frame; applying its
560
+ // (empty) static inputs first would drop the pointer the reflex holds,
561
+ // and a held button would be released and re-pressed on every decision.
562
+ const reflex = env.reflexFor(decision.move);
563
+ release(decision.actions.flatMap((label) => config.actions[label]?.inits ?? []));
564
+ if (!reflex) {
565
+ hold(staticInputs(decision));
566
+ }
567
+ const measured = flush();
568
+ if (pending) {
569
+ settle(pending, measured);
570
+ }
571
+ pending = { appliedAt: env.now(), decision, decisionMs, reflex, reflexFrames: 0, tick };
572
+ game = env.snapshot();
573
+ if (measured.complete) {
574
+ // The game ended under the previous decision's inputs; this one
575
+ // never got a window and is not counted.
576
+ result.completedAtTick = Math.max(0, tick - 1);
577
+ pending = null;
578
+ break;
579
+ }
580
+ }
581
+ if (pending && !stopped) {
582
+ await env.delay(Math.max(config.tickMs, config.finalHoldMs));
583
+ const measured = flush();
584
+ settle(pending, measured);
585
+ if (measured.complete && result.completedAtTick === null) {
586
+ result.completedAtTick = pending.tick;
587
+ }
588
+ pending = null;
589
+ }
590
+ };
591
+ const finish = (error) => {
592
+ stopped = true;
593
+ env.caf(rafId);
594
+ hold({ keys: [], pointer: null });
595
+ result.error = error;
596
+ result.wallMs = env.now() - started;
597
+ result.done = true;
598
+ };
599
+ const main = async () => {
600
+ try {
601
+ await run();
602
+ finish(null);
603
+ }
604
+ catch (error) {
605
+ finish(error instanceof Error ? error.message : String(error));
606
+ }
607
+ };
608
+ void main();
609
+ return result;
610
+ };