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,62 @@
1
+ export declare const playtestRunCommand: import("citty").CommandDef<{
2
+ readonly field: {
3
+ readonly description: "Print a single value from the JSON result, e.g. --field request_id or --field images[0].url. Prints scalars bare for shell capture.";
4
+ readonly type: "string";
5
+ };
6
+ readonly json: {
7
+ readonly description: "Print structured JSON to stdout.";
8
+ readonly type: "boolean";
9
+ };
10
+ readonly controls: {
11
+ readonly description: `Control scheme: a preset (${string}) or a JSON file. Default: the game's window.__GAME_PLAYTEST__ if it publishes one, else wasd.`;
12
+ readonly type: "string";
13
+ };
14
+ readonly expectProgress: {
15
+ readonly description: "Assert the objective advances (score rises) during the run.";
16
+ readonly type: "boolean";
17
+ };
18
+ readonly game: {
19
+ readonly description: "Deployed game slug to playtest (mutually exclusive with --url).";
20
+ readonly type: "string";
21
+ };
22
+ readonly goal: {
23
+ readonly description: "What the playtester is trying to do — what wins, what kills, which way is progress. Overrides the scheme's goal.";
24
+ readonly type: "string";
25
+ };
26
+ readonly headed: {
27
+ readonly description: "Show the browser.";
28
+ readonly type: "boolean";
29
+ };
30
+ readonly keepOpen: {
31
+ readonly description: "Leave the page open afterwards.";
32
+ readonly type: "boolean";
33
+ };
34
+ readonly minDisplacement: {
35
+ readonly description: "Per-decision movement that proves input works, in the units of the game's player.x/y (default 5 — pixels; a game in world units needs far less). Overrides the scheme's.";
36
+ readonly type: "string";
37
+ };
38
+ readonly model: {
39
+ readonly default: "jev-latest";
40
+ readonly description: "Decision model id.";
41
+ readonly type: "string";
42
+ };
43
+ readonly seed: {
44
+ readonly default: "12345";
45
+ readonly description: "Seed for the game's RNG.";
46
+ readonly type: "string";
47
+ };
48
+ readonly tickMs: {
49
+ readonly default: string;
50
+ readonly 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.`;
51
+ readonly type: "string";
52
+ };
53
+ readonly ticks: {
54
+ readonly default: "60";
55
+ readonly description: "Decisions to make.";
56
+ readonly type: "string";
57
+ };
58
+ readonly url: {
59
+ readonly description: "Where the game is served (mutually exclusive with --game).";
60
+ readonly type: "string";
61
+ };
62
+ }>;
@@ -0,0 +1,258 @@
1
+ import { defineCommand } from "citty";
2
+ import { consola } from "consola";
3
+ import { authErrorCode, createClient } from "../lib/api.js";
4
+ import { getBaseUrl, getToken } from "../lib/config.js";
5
+ import { outputArgs, writeStructured } from "../lib/output.js";
6
+ import { GameBrowser } from "../lib/playtest/browser.js";
7
+ import { DEFAULT_PRESET, PRESETS, PRESET_NAMES, parseControls, readControlsArg, } from "../lib/playtest/controls.js";
8
+ import { HarnessError } from "../lib/playtest/errors.js";
9
+ import { buildReport, runInPage, verdict } from "../lib/playtest/run.js";
10
+ import { assertKnownFlags } from "../lib/strict-args.js";
11
+ import { ensureAgentBrowser, projectSessionId, resolveGameUrl } from "./playtest.js";
12
+ /**
13
+ * `vg playtest run` — let a model play the game, and report how it went.
14
+ *
15
+ * The loop runs inside the game's page: several times a second it reads
16
+ * `window.__GAME_DIAGNOSTICS__`, asks the decision model (via
17
+ * `/api/playtest/decide` with a short-lived token; the server holds the
18
+ * provider key) which movement to hold and which actions to take, dispatches
19
+ * them as real held input, and repeats — with a per-frame reflex where the
20
+ * game's `__GAME_PLAYTEST__` provides one. Code does perception and
21
+ * keystrokes; the model only decides.
22
+ *
23
+ * Exit 0 = the game plays under the model. Exit 1 = it doesn't (the report
24
+ * says why). Exit 2 = the harness itself failed (bad flags, no browser, the
25
+ * game never booted, the model unreachable).
26
+ */
27
+ const HARNESS_FAILURE = 2;
28
+ /**
29
+ * Floor on the hold, so a fast model doesn't play at a jittery superhuman
30
+ * rate: ~6 decisions a second is a quick human's cadence. A real decision
31
+ * round trip is usually longer than this, in which case it never binds.
32
+ */
33
+ const DEFAULT_TICK_MS = 150;
34
+ const runArgs = {
35
+ controls: {
36
+ 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}.`,
37
+ type: "string",
38
+ },
39
+ expectProgress: {
40
+ description: "Assert the objective advances (score rises) during the run.",
41
+ type: "boolean",
42
+ },
43
+ game: {
44
+ description: "Deployed game slug to playtest (mutually exclusive with --url).",
45
+ type: "string",
46
+ },
47
+ goal: {
48
+ description: "What the playtester is trying to do — what wins, what kills, which way is progress. Overrides the scheme's goal.",
49
+ type: "string",
50
+ },
51
+ headed: { description: "Show the browser.", type: "boolean" },
52
+ keepOpen: { description: "Leave the page open afterwards.", type: "boolean" },
53
+ minDisplacement: {
54
+ description: "Per-decision movement that proves input works, in the units of the game's player.x/y (default 5 — pixels; a game in world units needs far less). Overrides the scheme's.",
55
+ type: "string",
56
+ },
57
+ model: { default: "jev-latest", description: "Decision model id.", type: "string" },
58
+ seed: { default: "12345", description: "Seed for the game's RNG.", type: "string" },
59
+ tickMs: {
60
+ default: String(DEFAULT_TICK_MS),
61
+ 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.`,
62
+ type: "string",
63
+ },
64
+ ticks: { default: "60", description: "Decisions to make.", type: "string" },
65
+ url: {
66
+ description: "Where the game is served (mutually exclusive with --game).",
67
+ type: "string",
68
+ },
69
+ ...outputArgs,
70
+ };
71
+ const numberArg = (raw, flag, check, hint) => {
72
+ // `Number("")` is 0, not NaN, so an empty value would slip past otherwise.
73
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
74
+ if (!check(value)) {
75
+ throw new HarnessError(`\`${flag}\` must be ${hint}.`);
76
+ }
77
+ return value;
78
+ };
79
+ const settingsFrom = (args) => {
80
+ if (!args.url && !args.game) {
81
+ throw new HarnessError("Pass --url <url> or --game <slug>.");
82
+ }
83
+ if (args.url && args.game) {
84
+ throw new HarnessError("Pass either --url or --game, not both.");
85
+ }
86
+ if (args.goal !== undefined && args.goal.trim() === "") {
87
+ throw new HarnessError("`--goal` must not be empty.");
88
+ }
89
+ if (args.model.trim() === "") {
90
+ throw new HarnessError("`--model` must not be empty.");
91
+ }
92
+ return {
93
+ expectProgress: args.expectProgress === true,
94
+ explicitControls: args.controls === undefined ? null : readControlsArg(args.controls),
95
+ goal: args.goal ?? null,
96
+ headed: args.headed === true,
97
+ keepOpen: args.keepOpen === true,
98
+ minDisplacement: args.minDisplacement === undefined
99
+ ? null
100
+ : numberArg(args.minDisplacement, "--min-displacement", (n) => Number.isFinite(n) && n > 0, "a positive number"),
101
+ model: args.model,
102
+ seed: numberArg(args.seed, "--seed", Number.isFinite, "a finite number"),
103
+ target: args.game ? `game:${args.game}` : (args.url ?? ""),
104
+ tickMs: numberArg(args.tickMs, "--tick-ms", (n) => Number.isFinite(n) && n >= 0 && n <= 5000, "between 0 and 5000 milliseconds"),
105
+ ticks: numberArg(args.ticks, "--ticks", (n) => Number.isInteger(n) && n > 0, "a positive integer"),
106
+ url: args.url ?? resolveGameUrl(args.game ?? null),
107
+ };
108
+ };
109
+ /**
110
+ * Which scheme drives this run: an explicit `--controls`, else the game's
111
+ * own manifest, else the wasd preset. `--goal` wins over all of them.
112
+ */
113
+ const chooseControls = (settings, manifest) => {
114
+ let controls = settings.explicitControls;
115
+ if (!controls) {
116
+ controls =
117
+ manifest === null
118
+ ? PRESETS.get(DEFAULT_PRESET)
119
+ : parseControls(manifest, "window.__GAME_PLAYTEST__");
120
+ }
121
+ if (!controls) {
122
+ throw new HarnessError("no control scheme available.");
123
+ }
124
+ return {
125
+ ...controls,
126
+ goal: settings.goal ?? controls.goal,
127
+ minDisplacement: settings.minDisplacement ?? controls.minDisplacement,
128
+ };
129
+ };
130
+ const isLoopback = (url) => {
131
+ const host = URL.canParse(url) ? new URL(url).hostname : null;
132
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
133
+ };
134
+ /**
135
+ * The page calls the API itself, and Chrome refuses a public page a request
136
+ * to a loopback address. Said up front, because in the page it is only ever
137
+ * "Failed to fetch".
138
+ */
139
+ const assertReachable = (gameUrl) => {
140
+ if (isLoopback(getBaseUrl()) && !isLoopback(gameUrl)) {
141
+ throw new HarnessError(`the game at ${gameUrl} is a public page and the API (${getBaseUrl()}) is on localhost — the browser blocks that request. Serve the game locally, or point VG_API_URL at a deployed API.`);
142
+ }
143
+ };
144
+ /**
145
+ * A token for this run, from `playtest.session`, and where the page should
146
+ * send decisions. The token is all the (untrusted) game page ever holds.
147
+ */
148
+ const mintSession = async (client) => {
149
+ try {
150
+ const { token } = await client.playtest.session();
151
+ return { decideUrl: new URL("/api/playtest/decide", getBaseUrl()).toString(), token };
152
+ }
153
+ catch (error) {
154
+ const code = authErrorCode(error);
155
+ if (code === "UNAUTHORIZED" || code === "FORBIDDEN") {
156
+ throw new HarnessError("Not authenticated. Run `vg login`, or check your VG_TOKEN / API key.");
157
+ }
158
+ throw new HarnessError(`couldn't start a playtest session: ${error instanceof Error ? error.message : String(error)}`);
159
+ }
160
+ };
161
+ const summarize = (report, failures, warnings) => {
162
+ const rate = report.decisionsPerSecond === null ? "" : ` at ${report.decisionsPerSecond}/s`;
163
+ consola.log(`The model made ${report.ticksRun} decisions${rate} (mean ${report.model.meanDecisionMs ?? "?"} ms each) on ${report.target}`);
164
+ consola.log(` frames +${report.framesAdvanced} moved ${report.distanceTravelled} (peak ${report.maxTickDisplacement}/tick) score ${report.scoreBefore} → ${report.scoreAfter} stuck ${report.stuckTicks} (longest run ${report.longestStuckRun})`);
165
+ const moves = Object.entries(report.decisions.moves)
166
+ .map(([label, count]) => `${label}×${count}`)
167
+ .join(" ");
168
+ const { progress } = report.decisions;
169
+ const judged = progress === null ? "n/a" : `${progress.first} → ${progress.last}`;
170
+ consola.log(` moves: ${moves || "none"} confidence ${report.decisions.meanConfidence ?? "n/a"} progress ${judged} tokens ${report.model.inputTokens}`);
171
+ for (const warning of warnings) {
172
+ consola.warn(warning);
173
+ }
174
+ if (failures.length > 0) {
175
+ consola.error(`FAILED — ${failures.join("; ")}`);
176
+ }
177
+ else {
178
+ consola.success("PASSED");
179
+ }
180
+ };
181
+ export const playtestRunCommand = defineCommand({
182
+ args: runArgs,
183
+ meta: {
184
+ description: "Let a model play the game and report how it went — reads the game's diagnostics each tick, decides what to hold, drives real input. Needs the diagnostics contract (see the playtest skill).",
185
+ name: "run",
186
+ },
187
+ run: async ({ args, rawArgs }) => {
188
+ assertKnownFlags(rawArgs, runArgs);
189
+ let settings;
190
+ try {
191
+ settings = settingsFrom(args);
192
+ }
193
+ catch (error) {
194
+ consola.error(error instanceof Error ? error.message : String(error));
195
+ process.exit(HARNESS_FAILURE);
196
+ }
197
+ if (!getToken()) {
198
+ consola.warn("Not logged in. Run `vg login` to authenticate.");
199
+ process.exit(1);
200
+ }
201
+ const client = createClient();
202
+ const { bin } = ensureAgentBrowser();
203
+ const browser = new GameBrowser(bin, process.env.AGENT_BROWSER_SESSION ?? projectSessionId());
204
+ // Ctrl-C mid-hold leaves the key down and the sampler running in a daemon
205
+ // page that outlives this process — the same poison an early exit causes.
206
+ for (const signal of ["SIGINT", "SIGTERM"]) {
207
+ process.on(signal, () => {
208
+ browser.stopAgent();
209
+ process.exit(HARNESS_FAILURE);
210
+ });
211
+ }
212
+ let opts;
213
+ let payload;
214
+ try {
215
+ assertReachable(settings.url);
216
+ const session = await mintSession(client);
217
+ const launched = browser.launch({
218
+ headed: settings.headed,
219
+ seed: settings.seed,
220
+ url: settings.url,
221
+ });
222
+ opts = {
223
+ controls: chooseControls(settings, launched.manifest),
224
+ expectProgress: settings.expectProgress,
225
+ model: settings.model,
226
+ tickMs: settings.tickMs,
227
+ ticks: settings.ticks,
228
+ };
229
+ const run = await runInPage(browser, opts, session);
230
+ const report = buildReport(opts, {
231
+ before: launched.before,
232
+ consoleErrors: browser.consoleErrors(),
233
+ gpu: browser.gpuInfo(),
234
+ pageErrors: browser.pageErrors(),
235
+ run,
236
+ seed: settings.seed,
237
+ seedApplied: launched.seedApplied,
238
+ target: settings.target,
239
+ });
240
+ payload = { ...report, ...verdict(report, opts) };
241
+ }
242
+ catch (error) {
243
+ browser.stopAgent();
244
+ const message = error instanceof Error ? error.message : String(error);
245
+ consola.error(error instanceof HarnessError ? message : `playtest harness failed: ${message}`);
246
+ process.exit(HARNESS_FAILURE);
247
+ }
248
+ if (!settings.keepOpen) {
249
+ browser.close();
250
+ }
251
+ if (!writeStructured(payload, args)) {
252
+ summarize(payload, payload.failures, payload.warnings);
253
+ }
254
+ if (payload.failures.length > 0) {
255
+ process.exit(1);
256
+ }
257
+ },
258
+ });
@@ -1,10 +1,33 @@
1
+ export interface Binary {
2
+ bin: string;
3
+ version: string;
4
+ }
5
+ /** The agent-browser binary to use. VG_AGENT_BROWSER_BIN overrides (dev). */
6
+ export declare const resolveBinary: () => Binary | null;
7
+ /**
8
+ * Install agent-browser globally, then provision its browser. Upstream ships
9
+ * these as two steps (`npm i -g` puts the Rust binary in place; `install`
10
+ * fetches Chrome for Testing and reuses an existing Chrome/Brave/Playwright
11
+ * install when it finds one), so a first run pays for both.
12
+ */
13
+ export declare const bootstrap: () => Binary;
14
+ /**
15
+ * Bring an agent-browser older than the minimum up to it.
16
+ *
17
+ * The floor exists because agent-browser is pre-1.0: the playtest skill teaches
18
+ * a command surface, and the bot script depends on response shapes, both of
19
+ * which a minor bump can move. Installing the spec only on first use would
20
+ * leave an older global install — already on PATH from some earlier project —
21
+ * driving every run, which is how a documented contract silently stops holding.
22
+ */
23
+ export declare const ensureMinimum: (resolved: Binary) => Binary;
1
24
  /**
2
25
  * The URL a game is served at: a per-slug subdomain of whatever host this CLI
3
26
  * is pointed at, so `VG_API_URL=…staging vg playtest --game x` playtests
4
27
  * staging rather than silently hitting production the way a hardcoded apex
5
28
  * would. Mirrors the derivation the deploy router does server-side.
6
29
  */
