vibedgames 0.5.1 → 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.
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Orchestrates one model playtest: build the in-page agent's config from the
3
+ * control scheme, inject it, wait for it to finish, and turn its records into
4
+ * the report. The loop itself — decide, apply, measure, repeat, plus the
5
+ * per-frame reflex — runs inside the page (agent.ts); nothing here touches
6
+ * the game per tick.
7
+ */
8
+ import { setTimeout as delay } from "node:timers/promises";
9
+ import { isJsonObject, isJsonString } from "../types.js";
10
+ import { browserEnv, inPageAgent } from "./agent.js";
11
+ import { HarnessError } from "./errors.js";
12
+ import { keyInitsFor, keyTable } from "./keys.js";
13
+ export const THRESHOLDS = {
14
+ /** Mean `move` confidence below which the state is probably too thin to decide from. */
15
+ confidence: 0.3,
16
+ displacement: 5,
17
+ /**
18
+ * Frames a run must advance to count as alive — the bot's gate — capped by
19
+ * `minFps` × the run's wall time, because a model run can legitimately be
20
+ * a couple of seconds long where the scripted sweep is twelve.
21
+ */
22
+ framesAdvanced: 100,
23
+ /** Decisions a rested no-input option stays out of the question. */
24
+ idleRestTicks: 8,
25
+ /** Idle decisions in a row (holding nothing, going nowhere) before the no-input option is rested. */
26
+ idleRun: 3,
27
+ minFps: 10,
28
+ /**
29
+ * A window counts as "didn't move" below this fraction of the displacement
30
+ * gate, so both scale together when a game measures in world units.
31
+ */
32
+ motionEpsilonRatio: 0.04,
33
+ /** Stuck ticks in a row after which the agent withdraws the move. */
34
+ stuckRun: 2,
35
+ /**
36
+ * Stuck ticks in a row that fail the run. The decision after a withdrawal
37
+ * was already in flight when it landed, so `stuckRun + 1` is what hitting
38
+ * one wall costs; past that the alternatives went nowhere too.
39
+ */
40
+ wedgedRun: 5,
41
+ };
42
+ /** The input-alive gate for this scheme, in the game's own `player` units. */
43
+ export const displacementGate = (controls) => controls.minDisplacement ?? THRESHOLDS.displacement;
44
+ const motionEpsilon = (controls) => displacementGate(controls) * THRESHOLDS.motionEpsilonRatio;
45
+ /** A yes/no answer at or above this probability is acted on. */
46
+ export const ACTION_THRESHOLD = 0.5;
47
+ /** Positions kept in the state's `trail`, newest last. */
48
+ const TRAIL_LENGTH = 6;
49
+ /** How long the last decision is held before its window is read. */
50
+ const FINAL_HOLD_MS = 250;
51
+ const DECISION_RETRIES = 2;
52
+ const DECISION_TIMEOUT_MS = 10_000;
53
+ /** How often the CLI asks the page whether the agent is done. */
54
+ const POLL_MS = 250;
55
+ const round = (value) => Number(value.toFixed(2));
56
+ /** The agent's config for this scheme: every key pre-resolved to a proper event init. */
57
+ export const agentConfig = (opts, session) => {
58
+ const move = {};
59
+ for (const [label, option] of Object.entries(opts.controls.move)) {
60
+ move[label] = {
61
+ description: option.description,
62
+ inits: keyInitsFor(option.keys),
63
+ pointer: option.pointer
64
+ ? { down: option.pointer.down === true, x: option.pointer.x, y: option.pointer.y }
65
+ : null,
66
+ };
67
+ }
68
+ const actions = {};
69
+ for (const [label, action] of Object.entries(opts.controls.actions)) {
70
+ actions[label] = { description: action.description, inits: keyInitsFor(action.keys) };
71
+ }
72
+ return {
73
+ actionThreshold: ACTION_THRESHOLD,
74
+ actions,
75
+ decideUrl: session.decideUrl,
76
+ decisionRetries: DECISION_RETRIES,
77
+ decisionTimeoutMs: DECISION_TIMEOUT_MS,
78
+ finalHoldMs: FINAL_HOLD_MS,
79
+ goal: opts.controls.goal,
80
+ idleRestTicks: THRESHOLDS.idleRestTicks,
81
+ idleRun: THRESHOLDS.idleRun,
82
+ keyTable: keyTable(),
83
+ model: opts.model,
84
+ motionEpsilon: motionEpsilon(opts.controls),
85
+ move,
86
+ stuckRun: THRESHOLDS.stuckRun,
87
+ tickMs: opts.tickMs,
88
+ ticks: opts.ticks,
89
+ token: session.token,
90
+ trailLength: TRAIL_LENGTH,
91
+ };
92
+ };
93
+ /**
94
+ * The agent as page source: its own function text applied to the config and
95
+ * to the real-browser env. Both functions are self-contained by contract, so
96
+ * their `toString()` is all the page needs.
97
+ */
98
+ export const agentSource = (config) => `(${inPageAgent.toString()})(${JSON.stringify(config)}, (${browserEnv.toString()})())`;
99
+ /** Upper bound on a run, after which the agent is stopped and the run is a harness failure. */
100
+ const budgetMs = (opts) => opts.ticks * (Math.max(opts.tickMs, 150) + DECISION_TIMEOUT_MS + 3500) + FINAL_HOLD_MS + 15_000;
101
+ /** Fold one measured window into the running metrics. */
102
+ const measure = (metrics, window, askedToMove, index, epsilon) => {
103
+ metrics.distance += window.path;
104
+ metrics.maxTickDisplacement = Math.max(metrics.maxTickDisplacement, window.peak);
105
+ const progressed = window.score > window.scoreBefore;
106
+ if (progressed && metrics.tickOfFirstScore === null) {
107
+ metrics.tickOfFirstScore = index;
108
+ }
109
+ // Stuck signature: frames advanced, the model asked the player to move, and
110
+ // nothing came of it. Counted as a RUN: one dead tick is a wall, several in
111
+ // a row is a player wedged in geometry — or a model that keeps choosing the
112
+ // wall, which the agent's reflex exists to break.
113
+ let stuck = false;
114
+ if (askedToMove) {
115
+ stuck = window.frame > window.frameBefore && window.peak < epsilon && !progressed;
116
+ if (stuck) {
117
+ metrics.stuckTicks += 1;
118
+ metrics.stuckRun += 1;
119
+ metrics.longestStuckRun = Math.max(metrics.longestStuckRun, metrics.stuckRun);
120
+ }
121
+ else {
122
+ metrics.stuckRun = 0;
123
+ }
124
+ }
125
+ return { progressed, stuck };
126
+ };
127
+ const timelineEntry = (record, progressed, stuck) => ({
128
+ actionProbabilities: record.actionProbabilities,
129
+ actions: record.actions,
130
+ confidence: record.confidence,
131
+ decisionMs: record.decisionMs,
132
+ frames: record.window.frame - record.window.frameBefore,
133
+ move: record.move,
134
+ path: record.window.path,
135
+ peak: record.window.peak,
136
+ progress: record.progress,
137
+ progressed,
138
+ reflexFrames: record.reflexFrames,
139
+ scoreDelta: record.window.score - record.window.scoreBefore,
140
+ stuck,
141
+ tick: record.tick,
142
+ });
143
+ const num = (value) => (Number.isFinite(value) ? Number(value) : 0);
144
+ const readWindow = (value) => {
145
+ if (!isJsonObject(value)) {
146
+ return null;
147
+ }
148
+ return {
149
+ complete: value.complete === true,
150
+ frame: num(value.frame),
151
+ frameBefore: num(value.frameBefore),
152
+ path: num(value.path),
153
+ peak: num(value.peak),
154
+ score: num(value.score),
155
+ scoreBefore: num(value.scoreBefore),
156
+ x: num(value.x),
157
+ y: num(value.y),
158
+ z: num(value.z),
159
+ };
160
+ };
161
+ const readRecord = (value) => {
162
+ const window = isJsonObject(value) ? readWindow(value.window) : null;
163
+ if (!isJsonObject(value) || !window || !isJsonString(value.move)) {
164
+ throw new HarnessError(`the agent published a malformed record: ${JSON.stringify(value).slice(0, 200)}`);
165
+ }
166
+ const probabilities = {};
167
+ if (isJsonObject(value.actionProbabilities)) {
168
+ for (const [label, probability] of Object.entries(value.actionProbabilities)) {
169
+ probabilities[label] = num(probability);
170
+ }
171
+ }
172
+ return {
173
+ actionProbabilities: probabilities,
174
+ actions: Array.isArray(value.actions) ? value.actions.filter(isJsonString) : [],
175
+ askedToMove: value.askedToMove === true,
176
+ confidence: Number.isFinite(value.confidence) ? Number(value.confidence) : null,
177
+ decisionMs: num(value.decisionMs),
178
+ inputTokens: num(value.inputTokens),
179
+ move: value.move,
180
+ outputTokens: num(value.outputTokens),
181
+ progress: Number.isFinite(value.progress) ? Number(value.progress) : null,
182
+ reflexFrames: num(value.reflexFrames),
183
+ tick: num(value.tick),
184
+ window,
185
+ };
186
+ };
187
+ /** The agent's records, folded into metrics and a timeline. */
188
+ export const resultFromAgent = (published, epsilon = THRESHOLDS.displacement * THRESHOLDS.motionEpsilonRatio) => {
189
+ if (!isJsonObject(published)) {
190
+ throw new HarnessError("the page lost the agent before its result could be read.");
191
+ }
192
+ if (isJsonString(published.error)) {
193
+ throw new HarnessError(published.error);
194
+ }
195
+ const records = Array.isArray(published.records) ? published.records.map(readRecord) : [];
196
+ const metrics = {
197
+ distance: 0,
198
+ longestStuckRun: 0,
199
+ maxTickDisplacement: 0,
200
+ stuckRun: 0,
201
+ stuckTicks: 0,
202
+ tickOfFirstScore: null,
203
+ };
204
+ const timeline = [];
205
+ const usage = { calls: 0, inputTokens: 0, maxDecisionMs: 0, outputTokens: 0, totalDecisionMs: 0 };
206
+ let lastWindow = null;
207
+ for (const record of records) {
208
+ const { progressed, stuck } = measure(metrics, record.window, record.askedToMove, record.tick, epsilon);
209
+ timeline.push(timelineEntry(record, progressed, stuck));
210
+ usage.calls += 1;
211
+ usage.inputTokens += record.inputTokens;
212
+ usage.outputTokens += record.outputTokens;
213
+ usage.totalDecisionMs += record.decisionMs;
214
+ usage.maxDecisionMs = Math.max(usage.maxDecisionMs, record.decisionMs);
215
+ lastWindow = record.window;
216
+ }
217
+ return {
218
+ completedAtTick: Number.isFinite(published.completedAtTick)
219
+ ? Number(published.completedAtTick)
220
+ : null,
221
+ lastWindow,
222
+ metrics,
223
+ timeline,
224
+ usage,
225
+ wallMs: num(published.wallMs),
226
+ };
227
+ };
228
+ /** Inject the agent, wait for it to finish, and read its result. */
229
+ export const runInPage = async (browser, opts, session) => {
230
+ browser.inject(agentSource(agentConfig(opts, session)));
231
+ const deadline = Date.now() + budgetMs(opts);
232
+ for (;;) {
233
+ const status = browser.agentStatus();
234
+ if (!status) {
235
+ throw new HarnessError("the page lost the agent; it probably navigated mid-run.");
236
+ }
237
+ if (status.done) {
238
+ break;
239
+ }
240
+ if (Date.now() > deadline) {
241
+ browser.stopAgent();
242
+ throw new HarnessError(`the run did not finish within ${Math.round(budgetMs(opts) / 1000)} s.`);
243
+ }
244
+ await delay(POLL_MS);
245
+ }
246
+ return resultFromAgent(browser.agentResult(), motionEpsilon(opts.controls));
247
+ };
248
+ /**
249
+ * The model's own progress judgments folded into one trajectory — its read at
250
+ * the first and last decision, 0–1, plus the mean and the high-water mark —
251
+ * or null when it gave none. Inferred rather than named so the report stays
252
+ * a plain JSON shape for `--json` / `--field`.
253
+ */
254
+ const summarizeProgress = (timeline) => {
255
+ const scored = timeline.map((entry) => entry.progress).filter((p) => p !== null);
256
+ const [first] = scored;
257
+ const last = scored.at(-1);
258
+ if (first === undefined || last === undefined) {
259
+ return null;
260
+ }
261
+ let sum = 0;
262
+ let max = 0;
263
+ for (const value of scored) {
264
+ sum += value;
265
+ max = Math.max(max, value);
266
+ }
267
+ return {
268
+ first: round(first),
269
+ last: round(last),
270
+ max: round(max),
271
+ mean: round(sum / scored.length),
272
+ };
273
+ };
274
+ /** Per-run histograms of what the model chose, how sure it was about moving, and how it judged the run. */
275
+ const summarizeDecisions = (timeline) => {
276
+ const moves = {};
277
+ const actions = {};
278
+ let confidenceSum = 0;
279
+ let confidenceCount = 0;
280
+ let reflexFrames = 0;
281
+ for (const entry of timeline) {
282
+ moves[entry.move] = (moves[entry.move] ?? 0) + 1;
283
+ for (const label of entry.actions) {
284
+ actions[label] = (actions[label] ?? 0) + 1;
285
+ }
286
+ if (entry.confidence !== null) {
287
+ confidenceSum += entry.confidence;
288
+ confidenceCount += 1;
289
+ }
290
+ reflexFrames += entry.reflexFrames;
291
+ }
292
+ return {
293
+ actions,
294
+ meanConfidence: confidenceCount > 0 ? round(confidenceSum / confidenceCount) : null,
295
+ moves,
296
+ progress: summarizeProgress(timeline),
297
+ reflexFrames,
298
+ };
299
+ };
300
+ export const buildReport = (opts, input) => {
301
+ const { before, run } = input;
302
+ const last = run.lastWindow;
303
+ const seconds = run.wallMs / 1000;
304
+ return {
305
+ complete: last ? last.complete : before.complete,
306
+ completedAtTick: run.completedAtTick,
307
+ consoleErrors: input.consoleErrors,
308
+ decisions: summarizeDecisions(run.timeline),
309
+ decisionsPerSecond: seconds > 0 ? round(run.timeline.length / seconds) : null,
310
+ distanceTravelled: round(run.metrics.distance),
311
+ framesAdvanced: (last ? last.frame : before.frame) - before.frame,
312
+ goal: opts.controls.goal,
313
+ // Which GPU rasterized the run. Under software rendering the functional
314
+ // checks still hold; any frame-rate read from the run does not.
315
+ gpu: input.gpu,
316
+ longestStuckRun: run.metrics.longestStuckRun,
317
+ maxTickDisplacement: round(run.metrics.maxTickDisplacement),
318
+ // The gate `maxTickDisplacement` was held to, so the number reads in context.
319
+ minDisplacement: displacementGate(opts.controls),
320
+ model: {
321
+ calls: run.usage.calls,
322
+ id: opts.model,
323
+ inputTokens: run.usage.inputTokens,
324
+ maxDecisionMs: run.usage.maxDecisionMs,
325
+ meanDecisionMs: run.usage.calls > 0 ? Math.round(run.usage.totalDecisionMs / run.usage.calls) : null,
326
+ outputTokens: run.usage.outputTokens,
327
+ },
328
+ pageErrors: input.pageErrors,
329
+ scoreAfter: last ? last.score : before.score,
330
+ scoreBefore: before.score,
331
+ seed: input.seed,
332
+ // How the seed actually landed, so a reader can tell a real seeded run
333
+ // from one where the hook quietly did nothing.
334
+ seedApplied: input.seedApplied,
335
+ stuckTicks: run.metrics.stuckTicks,
336
+ target: input.target,
337
+ tickMs: opts.tickMs,
338
+ tickOfFirstScore: run.metrics.tickOfFirstScore,
339
+ ticks: opts.ticks,
340
+ ticksRun: run.timeline.length,
341
+ timeline: run.timeline,
342
+ wallMs: run.wallMs,
343
+ };
344
+ };
345
+ /** Failures fail the run; warnings are findings a reader should weigh. */
346
+ export const verdict = (report, opts) => {
347
+ const failures = [];
348
+ const warnings = [];
349
+ const framesRequired = Math.min(THRESHOLDS.framesAdvanced, Math.round((report.wallMs / 1000) * THRESHOLDS.minFps));
350
+ if (report.framesAdvanced <= framesRequired) {
351
+ failures.push(`game loop stalled (framesAdvanced ${report.framesAdvanced} over ${report.wallMs} ms)`);
352
+ }
353
+ // Gated on the largest displacement any ONE tick achieved, not on the
354
+ // summed path: path accumulates every sampled wobble, and an idle bob
355
+ // would drift past a total-distance threshold.
356
+ const gate = displacementGate(opts.controls);
357
+ const holdsInput = (label) => {
358
+ const option = opts.controls.move[label];
359
+ return (option !== undefined && (option.keys.length > 0 || option.pointer !== null || option.reflex));
360
+ };
361
+ const triedToMove = report.timeline.some((entry) => holdsInput(entry.move));
362
+ if (!triedToMove && report.timeline.length > 0) {
363
+ // Not dead input: input was never tried. Blaming the controls here sends
364
+ // the author to the wrong file.
365
+ failures.push("the model never chose a movement — 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");
366
+ }
367
+ else if (report.maxTickDisplacement <= gate) {
368
+ failures.push(`player did not respond to input (maxTickDisplacement ${report.maxTickDisplacement}, needs > ${gate}) — 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`);
369
+ }
370
+ if (report.longestStuckRun >= THRESHOLDS.wedgedRun) {
371
+ failures.push(`player wedged for ${report.longestStuckRun} consecutive movement ticks (longestStuckRun) — the model kept choosing moves that went nowhere`);
372
+ }
373
+ if (report.scoreAfter <= report.scoreBefore) {
374
+ const { progress } = report.decisions;
375
+ // The model's read of the goal is the tie-breaker the score field lacks:
376
+ // a goal like "survive the wave" never raises `score`, but a model that
377
+ // judged the player closer to it at the end than at the start did play.
378
+ let judged = "";
379
+ if (progress !== null) {
380
+ const trend = `progress ${progress.first} → ${progress.last}`;
381
+ judged =
382
+ progress.last > progress.first
383
+ ? ` (though the model judged the player closer to the goal by the end: ${trend})`
384
+ : ` (and the model agreed: ${trend})`;
385
+ }
386
+ const message = `the run never progressed the objective${judged}`;
387
+ if (opts.expectProgress) {
388
+ failures.push(message);
389
+ }
390
+ else {
391
+ warnings.push(`${message} — pass --expect-progress once the controls express this game's scoring verb, to make that an assertion`);
392
+ }
393
+ }
394
+ if (report.completedAtTick !== null) {
395
+ warnings.push(`the run ended at tick ${report.completedAtTick} of ${opts.ticks} (complete became true) — a win, or a fail state the playtester couldn't avoid; read the timeline to tell which`);
396
+ }
397
+ const { meanConfidence } = report.decisions;
398
+ if (meanConfidence !== null && meanConfidence < THRESHOLDS.confidence) {
399
+ warnings.push(`the model was rarely sure which way to move (mean confidence ${meanConfidence}) — the diagnostics probably don't expose what a player sees; add hazards, goals and nearby entities with positions to __GAME_DIAGNOSTICS__`);
400
+ }
401
+ if (report.consoleErrors.length > 0) {
402
+ failures.push(`${report.consoleErrors.length} console error(s)`);
403
+ }
404
+ if (report.pageErrors.length > 0) {
405
+ failures.push(`${report.pageErrors.length} uncaught page error(s)`);
406
+ }
407
+ return { failures, warnings };
408
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vibedgames",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "bin": {
6
6
  "vg": "./dist/index.js"