vibedgames 0.2.0 → 0.3.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.
@@ -38,6 +38,25 @@ export const deployCommand = defineCommand({
38
38
  consola.error(`Directory does not exist: ${dir}`);
39
39
  process.exit(1);
40
40
  }
41
+ // Build-tool projects (package.json present): the root index.html is the
42
+ // source template, the playable game lives in the build output. Deploying
43
+ // the root uploads the whole source tree — wrong content and usually over
44
+ // the file caps — so prefer a build directory when one exists. Checked in
45
+ // popularity order: Vite/Rollup/Parcel → CRA/Preact → Next export/esbuild.
46
+ let deployDir = dir;
47
+ if (existsSync(join(dir, "package.json"))) {
48
+ for (const name of ["dist", "build", "out"]) {
49
+ if (existsSync(join(dir, name, "index.html"))) {
50
+ deployDir = join(dir, name);
51
+ consola.info(`Project root detected — deploying its build output ${name}/ instead.`);
52
+ break;
53
+ }
54
+ }
55
+ if (deployDir === dir) {
56
+ consola.warn("This looks like an unbuilt project (package.json, no dist/build/out) — " +
57
+ "run the build first, or the deployed index.html will reference missing source files.");
58
+ }
59
+ }
41
60
  // ---- Resolve project config ---------------------------------------------
42
61
  let config = null;
43
62
  try {
@@ -75,9 +94,9 @@ export const deployCommand = defineCommand({
75
94
  process.exit(1);
76
95
  }
77
96
  // ---- Walk files ---------------------------------------------------------
78
- const manifest = buildManifest(dir);
97
+ const manifest = buildManifest(deployDir);
79
98
  if (manifest.length === 0) {
80
- consola.error(`No files found in ${dir}`);
99
+ consola.error(`No files found in ${deployDir}`);
81
100
  process.exit(1);
82
101
  }
83
102
  const hasIndex = manifest.some((f) => f.path === "index.html");
@@ -0,0 +1,3 @@
1
+ /** Resolve (installing on first use) and exec the factory. Never returns. */
2
+ export declare function runFactory(args: string[]): never;
3
+ export declare const factoryCommand: import("citty").CommandDef<import("citty").ArgsDef>;
@@ -0,0 +1,70 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { defineCommand } from "citty";
5
+ import consola from "consola";
6
+ /**
7
+ * `vg factory` — the autonomous game factory, shipped as an optional plugin.
8
+ * The vg CLI carries none of it: the factory lives in a per-platform npm
9
+ * package (a bun-compiled standalone binary) that gets installed globally on
10
+ * first use, then every invocation just execs it with the args passed
11
+ * through. index.ts routes `vg factory …` here BEFORE citty parses anything,
12
+ * so even `--help`/`--version` reach the binary untouched; the citty command
13
+ * below exists only so `vg --help` lists the subcommand.
14
+ */
15
+ const PKG = `@vibedgames/factory-${process.platform}-${process.arch}`;
16
+ const BIN = process.platform === "win32" ? "vg-factory.exe" : "vg-factory";
17
+ function npmGlobalRoot() {
18
+ try {
19
+ const res = spawnSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 30_000 });
20
+ if (res.status !== 0 || res.error !== undefined)
21
+ return null;
22
+ const root = res.stdout.trim();
23
+ return root || null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /** The installed factory binary, or null. VG_FACTORY_BIN overrides (dev). */
30
+ function findBinary() {
31
+ const override = process.env.VG_FACTORY_BIN;
32
+ if (override)
33
+ return existsSync(override) ? override : null;
34
+ const root = npmGlobalRoot();
35
+ if (!root)
36
+ return null;
37
+ const path = join(root, PKG, "bin", BIN);
38
+ return existsSync(path) ? path : null;
39
+ }
40
+ /** Resolve (installing on first use) and exec the factory. Never returns. */
41
+ export function runFactory(args) {
42
+ let bin = findBinary();
43
+ if (!bin) {
44
+ consola.start(`Installing the factory (${PKG})…`);
45
+ const install = spawnSync("npm", ["install", "-g", PKG], { stdio: "inherit" });
46
+ if (install.status !== 0 || install.error !== undefined) {
47
+ consola.error(`Couldn't install the factory. Try manually: npm install -g ${PKG}`);
48
+ process.exit(1);
49
+ }
50
+ bin = findBinary();
51
+ if (!bin) {
52
+ consola.error(`Installed ${PKG} but couldn't find its binary under npm's global root. Check \`npm root -g\`.`);
53
+ process.exit(1);
54
+ }
55
+ consola.success("Factory installed.");
56
+ }
57
+ const result = spawnSync(bin, args, { stdio: "inherit" });
58
+ process.exit(result.status ?? 1);
59
+ }
60
+ export const factoryCommand = defineCommand({
61
+ meta: {
62
+ name: "factory",
63
+ description: "Run the vibedgames factory — an autonomous agent that builds a browser game and evolves it like a studio (optional plugin; installs on first use). All arguments are passed through: `vg factory` opens the dashboard, `vg factory start <slug>` resumes a game.",
64
+ },
65
+ run: ({ rawArgs }) => {
66
+ // Normally unreachable (index.ts routes `vg factory` before citty), but
67
+ // keeps the command functional if invoked programmatically.
68
+ runFactory(rawArgs);
69
+ },
70
+ });
@@ -1,6 +1,7 @@
1
1
  import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
3
  import { createClient } from "../lib/api.js";
4
+ import { CodexError, generateImagesWithCodex, placeCodexOutputs, resolveProvider, } from "../lib/codex.js";
4
5
  import { parseDownloadFlag, parseRunInput, readExplicitLocalFile } from "../lib/media-args.js";
5
6
  import { downloadMedia, extractMediaRefs } from "../lib/media-download.js";
6
7
  import { endpointPath, queueAppId, waitForCompletion } from "../lib/media-poll.js";
@@ -44,6 +45,10 @@ const runCommand = defineCommand({
44
45
  type: "boolean",
45
46
  description: "Submit to queue and return request_id without waiting.",
46
47
  },
48
+ provider: {
49
+ type: "string",
50
+ description: "Execution backend: vibedgames (default) or codex (delegate image generation to the local Codex CLI / your Codex plan). Also settable via VG_GENERATE_PROVIDER.",
51
+ },
47
52
  download: {
48
53
  type: "string",
49
54
  description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
@@ -56,8 +61,13 @@ const runCommand = defineCommand({
56
61
  // parseRunInput already skips non-`--` tokens, so the positional
57
62
  // endpoint_id and any subcommand name in argv are no-ops.
58
63
  const finalInput = parseRunInput(rawArgs);
59
- const client = createClient();
60
64
  const endpoint_id = args.endpoint_id;
65
+ const provider = resolveProvider(args.provider);
66
+ if (provider === "codex") {
67
+ await runViaCodex({ args, finalInput, downloadFlag, endpoint_id });
68
+ return;
69
+ }
70
+ const client = createClient();
61
71
  const submission = await client.generate.forward.mutate({
62
72
  target: "queue",
63
73
  method: "POST",
@@ -128,6 +138,66 @@ const runCommand = defineCommand({
128
138
  }
129
139
  },
130
140
  });
141
+ // Delegate image generation to the local Codex CLI instead of the
142
+ // vibedgames model runner. Produces local files directly (Codex writes
143
+ // to disk), so there's no queue, no request polling, and no vibedgames
144
+ // backend call. The `--download` template still controls output naming;
145
+ // without it we default to cwd.
146
+ async function runViaCodex(opts) {
147
+ const { args, finalInput, downloadFlag, endpoint_id } = opts;
148
+ if (args.async) {
149
+ consola.error("--async is not supported with --provider codex (Codex runs synchronously).");
150
+ process.exit(1);
151
+ }
152
+ let result;
153
+ try {
154
+ result = await generateImagesWithCodex({ input: finalInput });
155
+ }
156
+ catch (err) {
157
+ if (err instanceof CodexError) {
158
+ // Expected, user-facing failure (codex missing / declined / exec
159
+ // error). Present it cleanly with a deterministic exit code instead
160
+ // of an unhandled stack trace — consola.error goes to stderr, so it
161
+ // never corrupts a --json consumer's stdout. Codex's own output
162
+ // already streamed straight to stderr as it ran (and the message
163
+ // already names the vibedgames fallback), so we don't reprint here.
164
+ consola.error(err.message);
165
+ process.exit(1);
166
+ }
167
+ throw err;
168
+ }
169
+ const { requestId, rawFiles, prompt, ignoredReferences } = result;
170
+ // Warn about dropped (non-local) references on stderr regardless of
171
+ // --json/--quiet — stderr never corrupts the JSON payload — and also
172
+ // record them in the JSON so an agent parsing stdout sees the signal.
173
+ for (const ref of ignoredReferences) {
174
+ consola.warn(`Ignored non-local reference (codex needs a local file path): ${ref}`);
175
+ }
176
+ const template = downloadFlag.mode === "on" ? downloadFlag.template : undefined;
177
+ const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId);
178
+ const payload = {
179
+ status: "completed",
180
+ provider: "codex",
181
+ endpoint_id,
182
+ request_id: requestId,
183
+ result: { provider: "codex", prompt, images: downloaded.map((path) => ({ path })) },
184
+ downloaded_files: downloaded,
185
+ ...(failed.length > 0 ? { download_failures: failed } : {}),
186
+ ...(ignoredReferences.length > 0 ? { ignored_references: ignoredReferences } : {}),
187
+ };
188
+ if (isJsonOutput(args)) {
189
+ writeJson(payload);
190
+ }
191
+ else {
192
+ consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
193
+ for (const path of downloaded)
194
+ consola.log(` ${path}`);
195
+ for (const f of failed)
196
+ consola.warn(` failed: ${f.url} (${f.error})`);
197
+ }
198
+ if (failed.length > 0 && downloaded.length === 0)
199
+ process.exit(1);
200
+ }
131
201
  // ---- status -----------------------------------------------------------------
132
202
  const statusCommand = defineCommand({
133
203
  meta: {
@@ -1,6 +1,7 @@
1
1
  import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
- import { getBaseUrl, getToken } from "../lib/config.js";
3
+ import { createClient } from "../lib/api.js";
4
+ import { getToken } from "../lib/config.js";
4
5
  export const whoamiCommand = defineCommand({
5
6
  meta: {
6
7
  name: "whoami",
@@ -12,21 +13,24 @@ export const whoamiCommand = defineCommand({
12
13
  consola.warn("Not logged in. Run `vg login` to authenticate.");
13
14
  process.exit(1);
14
15
  }
15
- const baseUrl = getBaseUrl();
16
- const res = await fetch(`${baseUrl}/api/auth/get-session`, {
17
- headers: {
18
- Authorization: `Bearer ${token}`,
19
- },
20
- });
21
- if (!res.ok) {
22
- consola.error("Failed to fetch session. Try `vg login` again.");
23
- process.exit(1);
16
+ // Goes through tRPC (not the raw better-auth endpoint) so it resolves
17
+ // both session tokens and `vg_…` API keys.
18
+ const client = createClient();
19
+ try {
20
+ const user = await client.auth.me.query();
21
+ consola.log(`${user.name} (${user.email})`);
24
22
  }
25
- const data = (await res.json());
26
- if (!data?.user) {
27
- consola.warn("Session expired. Run `vg login` to re-authenticate.");
23
+ catch (err) {
24
+ // Only an auth error means "log in"; surface network/server failures as
25
+ // themselves so they aren't mistaken for a bad credential.
26
+ const code = err?.data?.code;
27
+ if (code === "UNAUTHORIZED" || code === "FORBIDDEN") {
28
+ consola.warn("Not authenticated. Run `vg login`, or check your VG_TOKEN / API key.");
29
+ }
30
+ else {
31
+ consola.error(`Failed to fetch current user: ${err instanceof Error ? err.message : String(err)}`);
32
+ }
28
33
  process.exit(1);
29
34
  }
30
- consola.log(`${data.user.name} (${data.user.email})`);
31
35
  },
32
36
  });
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { defineCommand, runMain } from "citty";
4
4
  import { completionsCommand } from "./commands/completions.js";
5
5
  import { deployCommand } from "./commands/deploy.js";
6
+ import { factoryCommand, runFactory } from "./commands/factory.js";
6
7
  import { forkCommand } from "./commands/fork.js";
7
8
  import { generateCommand } from "./commands/generate.js";
8
9
  import { initCommand } from "./commands/init.js";
@@ -17,7 +18,7 @@ const main = defineCommand({
17
18
  meta: {
18
19
  name: "vg",
19
20
  version: pkg.version,
20
- description: "vibedgames CLI",
21
+ description: "vibedgames CLI — agent-native game deploy & asset tooling (use --json for machine-readable output)",
21
22
  },
22
23
  subCommands: {
23
24
  new: newCommand,
@@ -25,6 +26,7 @@ const main = defineCommand({
25
26
  login: loginCommand,
26
27
  logout: logoutCommand,
27
28
  deploy: deployCommand,
29
+ factory: factoryCommand,
28
30
  fork: forkCommand,
29
31
  generate: generateCommand,
30
32
  update: updateCommand,
@@ -38,4 +40,10 @@ const subcommand = process.argv[2];
38
40
  if (subcommand && !["update", "init", "completions"].includes(subcommand)) {
39
41
  maybeScheduleAutoUpdate();
40
42
  }
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`.)
46
+ if (subcommand === "factory") {
47
+ runFactory(process.argv.slice(3));
48
+ }
41
49
  runMain(main);
@@ -0,0 +1,84 @@
1
+ export type Provider = "vibedgames" | "codex";
2
+ /**
3
+ * Expected, user-facing failure of the codex provider. Carries a clean
4
+ * message plus any output Codex itself emitted, so the caller can present
5
+ * it directly instead of dumping a stack trace. `notInstalled` flags the
6
+ * "`codex` binary missing" case so callers can suggest a fallback.
7
+ */
8
+ export declare class CodexError extends Error {
9
+ readonly notInstalled: boolean;
10
+ readonly output: string;
11
+ constructor(message: string, opts?: {
12
+ notInstalled?: boolean;
13
+ output?: string;
14
+ });
15
+ }
16
+ /**
17
+ * Resolve the effective provider from the `--provider` flag, falling back
18
+ * to the `VG_GENERATE_PROVIDER` env var and finally the vibedgames
19
+ * default. Unknown values throw so a typo (`--provider coddex`) fails
20
+ * loudly instead of silently hitting the paid backend.
21
+ */
22
+ export declare function resolveProvider(flag?: string): Provider;
23
+ export type CodexInput = {
24
+ prompt: string;
25
+ count: number;
26
+ sizeHint?: string;
27
+ /** Raw reference values from the input; may be local paths or URLs. */
28
+ referenceCandidates: string[];
29
+ };
30
+ /**
31
+ * Pull the fields Codex can act on out of the parsed `run` input. Pure:
32
+ * no filesystem access, so the reference values are returned verbatim and
33
+ * resolved to local files later.
34
+ */
35
+ export declare function parseCodexInput(input: Record<string, unknown>): CodexInput;
36
+ /**
37
+ * Build the natural-language instruction handed to `codex exec`. We pin
38
+ * exact output filenames and the working directory so the generated
39
+ * files land somewhere we can deterministically collect them.
40
+ */
41
+ export declare function buildCodexPrompt(input: CodexInput, filenames: string[], hasReferences: boolean): string;
42
+ /**
43
+ * Choose the on-disk destination for a collected Codex output, mirroring
44
+ * the `--download` template semantics used for the vibedgames path
45
+ * ({index}, {ext}, {request_id} placeholders; bare path treated as a
46
+ * directory or a literal file by extension).
47
+ */
48
+ export declare function renderLocalTarget(template: string | undefined, index: number, ext: string, requestId: string, count: number): string;
49
+ type CodexRun = {
50
+ requestId: string;
51
+ prompt: string;
52
+ /** Absolute paths to the images Codex produced, in a stable order. */
53
+ rawFiles: string[];
54
+ /**
55
+ * Reference inputs that were dropped because they weren't local files
56
+ * (Codex can only attach on-disk references). Surfaced to the caller so
57
+ * it isn't silently lost — especially under --json, where a warning to
58
+ * a suppressed logger would vanish.
59
+ */
60
+ ignoredReferences: string[];
61
+ };
62
+ /**
63
+ * Delegate image generation to the local `codex` CLI. Runs
64
+ * `codex exec` in an isolated temp workspace, then collects the produced
65
+ * images from that workspace (and, as a fallback, from Codex's default
66
+ * `generated_images` store). Throws with actionable guidance when Codex
67
+ * is missing, fails, or produces nothing.
68
+ */
69
+ export declare function generateImagesWithCodex(opts: {
70
+ input: Record<string, unknown>;
71
+ }): Promise<CodexRun>;
72
+ /**
73
+ * Copy Codex's raw outputs to their final destinations per the
74
+ * `--download` template (or default cwd naming). Returns the written
75
+ * paths and any per-file failures.
76
+ */
77
+ export declare function placeCodexOutputs(rawFiles: string[], template: string | undefined, requestId: string): {
78
+ downloaded: string[];
79
+ failed: {
80
+ url: string;
81
+ error: string;
82
+ }[];
83
+ };
84
+ export {};