7
- declare const resolveGameUrl: (slug: string | null) => string;
30
+ export declare const resolveGameUrl: (slug: string | null) => string;
8
31
  /**
9
32
  * The tokens in `args` that aren't flags or flag values — agent-browser's verb
10
33
  * and its positional arguments, in order.
@@ -35,7 +58,19 @@ export declare const expandGameFlag: (args: string[], resolveUrl?: typeof resolv
35
58
  * every session, not just this project's).
36
59
  */
37
60
  export declare const withScopedSession: (args: string[], sessionId: () => string) => string[];
61
+ /**
62
+ * A stable per-project session name. Keyed on the project root when there is
63
+ * one so every command run from anywhere inside the project shares a browser,
64
+ * and on the cwd otherwise. Hashed because the name lands in a socket path.
65
+ */
66
+ export declare const projectSessionId: () => string;
67
+ /**
68
+ * The agent-browser to drive: installed on first use, upgraded to the floor
69
+ * when older. Bootstrap covers `install` too: on a fresh machine that's the
70
+ * most natural first command, and re-running the provision step it just did
71
+ * is harmless.
72
+ */
73
+ export declare const ensureAgentBrowser: () => Binary;
38
74
  /** Resolve (installing on first use) and exec agent-browser. Never returns. */
39
75
  export declare const runPlaytest: (rawArgs: string[]) => never;
