vibedgames 0.3.1 → 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.
package/README.md CHANGED
@@ -42,7 +42,11 @@ vg generate upload <file> # upload an asset, get a URL
42
42
  vg generate docs <query> # search generative-model documentation
43
43
  ```
44
44
 
45
- Most commands support `--json` for machine-readable output.
45
+ Most commands support `--json` for machine-readable output, and `--field <path>`
46
+ to print one value out of it — `vg generate upload x.png --field url` prints the
47
+ bare URL, ready for `$(...)` capture, so no JSON processor is needed. The path is
48
+ dotted, takes `images[0]` or `images.0`, and counts negative indices from the
49
+ end; a path that doesn't resolve is an error rather than an empty line.
46
50
 
47
51
  `vg init` shells out to `npx skills add kyh/vibedgames` and installs for Claude
48
52
  Code, Cursor and Codex by default (symlinked from a shared `.agents/skills/`);
@@ -50,6 +54,12 @@ Code, Cursor and Codex by default (symlinked from a shared `.agents/skills/`);
50
54
  of the project. `vg update` runs automatically once a day — disable with
51
55
  `VG_NO_AUTO_UPDATE=1`.
52
56
 
57
+ Both self-update with whichever package manager installed the CLI, detected
58
+ from its install path (npm, pnpm, yarn or bun) — installing with a different
59
+ one would write a second copy into a prefix your shell may not be looking at.
60
+ If that manager isn't on PATH, the CLI prints the exact command to run instead
61
+ of failing with a bare exit code.
62
+
53
63
  `vg factory` is a pure passthrough to the [factory](../factory) binary, which is
54
64
  installed as a platform-specific optional package on first use — the CLI itself
55
65
  carries none of it.
@@ -6,8 +6,11 @@ const SUBCOMMANDS = [
6
6
  "login",
7
7
  "logout",
8
8
  "deploy",
9
+ "playtest",
10
+ "factory",
9
11
  "fork",
10
12
  "generate",
13
+ "credits",
11
14
  "update",
12
15
  "completions",
13
16
  "whoami",
@@ -3,4 +3,8 @@ export declare const creditsCommand: import("citty").CommandDef<{
3
3
  readonly type: "boolean";
4
4
  readonly description: "Print structured JSON to stdout.";
5
5
  };
6
+ readonly field: {
7
+ readonly type: "string";
8
+ 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.";
9
+ };
6
10
  }>;
@@ -2,15 +2,10 @@ import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
3
  import { createClient } from "../lib/api.js";
4
4
  import { getToken } from "../lib/config.js";
5
+ import { outputArgs, writeStructured } from "../lib/output.js";
5
6
  const MICRO_PER_USD = 1_000_000;
6
7
  const SUB_CENT_MICRO = MICRO_PER_USD / 100;
7
8
  const MAX_ENTRIES_SHOWN = 15;
8
- function isJsonOutput(args) {
9
- return Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
10
- }
11
- function writeJson(value) {
12
- process.stdout.write(JSON.stringify(value, null, 2) + "\n");
13
- }
14
9
  // Dollars from integer micro-USD. Two decimals normally; four when the
15
10
  // magnitude is sub-cent so small generation charges don't render as $0.00.
16
11
  function formatUsd(micro) {
@@ -74,7 +69,7 @@ export const creditsCommand = defineCommand({
74
69
  description: "Show your credit balance and recent usage.",
75
70
  },
76
71
  args: {
77
- json: { type: "boolean", description: "Print structured JSON to stdout." },
72
+ ...outputArgs,
78
73
  },
79
74
  run: async ({ args }) => {
80
75
  const token = getToken();
@@ -85,22 +80,21 @@ export const creditsCommand = defineCommand({
85
80
  const client = createClient();
86
81
  try {
87
82
  const { balanceMicro, entries } = await client.credits.me.query();
88
- if (isJsonOutput(args)) {
89
- writeJson({
90
- balance_micro: balanceMicro,
91
- balance_usd: balanceMicro / MICRO_PER_USD,
92
- entries: entries.map((e) => ({
93
- id: e.id,
94
- delta_micro: e.deltaMicro,
95
- kind: e.kind,
96
- request_id: e.requestId,
97
- endpoint_id: e.endpointId,
98
- note: e.note,
99
- created_at: e.createdAt.toISOString(),
100
- })),
101
- });
83
+ const payload = {
84
+ balance_micro: balanceMicro,
85
+ balance_usd: balanceMicro / MICRO_PER_USD,
86
+ entries: entries.map((e) => ({
87
+ id: e.id,
88
+ delta_micro: e.deltaMicro,
89
+ kind: e.kind,
90
+ request_id: e.requestId,
91
+ endpoint_id: e.endpointId,
92
+ note: e.note,
93
+ created_at: e.createdAt.toISOString(),
94
+ })),
95
+ };
96
+ if (writeStructured(payload, args))
102
97
  return;
103
- }
104
98
  consola.log(`Balance: ${formatUsd(balanceMicro)}`);
105
99
  if (entries.length === 0) {
106
100
  consola.log("No activity yet.");
@@ -5,10 +5,9 @@ import { defineCommand } from "citty";
5
5
  import consola from "consola";
6
6
  import { createClient } from "../lib/api.js";
7
7
  import { packSource } from "../lib/archive.js";
8
- import { findProjectRoot, projectConfigPath, readProjectConfig, writeProjectConfig, } from "../lib/config-file.js";
8
+ import { findProjectRoot, projectConfigPath, readProjectConfig, writeProjectConfig, SLUG_RE, } from "../lib/config-file.js";
9
9
  import { buildManifest } from "../lib/manifest.js";
10
10
  import { uploadAll } from "../lib/upload.js";
11
- const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
12
11
  export const deployCommand = defineCommand({
13
12
  meta: {
14
13
  name: "deploy",
@@ -1,4 +1,12 @@
1
1
  export declare const forkCommand: import("citty").CommandDef<{
2
+ readonly json: {
3
+ readonly type: "boolean";
4
+ readonly description: "Print structured JSON to stdout.";
5
+ };
6
+ readonly field: {
7
+ readonly type: "string";
8
+ 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.";
9
+ };
2
10
  readonly slug: {
3
11
  readonly type: "positional";
4
12
  readonly description: "Slug of the project to fork (e.g. bomberman).";
@@ -18,9 +26,4 @@ export declare const forkCommand: import("citty").CommandDef<{
18
26
  readonly description: "Overwrite the target directory if it exists.";
19
27
  readonly default: false;
20
28
  };
21
- readonly json: {
22
- readonly type: "boolean";
23
- readonly description: "Emit machine-readable JSON (for agents).";
24
- readonly default: false;
25
- };
26
29
  }>;
@@ -5,7 +5,8 @@ import { defineCommand } from "citty";
5
5
  import consola from "consola";
6
6
  import { createClient } from "../lib/api.js";
7
7
  import { extractSource } from "../lib/archive.js";
8
- const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
8
+ import { SLUG_RE } from "../lib/config-file.js";
9
+ import { isJsonOutput, outputArgs, writeStructured } from "../lib/output.js";
9
10
  export const forkCommand = defineCommand({
10
11
  meta: {
11
12
  name: "fork",
@@ -31,11 +32,7 @@ export const forkCommand = defineCommand({
31
32
  description: "Overwrite the target directory if it exists.",
32
33
  default: false,
33
34
  },
34
- json: {
35
- type: "boolean",
36
- description: "Emit machine-readable JSON (for agents).",
37
- default: false,
38
- },
35
+ ...outputArgs,
39
36
  },
40
37
  run: async ({ args }) => {
41
38
  const source = args.slug.trim().toLowerCase();
@@ -56,7 +53,7 @@ export const forkCommand = defineCommand({
56
53
  }
57
54
  const client = createClient();
58
55
  // ---- Resolve + download source -----------------------------------------
59
- if (!args.json)
56
+ if (!isJsonOutput(args) && !args.field)
60
57
  consola.start(`Forking ${source}`);
61
58
  let src;
62
59
  try {
@@ -86,10 +83,8 @@ export const forkCommand = defineCommand({
86
83
  const name = args.name ?? target.replace(/-/g, " ");
87
84
  writeFileSync(resolve(dir, "vibedgames.json"), `${JSON.stringify({ slug: target, name }, null, 2)}\n`);
88
85
  rewritePackageName(dir, target);
89
- if (args.json) {
90
- consola.log(JSON.stringify({ slug: target, dir, forkedFrom: source }));
86
+ if (writeStructured({ slug: target, dir, forkedFrom: source }, args))
91
87
  return;
92
- }
93
88
  consola.success(`Forked ${source} → ${target}`);
94
89
  consola.log(` ${dir}`);
95
90
  consola.log("");
@@ -6,6 +6,7 @@ import { parseDownloadFlag, parseRunInput, readExplicitLocalFile } from "../lib/
6
6
  import { downloadMedia, extractMediaRefs } from "../lib/media-download.js";
7
7
  import { endpointPath, queueAppId, waitForCompletion } from "../lib/media-poll.js";
8
8
  import { uploadFile } from "../lib/media-upload.js";
9
+ import { isJsonOutput, outputArgs, writeJson, writeStructured } from "../lib/output.js";
9
10
  import { isRecord } from "../lib/types.js";
10
11
  // Action-specific fields for the status-command payload. `result` wraps
11
12
  // the raw fal payload under `result:` so fal's own keys can't clobber
@@ -23,11 +24,13 @@ function buildActionFields(action, data) {
23
24
  }
24
25
  return {};
25
26
  }
26
- function isJsonOutput(args) {
27
- return Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
28
- }
29
- function writeJson(value) {
30
- process.stdout.write(JSON.stringify(value, null, 2) + "\n");
27
+ /**
28
+ * True when stdout is carrying data rather than a progress narrative, so
29
+ * spinners and status lines must stay off it. `--field` counts: its whole
30
+ * point is that the output can be captured by a shell verbatim.
31
+ */
32
+ function isStructuredOutput(args) {
33
+ return isJsonOutput(args) || Boolean(args.field);
31
34
  }
32
35
  function extractMediaUrls(result) {
33
36
  return extractMediaRefs(result).map((r) => r.url);
@@ -53,7 +56,7 @@ const runCommand = defineCommand({
53
56
  type: "string",
54
57
  description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
55
58
  },
56
- json: { type: "boolean", description: "Print structured JSON to stdout." },
59
+ ...outputArgs,
57
60
  quiet: { type: "boolean", description: "Suppress progress output during sync runs." },
58
61
  },
59
62
  run: async ({ args, rawArgs }) => {
@@ -87,16 +90,14 @@ const runCommand = defineCommand({
87
90
  request_id: requestId,
88
91
  hint: `Check status: vg generate status ${endpoint_id} ${requestId}`,
89
92
  };
90
- if (isJsonOutput(args))
91
- writeJson(payload);
92
- else {
93
+ if (!writeStructured(payload, args)) {
93
94
  consola.success(`Submitted ${endpoint_id}`);
94
95
  consola.log(` request_id: ${requestId}`);
95
96
  }
96
97
  return;
97
98
  }
98
99
  const completed = await waitForCompletion(client, endpoint_id, requestId, {
99
- quiet: Boolean(args.quiet) || isJsonOutput(args),
100
+ quiet: Boolean(args.quiet) || isStructuredOutput(args),
100
101
  });
101
102
  let downloaded;
102
103
  if (downloadFlag.mode === "on") {
@@ -117,10 +118,7 @@ const runCommand = defineCommand({
117
118
  ? { download_failures: downloaded.failed }
118
119
  : {}),
119
120
  };
120
- if (isJsonOutput(args)) {
121
- writeJson(payload);
122
- }
123
- else {
121
+ if (!writeStructured(payload, args)) {
124
122
  consola.success(`Run completed (${completed.request_id})`);
125
123
  if (downloaded) {
126
124
  for (const path of downloaded.downloaded)
@@ -185,10 +183,7 @@ async function runViaCodex(opts) {
185
183
  ...(failed.length > 0 ? { download_failures: failed } : {}),
186
184
  ...(ignoredReferences.length > 0 ? { ignored_references: ignoredReferences } : {}),
187
185
  };
188
- if (isJsonOutput(args)) {
189
- writeJson(payload);
190
- }
191
- else {
186
+ if (!writeStructured(payload, args)) {
192
187
  consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
193
188
  for (const path of downloaded)
194
189
  consola.log(` ${path}`);
@@ -214,7 +209,7 @@ const statusCommand = defineCommand({
214
209
  type: "string",
215
210
  description: "Download media from the result (implies --result).",
216
211
  },
217
- json: { type: "boolean" },
212
+ ...outputArgs,
218
213
  },
219
214
  run: async ({ args, rawArgs }) => {
220
215
  if (args.result && args.cancel) {
@@ -284,27 +279,26 @@ const statusCommand = defineCommand({
284
279
  ? { download_failures: downloaded.failed }
285
280
  : {}),
286
281
  };
287
- if (isJsonOutput(args)) {
288
- writeJson(payload);
289
- }
290
- else if (action === "status") {
291
- const status = isRecord(data) && typeof data.status === "string" ? data.status : "?";
292
- consola.log(`status: ${status}`);
293
- if (isRecord(data) && typeof data.queue_position === "number") {
294
- consola.log(`queue_position: ${data.queue_position}`);
295
- }
296
- }
297
- else {
298
- consola.success(`${action} ${args.endpoint_id} ${args.request_id}`);
299
- if (downloaded) {
300
- for (const p of downloaded.downloaded)
301
- consola.log(` ${p}`);
302
- for (const f of downloaded.failed)
303
- consola.warn(` failed: ${f.url} (${f.error})`);
282
+ if (!writeStructured(payload, args)) {
283
+ if (action === "status") {
284
+ const status = isRecord(data) && typeof data.status === "string" ? data.status : "?";
285
+ consola.log(`status: ${status}`);
286
+ if (isRecord(data) && typeof data.queue_position === "number") {
287
+ consola.log(`queue_position: ${data.queue_position}`);
288
+ }
304
289
  }
305
- if (action === "result" && !downloaded?.downloaded.length) {
306
- for (const url of extractMediaUrls(data))
307
- consola.log(` ${url}`);
290
+ else {
291
+ consola.success(`${action} ${args.endpoint_id} ${args.request_id}`);
292
+ if (downloaded) {
293
+ for (const p of downloaded.downloaded)
294
+ consola.log(` ${p}`);
295
+ for (const f of downloaded.failed)
296
+ consola.warn(` failed: ${f.url} (${f.error})`);
297
+ }
298
+ if (action === "result" && !downloaded?.downloaded.length) {
299
+ for (const url of extractMediaUrls(data))
300
+ consola.log(` ${url}`);
301
+ }
308
302
  }
309
303
  }
310
304
  if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
@@ -329,7 +323,7 @@ const modelsCommand = defineCommand({
329
323
  type: "string",
330
324
  description: "Expand fields: openapi-3.0, enterprise_status. Repeat or comma-separate.",
331
325
  },
332
- json: { type: "boolean" },
326
+ ...outputArgs,
333
327
  },
334
328
  run: async ({ args }) => {
335
329
  const query = {};
@@ -355,9 +349,7 @@ const modelsCommand = defineCommand({
355
349
  path: "/v1/models",
356
350
  query,
357
351
  });
358
- if (isJsonOutput(args))
359
- writeJson(data);
360
- else
352
+ if (!writeStructured(data, args))
361
353
  printModels(data);
362
354
  },
363
355
  });
@@ -393,7 +385,7 @@ const schemaCommand = defineCommand({
393
385
  args: {
394
386
  endpoint_id: { type: "positional", required: true },
395
387
  format: { type: "string", description: "compact (default) | openapi" },
396
- json: { type: "boolean" },
388
+ ...outputArgs,
397
389
  },
398
390
  run: async ({ args }) => {
399
391
  const expand = args.format === "openapi" ? ["openapi-3.0"] : [];
@@ -408,7 +400,8 @@ const schemaCommand = defineCommand({
408
400
  ...(expand.length > 0 ? { expand } : {}),
409
401
  },
410
402
  });
411
- writeJson(data);
403
+ if (!writeStructured(data, args))
404
+ writeJson(data);
412
405
  },
413
406
  });
414
407
  // ---- pricing ----------------------------------------------------------------
@@ -416,7 +409,7 @@ const pricingCommand = defineCommand({
416
409
  meta: { name: "pricing", description: "Fetch pricing for a model." },
417
410
  args: {
418
411
  endpoint_id: { type: "positional", required: true },
419
- json: { type: "boolean" },
412
+ ...outputArgs,
420
413
  },
421
414
  run: async ({ args }) => {
422
415
  const client = createClient();
@@ -426,7 +419,8 @@ const pricingCommand = defineCommand({
426
419
  path: "/v1/models/pricing",
427
420
  query: { endpoint_id: args.endpoint_id },
428
421
  });
429
- writeJson(data);
422
+ if (!writeStructured(data, args))
423
+ writeJson(data);
430
424
  },
431
425
  });
432
426
  // ---- docs -------------------------------------------------------------------
@@ -434,7 +428,7 @@ const docsCommand = defineCommand({
434
428
  meta: { name: "docs", description: "Search generative-model documentation." },
435
429
  args: {
436
430
  query: { type: "positional", required: true },
437
- json: { type: "boolean" },
431
+ ...outputArgs,
438
432
  },
439
433
  run: async ({ args }) => {
440
434
  const client = createClient();
@@ -449,7 +443,8 @@ const docsCommand = defineCommand({
449
443
  params: { name: "search_fal", arguments: { query: args.query } },
450
444
  },
451
445
  });
452
- writeJson(data);
446
+ if (!writeStructured(data, args))
447
+ writeJson(data);
453
448
  },
454
449
  });
455
450
  // ---- upload -----------------------------------------------------------------
@@ -460,7 +455,7 @@ const uploadCommand = defineCommand({
460
455
  },
461
456
  args: {
462
457
  path: { type: "positional", required: true },
463
- json: { type: "boolean" },
458
+ ...outputArgs,
464
459
  },
465
460
  run: async ({ args }) => {
466
461
  const stat = readExplicitLocalFile(args.path);
@@ -470,9 +465,7 @@ const uploadCommand = defineCommand({
470
465
  }
471
466
  const client = createClient();
472
467
  const url = await uploadFile(client, stat);
473
- if (isJsonOutput(args))
474
- writeJson({ url });
475
- else
468
+ if (!writeStructured({ url }, args))
476
469
  process.stdout.write(url + "\n");
477
470
  },
478
471
  });
@@ -1,8 +1,9 @@
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";
4
6
  const REPO = "kyh/vibedgames";
5
- const PKG = "vibedgames";
6
7
  const DEFAULT_AGENTS = "claude-code,cursor,codex";
7
8
  const description = "Install/update vibedgames skills and the vg CLI";
8
9
  const skillsAddArgs = (agents, global, yes) => {
@@ -50,12 +51,21 @@ export const initCommand = defineCommand({
50
51
  .split(",")
51
52
  .map((s) => s.trim())
52
53
  .filter(Boolean);
54
+ // Whatever installed this CLI is what should upgrade it. Installing with a
55
+ // different manager writes a second copy into a prefix the shell may not
56
+ // even be looking at, so `vg --version` would not move.
57
+ const manager = detectPackageManager(fileURLToPath(import.meta.url));
53
58
  consola.start("Installing/updating vibedgames skills and the vg CLI...");
54
59
  const [add, cli] = await Promise.all([
55
60
  run("npx", skillsAddArgs(agents, args.global, args.yes)),
56
- run("npm", ["install", "-g", PKG]),
61
+ run(manager, globalInstallArgs(manager)),
57
62
  ]);
58
63
  if (add.code !== 0) {
64
+ if (isMissingCommand(add)) {
65
+ throw new Error("`npx` was not found on PATH. It ships with Node, so this usually means " +
66
+ "the vg CLI is running from a standalone build — install Node, or add " +
67
+ `the skills yourself with: npx skills add ${REPO}`);
68
+ }
59
69
  if (add.output.trim())
60
70
  consola.error(add.output.trim());
61
71
  throw new Error(`skills add exited with code ${add.code}`);
@@ -71,11 +81,13 @@ export const initCommand = defineCommand({
71
81
  consola.success("Refreshed installed skills to latest");
72
82
  }
73
83
  if (cli.code !== 0) {
74
- if (cli.output.trim())
84
+ if (cli.output.trim() && !isMissingCommand(cli))
75
85
  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}`);
