vibedgames 0.3.1 → 0.4.1

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.
@@ -1,8 +1,10 @@
1
+ import { fileURLToPath } from "node:url";
1
2
  import { defineCommand } from "citty";
2
3
  import consola from "consola";
3
- import { run } from "../lib/run.js";
4
+ import { detectPackageManager, globalInstallArgs, globalInstallCommand, PKG_NAME, } from "../lib/package-manager.js";
5
+ import { isMissingCommand, run } from "../lib/run.js";
6
+ import { assertKnownFlags } from "../lib/strict-args.js";
4
7
  const REPO = "kyh/vibedgames";
5
- const PKG = "vibedgames";
6
8
  const DEFAULT_AGENTS = "claude-code,cursor,codex";
7
9
  const description = "Install/update vibedgames skills and the vg CLI";
8
10
  const skillsAddArgs = (agents, global, yes) => {
@@ -23,45 +25,58 @@ const skillsUpdateArgs = (global, yes) => {
23
25
  args.push("-y");
24
26
  return args;
25
27
  };
28
+ const initArgs = {
29
+ agent: {
30
+ type: "string",
31
+ description: "Comma-separated target agents. Default installs for Claude Code, Cursor, and Codex (symlinked from a shared .agents/skills/ dir). Pass '*' for every supported agent.",
32
+ alias: "a",
33
+ default: DEFAULT_AGENTS,
34
+ },
35
+ global: {
36
+ type: "boolean",
37
+ description: "Install to user directory instead of project",
38
+ default: false,
39
+ alias: "g",
40
+ },
41
+ yes: {
42
+ type: "boolean",
43
+ description: "Skip confirmation prompts",
44
+ default: true,
45
+ alias: "y",
46
+ },
47
+ };
26
48
  export const initCommand = defineCommand({
27
49
  meta: { name: "init", description },
28
- args: {
29
- agent: {
30
- type: "string",
31
- description: "Comma-separated target agents. Default installs for Claude Code, Cursor, and Codex (symlinked from a shared .agents/skills/ dir). Pass '*' for every supported agent.",
32
- alias: "a",
33
- default: DEFAULT_AGENTS,
34
- },
35
- global: {
36
- type: "boolean",
37
- description: "Install to user directory instead of project",
38
- default: false,
39
- alias: "g",
40
- },
41
- yes: {
42
- type: "boolean",
43
- description: "Skip confirmation prompts",
44
- default: true,
45
- alias: "y",
46
- },
47
- },
48
- run: async ({ args }) => {
50
+ args: initArgs,
51
+ run: async ({ args, rawArgs }) => {
52
+ assertKnownFlags(rawArgs, initArgs);
49
53
  const agents = args.agent
50
54
  .split(",")
51
55
  .map((s) => s.trim())
52
56
  .filter(Boolean);
53
- consola.start("Installing/updating vibedgames skills and the vg CLI...");
57
+ // Whatever installed this CLI is what should upgrade it. Installing with a
58
+ // different manager writes a second copy into a prefix the shell may not
59
+ // even be looking at, so `vg --version` would not move.
60
+ const manager = detectPackageManager(fileURLToPath(import.meta.url));
61
+ consola.start("Installing/updating vibedgames skills and the vg CLI (this takes a few minutes — `skills` fetches the repo once per skill)...");
54
62
  const [add, cli] = await Promise.all([
55
- run("npx", skillsAddArgs(agents, args.global, args.yes)),
56
- run("npm", ["install", "-g", PKG]),
63
+ run("npx", skillsAddArgs(agents, args.global, args.yes), { stream: true }),
64
+ run(manager, globalInstallArgs(manager)),
57
65
  ]);
58
66
  if (add.code !== 0) {
67
+ if (isMissingCommand(add)) {
68
+ throw new Error("`npx` was not found on PATH. It ships with Node, so this usually means " +
69
+ "the vg CLI is running from a standalone build — install Node, or add " +
70
+ `the skills yourself with: npx skills add ${REPO}`);
71
+ }
59
72
  if (add.output.trim())
60
73
  consola.error(add.output.trim());
61
74
  throw new Error(`skills add exited with code ${add.code}`);
62
75
  }
63
76
  consola.success(`Installed vibedgames skills for ${agents.join(", ")}`);
64
- const update = await run("npx", skillsUpdateArgs(args.global, args.yes));
77
+ const update = await run("npx", skillsUpdateArgs(args.global, args.yes), {
78
+ stream: true,
79
+ });
65
80
  if (update.code !== 0) {
66
81
  if (update.output.trim())
67
82
  consola.warn(update.output.trim());
@@ -71,11 +86,13 @@ export const initCommand = defineCommand({
71
86
  consola.success("Refreshed installed skills to latest");
72
87
  }
73
88
  if (cli.code !== 0) {
74
- if (cli.output.trim())
89
+ if (cli.output.trim() && !isMissingCommand(cli))
75
90
  consola.warn(cli.output.trim());
76
- consola.warn(`Couldn't install the vg CLI globally (npm exit ${cli.code}). Install manually: npm install -g ${PKG}`);
91
+ consola.warn(isMissingCommand(cli)
92
+ ? `Couldn't find ${manager} to update the vg CLI. Update manually: ${globalInstallCommand(manager)}`
93
+ : `Couldn't install the vg CLI globally (${manager} exit ${cli.code}). Install manually: ${globalInstallCommand(manager)}`);
77
94
  return;
78
95
  }
79
- consola.success("Installed/updated vg CLI globally");
96
+ consola.success(`Installed/updated ${PKG_NAME} globally with ${manager}`);
80
97
  },
81
98
  });
@@ -6,7 +6,7 @@ export declare const newCommand: import("citty").CommandDef<{
6
6
  };
7
7
  readonly engine: {
8
8
  readonly type: "string";
9
- readonly description: "Engine preset: phaser (default), threejs, or none.";
9
+ readonly description: `Engine preset: ${string} (default: phaser).`;
10
10
  readonly default: "phaser";
11
11
  };
12
12
  readonly template: {
@@ -3,7 +3,8 @@ import { resolve } from "node:path";
3
3
  import { defineCommand } from "citty";
4
4
  import consola from "consola";
5
5
  import tiged from "tiged";
6
- const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
6
+ import { SLUG_RE } from "../lib/config-file.js";
7
+ import { assertKnownFlags } from "../lib/strict-args.js";
7
8
  const ENGINES = {
8
9
  // phaserjs/template-vite-ts is the official Phaser 4 + Vite + TypeScript
9
10
  // starter (despite the description still saying "Phaser 3" — package.json
@@ -95,38 +96,42 @@ const NONE_FILES = [
95
96
  },
96
97
  { path: ".gitignore", content: () => `node_modules\ndist\n.DS_Store\n` },
97
98
  ];
99
+ // Derived so `--help` and the error message can't drift from the presets again.
100
+ const ENGINE_IDS = Object.keys(ENGINES);
101
+ const newArgs = {
102
+ slug: {
103
+ type: "positional",
104
+ description: "Lowercase, hyphenated slug — used as the directory name and deploy subdomain.",
105
+ required: true,
106
+ },
107
+ engine: {
108
+ type: "string",
109
+ description: `Engine preset: ${ENGINE_IDS.join(", ")} (default: phaser).`,
110
+ default: "phaser",
111
+ },
112
+ template: {
113
+ type: "string",
114
+ description: "Override the engine preset and fetch from an arbitrary degit spec (e.g. owner/repo, owner/repo#branch). Skips the engine preset entirely.",
115
+ },
116
+ here: {
117
+ type: "boolean",
118
+ description: "Write into the current directory instead of creating <slug>/.",
119
+ default: false,
120
+ },
121
+ force: {
122
+ type: "boolean",
123
+ description: "Overwrite an existing target directory.",
124
+ default: false,
125
+ },
126
+ };
98
127
  export const newCommand = defineCommand({
99
128
  meta: {
100
129
  name: "new",
101
- description: "Scaffold a new browser game. Pulls an official engine template (phaser, threejs) or generates a minimal canvas starter.",
102
- },
103
- args: {
104
- slug: {
105
- type: "positional",
106
- description: "Lowercase, hyphenated slug — used as the directory name and deploy subdomain.",
107
- required: true,
108
- },
109
- engine: {
110
- type: "string",
111
- description: "Engine preset: phaser (default), threejs, or none.",
112
- default: "phaser",
113
- },
114
- template: {
115
- type: "string",
116
- description: "Override the engine preset and fetch from an arbitrary degit spec (e.g. owner/repo, owner/repo#branch). Skips the engine preset entirely.",
117
- },
118
- here: {
119
- type: "boolean",
120
- description: "Write into the current directory instead of creating <slug>/.",
121
- default: false,
122
- },
123
- force: {
124
- type: "boolean",
125
- description: "Overwrite an existing target directory.",
126
- default: false,
127
- },
130
+ description: "Scaffold a new browser game. Pulls an engine template (phaser, threejs, react-r3f) or generates a minimal canvas starter.",
128
131
  },
129
- run: async ({ args }) => {
132
+ args: newArgs,
133
+ run: async ({ args, rawArgs }) => {
134
+ assertKnownFlags(rawArgs, newArgs);
130
135
  const slug = args.slug.trim().toLowerCase();
131
136
  if (!SLUG_RE.test(slug)) {
132
137
  consola.error(`Invalid slug: ${args.slug}\n Use lowercase letters, digits, and hyphens (e.g. "asteroid-belt").`);
@@ -140,7 +145,7 @@ export const newCommand = defineCommand({
140
145
  }
141
146
  : ENGINES[args.engine];
142
147
  if (!preset) {
143
- consola.error(`Unknown engine: ${args.engine}. Use one of: ${Object.keys(ENGINES).join(", ")}.`);
148
+ consola.error(`Unknown engine: ${args.engine}. Use one of: ${ENGINE_IDS.join(", ")}.`);
144
149
  process.exit(1);
145
150
  }
146
151
  const target = args.here ? process.cwd() : resolve(process.cwd(), slug);
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The URL a game is served at: a per-slug subdomain of whatever host this CLI
3
+ * is pointed at, so `VG_API_URL=…staging vg playtest --game x` playtests
4
+ * staging rather than silently hitting production the way a hardcoded apex
5
+ * would. Mirrors the derivation the deploy router does server-side.
6
+ */
7
+ declare function resolveGameUrl(slug: string | null): string;
8
+ /**
9
+ * The tokens in `args` that aren't flags or flag values — agent-browser's verb
10
+ * and its positional arguments, in order.
11
+ *
12
+ * A bare token is a flag's value if a flag sits immediately before it, and a
13
+ * verb otherwise — `--session p1 snapshot` has `p1` claimed by `--session`,
14
+ * leaving `snapshot`. `--session=p1` carries its own value and claims nothing.
15
+ * That holds for any single-valued flag, known or not, so no mirror of
16
+ * upstream's options can drift here.
17
+ *
18
+ * Deliberately incomplete: agent-browser's boolean flags take an OPTIONAL
19
+ * `true`/`false`, so `--headed snapshot` is genuinely ambiguous without knowing
20
+ * that `--headed` is boolean — and knowing that for ~50 options means mirroring
21
+ * a grammar that moves every release. This catches the shapes people actually
22
+ * type; anything past it reaches agent-browser as before.
23
+ */
24
+ export declare function bareTokens(args: string[]): string[];
25
+ export declare function expandGameFlag(args: string[], resolveUrl?: typeof resolveGameUrl): string[];
26
+ /**
27
+ * agent-browser's session defaults to the literal name `default`, which is
28
+ * shared by every caller on the machine. Two `vg playtest` runs — two projects
29
+ * in two terminals, or two agents on one box — then drive the SAME browser tab:
30
+ * one navigates away mid-run and the other screenshots its page. Scope the
31
+ * session to the project so concurrent playtests can't collide.
32
+ *
33
+ * Left alone when the caller already chose a session, or set one in the
34
+ * environment, or is asking about sessions themselves (`session list` must see
35
+ * every session, not just this project's).
36
+ */
37
+ export declare function withScopedSession(args: string[], sessionId: () => string): string[];
38
+ /** Resolve (installing on first use) and exec agent-browser. Never returns. */
39
+ export declare function runPlaytest(rawArgs: string[]): never;
40
+ export declare const playtestCommand: import("citty").CommandDef<import("citty").ArgsDef>;
41
+ export {};
@@ -0,0 +1,359 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { defineCommand } from "citty";
5
+ import consola from "consola";
6
+ import spawn from "cross-spawn";
7
+ import { getBaseUrl, getConfigDir } from "../lib/config.js";
8
+ import { isNewerVersion } from "../lib/update.js";
9
+ import { SLUG_RE, findProjectRoot, readProjectConfig } from "../lib/config-file.js";
10
+ /**
11
+ * `vg playtest` — drive a browser to actually play the game.
12
+ *
13
+ * This is a thin passthrough to agent-browser (a native browser-automation CLI
14
+ * built for agents), not a wrapper with its own vocabulary: every argument goes
15
+ * through untouched so the skill can teach upstream's command surface and we
16
+ * inherit its improvements for free. index.ts routes `vg playtest …` here
17
+ * BEFORE citty parses anything, so `--help`/`--version` reach the binary; the
18
+ * citty command below exists only so `vg --help` lists the subcommand.
19
+ *
20
+ * The one thing layered on top is `--game [slug]`, which resolves a deployed
21
+ * game's URL so an agent can playtest what it just shipped with no local setup.
22
+ *
23
+ * A minimum version is enforced: agent-browser is pre-1.0, so a minor bump can
24
+ * move the command surface out from under the playtest skill.
25
+ */
26
+ const PKG = "agent-browser";
27
+ const MIN_VERSION = "0.34.0";
28
+ const PKG_SPEC = `${PKG}@^${MIN_VERSION}`;
29
+ /** Stands in for a version string we could not read. Always meets the floor. */
30
+ const UNKNOWN_VERSION = "unknown";
31
+ /** How long a failed upgrade suppresses the next attempt. */
32
+ const UPGRADE_RETRY_MS = 24 * 60 * 60_000;
33
+ /**
34
+ * Subcommands that take a URL. Used to decide whether a bare `--game` still
35
+ * needs an `open` in front of it, and — over `bareTokens` — to tell a misplaced
36
+ * `--game` from a well-formed one. An unknown verb still degrades to
37
+ * agent-browser's own error rather than to a wrong guess here.
38
+ */
39
+ const URL_TAKING = new Set(["open", "goto", "navigate", "url"]);
40
+ /**
41
+ * Verbs this module recognizes, used only to tell a subcommand from a flag's
42
+ * value. `diff` is here because `diff url` is how two URLs are compared.
43
+ */
44
+ const KNOWN_VERBS = new Set([...URL_TAKING, "diff"]);
45
+ /**
46
+ * The installed agent-browser's version, or null if the binary can't be run.
47
+ *
48
+ * Doubles as the "is it installed?" probe: a version we can read is proof the
49
+ * binary works, which a bare exit code isn't.
50
+ */
51
+ function installedVersion(bin) {
52
+ // cross-spawn's sync sets `error` to null on success (node's spawnSync leaves
53
+ // it undefined), so test truthiness rather than comparing against undefined.
54
+ const res = spawn.sync(bin, ["--version"], { encoding: "utf8", timeout: 30_000 });
55
+ if (res.status !== 0 || res.error)
56
+ return null;
57
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(res.stdout ?? "");
58
+ return match ? match[0] : UNKNOWN_VERSION;
59
+ }
60
+ /**
61
+ * Whether a version is new enough for the playtest skill.
62
+ *
63
+ * A floor, not an exact pin, so a newer agent-browser is left alone: someone
64
+ * running 0.35 installed it for a reason, and downgrading a shared global tool
65
+ * to match this skill would break their other work to fix a risk that may not
66
+ * exist. PKG_SPEC still caps what a *fresh* install pulls in.
67
+ *
68
+ * An unparseable version passes — `isNewerVersion` returns false for anything
69
+ * that isn't `x.y.z` — because a binary from brew or cargo may not report a
70
+ * semver at all, and blocking it would be worse than trusting it.
71
+ */
72
+ function meetsMinimum(version) {
73
+ return !isNewerVersion(MIN_VERSION, version);
74
+ }
75
+ /** The agent-browser binary to use. VG_AGENT_BROWSER_BIN overrides (dev). */
76
+ function resolveBinary() {
77
+ const override = process.env.VG_AGENT_BROWSER_BIN;
78
+ // A dev-pointed binary is taken on trust — it is typically a local build with
79
+ // no npm version to read, and `meetsMinimum` waves an unparseable one through.
80
+ if (override)
81
+ return existsSync(override) ? { bin: override, version: UNKNOWN_VERSION } : null;
82
+ const version = installedVersion(PKG);
83
+ return version === null ? null : { bin: PKG, version };
84
+ }
85
+ /**
86
+ * Install agent-browser globally, then provision its browser. Upstream ships
87
+ * these as two steps (`npm i -g` puts the Rust binary in place; `install`
88
+ * fetches Chrome for Testing and reuses an existing Chrome/Brave/Playwright
89
+ * install when it finds one), so a first run pays for both.
90
+ */
91
+ function bootstrap() {
92
+ consola.start(`Installing the playtest browser (${PKG})…`);
93
+ const resolved = installGlobal();
94
+ if (!resolved) {
95
+ consola.error(`Couldn't install ${PKG}, or it isn't on PATH afterwards. Try manually: npm install -g ${PKG_SPEC} — and check that npm's global bin directory is in your PATH (\`npm bin -g\`).`);
96
+ process.exit(1);
97
+ }
98
+ consola.start("Provisioning the browser (first run only)…");
99
+ const provision = spawn.sync(resolved.bin, ["install"], { stdio: "inherit" });
100
+ if (provision.status !== 0) {
101
+ consola.error(`\`${PKG} install\` failed. On Linux you may need system libraries: ${PKG} install --with-deps`);
102
+ process.exit(1);
103
+ }
104
+ consola.success("Playtest browser ready.");
105
+ return resolved;
106
+ }
107
+ /**
108
+ * Bring an agent-browser older than the minimum up to it.
109
+ *
110
+ * The floor exists because agent-browser is pre-1.0: the playtest skill teaches
111
+ * a command surface, and the bot script depends on response shapes, both of
112
+ * which a minor bump can move. Installing the spec only on first use would
113
+ * leave an older global install — already on PATH from some earlier project —
114
+ * driving every run, which is how a documented contract silently stops holding.
115
+ */
116
+ function ensureMinimum(resolved) {
117
+ if (meetsMinimum(resolved.version))
118
+ return resolved;
119
+ // The bot script runs `vg playtest` once per step, so an upgrade that cannot
120
+ // stick — read-only npm prefix, offline, locked-down CI — would otherwise
121
+ // retry its npm round-trip on every one of them. Recorded per user rather
122
+ // than in a shared /tmp, where one account's stamp would silently suppress
123
+ // everyone else's upgrade.
124
+ const stamp = join(getConfigDir(), `${PKG}-upgrade-failed-${resolved.version}`);
125
+ if (recentlyFailed(stamp))
126
+ return resolved;
127
+ consola.warn(`Found ${PKG} ${resolved.version}, but the playtest skill needs at least ${MIN_VERSION}. Upgrading…`);
128
+ const upgraded = installGlobal();
129
+ if (!upgraded || !meetsMinimum(upgraded.version)) {
130
+ // Continue anyway: an older binary handles most commands fine, and failing
131
+ // outright would strand anyone who can't write to npm's global prefix.
132
+ try {
133
+ mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 });
134
+ writeFileSync(stamp, "");
135
+ }
136
+ catch {
137
+ // A stamp we cannot write only costs a retry next time.
138
+ }
139
+ consola.warn(`Couldn't upgrade ${PKG}. Continuing on ${resolved.version} — run \`npm install -g ${PKG_SPEC}\` if commands misbehave.`);
140
+ return resolved;
141
+ }
142
+ return upgraded;
143
+ }
144
+ /**
145
+ * Whether an upgrade was already tried recently. Time-boxed rather than
146
+ * permanent: the usual reason one fails is being offline, and a machine that is
147
+ * online tomorrow should get the upgrade rather than stay pinned by a stamp it
148
+ * wrote once.
149
+ */
150
+ function recentlyFailed(stamp) {
151
+ try {
152
+ return Date.now() - statSync(stamp).mtimeMs < UPGRADE_RETRY_MS;
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ }
158
+ /** `npm install -g` the pinned spec, then re-resolve. Null if either step fails. */
159
+ function installGlobal() {
160
+ // Bounded so a wedged registry or install script can't hang `vg playtest`
161
+ // forever; generous enough not to cut off a slow but working download.
162
+ const res = spawn.sync("npm", ["install", "-g", PKG_SPEC], {
163
+ stdio: "inherit",
164
+ timeout: 10 * 60_000,
165
+ });
166
+ return res.status === 0 && !res.error ? resolveBinary() : null;
167
+ }
168
+ /**
169
+ * The URL a game is served at: a per-slug subdomain of whatever host this CLI
170
+ * is pointed at, so `VG_API_URL=…staging vg playtest --game x` playtests
171
+ * staging rather than silently hitting production the way a hardcoded apex
172
+ * would. Mirrors the derivation the deploy router does server-side.
173
+ */
174
+ function resolveGameUrl(slug) {
175
+ const resolved = slug ?? projectSlug();
176
+ // The slug lands in the host, so anything outside the deploy grammar could
177
+ // steer the browser off `*.vibedgames.com` entirely — `../`, an embedded
178
+ // `/`, or `evil.com#` would all re-point the origin.
179
+ if (!SLUG_RE.test(resolved)) {
180
+ consola.error(`Invalid game slug "${resolved}". Use lowercase letters, digits, and hyphens.`);
181
+ process.exit(1);
182
+ }
183
+ const base = new URL(getBaseUrl());
184
+ if (base.hostname === "localhost" || base.hostname === "127.0.0.1") {
185
+ consola.error(`\`--game\` resolves a deployed game's subdomain, which a local API URL (${base.host}) doesn't serve. Pass the game's URL directly instead.`);
186
+ process.exit(1);
187
+ }
188
+ return `${base.protocol}//${resolved}.${base.host}`;
189
+ }
190
+ /** The current project's slug, from the nearest vibedgames.json. */
191
+ function projectSlug() {
192
+ let config = null;
193
+ try {
194
+ config = readProjectConfig(process.cwd());
195
+ }
196
+ catch (err) {
197
+ consola.error(err instanceof Error ? err.message : String(err));
198
+ process.exit(1);
199
+ }
200
+ if (!config) {
201
+ consola.error("`--game` with no slug reads vibedgames.json, and none was found here. Pass a slug (`vg playtest --game my-game`) or run from a deployed project.");
202
+ process.exit(1);
203
+ }
204
+ return config.slug;
205
+ }
206
+ /**
207
+ * The tokens in `args` that aren't flags or flag values — agent-browser's verb
208
+ * and its positional arguments, in order.
209
+ *
210
+ * A bare token is a flag's value if a flag sits immediately before it, and a
211
+ * verb otherwise — `--session p1 snapshot` has `p1` claimed by `--session`,
212
+ * leaving `snapshot`. `--session=p1` carries its own value and claims nothing.
213
+ * That holds for any single-valued flag, known or not, so no mirror of
214
+ * upstream's options can drift here.
215
+ *
216
+ * Deliberately incomplete: agent-browser's boolean flags take an OPTIONAL
217
+ * `true`/`false`, so `--headed snapshot` is genuinely ambiguous without knowing
218
+ * that `--headed` is boolean — and knowing that for ~50 options means mirroring
219
+ * a grammar that moves every release. This catches the shapes people actually
220
+ * type; anything past it reaches agent-browser as before.
221
+ */
222
+ export function bareTokens(args) {
223
+ return args.filter((arg, index) => {
224
+ if (arg.startsWith("-"))
225
+ return false;
226
+ // A token that IS a known verb is one, whatever precedes it. "Preceded by a
227
+ // flag" can't tell a boolean flag from a valued one, so `--headed open`
228
+ // would otherwise read `open` as `--headed`'s value, see no verb at all,
229
+ // and insert a second one — agent-browser then navigates to the literal
230
+ // string "open" and lands on chrome-error://.
231
+ //
232
+ // The cost is a session or profile named exactly after a verb
233
+ // (`--session open`), which is now read as the verb. That is the rarer
234
+ // input by a wide margin, and it fails loudly instead of silently going
235
+ // somewhere wrong.
236
+ // `--game`'s own value is exempt: that flag is ours, so we know it takes a
237
+ // value, and a game may legitimately be called `open` or `diff`.
238
+ const previous = args[index - 1];
239
+ if (KNOWN_VERBS.has(arg) && previous !== "--game")
240
+ return true;
241
+ return !(previous !== undefined && previous.startsWith("-") && !previous.includes("="));
242
+ });
243
+ }
244
+ export function expandGameFlag(args, resolveUrl = resolveGameUrl) {
245
+ if (!args.includes("--game"))
246
+ return args;
247
+ // Catch `vg playtest snapshot --game x`, where the URL has nowhere to go —
248
+ // agent-browser silently runs the snapshot and ignores the stray URL, so
249
+ // leaving it to upstream costs a wrong answer rather than an error. Skipped
250
+ // when some verb here does take a URL, which is the well-formed case.
251
+ // Both questions — "is a URL-taking verb already here?" and "is some OTHER
252
+ // verb here?" — are read off the same list. Scanning the raw args for the
253
+ // first would also match a flag's value, so `--profile open --game x` would
254
+ // count the profile name as the verb and hand agent-browser a URL with no
255
+ // subcommand at all.
256
+ // Only the VERB decides whether a URL is wanted — `diff` reads its own on the
257
+ // next token. Asking whether ANY bare token is URL-taking lets a positional
258
+ // argument answer for the command: `click open --game x` would pass the guard
259
+ // on the selector named `open` and click the current page.
260
+ const bare = bareTokens(args);
261
+ const verb = bare[0];
262
+ const hasUrlVerb = verb !== undefined &&
263
+ (URL_TAKING.has(verb) || (verb === "diff" && bare[1] !== undefined && URL_TAKING.has(bare[1])));
264
+ // A verb that only appears AFTER the flag can't receive the URL: substituting
265
+ // in place would emit `<url> open`, whose first positional agent-browser
266
+ // reads as the subcommand. Say so rather than hand over a dead command.
267
+ const verbLeads = bareTokens(args.slice(0, args.indexOf("--game"))).some((token) => URL_TAKING.has(token));
268
+ if (hasUrlVerb && !verbLeads) {
269
+ consola.error("`--game` supplies the URL to a verb, so it has to come after one: `vg playtest open --game my-game`.");
270
+ process.exit(1);
271
+ }
272
+ const subcommand = hasUrlVerb ? null : (verb ?? null);
273
+ if (subcommand !== null) {
274
+ consola.error(`\`--game\` supplies a URL, so it only works with \`${[...URL_TAKING].join("`, `")}\` — not \`${subcommand}\`. Open the game first, then run \`vg playtest ${subcommand} …\` against it.`);
275
+ process.exit(1);
276
+ }
277
+ const out = [];
278
+ // `entries()` types each element as string, so no assertion is needed to
279
+ // index the array; `consumed` skips a slug already claimed by its flag.
280
+ let consumed = false;
281
+ let opened = false;
282
+ for (const [index, arg] of args.entries()) {
283
+ if (consumed) {
284
+ consumed = false;
285
+ continue;
286
+ }
287
+ if (arg !== "--game") {
288
+ out.push(arg);
289
+ continue;
290
+ }
291
+ const next = args[index + 1];
292
+ const slug = next !== undefined && !next.startsWith("-") ? next : null;
293
+ consumed = slug !== null;
294
+ // Decided from the whole array rather than from what came before the flag,
295
+ // so `--game x open` substitutes in place instead of emitting a second
296
+ // `open`. Once per expansion, so repeating `--game` yields one verb and
297
+ // several URLs — the shape `diff url` wants.
298
+ if (!hasUrlVerb && !opened) {
299
+ out.push("open");
300
+ opened = true;
301
+ }
302
+ out.push(resolveUrl(slug));
303
+ }
304
+ return out;
305
+ }
306
+ /**
307
+ * agent-browser's session defaults to the literal name `default`, which is
308
+ * shared by every caller on the machine. Two `vg playtest` runs — two projects
309
+ * in two terminals, or two agents on one box — then drive the SAME browser tab:
310
+ * one navigates away mid-run and the other screenshots its page. Scope the
311
+ * session to the project so concurrent playtests can't collide.
312
+ *
313
+ * Left alone when the caller already chose a session, or set one in the
314
+ * environment, or is asking about sessions themselves (`session list` must see
315
+ * every session, not just this project's).
316
+ */
317
+ export function withScopedSession(args, sessionId) {
318
+ if (args.includes("--session") || args.some((a) => a.startsWith("--session=")))
319
+ return args;
320
+ if (process.env.AGENT_BROWSER_SESSION)
321
+ return args;
322
+ const verb = bareTokens(args)[0];
323
+ // No verb means `--help`/`--version`, and `install`/`session` are machine-wide
324
+ // — `session list` has to see every session, not just this project's.
325
+ if (verb === undefined || verb === "session" || verb === "install")
326
+ return args;
327
+ return ["--session", sessionId(), ...args];
328
+ }
329
+ /**
330
+ * A stable per-project session name. Keyed on the project root when there is
331
+ * one so every command run from anywhere inside the project shares a browser,
332
+ * and on the cwd otherwise. Hashed because the name lands in a socket path.
333
+ */
334
+ function projectSessionId() {
335
+ const root = findProjectRoot(process.cwd()) ?? process.cwd();
336
+ const digest = createHash("sha256").update(root).digest("hex").slice(0, 12);
337
+ return `vg-${digest}`;
338
+ }
339
+ /** Resolve (installing on first use) and exec agent-browser. Never returns. */
340
+ export function runPlaytest(rawArgs) {
341
+ const args = withScopedSession(expandGameFlag(rawArgs), projectSessionId);
342
+ // Bootstrap covers `install` too: on a fresh machine that's the most natural
343
+ // first command, and re-running the provision step it just did is harmless.
344
+ const resolved = resolveBinary();
345
+ const { bin } = resolved ? ensureMinimum(resolved) : bootstrap();
346
+ const result = spawn.sync(bin, args, { stdio: "inherit" });
347
+ process.exit(result.status ?? 1);
348
+ }
349
+ export const playtestCommand = defineCommand({
350
+ meta: {
351
+ name: "playtest",
352
+ 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.",
353
+ },
354
+ run: ({ rawArgs }) => {
355
+ // Normally unreachable (index.ts routes `vg playtest` before citty), but
356
+ // keeps the command functional if invoked programmatically.
357
+ runPlaytest(rawArgs);
358
+ },
359
+ });
@@ -7,7 +7,7 @@ export declare const updateCommand: import("citty").CommandDef<{
7
7
  };
8
8
  readonly auto: {
9
9
  readonly type: "boolean";
10
- readonly description: "(internal) silent background mode: only update when npm has a newer version";
10
+ readonly description: "(internal) silent background mode: only update when the registry has a newer version";
11
11
  readonly default: false;
12
12
  };
13
13
  }>;