40
76
  export declare const playtestCommand: import("citty").CommandDef<import("citty").ArgsDef>;
41
- export {};
@@ -72,7 +72,7 @@ const installedVersion = (bin) => {
72
72
  */
73
73
  const meetsMinimum = (version) => !isNewerVersion(MIN_VERSION, version);
74
74
  /** The agent-browser binary to use. VG_AGENT_BROWSER_BIN overrides (dev). */
75
- const resolveBinary = () => {
75
+ export const resolveBinary = () => {
76
76
  const override = process.env.VG_AGENT_BROWSER_BIN;
77
77
  // A dev-pointed binary is taken on trust — it is typically a local build with
78
78
  // no npm version to read, and `meetsMinimum` waves an unparseable one through.
@@ -98,7 +98,7 @@ const installGlobal = () => {
98
98
  * fetches Chrome for Testing and reuses an existing Chrome/Brave/Playwright
99
99
  * install when it finds one), so a first run pays for both.
100
100
  */
101
- const bootstrap = () => {
101
+ export const bootstrap = () => {
102
102
  consola.start(`Installing the playtest browser (${PKG})…`);
103
103
  const resolved = installGlobal();
104
104
  if (!resolved) {
@@ -137,7 +137,7 @@ const recentlyFailed = (stamp) => {
137
137
  * leave an older global install — already on PATH from some earlier project —
138
138
  * driving every run, which is how a documented contract silently stops holding.
139
139
  */
140
- const ensureMinimum = (resolved) => {
140
+ export const ensureMinimum = (resolved) => {
141
141
  if (meetsMinimum(resolved.version)) {
142
142
  return resolved;
143
143
  }
@@ -189,7 +189,7 @@ const projectSlug = () => {
189
189
  * staging rather than silently hitting production the way a hardcoded apex
190
190
  * would. Mirrors the derivation the deploy router does server-side.
191
191
  */
192
- const resolveGameUrl = (slug) => {
192
+ export const resolveGameUrl = (slug) => {
193
193
  const resolved = slug ?? projectSlug();
194
194
  // The slug lands in the host, so anything outside the deploy grammar could
195
195
  // steer the browser off `*.vibedgames.com` entirely — `../`, an embedded
@@ -337,24 +337,31 @@ export const withScopedSession = (args, sessionId) => {
337
337
  * one so every command run from anywhere inside the project shares a browser,
338
338
  * and on the cwd otherwise. Hashed because the name lands in a socket path.
339
339
  */
340
- const projectSessionId = () => {
340
+ export const projectSessionId = () => {
341
341
  const root = findProjectRoot(process.cwd()) ?? process.cwd();
342
342
  const digest = createHash("sha256").update(root).digest("hex").slice(0, 12);
343
343
  return `vg-${digest}`;
344
344
  };
345
+ /**
346
+ * The agent-browser to drive: installed on first use, upgraded to the floor
347
+ * when older. Bootstrap covers `install` too: on a fresh machine that's the
348
+ * most natural first command, and re-running the provision step it just did
349
+ * is harmless.
350
+ */
351
+ export const ensureAgentBrowser = () => {
352
+ const resolved = resolveBinary();
353
+ return resolved ? ensureMinimum(resolved) : bootstrap();
354
+ };
345
355
  /** Resolve (installing on first use) and exec agent-browser. Never returns. */
346
356
  export const runPlaytest = (rawArgs) => {
347
357
  const args = withScopedSession(expandGameFlag(rawArgs), projectSessionId);
348
- // Bootstrap covers `install` too: on a fresh machine that's the most natural
349
- // first command, and re-running the provision step it just did is harmless.
350
- const resolved = resolveBinary();
351
- const { bin } = resolved ? ensureMinimum(resolved) : bootstrap();
358
+ const { bin } = ensureAgentBrowser();
352
359
  const result = spawn.sync(bin, args, { stdio: "inherit" });
353
360
  process.exit(result.status ?? 1);
354
361
  };
355
362
  export const playtestCommand = defineCommand({
356
363
  meta: {
357
- description: "Drive a real browser to play a game — snapshot, click, hold keys, read state, screenshot, diff (installs the browser on first use). All arguments pass through: `vg playtest open <url>`, `vg playtest --game <slug>` to open a deployed game, `vg playtest --help` for the full command surface.",
364
+ description: "Drive a real browser to play a game — snapshot, click, hold keys, read state, screenshot, diff (installs the browser on first use). All arguments pass through: `vg playtest open <url>`, `vg playtest --game <slug>` to open a deployed game, `vg playtest --help` for the full command surface. `vg playtest run` is the exception: a model plays the game and reports (`vg playtest run --help`).",
358
365
  name: "playtest",
359
366
  },
360
367
  run: ({ rawArgs }) => {
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { initCommand } from "./commands/init.js";
11
11
  import { loginCommand } from "./commands/login.js";
12
12
  import { logoutCommand } from "./commands/logout.js";
13
13
  import { newCommand } from "./commands/new.js";
14
+ import { playtestRunCommand } from "./commands/playtest-run.js";
14
15
  import { playtestCommand, runPlaytest } from "./commands/playtest.js";
15
16
  import { updateCommand } from "./commands/update.js";
16
17
  import { whoamiCommand } from "./commands/whoami.js";
@@ -35,7 +36,16 @@ const main = defineCommand({
35
36
  login: loginCommand,
36
37
  logout: logoutCommand,
37
38
  new: newCommand,
38
- playtest: playtestCommand,
39
+ // `run` is the one `vg playtest` verb that is ours rather than
40
+ // agent-browser's: the model-driven playtest. index.ts routes every other
41
+ // `vg playtest …` straight to the binary below. Only the meta is reused:
42
+ // citty runs a parent's `run` AFTER its subcommand, so carrying the
43
+ // passthrough here would forward `run …` to agent-browser once the
44
+ // playtest had finished and turn every passing run into an exit 1.
45
+ playtest: defineCommand({
46
+ meta: playtestCommand.meta,
47
+ subCommands: { run: playtestRunCommand },
48
+ }),
39
49
  update: updateCommand,
40
50
  whoami: whoamiCommand,
41
51
  },
@@ -53,7 +63,7 @@ if (subcommand && !["update", "init", "completions"].includes(subcommand)) {
53
63
  if (subcommand === "factory") {
54
64
  runFactory(process.argv.slice(3));
55
65
  }
56
- if (subcommand === "playtest") {
66
+ if (subcommand === "playtest" && process.argv.at(3) !== "run") {
57
67
  runPlaytest(process.argv.slice(3));
58
68
  }
59
69
  runMain(main);
@@ -0,0 +1,188 @@
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
+ /** A parsed JSON document — the shape of everything that crosses the page boundary. */
26
+ type Json = string | number | boolean | null | Json[] | {
27
+ [key: string]: Json;
28
+ };
29
+ export interface AgentKeyInit {
30
+ code: string;
31
+ key: string;
32
+ keyCode: number;
33
+ which: number;
34
+ altKey: boolean;
35
+ ctrlKey: boolean;
36
+ shiftKey: boolean;
37
+ bubbles: true;
38
+ }
39
+ export interface AgentPointer {
40
+ x: number;
41
+ y: number;
42
+ down: boolean;
43
+ }
44
+ export interface AgentMove {
45
+ description: string;
46
+ inits: AgentKeyInit[];
47
+ pointer: AgentPointer | null;
48
+ }
49
+ export interface AgentAction {
50
+ description: string;
51
+ inits: AgentKeyInit[];
52
+ }
53
+ export interface AgentConfig {
54
+ decideUrl: string;
55
+ token: string;
56
+ model: string;
57
+ goal: string;
58
+ move: Record<string, AgentMove>;
59
+ actions: Record<string, AgentAction>;
60
+ /** Every supported KeyboardEvent code, for inputs a reflex returns. */
61
+ keyTable: Record<string, AgentKeyInit>;
62
+ ticks: number;
63
+ tickMs: number;
64
+ finalHoldMs: number;
65
+ actionThreshold: number;
66
+ motionEpsilon: number;
67
+ stuckRun: number;
68
+ /** Decisions in a row of holding nothing, going nowhere, before the no-input option is rested. */
69
+ idleRun: number;
70
+ /** How many decisions a rested no-input option stays out of the question. */
71
+ idleRestTicks: number;
72
+ trailLength: number;
73
+ decisionRetries: number;
74
+ decisionTimeoutMs: number;
75
+ }
76
+ export interface AgentSample {
77
+ x: number;
78
+ y: number;
79
+ z: number;
80
+ frame: number;
81
+ score: number;
82
+ complete: boolean;
83
+ }
84
+ export interface AgentWindow {
85
+ path: number;
86
+ peak: number;
87
+ frameBefore: number;
88
+ frame: number;
89
+ scoreBefore: number;
90
+ score: number;
91
+ x: number;
92
+ y: number;
93
+ z: number;
94
+ complete: boolean;
95
+ }
96
+ export interface AgentRecord {
97
+ tick: number;
98
+ move: string;
99
+ actions: string[];
100
+ actionProbabilities: Record<string, number>;
101
+ confidence: number | null;
102
+ decisionMs: number;
103
+ inputTokens: number;
104
+ outputTokens: number;
105
+ /** Frames on which the option's reflex produced the held input. */
106
+ reflexFrames: number;
107
+ /**
108
+ * The model's own read of how close the player is to `goal`, 0–1, from the
109
+ * `progress` score question; null when it gave none.
110
+ */
111
+ progress: number | null;
112
+ /** Whether the move asked the player to move at all, so a still window can count as stuck. */
113
+ askedToMove: boolean;
114
+ window: AgentWindow;
115
+ }
116
+ export interface AgentUsage {
117
+ calls: number;
118
+ inputTokens: number;
119
+ outputTokens: number;
120
+ totalDecisionMs: number;
121
+ maxDecisionMs: number;
122
+ }
123
+ export interface AgentResult {
124
+ done: boolean;
125
+ error: string | null;
126
+ records: AgentRecord[];
127
+ usage: AgentUsage;
128
+ wallMs: number;
129
+ completedAtTick: number | null;
130
+ stop: () => void;
131
+ }
132
+ /** The game's diagnostics, as far as the agent reads them. */
133
+ export interface Diagnostics {
134
+ frame?: number;
135
+ score?: number;
136
+ complete?: boolean;
137
+ player?: {
138
+ x?: number;
139
+ y?: number;
140
+ z?: number;
141
+ };
142
+ }
143
+ /** What a reflex may hand back: key codes to hold and/or a pointer position. */
144
+ export interface ReflexInputs {
145
+ keys?: string[];
146
+ pointer?: {
147
+ x: number;
148
+ y: number;
149
+ down?: boolean;
150
+ } | null;
151
+ }
152
+ export type Reflex = (game: Diagnostics | null) => ReflexInputs | null | undefined;
153
+ export interface AgentResponse {
154
+ ok: boolean;
155
+ status: number;
156
+ text: () => Promise<string>;
157
+ }
158
+ export interface AgentRequest {
159
+ method: string;
160
+ headers: Record<string, string>;
161
+ body: string;
162
+ }
163
+ /** The page, as the agent sees it. */
164
+ export interface AgentEnv {
165
+ now: () => number;
166
+ fetch: (url: string, init: AgentRequest) => Promise<AgentResponse>;
167
+ raf: (frame: () => void) => number;
168
+ caf: (id: number) => void;
169
+ delay: (ms: number) => Promise<void>;
170
+ read: () => AgentSample;
171
+ /** A JSON-safe copy of the diagnostics, for the model. */
172
+ snapshot: () => Json;
173
+ /** The live diagnostics object, for a reflex. */
174
+ live: () => Diagnostics | null;
175
+ dispatchKey: (type: "keydown" | "keyup", init: AgentKeyInit) => void;
176
+ dispatchPointer: (pointer: AgentPointer, type: "pointermove" | "pointerdown" | "pointerup") => void;
177
+ reflexFor: (label: string) => Reflex | null;
178
+ publish: (result: AgentResult) => void;
179
+ }
180
+ /** The real page as an AgentEnv. Only ever runs in the browser; injected beside the agent. */
181
+ export declare const browserEnv: () => AgentEnv;
182
+ /**
183
+ * Run the playtest inside the page. Returns the live result object, which is
184
+ * also published as `window.__PLAYTEST_AGENT__`; `done` flips when the run
185
+ * ends, `error` says why if it ended early.
186
+ */
187
+ export declare const inPageAgent: (config: AgentConfig, env: AgentEnv) => AgentResult;
188
+ export {};