vibedgames 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 {};
@@ -0,0 +1,347 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, statSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { basename, dirname, extname, join, resolve } from "node:path";
5
+ import spawn from "cross-spawn";
6
+ import { readExplicitLocalFile } from "./media-args.js";
7
+ import { disambiguateTargets } from "./media-download.js";
8
+ /**
9
+ * Expected, user-facing failure of the codex provider. Carries a clean
10
+ * message plus any output Codex itself emitted, so the caller can present
11
+ * it directly instead of dumping a stack trace. `notInstalled` flags the
12
+ * "`codex` binary missing" case so callers can suggest a fallback.
13
+ */
14
+ export class CodexError extends Error {
15
+ notInstalled;
16
+ output;
17
+ constructor(message, opts = {}) {
18
+ super(message);
19
+ this.name = "CodexError";
20
+ this.notInstalled = opts.notInstalled ?? false;
21
+ this.output = opts.output ?? "";
22
+ }
23
+ }
24
+ /**
25
+ * Resolve the effective provider from the `--provider` flag, falling back
26
+ * to the `VG_GENERATE_PROVIDER` env var and finally the vibedgames
27
+ * default. Unknown values throw so a typo (`--provider coddex`) fails
28
+ * loudly instead of silently hitting the paid backend.
29
+ */
30
+ export function resolveProvider(flag) {
31
+ const raw = (flag ?? process.env.VG_GENERATE_PROVIDER ?? "").trim().toLowerCase();
32
+ if (raw === "codex")
33
+ return "codex";
34
+ if (raw === "" || raw === "vibedgames" || raw === "fal" || raw === "default") {
35
+ return "vibedgames";
36
+ }
37
+ throw new Error(`Unknown --provider "${raw}". Supported: vibedgames (default), codex.`);
38
+ }
39
+ // Input keys we map onto Codex's natural-language image request. Codex
40
+ // only exposes a single built-in image model, so most fal-style params
41
+ // don't apply — we fold the few that have a meaning (prompt, count,
42
+ // size, reference images) into the prompt / CLI flags and ignore the
43
+ // rest rather than erroring.
44
+ const PROMPT_KEYS = ["prompt", "text"];
45
+ const COUNT_KEYS = ["num_images", "num_outputs", "n", "count"];
46
+ const REF_KEYS = [
47
+ "image_url",
48
+ "image_urls",
49
+ "image",
50
+ "images",
51
+ "input_image",
52
+ "reference_image_url",
53
+ "reference_image_urls",
54
+ ];
55
+ const MAX_IMAGES = 8;
56
+ const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "webp", "gif"]);
57
+ /**
58
+ * Pull the fields Codex can act on out of the parsed `run` input. Pure:
59
+ * no filesystem access, so the reference values are returned verbatim and
60
+ * resolved to local files later.
61
+ */
62
+ export function parseCodexInput(input) {
63
+ let prompt = "";
64
+ for (const key of PROMPT_KEYS) {
65
+ const v = input[key];
66
+ if (typeof v === "string" && v.trim().length > 0) {
67
+ prompt = v.trim();
68
+ break;
69
+ }
70
+ }
71
+ let count = 1;
72
+ for (const key of COUNT_KEYS) {
73
+ const v = input[key];
74
+ if (typeof v === "number" && Number.isFinite(v)) {
75
+ count = Math.max(1, Math.min(MAX_IMAGES, Math.floor(v)));
76
+ break;
77
+ }
78
+ }
79
+ const referenceCandidates = [];
80
+ for (const key of REF_KEYS) {
81
+ const v = input[key];
82
+ if (typeof v === "string")
83
+ referenceCandidates.push(v);
84
+ else if (Array.isArray(v)) {
85
+ for (const item of v)
86
+ if (typeof item === "string")
87
+ referenceCandidates.push(item);
88
+ }
89
+ }
90
+ return { prompt, count, sizeHint: buildSizeHint(input), referenceCandidates };
91
+ }
92
+ function buildSizeHint(input) {
93
+ const parts = [];
94
+ const size = input.image_size ?? input.size;
95
+ if (typeof size === "string" && size.trim().length > 0)
96
+ parts.push(size.trim());
97
+ const aspect = input.aspect_ratio;
98
+ if (typeof aspect === "string" && aspect.trim().length > 0) {
99
+ parts.push(`aspect ratio ${aspect.trim()}`);
100
+ }
101
+ const w = input.width;
102
+ const h = input.height;
103
+ if (typeof w === "number" && typeof h === "number")
104
+ parts.push(`${w}x${h}px`);
105
+ return parts.length > 0 ? parts.join(", ") : undefined;
106
+ }
107
+ /**
108
+ * Build the natural-language instruction handed to `codex exec`. We pin
109
+ * exact output filenames and the working directory so the generated
110
+ * files land somewhere we can deterministically collect them.
111
+ */
112
+ export function buildCodexPrompt(input, filenames, hasReferences) {
113
+ const n = filenames.length;
114
+ const noun = n === 1 ? "image" : `${n} images`;
115
+ const lines = [
116
+ hasReferences
117
+ ? `Edit the attached reference image to produce ${noun} using your built-in image generation.`
118
+ : `Generate ${noun} using your built-in image generation.`,
119
+ `Prompt: ${input.prompt}`,
120
+ ];
121
+ if (input.sizeHint)
122
+ lines.push(`Size: ${input.sizeHint}.`);
123
+ lines.push(`Save the output as PNG into the current working directory using exactly ` +
124
+ `these filenames: ${filenames.join(", ")}.`, `Do not read, create, or modify any other files, and do not write or run code. $imagegen`);
125
+ return lines.join("\n");
126
+ }
127
+ /**
128
+ * Choose the on-disk destination for a collected Codex output, mirroring
129
+ * the `--download` template semantics used for the vibedgames path
130
+ * ({index}, {ext}, {request_id} placeholders; bare path treated as a
131
+ * directory or a literal file by extension).
132
+ */
133
+ export function renderLocalTarget(template, index, ext, requestId, count) {
134
+ if (!template) {
135
+ return resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
136
+ }
137
+ if (template.includes("{")) {
138
+ const rendered = template
139
+ .replaceAll("{index}", String(index))
140
+ .replaceAll("{ext}", ext)
141
+ .replaceAll("{request_id}", requestId)
142
+ .replaceAll("{name}", "output");
143
+ return resolve(rendered);
144
+ }
145
+ if (extname(template)) {
146
+ if (count <= 1)
147
+ return resolve(template);
148
+ const e = extname(template);
149
+ const stem = template.slice(0, template.length - e.length);
150
+ return resolve(index === 0 ? template : `${stem}_${index}${e}`);
151
+ }
152
+ return resolve(template, `codex-image-${index}.${ext}`);
153
+ }
154
+ function codexHome() {
155
+ return process.env.CODEX_HOME ?? join(homedir(), ".codex");
156
+ }
157
+ function listImages(dir) {
158
+ let names;
159
+ try {
160
+ names = readdirSync(dir);
161
+ }
162
+ catch {
163
+ return [];
164
+ }
165
+ const out = [];
166
+ for (const name of names) {
167
+ const ext = extname(name).slice(1).toLowerCase();
168
+ if (!IMAGE_EXT.has(ext))
169
+ continue;
170
+ const full = join(dir, name);
171
+ try {
172
+ if (statSync(full).isFile())
173
+ out.push(full);
174
+ }
175
+ catch {
176
+ // Raced away between readdir and stat; skip.
177
+ }
178
+ }
179
+ return out.toSorted();
180
+ }
181
+ // Keep the `limit` most-recently-modified paths (by mtime), returned in
182
+ // stable name order. Used to bound the shared-store fallback.
183
+ function pickNewest(paths, limit) {
184
+ if (paths.length <= limit)
185
+ return paths;
186
+ const withTime = paths.map((p) => {
187
+ let mtimeMs = 0;
188
+ try {
189
+ mtimeMs = statSync(p).mtimeMs;
190
+ }
191
+ catch {
192
+ // Gone between listing and stat; sort it oldest.
193
+ }
194
+ return { p, mtimeMs };
195
+ });
196
+ return withTime
197
+ .toSorted((a, b) => b.mtimeMs - a.mtimeMs)
198
+ .slice(0, limit)
199
+ .map((x) => x.p)
200
+ .toSorted();
201
+ }
202
+ /**
203
+ * Delegate image generation to the local `codex` CLI. Runs
204
+ * `codex exec` in an isolated temp workspace, then collects the produced
205
+ * images from that workspace (and, as a fallback, from Codex's default
206
+ * `generated_images` store). Throws with actionable guidance when Codex
207
+ * is missing, fails, or produces nothing.
208
+ */
209
+ export async function generateImagesWithCodex(opts) {
210
+ const parsed = parseCodexInput(opts.input);
211
+ if (!parsed.prompt) {
212
+ throw new CodexError("codex image generation requires a prompt (--prompt).");
213
+ }
214
+ // Codex can only attach on-disk references. Record any non-local ones
215
+ // (e.g. uploaded URLs) so the caller can surface them even under --json,
216
+ // rather than silently generating plain text-to-image.
217
+ const references = [];
218
+ const ignoredReferences = [];
219
+ for (const candidate of parsed.referenceCandidates) {
220
+ const local = readExplicitLocalFile(candidate);
221
+ if (local)
222
+ references.push(local.path);
223
+ else
224
+ ignoredReferences.push(candidate);
225
+ }
226
+ const requestId = randomBytes(4).toString("hex");
227
+ const workDir = mkdtempSync(join(tmpdir(), "vg-codex-"));
228
+ const filenames = Array.from({ length: parsed.count }, (_, i) => `output-${i}.png`);
229
+ const prompt = buildCodexPrompt(parsed, filenames, references.length > 0);
230
+ const bin = process.env.VG_CODEX_BIN ?? "codex";
231
+ const args = [
232
+ "exec",
233
+ "--skip-git-repo-check",
234
+ "-s",
235
+ "workspace-write",
236
+ "-C",
237
+ workDir,
238
+ ...references.flatMap((r) => ["-i", r]),
239
+ prompt,
240
+ ];
241
+ // Snapshot Codex's default image store so we can tell which files this
242
+ // run produced if the model saves there instead of the workspace.
243
+ const storeDir = join(codexHome(), "generated_images");
244
+ const before = new Set(listImages(storeDir));
245
+ const outcome = await spawnCodex(bin, args, workDir);
246
+ if (outcome.notFound) {
247
+ throw new CodexError(`The \`codex\` CLI was not found on PATH. Install it (npm install -g @openai/codex) ` +
248
+ `and sign in with \`codex login\`, or drop --provider codex to use vibedgames. ` +
249
+ `Set VG_CODEX_BIN to point at a specific binary.`, { notInstalled: true });
250
+ }
251
+ if (outcome.code !== 0) {
252
+ throw new CodexError(`codex exec exited with code ${outcome.code}.`, {
253
+ output: outcome.output,
254
+ });
255
+ }
256
+ // Prefer the exact filenames we pinned in the prompt — those are the
257
+ // images Codex produced for this run. A stray/incidental PNG in the
258
+ // workspace must NOT count as output nor suppress the store fallback.
259
+ const pinned = new Set(filenames);
260
+ const fromWork = listImages(workDir);
261
+ const pinnedWork = fromWork.filter((p) => pinned.has(basename(p)));
262
+ // Fallback for when Codex ignored the workspace and wrote to its shared
263
+ // store instead. That store is not scoped to this invocation, so cap to
264
+ // the newest `count` new files to limit picking up a concurrent run's
265
+ // outputs (best-effort — Codex names store files itself, so there's no
266
+ // requestId to match on).
267
+ const fromStore = pickNewest(listImages(storeDir).filter((p) => !before.has(p)), parsed.count);
268
+ // Pinned workspace files win; then the store; then, as a last resort,
269
+ // any workspace PNG (Codex saved images but chose different names) —
270
+ // capped to `count` like the store branch so an unexpected extra file
271
+ // can't inflate the output set.
272
+ const rawFiles = pinnedWork.length > 0
273
+ ? pinnedWork
274
+ : fromStore.length > 0
275
+ ? fromStore
276
+ : pickNewest(fromWork, parsed.count);
277
+ if (rawFiles.length === 0) {
278
+ throw new CodexError(`codex produced no image files. It may have declined the request or lack ` +
279
+ `image-generation access on the signed-in plan.`, { output: outcome.output });
280
+ }
281
+ return { requestId, prompt, rawFiles, ignoredReferences };
282
+ }
283
+ /**
284
+ * Copy Codex's raw outputs to their final destinations per the
285
+ * `--download` template (or default cwd naming). Returns the written
286
+ * paths and any per-file failures.
287
+ */
288
+ export function placeCodexOutputs(rawFiles, template, requestId) {
289
+ const downloaded = [];
290
+ // Keyed `url` (holding the source path) to match the shape the
291
+ // vibedgames run/status paths use for `download_failures`, so agents
292
+ // reading `download_failures[].url` on the shared --json surface work
293
+ // uniformly across providers.
294
+ const failed = [];
295
+ // Render every target first, then disambiguate colliding paths the same
296
+ // way downloadMedia does — a multi-image run with a template that lacks
297
+ // {index} (e.g. `{request_id}.{ext}` or a fixed filename) would
298
+ // otherwise overwrite earlier outputs while still reporting each path.
299
+ const rendered = rawFiles.map((source, index) => {
300
+ const ext = extname(source).slice(1).toLowerCase() || "png";
301
+ return renderLocalTarget(template, index, ext, requestId, rawFiles.length);
302
+ });
303
+ const targets = disambiguateTargets(rendered);
304
+ rawFiles.forEach((source, index) => {
305
+ const target = targets[index];
306
+ try {
307
+ if (resolve(source) !== target) {
308
+ mkdirSync(dirname(target), { recursive: true });
309
+ copyFileSync(source, target);
310
+ }
311
+ downloaded.push(target);
312
+ }
313
+ catch (err) {
314
+ failed.push({ url: source, error: err instanceof Error ? err.message : String(err) });
315
+ }
316
+ });
317
+ return { downloaded, failed };
318
+ }
319
+ function spawnCodex(bin, args, cwd) {
320
+ return new Promise((resolvePromise) => {
321
+ const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
322
+ let output = "";
323
+ // Forward Codex's own stdout/stderr straight to our stderr so the user
324
+ // sees its progress and messages directly. It goes to stderr (never
325
+ // stdout) so it can't corrupt our `--json` payload. We also buffer it
326
+ // so a failure can surface the tail even for a caller that isn't
327
+ // watching the live stream.
328
+ child.stdout?.on("data", (c) => {
329
+ output += c.toString("utf8");
330
+ process.stderr.write(c);
331
+ });
332
+ child.stderr?.on("data", (c) => {
333
+ output += c.toString("utf8");
334
+ process.stderr.write(c);
335
+ });
336
+ child.on("error", (err) => {
337
+ resolvePromise({
338
+ code: 1,
339
+ output: output + err.message,
340
+ notFound: err.code === "ENOENT",
341
+ });
342
+ });
343
+ child.on("close", (code) => {
344
+ resolvePromise({ code: code ?? 1, output, notFound: false });
345
+ });
346
+ });
347
+ }
@@ -7,7 +7,14 @@ import { basename, extname, isAbsolute, join, resolve } from "node:path";
7
7
  // here: it's a `vg generate status` flag, not a `run` flag, so swallowing it
