vibedgames 0.3.0 → 0.4.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.
@@ -3,7 +3,7 @@ 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
7
  const ENGINES = {
8
8
  // phaserjs/template-vite-ts is the official Phaser 4 + Vite + TypeScript
9
9
  // starter (despite the description still saying "Phaser 3" — package.json
@@ -0,0 +1,29 @@
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
+ /** Resolve (installing on first use) and exec agent-browser. Never returns. */
27
+ export declare function runPlaytest(rawArgs: string[]): never;
28
+ export declare const playtestCommand: import("citty").CommandDef<import("citty").ArgsDef>;
29
+ export {};
@@ -0,0 +1,325 @@
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { defineCommand } from "citty";
4
+ import consola from "consola";
5
+ import spawn from "cross-spawn";
6
+ import { getBaseUrl, getConfigDir } from "../lib/config.js";
7
+ import { isNewerVersion } from "../lib/update.js";
8
+ import { SLUG_RE, readProjectConfig } from "../lib/config-file.js";
9
+ /**
10
+ * `vg playtest` — drive a browser to actually play the game.
11
+ *
12
+ * This is a thin passthrough to agent-browser (a native browser-automation CLI
13
+ * built for agents), not a wrapper with its own vocabulary: every argument goes
14
+ * through untouched so the skill can teach upstream's command surface and we
15
+ * inherit its improvements for free. index.ts routes `vg playtest …` here
16
+ * BEFORE citty parses anything, so `--help`/`--version` reach the binary; the
17
+ * citty command below exists only so `vg --help` lists the subcommand.
18
+ *
19
+ * The one thing layered on top is `--game [slug]`, which resolves a deployed
20
+ * game's URL so an agent can playtest what it just shipped with no local setup.
21
+ *
22
+ * A minimum version is enforced: agent-browser is pre-1.0, so a minor bump can
23
+ * move the command surface out from under the playtest skill.
24
+ */
25
+ const PKG = "agent-browser";
26
+ const MIN_VERSION = "0.34.0";
27
+ const PKG_SPEC = `${PKG}@^${MIN_VERSION}`;
28
+ /** Stands in for a version string we could not read. Always meets the floor. */
29
+ const UNKNOWN_VERSION = "unknown";
30
+ /** How long a failed upgrade suppresses the next attempt. */
31
+ const UPGRADE_RETRY_MS = 24 * 60 * 60_000;
32
+ /**
33
+ * Subcommands that take a URL. Used to decide whether a bare `--game` still
34
+ * needs an `open` in front of it, and — over `bareTokens` — to tell a misplaced
35
+ * `--game` from a well-formed one. An unknown verb still degrades to
36
+ * agent-browser's own error rather than to a wrong guess here.
37
+ */
38
+ const URL_TAKING = new Set(["open", "goto", "navigate", "url"]);
39
+ /**
40
+ * Verbs this module recognizes, used only to tell a subcommand from a flag's
41
+ * value. `diff` is here because `diff url` is how two URLs are compared.
42
+ */
43
+ const KNOWN_VERBS = new Set([...URL_TAKING, "diff"]);
44
+ /**
45
+ * The installed agent-browser's version, or null if the binary can't be run.
46
+ *
47
+ * Doubles as the "is it installed?" probe: a version we can read is proof the
48
+ * binary works, which a bare exit code isn't.
49
+ */
50
+ function installedVersion(bin) {
51
+ // cross-spawn's sync sets `error` to null on success (node's spawnSync leaves
52
+ // it undefined), so test truthiness rather than comparing against undefined.
53
+ const res = spawn.sync(bin, ["--version"], { encoding: "utf8", timeout: 30_000 });
54
+ if (res.status !== 0 || res.error)
55
+ return null;
56
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(res.stdout ?? "");
57
+ return match ? match[0] : UNKNOWN_VERSION;
58
+ }
59
+ /**
60
+ * Whether a version is new enough for the playtest skill.
61
+ *
62
+ * A floor, not an exact pin, so a newer agent-browser is left alone: someone
63
+ * running 0.35 installed it for a reason, and downgrading a shared global tool
64
+ * to match this skill would break their other work to fix a risk that may not
65
+ * exist. PKG_SPEC still caps what a *fresh* install pulls in.
66
+ *
67
+ * An unparseable version passes — `isNewerVersion` returns false for anything
68
+ * that isn't `x.y.z` — because a binary from brew or cargo may not report a
69
+ * semver at all, and blocking it would be worse than trusting it.
70
+ */
71
+ function meetsMinimum(version) {
72
+ return !isNewerVersion(MIN_VERSION, version);
73
+ }
74
+ /** The agent-browser binary to use. VG_AGENT_BROWSER_BIN overrides (dev). */
75
+ function resolveBinary() {
76
+ const override = process.env.VG_AGENT_BROWSER_BIN;
77
+ // A dev-pointed binary is taken on trust — it is typically a local build with
78
+ // no npm version to read, and `meetsMinimum` waves an unparseable one through.
79
+ if (override)
80
+ return existsSync(override) ? { bin: override, version: UNKNOWN_VERSION } : null;
81
+ const version = installedVersion(PKG);
82
+ return version === null ? null : { bin: PKG, version };
83
+ }
84
+ /**
85
+ * Install agent-browser globally, then provision its browser. Upstream ships
86
+ * these as two steps (`npm i -g` puts the Rust binary in place; `install`
87
+ * fetches Chrome for Testing and reuses an existing Chrome/Brave/Playwright
88
+ * install when it finds one), so a first run pays for both.
89
+ */
90
+ function bootstrap() {
91
+ consola.start(`Installing the playtest browser (${PKG})…`);
92
+ const resolved = installGlobal();
93
+ if (!resolved) {
94
+ 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\`).`);
95
+ process.exit(1);
96
+ }
97
+ consola.start("Provisioning the browser (first run only)…");
98
+ const provision = spawn.sync(resolved.bin, ["install"], { stdio: "inherit" });
99
+ if (provision.status !== 0) {
100
+ consola.error(`\`${PKG} install\` failed. On Linux you may need system libraries: ${PKG} install --with-deps`);
101
+ process.exit(1);
102
+ }
103
+ consola.success("Playtest browser ready.");
104
+ return resolved;
105
+ }
106
+ /**
107
+ * Bring an agent-browser older than the minimum up to it.
108
+ *
109
+ * The floor exists because agent-browser is pre-1.0: the playtest skill teaches
110
+ * a command surface, and the bot script depends on response shapes, both of
111
+ * which a minor bump can move. Installing the spec only on first use would
112
+ * leave an older global install — already on PATH from some earlier project —
113
+ * driving every run, which is how a documented contract silently stops holding.
114
+ */
115
+ function ensureMinimum(resolved) {
116
+ if (meetsMinimum(resolved.version))
117
+ return resolved;
118
+ // The bot script runs `vg playtest` once per step, so an upgrade that cannot
119
+ // stick — read-only npm prefix, offline, locked-down CI — would otherwise
120
+ // retry its npm round-trip on every one of them. Recorded per user rather
121
+ // than in a shared /tmp, where one account's stamp would silently suppress
122
+ // everyone else's upgrade.
123
+ const stamp = join(getConfigDir(), `${PKG}-upgrade-failed-${resolved.version}`);
124
+ if (recentlyFailed(stamp))
125
+ return resolved;
126
+ consola.warn(`Found ${PKG} ${resolved.version}, but the playtest skill needs at least ${MIN_VERSION}. Upgrading…`);
127
+ const upgraded = installGlobal();
128
+ if (!upgraded || !meetsMinimum(upgraded.version)) {
129
+ // Continue anyway: an older binary handles most commands fine, and failing
130
+ // outright would strand anyone who can't write to npm's global prefix.
131
+ try {
132
+ mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 });
133
+ writeFileSync(stamp, "");
134
+ }
135
+ catch {
136
+ // A stamp we cannot write only costs a retry next time.
137
+ }
138
+ consola.warn(`Couldn't upgrade ${PKG}. Continuing on ${resolved.version} — run \`npm install -g ${PKG_SPEC}\` if commands misbehave.`);
139
+ return resolved;
140
+ }
141
+ return upgraded;
142
+ }
143
+ /**
144
+ * Whether an upgrade was already tried recently. Time-boxed rather than
145
+ * permanent: the usual reason one fails is being offline, and a machine that is
146
+ * online tomorrow should get the upgrade rather than stay pinned by a stamp it
147
+ * wrote once.
148
+ */
149
+ function recentlyFailed(stamp) {
150
+ try {
151
+ return Date.now() - statSync(stamp).mtimeMs < UPGRADE_RETRY_MS;
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ /** `npm install -g` the pinned spec, then re-resolve. Null if either step fails. */
158
+ function installGlobal() {
159
+ // Bounded so a wedged registry or install script can't hang `vg playtest`
160
+ // forever; generous enough not to cut off a slow but working download.
161
+ const res = spawn.sync("npm", ["install", "-g", PKG_SPEC], {
162
+ stdio: "inherit",
163
+ timeout: 10 * 60_000,
164
+ });
165
+ return res.status === 0 && !res.error ? resolveBinary() : null;
166
+ }
167
+ /**
168
+ * The URL a game is served at: a per-slug subdomain of whatever host this CLI
169
+ * is pointed at, so `VG_API_URL=…staging vg playtest --game x` playtests
170
+ * staging rather than silently hitting production the way a hardcoded apex
171
+ * would. Mirrors the derivation the deploy router does server-side.
172
+ */
173
+ function resolveGameUrl(slug) {
174
+ const resolved = slug ?? projectSlug();
175
+ // The slug lands in the host, so anything outside the deploy grammar could
176
+ // steer the browser off `*.vibedgames.com` entirely — `../`, an embedded
177
+ // `/`, or `evil.com#` would all re-point the origin.
178
+ if (!SLUG_RE.test(resolved)) {
179
+ consola.error(`Invalid game slug "${resolved}". Use lowercase letters, digits, and hyphens.`);
180
+ process.exit(1);
181
+ }
182
+ const base = new URL(getBaseUrl());
183
+ if (base.hostname === "localhost" || base.hostname === "127.0.0.1") {
184
+ 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.`);
185
+ process.exit(1);
186
+ }
187
+ return `${base.protocol}//${resolved}.${base.host}`;
188
+ }
189
+ /** The current project's slug, from the nearest vibedgames.json. */
190
+ function projectSlug() {
191
+ let config = null;
192
+ try {
193
+ config = readProjectConfig(process.cwd());
194
+ }
195
+ catch (err) {
196
+ consola.error(err instanceof Error ? err.message : String(err));
197
+ process.exit(1);
198
+ }
199
+ if (!config) {
200
+ 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.");
201
+ process.exit(1);
202
+ }
203
+ return config.slug;
204
+ }
205
+ /**
206
+ * The tokens in `args` that aren't flags or flag values — agent-browser's verb
207
+ * and its positional arguments, in order.
208
+ *
209
+ * A bare token is a flag's value if a flag sits immediately before it, and a
210
+ * verb otherwise — `--session p1 snapshot` has `p1` claimed by `--session`,
211
+ * leaving `snapshot`. `--session=p1` carries its own value and claims nothing.
212
+ * That holds for any single-valued flag, known or not, so no mirror of
213
+ * upstream's options can drift here.
214
+ *
215
+ * Deliberately incomplete: agent-browser's boolean flags take an OPTIONAL
216
+ * `true`/`false`, so `--headed snapshot` is genuinely ambiguous without knowing
217
+ * that `--headed` is boolean — and knowing that for ~50 options means mirroring
218
+ * a grammar that moves every release. This catches the shapes people actually
219
+ * type; anything past it reaches agent-browser as before.
220
+ */
221
+ export function bareTokens(args) {
222
+ return args.filter((arg, index) => {
223
+ if (arg.startsWith("-"))
224
+ return false;
225
+ // A token that IS a known verb is one, whatever precedes it. "Preceded by a
226
+ // flag" can't tell a boolean flag from a valued one, so `--headed open`
227
+ // would otherwise read `open` as `--headed`'s value, see no verb at all,
228
+ // and insert a second one — agent-browser then navigates to the literal
229
+ // string "open" and lands on chrome-error://.
230
+ //
231
+ // The cost is a session or profile named exactly after a verb
232
+ // (`--session open`), which is now read as the verb. That is the rarer
233
+ // input by a wide margin, and it fails loudly instead of silently going
234
+ // somewhere wrong.
235
+ // `--game`'s own value is exempt: that flag is ours, so we know it takes a
236
+ // value, and a game may legitimately be called `open` or `diff`.
237
+ const previous = args[index - 1];
238
+ if (KNOWN_VERBS.has(arg) && previous !== "--game")
239
+ return true;
240
+ return !(previous !== undefined && previous.startsWith("-") && !previous.includes("="));
241
+ });
242
+ }
243
+ export function expandGameFlag(args, resolveUrl = resolveGameUrl) {
244
+ if (!args.includes("--game"))
245
+ return args;
246
+ // Catch `vg playtest snapshot --game x`, where the URL has nowhere to go —
247
+ // agent-browser silently runs the snapshot and ignores the stray URL, so
248
+ // leaving it to upstream costs a wrong answer rather than an error. Skipped
249
+ // when some verb here does take a URL, which is the well-formed case.
250
+ // Both questions — "is a URL-taking verb already here?" and "is some OTHER
251
+ // verb here?" — are read off the same list. Scanning the raw args for the
252
+ // first would also match a flag's value, so `--profile open --game x` would
253
+ // count the profile name as the verb and hand agent-browser a URL with no
254
+ // subcommand at all.
255
+ // Only the VERB decides whether a URL is wanted — `diff` reads its own on the
256
+ // next token. Asking whether ANY bare token is URL-taking lets a positional
257
+ // argument answer for the command: `click open --game x` would pass the guard
258
+ // on the selector named `open` and click the current page.
259
+ const bare = bareTokens(args);
260
+ const verb = bare[0];
261
+ const hasUrlVerb = verb !== undefined &&
262
+ (URL_TAKING.has(verb) || (verb === "diff" && bare[1] !== undefined && URL_TAKING.has(bare[1])));
263
+ // A verb that only appears AFTER the flag can't receive the URL: substituting
264
+ // in place would emit `<url> open`, whose first positional agent-browser
265
+ // reads as the subcommand. Say so rather than hand over a dead command.
266
+ const verbLeads = bareTokens(args.slice(0, args.indexOf("--game"))).some((token) => URL_TAKING.has(token));
267
+ if (hasUrlVerb && !verbLeads) {
268
+ consola.error("`--game` supplies the URL to a verb, so it has to come after one: `vg playtest open --game my-game`.");
269
+ process.exit(1);
270
+ }
271
+ const subcommand = hasUrlVerb ? null : (verb ?? null);
272
+ if (subcommand !== null) {
273
+ 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.`);
274
+ process.exit(1);
275
+ }
276
+ const out = [];
277
+ // `entries()` types each element as string, so no assertion is needed to
278
+ // index the array; `consumed` skips a slug already claimed by its flag.
279
+ let consumed = false;
280
+ let opened = false;
281
+ for (const [index, arg] of args.entries()) {
282
+ if (consumed) {
283
+ consumed = false;
284
+ continue;
285
+ }
286
+ if (arg !== "--game") {
287
+ out.push(arg);
288
+ continue;
289
+ }
290
+ const next = args[index + 1];
291
+ const slug = next !== undefined && !next.startsWith("-") ? next : null;
292
+ consumed = slug !== null;
293
+ // Decided from the whole array rather than from what came before the flag,
294
+ // so `--game x open` substitutes in place instead of emitting a second
295
+ // `open`. Once per expansion, so repeating `--game` yields one verb and
296
+ // several URLs — the shape `diff url` wants.
297
+ if (!hasUrlVerb && !opened) {
298
+ out.push("open");
299
+ opened = true;
300
+ }
301
+ out.push(resolveUrl(slug));
302
+ }
303
+ return out;
304
+ }
305
+ /** Resolve (installing on first use) and exec agent-browser. Never returns. */
306
+ export function runPlaytest(rawArgs) {
307
+ const args = expandGameFlag(rawArgs);
308
+ // Bootstrap covers `install` too: on a fresh machine that's the most natural
309
+ // first command, and re-running the provision step it just did is harmless.
310
+ const resolved = resolveBinary();
311
+ const { bin } = resolved ? ensureMinimum(resolved) : bootstrap();
312
+ const result = spawn.sync(bin, args, { stdio: "inherit" });
313
+ process.exit(result.status ?? 1);
314
+ }
315
+ export const playtestCommand = defineCommand({
316
+ meta: {
317
+ name: "playtest",
318
+ 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.",
319
+ },
320
+ run: ({ rawArgs }) => {
321
+ // Normally unreachable (index.ts routes `vg playtest` before citty), but
322
+ // keeps the command functional if invoked programmatically.
323
+ runPlaytest(rawArgs);
324
+ },
325
+ });
@@ -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
  }>;
@@ -1,9 +1,10 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
2
3
  import { defineCommand } from "citty";
3
4
  import consola from "consola";
4
- import { run } from "../lib/run.js";
5
+ import { detectPackageManager, globalInstallArgs, globalInstallCommand, } from "../lib/package-manager.js";
6
+ import { isMissingCommand, run } from "../lib/run.js";
5
7
  import { fetchLatestVersion, isNewerVersion } from "../lib/update.js";
6
- const PKG = "vibedgames";
7
8
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
8
9
  const skillsUpdateArgs = (global) => {
9
10
  const args = ["-y", "skills", "update", "-y"];
@@ -25,33 +26,38 @@ export const updateCommand = defineCommand({
25
26
  },
26
27
  auto: {
27
28
  type: "boolean",
28
- description: "(internal) silent background mode: only update when npm has a newer version",
29
+ description: "(internal) silent background mode: only update when the registry has a newer version",
29
30
  default: false,
30
31
  },
31
32
  },
32
33
  run: async ({ args }) => {
34
+ // Upgrade with whatever installed this CLI: another manager would write a
35
+ // second copy into a different global prefix, leaving the one on PATH stale.
36
+ const manager = detectPackageManager(fileURLToPath(import.meta.url));
33
37
  if (args.auto) {
34
38
  const latest = await fetchLatestVersion();
35
39
  if (!latest || !isNewerVersion(latest, pkg.version))
36
40
  return;
37
41
  await Promise.all([
38
- run("npm", ["install", "-g", PKG]),
42
+ run(manager, globalInstallArgs(manager)),
39
43
  run("npx", skillsUpdateArgs(args.global)),
40
44
  ]);
41
45
  return;
42
46
  }
43
47
  consola.start("Updating the vg CLI and vibedgames skills...");
44
48
  const [cli, skills] = await Promise.all([
45
- run("npm", ["install", "-g", PKG]),
49
+ run(manager, globalInstallArgs(manager)),
46
50
  run("npx", skillsUpdateArgs(args.global)),
47
51
  ]);
48
52
  if (cli.code === 0) {
49
- consola.success("vg CLI updated to latest");
53
+ consola.success(`vg CLI updated to latest with ${manager}`);
50
54
  }
51
55
  else {
52
- if (cli.output.trim())
56
+ if (cli.output.trim() && !isMissingCommand(cli))
53
57
  consola.warn(cli.output.trim());
54
- consola.warn(`Couldn't update the vg CLI (npm exit ${cli.code}). Update manually: npm install -g ${PKG}`);
58
+ consola.warn(isMissingCommand(cli)
59
+ ? `Couldn't find ${manager} to update the vg CLI. Update manually: ${globalInstallCommand(manager)}`
60
+ : `Couldn't update the vg CLI (${manager} exit ${cli.code}). Update manually: ${globalInstallCommand(manager)}`);
55
61
  }
56
62
  if (skills.code === 0) {
57
63
  consola.success("Skills updated to latest");
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { defineCommand, runMain } from "citty";
4
4
  import { completionsCommand } from "./commands/completions.js";
5
+ import { creditsCommand } from "./commands/credits.js";
5
6
  import { deployCommand } from "./commands/deploy.js";
6
7
  import { factoryCommand, runFactory } from "./commands/factory.js";
7
8
  import { forkCommand } from "./commands/fork.js";
@@ -10,6 +11,7 @@ import { initCommand } from "./commands/init.js";
10
11
  import { loginCommand } from "./commands/login.js";
11
12
  import { logoutCommand } from "./commands/logout.js";
12
13
  import { newCommand } from "./commands/new.js";
14
+ import { playtestCommand, runPlaytest } from "./commands/playtest.js";
13
15
  import { updateCommand } from "./commands/update.js";
14
16
  import { whoamiCommand } from "./commands/whoami.js";
15
17
  import { maybeScheduleAutoUpdate } from "./lib/update.js";
@@ -26,9 +28,11 @@ const main = defineCommand({
26
28
  login: loginCommand,
27
29
  logout: logoutCommand,
28
30
  deploy: deployCommand,
31
+ playtest: playtestCommand,
29
32
  factory: factoryCommand,
30
33
  fork: forkCommand,
31
34
  generate: generateCommand,
35
+ credits: creditsCommand,
32
36
  update: updateCommand,
33
37
  completions: completionsCommand,
34
38
  whoami: whoamiCommand,
@@ -40,10 +44,14 @@ const subcommand = process.argv[2];
40
44
  if (subcommand && !["update", "init", "completions"].includes(subcommand)) {
41
45
  maybeScheduleAutoUpdate();
42
46
  }
43
- // `vg factory` is a pure passthrough to the factory plugin binary — route it
44
- // before citty runs so flags like --help/--version reach the binary instead
45
- // of being intercepted here. (The registered command keeps it in `vg --help`.)
47
+ // `vg factory` and `vg playtest` are pure passthroughs to their binaries —
48
+ // route them before citty runs so flags like --help/--version reach the binary
49
+ // instead of being intercepted here. (The registered commands keep them in
50
+ // `vg --help`.)
46
51
  if (subcommand === "factory") {
47
52
  runFactory(process.argv.slice(3));
48
53
  }
54
+ if (subcommand === "playtest") {
55
+ runPlaytest(process.argv.slice(3));
56
+ }
49
57
  runMain(main);
@@ -2,6 +2,12 @@ export type ProjectConfig = {
2
2
  slug: string;
3
3
  name?: string;
4
4
  };
5
+ /**
6
+ * The slug grammar every surface must agree on — it is the deploy target, the
7
+ * fork target, and the label in `{slug}.vibedgames.com`. Kept here rather than
8
+ * per-command so a validator can't drift and reject a slug that deploy accepts.
9
+ */
10
+ export declare const SLUG_RE: RegExp;
5
11
  /** The directory containing the nearest vibedgames.json at or above `dir`,
6
12
  * or null if none — i.e. the project root to archive as forkable source. */
7
13
  export declare function findProjectRoot(dir: string): string | null;
@@ -1,6 +1,12 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
3
  const FILENAME = "vibedgames.json";
4
+ /**
5
+ * The slug grammar every surface must agree on — it is the deploy target, the
6
+ * fork target, and the label in `{slug}.vibedgames.com`. Kept here rather than
7
+ * per-command so a validator can't drift and reject a slug that deploy accepts.
8
+ */
9
+ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
4
10
  // Walk from `dir` up toward the filesystem root, stopping at the first
5
11
  // vibedgames.json. Lets `vg deploy ./dist` pick up the config from the
6
12
  // project root even when the build step doesn't copy it into the output.
@@ -27,6 +27,8 @@ const CONTENT_TYPES = {
27
27
  avif: "image/avif",
28
28
  ico: "image/x-icon",
29
29
  wasm: "application/wasm",
30
+ glb: "model/gltf-binary",
31
+ gltf: "model/gltf+json",
30
32
  mp3: "audio/mpeg",
31
33
  ogg: "audio/ogg",
32
34
  wav: "audio/wav",
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Shared stdout helpers for machine-readable output.
3
+ *
4
+ * The skills are written for an agent, so nearly every command grew a
5
+ * `--json` flag and the docs then piped it through `jq` to pull out a single
6
+ * value. That made `jq` a hard prerequisite for following the generate
7
+ * skill at all. `--field` removes it: the CLI does the selection itself and
8
+ * prints a bare scalar that a shell can capture directly.
9
+ */
10
+ export type OutputArgs = {
11
+ json?: boolean;
12
+ field?: string;
13
+ };
14
+ export declare function isJsonOutput(args: OutputArgs): boolean;
15
+ export declare function writeJson(value: unknown): void;
16
+ /**
17
+ * Resolve a dotted path against a decoded JSON value. Supports array indexing
18
+ * in both `items[0]` and `items.0` spellings, since agents write both.
19
+ * Returns `undefined` for any path that doesn't resolve.
20
+ */
21
+ export declare function selectField(value: unknown, path: string): unknown;
22
+ /**
23
+ * Render one selected value for shell capture. Scalars print bare so
24
+ * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
25
+ * line so they can be looped over; anything structural falls back to JSON.
26
+ */
27
+ export declare function formatField(value: unknown): string;
28
+ /**
29
+ * The standard exit path for a command that produced structured data.
30
+ * `--field` wins over `--json` when both are passed, since asking for one
31
+ * value is the more specific request. Returns false when neither flag was
32
+ * given, so the caller can fall through to its human-readable rendering.
33
+ */
34
+ export declare function writeStructured(value: unknown, args: OutputArgs): boolean;
35
+ /** The `--json`/`--field` arg pair, for spreading into a citty `args` block. */
36
+ export declare const outputArgs: {
37
+ readonly json: {
38
+ readonly type: "boolean";
39
+ readonly description: "Print structured JSON to stdout.";
40
+ };
41
+ readonly field: {
42
+ readonly type: "string";
43
+ 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.";
44
+ };
45
+ };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Shared stdout helpers for machine-readable output.
3
+ *
4
+ * The skills are written for an agent, so nearly every command grew a
5
+ * `--json` flag and the docs then piped it through `jq` to pull out a single
6
+ * value. That made `jq` a hard prerequisite for following the generate
7
+ * skill at all. `--field` removes it: the CLI does the selection itself and
8
+ * prints a bare scalar that a shell can capture directly.
9
+ */
10
+ export function isJsonOutput(args) {
11
+ return Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
12
+ }
13
+ export function writeJson(value) {
14
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
15
+ }
16
+ /**
17
+ * Resolve a dotted path against a decoded JSON value. Supports array indexing
18
+ * in both `items[0]` and `items.0` spellings, since agents write both.
19
+ * Returns `undefined` for any path that doesn't resolve.
20
+ */
21
+ export function selectField(value, path) {
22
+ const segments = path
23
+ .replace(/\[(-?\d+)\]/g, ".$1")
24
+ .split(".")
25
+ .filter(Boolean);
26
+ let current = value;
27
+ for (const segment of segments) {
28
+ if (current === null || current === undefined)
29
+ return undefined;
30
+ if (Array.isArray(current)) {
31
+ const index = Number(segment);
32
+ if (!Number.isInteger(index))
33
+ return undefined;
34
+ // Negative indices count from the end, which is handy for "the last
35
+ // frame" style selections.
36
+ current = current.at(index);
37
+ continue;
38
+ }
39
+ if (typeof current !== "object")
40
+ return undefined;
41
+ current = current[segment];
42
+ }
43
+ return current;
44
+ }
45
+ /**
46
+ * Render one selected value for shell capture. Scalars print bare so
47
+ * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
48
+ * line so they can be looped over; anything structural falls back to JSON.
49
+ */
50
+ export function formatField(value) {
51
+ if (value === null || value === undefined)
52
+ return "";
53
+ if (Array.isArray(value)) {
54
+ if (value.every((v) => v === null || ["string", "number", "boolean"].includes(typeof v))) {
55
+ return value.map((v) => (v === null ? "" : String(v))).join("\n");
56
+ }
57
+ return JSON.stringify(value, null, 2);
58
+ }
59
+ if (typeof value === "object")
60
+ return JSON.stringify(value, null, 2);
61
+ return String(value);
62
+ }
63
+ /**
64
+ * The standard exit path for a command that produced structured data.
65
+ * `--field` wins over `--json` when both are passed, since asking for one
66
+ * value is the more specific request. Returns false when neither flag was
67
+ * given, so the caller can fall through to its human-readable rendering.
68
+ */
69
+ export function writeStructured(value, args) {
70
+ if (args.field) {
71
+ const selected = selectField(value, args.field);
72
+ if (selected === undefined) {
73
+ // Silence here would look like an empty result rather than a typo, and
74
+ // an agent would happily carry the empty string forward.
75
+ process.stderr.write(`No such field: ${args.field}\n`);
76
+ process.exit(1);
77
+ }
78
+ process.stdout.write(`${formatField(selected)}\n`);
79
+ return true;
80
+ }
81
+ if (isJsonOutput(args)) {
82
+ writeJson(value);
83
+ return true;
84
+ }
85
+ return false;
86
+ }
87
+ /** The `--json`/`--field` arg pair, for spreading into a citty `args` block. */
88
+ export const outputArgs = {
89
+ json: { type: "boolean", description: "Print structured JSON to stdout." },
90
+ field: {
91
+ type: "string",
92
+ 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.",
93
+ },
94
+ };