86
+ consola.warn(isMissingCommand(cli)
87
+ ? `Couldn't find ${manager} to update the vg CLI. Update manually: ${globalInstallCommand(manager)}`
88
+ : `Couldn't install the vg CLI globally (${manager} exit ${cli.code}). Install manually: ${globalInstallCommand(manager)}`);
77
89
  return;
78
90
  }
79
- consola.success("Installed/updated vg CLI globally");
91
+ consola.success(`Installed/updated ${PKG_NAME} globally with ${manager}`);
80
92
  },
81
93
  });
@@ -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
@@ -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 { playtestCommand, runPlaytest } from "./commands/playtest.js";
14
15
  import { updateCommand } from "./commands/update.js";
15
16
  import { whoamiCommand } from "./commands/whoami.js";
16
17
  import { maybeScheduleAutoUpdate } from "./lib/update.js";
@@ -27,6 +28,7 @@ const main = defineCommand({
27
28
  login: loginCommand,
28
29
  logout: logoutCommand,
29
30
  deploy: deployCommand,
31
+ playtest: playtestCommand,
30
32
  factory: factoryCommand,
31
33
  fork: forkCommand,
32
34
  generate: generateCommand,
@@ -42,10 +44,14 @@ const subcommand = process.argv[2];
42
44
  if (subcommand && !["update", "init", "completions"].includes(subcommand)) {
43
45
  maybeScheduleAutoUpdate();
44
46
  }
45
- // `vg factory` is a pure passthrough to the factory plugin binary — route it
46
- // before citty runs so flags like --help/--version reach the binary instead
47
- // 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`.)
48
51
  if (subcommand === "factory") {
49
52
  runFactory(process.argv.slice(3));
50
53
  }
54
+ if (subcommand === "playtest") {
55
+ runPlaytest(process.argv.slice(3));
56
+ }
51
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
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Work out which package manager installed this CLI, so a self-update uses it.
3
+ *
4
+ * `vg init` and `vg update` both used to shell out to `npm install -g
5
+ * vibedgames` unconditionally. On a machine where the CLI came from pnpm, bun
6
+ * or yarn, that is wrong twice over: npm may not be installed at all, and if it
7
+ * is, it installs a *second* copy into a different global prefix — so the
8
+ * update silently lands somewhere the shell isn't looking and `vg --version`
9
+ * doesn't move.
10
+ *
11
+ * The install path is the evidence. Each manager puts globals somewhere
12
+ * recognisable, so the directory this file was loaded from names the manager
13
+ * that put it there.
14
+ */
15
+ export type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
16
+ export declare const PKG_NAME = "vibedgames";
17
+ /**
18
+ * `installPath` is where the CLI is installed — normally the directory this
19
+ * module resolves from. Bun's own runtime is a signal in its own right.
20
+ */
21
+ export declare function detectPackageManager(installPath: string, env?: NodeJS.ProcessEnv): PackageManager;
22
+ /** The argv that installs or upgrades a package globally, per manager. */
23
+ export declare function globalInstallArgs(manager: PackageManager, pkg?: string): string[];
24
+ /** The command a user can copy-paste when the automatic update can't run. */
25
+ export declare function globalInstallCommand(manager: PackageManager, pkg?: string): string;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Work out which package manager installed this CLI, so a self-update uses it.
3
+ *
4
+ * `vg init` and `vg update` both used to shell out to `npm install -g
5
+ * vibedgames` unconditionally. On a machine where the CLI came from pnpm, bun
6
+ * or yarn, that is wrong twice over: npm may not be installed at all, and if it
7
+ * is, it installs a *second* copy into a different global prefix — so the
8
+ * update silently lands somewhere the shell isn't looking and `vg --version`
9
+ * doesn't move.
10
+ *
11
+ * The install path is the evidence. Each manager puts globals somewhere
12
+ * recognisable, so the directory this file was loaded from names the manager
13
+ * that put it there.
14
+ */
15
+ export const PKG_NAME = "vibedgames";
16
+ /**
17
+ * Global install directory fingerprints, most specific first.
18
+ *
19
+ * The npm entries come last because they are the loosest: `lib/node_modules`
20
+ * is npm's global prefix on unix and `npm\node_modules` is its Windows one,
21
+ * but neither is distinctive enough to check before the managers that have a
22
+ * directory named after them.
23
+ */
24
+ const SIGNATURES = [
25
+ ["bun", /[/\\]\.bun[/\\]/],
26
+ // pnpm's global store, not a project-local `node_modules/.pnpm`.
27
+ ["pnpm", /[/\\](?:pnpm[/\\]global|\.pnpm-global|Library[/\\]pnpm)[/\\]/],
28
+ ["yarn", /[/\\](?:\.yarn|yarn[/\\]global|\.config[/\\]yarn)[/\\]/],
29
+ ["npm", /[/\\]lib[/\\]node_modules[/\\]/],
30
+ ["npm", /[/\\]npm[/\\]node_modules[/\\]/],
31
+ ];
32
+ /**
33
+ * `npm_config_user_agent` is set by whichever manager is running us — reliable
34
+ * when `vg` was invoked through a script (`pnpm vg …`), absent otherwise.
35
+ */
36
+ function fromUserAgent(userAgent) {
37
+ if (!userAgent)
38
+ return null;
39
+ const name = userAgent.split("/")[0];
40
+ return name === "npm" || name === "pnpm" || name === "yarn" || name === "bun" ? name : null;
41
+ }
42
+ /**
43
+ * `installPath` is where the CLI is installed — normally the directory this
44
+ * module resolves from. Bun's own runtime is a signal in its own right.
45
+ */
46
+ export function detectPackageManager(installPath, env = process.env) {
47
+ for (const [manager, signature] of SIGNATURES) {
48
+ if (signature.test(installPath))
49
+ return manager;
50
+ }
51
+ // Bun reports itself in versions; running under it means `bun add` works.
52
+ if (typeof globalThis.Bun !== "undefined")
53
+ return "bun";
54
+ return fromUserAgent(env.npm_config_user_agent) ?? "npm";
55
+ }
56
+ /** The argv that installs or upgrades a package globally, per manager. */
57
+ export function globalInstallArgs(manager, pkg = PKG_NAME) {
58
+ switch (manager) {
59
+ case "pnpm":
60
+ return ["add", "-g", pkg];
61
+ case "yarn":
62
+ return ["global", "add", pkg];
63
+ case "bun":
64
+ return ["add", "-g", pkg];
65
+ case "npm":
66
+ return ["install", "-g", pkg];
67
+ }
68
+ }
69
+ /** The command a user can copy-paste when the automatic update can't run. */
70
+ export function globalInstallCommand(manager, pkg = PKG_NAME) {
71
+ return `${manager} ${globalInstallArgs(manager, pkg).join(" ")}`;
72
+ }
package/dist/lib/run.d.ts CHANGED
@@ -2,4 +2,10 @@ export type RunResult = {
2
2
  code: number;
3
3
  output: string;
4
4
  };
5
+ /**
6
+ * True when the command never started, as opposed to running and failing.
7
+ * `run` turns a spawn error into an exit code, so the message is the only
8
+ * thing that separates "no such binary" from "the binary said no".
9
+ */
10
+ export declare const isMissingCommand: (result: RunResult) => boolean;
5
11
  export declare const run: (cmd: string, args: string[]) => Promise<RunResult>;
package/dist/lib/run.js CHANGED
@@ -1,4 +1,10 @@
1
1
  import spawn from "cross-spawn";
2
+ /**
3
+ * True when the command never started, as opposed to running and failing.
4
+ * `run` turns a spawn error into an exit code, so the message is the only
5
+ * thing that separates "no such binary" from "the binary said no".
6
+ */
7
+ export const isMissingCommand = (result) => result.code !== 0 && /ENOENT|not found|not recognized/i.test(result.output);
2
8
  export const run = (cmd, args) => new Promise((resolve) => {
3
9
  const chunks = [];
4
10
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vibedgames",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "bin": {
6
6
  "vg": "./dist/index.js"
@@ -20,11 +20,11 @@
20
20
  "tiged": "^2.12.8"
21
21
  },
22
22
  "devDependencies": {
23
- "@cloudflare/workers-types": "^5.20260724.1",
23
+ "@cloudflare/workers-types": "^5.20260814.1",
24
24
  "@kyh/tsconfig": "^1.2.0",
25
25
  "@trpc/server": "^11.18.0",
26
26
  "@types/cross-spawn": "^6.0.6",
27
- "@types/node": "^26.1.1",
27
+ "@types/node": "^26.2.0",
28
28
  "typescript": "^7.0.2",
29
29
  "@repo/api": "^0.1.0"
30
30
  },
@@ -32,7 +32,7 @@
32
32
  "build": "tsc && chmod +x dist/index.js",
33
33
  "dev": "tsc --watch",
34
34
  "clean": "rm -rf .turbo dist node_modules",
35
- "test": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts test/codex.test.ts",
35
+ "test": "node --import tsx --test test/*.test.ts",
36
36
  "typecheck": "tsc --noEmit"
37
37
  }
38
38
  }