8
8
  // would block users from passing a legitimate `logs` parameter to a
9
9
  // model endpoint.
10
- const RUN_RESERVED_FLAGS = new Set(["--json", "--help", "--quiet", "--async", "--download"]);
10
+ const RUN_RESERVED_FLAGS = new Set([
11
+ "--json",
12
+ "--help",
13
+ "--quiet",
14
+ "--async",
15
+ "--download",
16
+ "--provider",
17
+ ]);
11
18
  /**
12
19
  * Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
13
20
  * values that look like JSON (true/false/null/numbers/objects/arrays) and
@@ -28,4 +28,5 @@ export declare function downloadMedia(opts: {
28
28
  template?: string;
29
29
  requestId: string;
30
30
  }): Promise<DownloadResult>;
31
+ export declare function disambiguateTargets(paths: string[]): string[];
31
32
  export {};
@@ -154,7 +154,9 @@ function sanitizeFilename(name) {
154
154
  return null;
155
155
  return base;
156
156
  }
157
- function disambiguateTargets(paths) {
157
+ // Exported so the codex provider (lib/codex.ts) reuses identical
158
+ // `_1`/`_2` collision-suffix behavior when placing its local outputs.
159
+ export function disambiguateTargets(paths) {
158
160
  const counts = new Map();
159
161
  for (const p of paths)
160
162
  counts.set(p, (counts.get(p) ?? 0) + 1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vibedgames",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "private": false,
5
5
  "bin": {
6
6
  "vg": "./dist/index.js"
@@ -10,29 +10,29 @@
10
10
  ],
11
11
  "type": "module",
12
12
  "dependencies": {
13
- "@trpc/client": "^11.17.0",
13
+ "@trpc/client": "^11.18.0",
14
14
  "citty": "^0.2.2",
15
15
  "consola": "^3.4.2",
16
16
  "cross-spawn": "^7.0.6",
17
- "ignore": "^7.0.5",
17
+ "ignore": "^7.0.6",
18
18
  "superjson": "^2.2.6",
19
- "tar": "^7.4.3",
19
+ "tar": "^7.5.22",
20
20
  "tiged": "^2.12.8"
21
21
  },
22
22
  "devDependencies": {
23
- "@cloudflare/workers-types": "^4.20260522.1",
24
- "@kyh/tsconfig": "^1.1.14",
25
- "@trpc/server": "^11.17.0",
23
+ "@cloudflare/workers-types": "^5.20260724.1",
24
+ "@kyh/tsconfig": "^1.2.0",
25
+ "@trpc/server": "^11.18.0",
26
26
  "@types/cross-spawn": "^6.0.6",
27
- "@types/node": "^25.9.1",
28
- "typescript": "^6.0.3",
27
+ "@types/node": "^26.1.1",
28
+ "typescript": "^7.0.2",
29
29
  "@repo/api": "^0.1.0"
30
30
  },
31
31
  "scripts": {
32
- "build": "tsc",
32
+ "build": "tsc && chmod +x dist/index.js",
33
33
  "dev": "tsc --watch",
34
34
  "clean": "rm -rf .turbo dist node_modules",
35
- "test:media": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts",
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",
36
36
  "typecheck": "tsc --noEmit"
37
37
  }
38
38
  }