vibedgames 0.6.3 → 0.8.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.
Files changed (140) hide show
  1. package/README.md +14 -9
  2. package/dist/THIRD_PARTY_NOTICES.txt +383 -0
  3. package/dist/chunk-2QBYTIMH.js +511 -0
  4. package/dist/chunk-6FZPPUQH.js +107 -0
  5. package/dist/chunk-AZGENOOR.js +22 -0
  6. package/dist/chunk-CAKBGDCY.js +47 -0
  7. package/dist/chunk-CU7UY5YJ.js +1108 -0
  8. package/dist/chunk-CZPKN32Z.js +257 -0
  9. package/dist/chunk-FL6IFBUF.js +22 -0
  10. package/dist/chunk-FNYBZNW2.js +165 -0
  11. package/dist/chunk-GUF6ADBF.js +273 -0
  12. package/dist/chunk-H4NBRFBY.js +79 -0
  13. package/dist/chunk-HASKWB6B.js +111 -0
  14. package/dist/chunk-I6O4HIDY.js +1063 -0
  15. package/dist/chunk-IO6OM6WM.js +466 -0
  16. package/dist/chunk-J6PKNPI2.js +26 -0
  17. package/dist/chunk-JT2AU24K.js +759 -0
  18. package/dist/chunk-K5SC6SXO.js +172 -0
  19. package/dist/chunk-MBXCVCC4.js +478 -0
  20. package/dist/chunk-PEUP4MZR.js +59 -0
  21. package/dist/chunk-PQDBCZRT.js +2017 -0
  22. package/dist/chunk-RIGKOLNN.js +1360 -0
  23. package/dist/chunk-RNBUX5VF.js +68 -0
  24. package/dist/chunk-RYFO3ZPO.js +71 -0
  25. package/dist/chunk-RZ4DIJQW.js +68 -0
  26. package/dist/chunk-SAANBZ25.js +118 -0
  27. package/dist/chunk-TMK6V5FV.js +395 -0
  28. package/dist/chunk-TYVYWBY6.js +69 -0
  29. package/dist/chunk-VFFOT7KD.js +2980 -0
  30. package/dist/chunk-W5XP4ZVU.js +159 -0
  31. package/dist/chunk-X4ZABSCN.js +415 -0
  32. package/dist/chunk-XDC7QGOF.js +32 -0
  33. package/dist/chunk-XK5RZQMX.js +1780 -0
  34. package/dist/chunk-Y552BNFZ.js +41 -0
  35. package/dist/chunk-Z4Z24FWO.js +39 -0
  36. package/dist/chunk-ZI6PKVXG.js +64 -0
  37. package/dist/chunk-ZYCSYJWX.js +87 -0
  38. package/dist/index.js +67 -60
  39. package/package.json +13 -16
  40. package/templates/none/_gitignore +3 -0
  41. package/templates/none/index.html +29 -0
  42. package/templates/none/package.json +16 -0
  43. package/templates/none/src/main.ts +16 -0
  44. package/templates/none/tsconfig.json +18 -0
  45. package/templates/none/vite.config.ts +8 -0
  46. package/templates/phaser/_gitignore +3 -0
  47. package/templates/phaser/index.html +24 -0
  48. package/templates/phaser/package.json +19 -0
  49. package/templates/phaser/src/main.ts +16 -0
  50. package/templates/phaser/src/scenes/game-scene.ts +65 -0
  51. package/templates/phaser/tsconfig.json +18 -0
  52. package/templates/phaser/vite.config.ts +8 -0
  53. package/templates/react-r3f/_gitignore +3 -0
  54. package/templates/react-r3f/index.html +24 -0
  55. package/templates/react-r3f/package.json +27 -0
  56. package/templates/react-r3f/src/app.tsx +33 -0
  57. package/templates/react-r3f/src/main.tsx +15 -0
  58. package/templates/react-r3f/tsconfig.json +19 -0
  59. package/templates/react-r3f/vite.config.ts +10 -0
  60. package/templates/threejs/_gitignore +3 -0
  61. package/templates/threejs/index.html +36 -0
  62. package/templates/threejs/package.json +20 -0
  63. package/templates/threejs/src/main.ts +44 -0
  64. package/templates/threejs/tsconfig.json +18 -0
  65. package/templates/threejs/vite.config.ts +8 -0
  66. package/dist/commands/completions.d.ts +0 -7
  67. package/dist/commands/completions.js +0 -145
  68. package/dist/commands/credits.d.ts +0 -10
  69. package/dist/commands/credits.js +0 -136
  70. package/dist/commands/deploy.d.ts +0 -26
  71. package/dist/commands/deploy.js +0 -257
  72. package/dist/commands/factory.d.ts +0 -3
  73. package/dist/commands/factory.js +0 -73
  74. package/dist/commands/fork.d.ts +0 -29
  75. package/dist/commands/fork.js +0 -124
  76. package/dist/commands/generate.d.ts +0 -1
  77. package/dist/commands/generate.js +0 -565
  78. package/dist/commands/init.d.ts +0 -20
  79. package/dist/commands/init.js +0 -105
  80. package/dist/commands/login.d.ts +0 -1
  81. package/dist/commands/login.js +0 -45
  82. package/dist/commands/logout.d.ts +0 -1
  83. package/dist/commands/logout.js +0 -13
  84. package/dist/commands/new.d.ts +0 -26
  85. package/dist/commands/new.js +0 -318
  86. package/dist/commands/playtest-run.d.ts +0 -66
  87. package/dist/commands/playtest-run.js +0 -268
  88. package/dist/commands/playtest.d.ts +0 -76
  89. package/dist/commands/playtest.js +0 -372
  90. package/dist/commands/update.d.ts +0 -13
  91. package/dist/commands/update.js +0 -82
  92. package/dist/commands/whoami.d.ts +0 -10
  93. package/dist/commands/whoami.js +0 -44
  94. package/dist/index.d.ts +0 -2
  95. package/dist/lib/api.d.ts +0 -18
  96. package/dist/lib/api.js +0 -27
  97. package/dist/lib/archive.d.ts +0 -17
  98. package/dist/lib/archive.js +0 -228
  99. package/dist/lib/codex.d.ts +0 -117
  100. package/dist/lib/codex.js +0 -426
  101. package/dist/lib/config-file.d.ts +0 -16
  102. package/dist/lib/config-file.js +0 -54
  103. package/dist/lib/config.d.ts +0 -11
  104. package/dist/lib/config.js +0 -54
  105. package/dist/lib/manifest.d.ts +0 -10
  106. package/dist/lib/manifest.js +0 -91
  107. package/dist/lib/media-args.d.ts +0 -30
  108. package/dist/lib/media-args.js +0 -219
  109. package/dist/lib/media-download.d.ts +0 -37
  110. package/dist/lib/media-download.js +0 -268
  111. package/dist/lib/media-poll.d.ts +0 -18
  112. package/dist/lib/media-poll.js +0 -86
  113. package/dist/lib/media-upload.d.ts +0 -12
  114. package/dist/lib/media-upload.js +0 -52
  115. package/dist/lib/output.d.ts +0 -68
  116. package/dist/lib/output.js +0 -102
  117. package/dist/lib/package-manager.d.ts +0 -25
  118. package/dist/lib/package-manager.js +0 -77
  119. package/dist/lib/playtest/agent.d.ts +0 -192
  120. package/dist/lib/playtest/agent.js +0 -652
  121. package/dist/lib/playtest/browser.d.ts +0 -109
  122. package/dist/lib/playtest/browser.js +0 -219
  123. package/dist/lib/playtest/controls.d.ts +0 -47
  124. package/dist/lib/playtest/controls.js +0 -218
  125. package/dist/lib/playtest/errors.d.ts +0 -9
  126. package/dist/lib/playtest/errors.js +0 -12
  127. package/dist/lib/playtest/keys.d.ts +0 -41
  128. package/dist/lib/playtest/keys.js +0 -157
  129. package/dist/lib/playtest/run.d.ts +0 -195
  130. package/dist/lib/playtest/run.js +0 -409
  131. package/dist/lib/run.d.ts +0 -19
  132. package/dist/lib/run.js +0 -23
  133. package/dist/lib/strict-args.d.ts +0 -27
  134. package/dist/lib/strict-args.js +0 -78
  135. package/dist/lib/types.d.ts +0 -16
  136. package/dist/lib/types.js +0 -10
  137. package/dist/lib/update.d.ts +0 -10
  138. package/dist/lib/update.js +0 -110
  139. package/dist/lib/upload.d.ts +0 -16
  140. package/dist/lib/upload.js +0 -41
@@ -0,0 +1,1360 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ require_cross_spawn
9
+ } from "./chunk-2QBYTIMH.js";
10
+ import {
11
+ resolveSetting
12
+ } from "./chunk-6FZPPUQH.js";
13
+ import {
14
+ createClient,
15
+ forwardJson
16
+ } from "./chunk-PQDBCZRT.js";
17
+ import "./chunk-Z4Z24FWO.js";
18
+ import "./chunk-PEUP4MZR.js";
19
+ import {
20
+ isJsonOutput,
21
+ outputArgs,
22
+ writeJson,
23
+ writeStructured
24
+ } from "./chunk-ZYCSYJWX.js";
25
+ import "./chunk-RYFO3ZPO.js";
26
+ import {
27
+ isJsonNumber,
28
+ isJsonObject,
29
+ isJsonString
30
+ } from "./chunk-J6PKNPI2.js";
31
+ import {
32
+ consola
33
+ } from "./chunk-CU7UY5YJ.js";
34
+ import {
35
+ defineCommand
36
+ } from "./chunk-MBXCVCC4.js";
37
+ import {
38
+ __toESM
39
+ } from "./chunk-CAKBGDCY.js";
40
+
41
+ // src/commands/generate.ts
42
+ import { setTimeout as sleep2 } from "node:timers/promises";
43
+
44
+ // src/lib/codex.ts
45
+ var import_cross_spawn = __toESM(require_cross_spawn(), 1);
46
+ import { randomBytes } from "node:crypto";
47
+ import { copyFileSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, statSync as statSync2 } from "node:fs";
48
+ import { homedir as homedir2, tmpdir } from "node:os";
49
+ import path3 from "node:path";
50
+
51
+ // src/lib/media-args.ts
52
+ import { statSync } from "node:fs";
53
+ import { homedir } from "node:os";
54
+ import path from "node:path";
55
+ var RUN_RESERVED_FLAGS = /* @__PURE__ */ new Set([
56
+ "--json",
57
+ "--help",
58
+ "--quiet",
59
+ "--async",
60
+ "--download",
61
+ "--provider"
62
+ ]);
63
+ var assign = (out, key, value) => {
64
+ const existing = out[key];
65
+ if (existing !== void 0) {
66
+ if (Array.isArray(existing)) {
67
+ existing.push(value);
68
+ } else {
69
+ out[key] = [existing, value];
70
+ }
71
+ return;
72
+ }
73
+ out[key] = value;
74
+ };
75
+ var parseValue = (raw) => {
76
+ if (raw === "true") {
77
+ return true;
78
+ }
79
+ if (raw === "false") {
80
+ return false;
81
+ }
82
+ if (raw === "null") {
83
+ return null;
84
+ }
85
+ if (raw.length > 0 && (raw[0] === "{" || raw[0] === "[")) {
86
+ try {
87
+ return JSON.parse(raw);
88
+ } catch {
89
+ return raw;
90
+ }
91
+ }
92
+ if (/^-?\d+(?:\.\d+)?$/u.test(raw)) {
93
+ const n = Number(raw);
94
+ if (Number.isFinite(n)) {
95
+ return n;
96
+ }
97
+ }
98
+ return raw;
99
+ };
100
+ var parseRunInput = (argv) => {
101
+ const out = {};
102
+ for (let i = 0; i < argv.length; i += 1) {
103
+ const arg = argv[i];
104
+ if (!arg || !arg.startsWith("--")) {
105
+ continue;
106
+ }
107
+ if (arg === "--") {
108
+ break;
109
+ }
110
+ const eqIdx = arg.indexOf("=");
111
+ const name = eqIdx === -1 ? arg : arg.slice(0, eqIdx);
112
+ const inlineValue = eqIdx === -1 ? void 0 : arg.slice(eqIdx + 1);
113
+ if (RUN_RESERVED_FLAGS.has(name)) {
114
+ if (name === "--download" && inlineValue === void 0) {
115
+ const next2 = argv[i + 1];
116
+ if (next2 && !next2.startsWith("--")) {
117
+ i += 1;
118
+ }
119
+ }
120
+ continue;
121
+ }
122
+ const key = name.slice(2);
123
+ if (inlineValue !== void 0) {
124
+ assign(out, key, parseValue(inlineValue));
125
+ continue;
126
+ }
127
+ const next = argv[i + 1];
128
+ if (next === void 0 || next.startsWith("--")) {
129
+ assign(out, key, true);
130
+ continue;
131
+ }
132
+ assign(out, key, parseValue(next));
133
+ i += 1;
134
+ }
135
+ return out;
136
+ };
137
+ var expandHome = (value) => {
138
+ if (value === "~") {
139
+ return homedir();
140
+ }
141
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
142
+ return path.join(homedir(), value.slice(2));
143
+ }
144
+ return value;
145
+ };
146
+ var contentTypeForPath = (file) => {
147
+ const ext = path.extname(file).slice(1).toLowerCase();
148
+ const map = new Map(
149
+ Object.entries({
150
+ avif: "image/avif",
151
+ bmp: "image/bmp",
152
+ flac: "audio/flac",
153
+ gif: "image/gif",
154
+ jpeg: "image/jpeg",
155
+ jpg: "image/jpeg",
156
+ json: "application/json",
157
+ m4a: "audio/mp4",
158
+ mov: "video/quicktime",
159
+ mp3: "audio/mpeg",
160
+ mp4: "video/mp4",
161
+ ogg: "audio/ogg",
162
+ png: "image/png",
163
+ tif: "image/tiff",
164
+ tiff: "image/tiff",
165
+ txt: "text/plain",
166
+ wav: "audio/wav",
167
+ webm: "video/webm",
168
+ webp: "image/webp"
169
+ })
170
+ );
171
+ return map.get(ext) ?? "application/octet-stream";
172
+ };
173
+ var readExplicitLocalFile = (value) => {
174
+ if (value.startsWith("http://") || value.startsWith("https://")) {
175
+ return null;
176
+ }
177
+ if (value.startsWith("data:")) {
178
+ return null;
179
+ }
180
+ if (value.length === 0) {
181
+ return null;
182
+ }
183
+ const expanded = expandHome(value);
184
+ const abs = path.isAbsolute(expanded) ? expanded : path.resolve(expanded);
185
+ let stat;
186
+ try {
187
+ stat = statSync(abs);
188
+ } catch {
189
+ return null;
190
+ }
191
+ if (!stat.isFile()) {
192
+ return null;
193
+ }
194
+ return {
195
+ contentType: contentTypeForPath(abs),
196
+ filename: path.basename(abs),
197
+ path: abs
198
+ };
199
+ };
200
+ var parseDownloadFlag = (argv) => {
201
+ let lastIdx = -1;
202
+ let inlineValue;
203
+ for (let i = 0; i < argv.length; i += 1) {
204
+ const arg = argv[i];
205
+ if (!arg) {
206
+ continue;
207
+ }
208
+ if (arg === "--") {
209
+ break;
210
+ }
211
+ if (arg === "--download") {
212
+ lastIdx = i;
213
+ inlineValue = void 0;
214
+ } else if (arg.startsWith("--download=")) {
215
+ lastIdx = i;
216
+ inlineValue = arg.slice("--download=".length);
217
+ }
218
+ }
219
+ if (lastIdx === -1) {
220
+ return { mode: "off" };
221
+ }
222
+ const candidate = inlineValue ?? argv[lastIdx + 1];
223
+ if (candidate === "false") {
224
+ return { mode: "off" };
225
+ }
226
+ if (candidate === void 0 || candidate === "" || candidate.startsWith("--") || candidate === "true") {
227
+ return { mode: "on" };
228
+ }
229
+ return { mode: "on", template: candidate };
230
+ };
231
+
232
+ // src/lib/media-download.ts
233
+ import { mkdirSync, writeFileSync } from "node:fs";
234
+ import path2 from "node:path";
235
+ var MEDIA_EXT = /* @__PURE__ */ new Set([
236
+ "png",
237
+ "jpg",
238
+ "jpeg",
239
+ "webp",
240
+ "gif",
241
+ "bmp",
242
+ "tif",
243
+ "tiff",
244
+ "avif",
245
+ "mp4",
246
+ "mov",
247
+ "webm",
248
+ "mp3",
249
+ "wav",
250
+ "ogg",
251
+ "flac",
252
+ "m4a"
253
+ ]);
254
+ var TRUSTED_HOST_SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
255
+ var TRUSTED_HOSTS = /* @__PURE__ */ new Set(["fal.media", "fal.run", "fal.ai"]);
256
+ var isTrustedFalContentHost = (url) => {
257
+ let parsed;
258
+ try {
259
+ parsed = new URL(url);
260
+ } catch {
261
+ return false;
262
+ }
263
+ if (parsed.protocol !== "https:") {
264
+ return false;
265
+ }
266
+ const host = parsed.hostname.toLowerCase();
267
+ if (TRUSTED_HOSTS.has(host)) {
268
+ return true;
269
+ }
270
+ return TRUSTED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));
271
+ };
272
+ var extFromUrl = (url) => {
273
+ try {
274
+ const { pathname } = new URL(url);
275
+ const dot = pathname.lastIndexOf(".");
276
+ return dot === -1 ? "" : pathname.slice(dot + 1).toLowerCase();
277
+ } catch {
278
+ return "";
279
+ }
280
+ };
281
+ var sanitizeFilename = (name) => {
282
+ const base = name.replaceAll(/[\\/]+/gu, "/").split("/").pop() ?? "";
283
+ if (!base || base === "." || base === "..") {
284
+ return null;
285
+ }
286
+ return base;
287
+ };
288
+ var visit = (value, refs, seen) => {
289
+ if (Array.isArray(value)) {
290
+ for (const v of value) {
291
+ visit(v, refs, seen);
292
+ }
293
+ return;
294
+ }
295
+ if (!isJsonObject(value)) {
296
+ return;
297
+ }
298
+ const { url } = value;
299
+ if (isJsonString(url) && isTrustedFalContentHost(url) && !seen.has(url)) {
300
+ const contentType = isJsonString(value.content_type) ? value.content_type.toLowerCase() : null;
301
+ const filenameField = isJsonString(value.file_name) ? sanitizeFilename(value.file_name) : null;
302
+ const ext = filenameField ? path2.extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
303
+ const looksMedia = contentType === null ? MEDIA_EXT.has(ext) : /^(?:image|video|audio)\//u.test(contentType);
304
+ if (looksMedia) {
305
+ seen.add(url);
306
+ refs.push({
307
+ contentType,
308
+ filename: filenameField ?? `output${ext ? `.${ext}` : ""}`,
309
+ url
310
+ });
311
+ }
312
+ }
313
+ for (const child of Object.values(value)) {
314
+ visit(child, refs, seen);
315
+ }
316
+ };
317
+ var extractMediaRefs = (result) => {
318
+ const seen = /* @__PURE__ */ new Set();
319
+ const refs = [];
320
+ visit(result, refs, seen);
321
+ return refs;
322
+ };
323
+ var EXT_FOR_CONTENT_TYPE = new Map(
324
+ Object.entries({
325
+ "audio/mpeg": "mp3",
326
+ "audio/ogg": "ogg",
327
+ "audio/wav": "wav",
328
+ "image/avif": "avif",
329
+ "image/gif": "gif",
330
+ "image/jpeg": "jpg",
331
+ "image/png": "png",
332
+ "image/webp": "webp",
333
+ "video/mp4": "mp4",
334
+ "video/quicktime": "mov",
335
+ "video/webm": "webm"
336
+ })
337
+ );
338
+ var EXT_ALIASES = new Map(
339
+ Object.entries({
340
+ htm: "html",
341
+ jpeg: "jpg",
342
+ tif: "tiff"
343
+ })
344
+ );
345
+ var canonicalExt = (ext) => EXT_ALIASES.get(ext) ?? ext;
346
+ var mislabelOf = (target, ref) => {
347
+ const asked = canonicalExt(path2.extname(target).slice(1).toLowerCase());
348
+ if (!asked) {
349
+ return null;
350
+ }
351
+ const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : void 0;
352
+ if (!actual || canonicalExt(actual) === asked) {
353
+ return null;
354
+ }
355
+ return { actual, path: target };
356
+ };
357
+ var disambiguateTargets = (paths) => {
358
+ const counts = /* @__PURE__ */ new Map();
359
+ for (const p of paths) {
360
+ counts.set(p, (counts.get(p) ?? 0) + 1);
361
+ }
362
+ const seen = /* @__PURE__ */ new Map();
363
+ return paths.map((p) => {
364
+ if ((counts.get(p) ?? 0) <= 1) {
365
+ return p;
366
+ }
367
+ const n = seen.get(p) ?? 0;
368
+ seen.set(p, n + 1);
369
+ if (n === 0) {
370
+ return p;
371
+ }
372
+ const ext = path2.extname(p);
373
+ return `${p.slice(0, p.length - ext.length)}_${n}${ext}`;
374
+ });
375
+ };
376
+ var renderTemplate = (ref, template, index, requestId) => {
377
+ const ext = (() => {
378
+ const fromName = path2.extname(ref.filename).slice(1);
379
+ if (fromName) {
380
+ return fromName;
381
+ }
382
+ return extFromUrl(ref.url) || "bin";
383
+ })();
384
+ const lowerName = ref.filename.toLowerCase();
385
+ const dotExt = `.${ext.toLowerCase()}`;
386
+ const stem = lowerName.endsWith(dotExt) ? ref.filename.slice(0, -dotExt.length) || "output" : ref.filename || "output";
387
+ if (!template || !template.includes("{")) {
388
+ if (template && path2.extname(template)) {
389
+ return path2.resolve(template);
390
+ }
391
+ const dir = template ?? process.cwd();
392
+ return path2.resolve(dir, ref.filename || `output-${index}.${ext}`);
393
+ }
394
+ const rendered = template.replaceAll("{index}", String(index)).replaceAll("{name}", stem).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId);
395
+ return path2.resolve(rendered);
396
+ };
397
+ var downloadMedia = async (opts) => {
398
+ const initial = opts.refs.map((ref, i) => renderTemplate(ref, opts.template, i, opts.requestId));
399
+ const targets = disambiguateTargets(initial);
400
+ const dirs = new Set(targets.map((t) => path2.dirname(t)));
401
+ for (const d of dirs) {
402
+ mkdirSync(d, { recursive: true });
403
+ }
404
+ const outcomes = await Promise.all(
405
+ opts.refs.map(async (ref, i) => {
406
+ const target = targets[i];
407
+ if (target === void 0) {
408
+ return { error: "no download target", ok: false, url: ref.url };
409
+ }
410
+ try {
411
+ const res = await fetch(ref.url);
412
+ if (!res.ok) {
413
+ return { error: `${res.status} ${res.statusText}`, ok: false, url: ref.url };
414
+ }
415
+ const bytes = new Uint8Array(await res.arrayBuffer());
416
+ writeFileSync(target, bytes);
417
+ return { mislabel: mislabelOf(target, ref), ok: true, target };
418
+ } catch (error) {
419
+ return {
420
+ error: error instanceof Error ? error.message : String(error),
421
+ ok: false,
422
+ url: ref.url
423
+ };
424
+ }
425
+ })
426
+ );
427
+ const downloaded = [];
428
+ const failed = [];
429
+ const mislabeled = [];
430
+ for (const o of outcomes) {
431
+ if (!o.ok) {
432
+ failed.push({ error: o.error, url: o.url });
433
+ continue;
434
+ }
435
+ downloaded.push(o.target);
436
+ if (o.mislabel) {
437
+ mislabeled.push(o.mislabel);
438
+ }
439
+ }
440
+ return { downloaded, failed, mislabeled };
441
+ };
442
+
443
+ // src/lib/codex.ts
444
+ var CodexError = class extends Error {
445
+ notInstalled;
446
+ output;
447
+ constructor(message, opts = {}) {
448
+ super(message);
449
+ this.name = "CodexError";
450
+ this.notInstalled = opts.notInstalled ?? false;
451
+ this.output = opts.output ?? "";
452
+ }
453
+ };
454
+ var parseProvider = (raw, from = "--provider") => {
455
+ const name = raw.trim().toLowerCase();
456
+ if (name === "codex") {
457
+ return "codex";
458
+ }
459
+ if (name === "vibedgames") {
460
+ return "vibedgames";
461
+ }
462
+ throw new Error(`Unknown provider "${name}" (${from}). Supported: vibedgames, codex.`);
463
+ };
464
+ var CODEX_ENDPOINT = "codex";
465
+ var isOpenAiImageEndpoint = (endpointId) => /^openai\/gpt-image/iu.test(endpointId);
466
+ var isLocalReference = (ref) => !/^(?:https?:|data:)/iu.test(ref);
467
+ var chooseProvider = (flag, run) => {
468
+ if (flag !== void 0 && flag.trim() !== "") {
469
+ return { provider: parseProvider(flag) };
470
+ }
471
+ if (run.endpointId === CODEX_ENDPOINT) {
472
+ return { provider: "codex" };
473
+ }
474
+ const preference = resolveSetting("generate.provider");
475
+ const from = preference.source === "env" ? "VG_GENERATE_PROVIDER" : "generate.provider";
476
+ if (parseProvider(preference.value, from) !== "codex" || !isOpenAiImageEndpoint(run.endpointId)) {
477
+ return { provider: "vibedgames" };
478
+ }
479
+ if (run.async) {
480
+ return {
481
+ note: `${from} is codex, but codex can't run --async, so this run uses vibedgames.`,
482
+ provider: "vibedgames"
483
+ };
484
+ }
485
+ if (!parseCodexInput(run.input).referenceCandidates.every((ref) => isLocalReference(ref))) {
486
+ return {
487
+ note: `${from} is codex, but codex only attaches local reference files, so this run uses vibedgames.`,
488
+ provider: "vibedgames"
489
+ };
490
+ }
491
+ return { provider: "codex" };
492
+ };
493
+ var PROMPT_KEYS = ["prompt", "text"];
494
+ var COUNT_KEYS = ["num_images", "num_outputs", "n", "count"];
495
+ var REF_KEYS = [
496
+ "image_url",
497
+ "image_urls",
498
+ "image",
499
+ "images",
500
+ "input_image",
501
+ "reference_image_url",
502
+ "reference_image_urls"
503
+ ];
504
+ var MAX_IMAGES = 8;
505
+ var IMAGE_EXT = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "webp", "gif"]);
506
+ var buildSizeHint = (input) => {
507
+ const parts = [];
508
+ const size = input.image_size ?? input.size;
509
+ if (isJsonString(size) && size.trim().length > 0) {
510
+ parts.push(size.trim());
511
+ }
512
+ const aspect = input.aspect_ratio;
513
+ if (isJsonString(aspect) && aspect.trim().length > 0) {
514
+ parts.push(`aspect ratio ${aspect.trim()}`);
515
+ }
516
+ const w = input.width;
517
+ const h = input.height;
518
+ if (isJsonNumber(w) && isJsonNumber(h)) {
519
+ parts.push(`${w}x${h}px`);
520
+ }
521
+ return parts.length > 0 ? parts.join(", ") : void 0;
522
+ };
523
+ var parseCodexInput = (input) => {
524
+ let prompt = "";
525
+ for (const key of PROMPT_KEYS) {
526
+ const v = input[key];
527
+ if (isJsonString(v) && v.trim().length > 0) {
528
+ prompt = v.trim();
529
+ break;
530
+ }
531
+ }
532
+ let count = 1;
533
+ for (const key of COUNT_KEYS) {
534
+ const v = input[key];
535
+ if (isJsonNumber(v)) {
536
+ count = Math.max(1, Math.min(MAX_IMAGES, Math.floor(v)));
537
+ break;
538
+ }
539
+ }
540
+ const referenceCandidates = [];
541
+ for (const key of REF_KEYS) {
542
+ const v = input[key];
543
+ if (isJsonString(v)) {
544
+ referenceCandidates.push(v);
545
+ } else if (Array.isArray(v)) {
546
+ for (const item of v) {
547
+ if (isJsonString(item)) {
548
+ referenceCandidates.push(item);
549
+ }
550
+ }
551
+ }
552
+ }
553
+ return { count, prompt, referenceCandidates, sizeHint: buildSizeHint(input) };
554
+ };
555
+ var buildCodexPrompt = (input, filenames, hasReferences) => {
556
+ const n = filenames.length;
557
+ const noun = n === 1 ? "image" : `${n} images`;
558
+ const lines = [
559
+ hasReferences ? `Edit the attached reference image to produce ${noun} using your built-in image generation.` : `Generate ${noun} using your built-in image generation.`,
560
+ `Prompt: ${input.prompt}`
561
+ ];
562
+ if (input.sizeHint) {
563
+ lines.push(
564
+ `Size: aim for ${input.sizeHint}. Use the closest size the generator offers and save that as-is \u2014 never resize, crop or ask about it.`
565
+ );
566
+ }
567
+ lines.push(
568
+ `Save the output as PNG into the current working directory using exactly these filenames: ${filenames.join(", ")}.`,
569
+ `Do not read, create, or modify any other files, and do not write or run code. $imagegen`
570
+ );
571
+ return lines.join("\n");
572
+ };
573
+ var renderLocalTarget = (template, index, ext, requestId, count) => {
574
+ if (!template) {
575
+ return path3.resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
576
+ }
577
+ if (template.includes("{")) {
578
+ const rendered = template.replaceAll("{index}", String(index)).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId).replaceAll("{name}", "output");
579
+ return path3.resolve(rendered);
580
+ }
581
+ if (path3.extname(template)) {
582
+ if (count <= 1) {
583
+ return path3.resolve(template);
584
+ }
585
+ const e = path3.extname(template);
586
+ const stem = template.slice(0, template.length - e.length);
587
+ return path3.resolve(index === 0 ? template : `${stem}_${index}${e}`);
588
+ }
589
+ return path3.resolve(template, `codex-image-${index}.${ext}`);
590
+ };
591
+ var codexHome = () => process.env.CODEX_HOME ?? path3.join(homedir2(), ".codex");
592
+ var listImages = (dir, depth = 1) => {
593
+ let entries;
594
+ try {
595
+ entries = readdirSync(dir, { withFileTypes: true });
596
+ } catch {
597
+ return [];
598
+ }
599
+ const out = [];
600
+ for (const entry of entries) {
601
+ const full = path3.join(dir, entry.name);
602
+ if (entry.isDirectory()) {
603
+ if (depth > 0) {
604
+ out.push(...listImages(full, depth - 1));
605
+ }
606
+ } else if (entry.isFile() && IMAGE_EXT.has(path3.extname(entry.name).slice(1).toLowerCase())) {
607
+ out.push(full);
608
+ }
609
+ }
610
+ return out.toSorted();
611
+ };
612
+ var pickNewest = (paths, limit) => {
613
+ if (paths.length <= limit) {
614
+ return paths;
615
+ }
616
+ const withTime = paths.map((p) => {
617
+ let mtimeMs = 0;
618
+ try {
619
+ ({ mtimeMs } = statSync2(p));
620
+ } catch {
621
+ }
622
+ return { mtimeMs, p };
623
+ });
624
+ return withTime.toSorted((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit).map((x) => x.p).toSorted();
625
+ };
626
+ var spawnCodex = (bin, args, cwd) => (
627
+ // oxlint-disable-next-line promise/avoid-new -- child_process.spawn is event-based
628
+ new Promise((resolve) => {
629
+ const child = (0, import_cross_spawn.default)(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
630
+ let output = "";
631
+ child.stdout?.on("data", (c) => {
632
+ output += c.toString("utf-8");
633
+ process.stderr.write(c);
634
+ });
635
+ child.stderr?.on("data", (c) => {
636
+ output += c.toString("utf-8");
637
+ process.stderr.write(c);
638
+ });
639
+ child.on("error", (err) => {
640
+ resolve({
641
+ code: 1,
642
+ notFound: err.code === "ENOENT",
643
+ output: output + err.message
644
+ });
645
+ });
646
+ child.on("close", (code) => {
647
+ resolve({ code: code ?? 1, notFound: false, output });
648
+ });
649
+ })
650
+ );
651
+ var codexExecArgs = (workDir, references, prompt) => [
652
+ "exec",
653
+ "--skip-git-repo-check",
654
+ "-s",
655
+ "workspace-write",
656
+ "-C",
657
+ workDir,
658
+ ...references.flatMap((r) => ["-i", r]),
659
+ // `-i` is variadic (`--image <FILE>...`): without the separator it
660
+ // swallows the prompt as one more image and codex waits on stdin for one.
661
+ "--",
662
+ prompt
663
+ ];
664
+ var generateImagesWithCodex = async (opts) => {
665
+ const parsed = parseCodexInput(opts.input);
666
+ if (!parsed.prompt) {
667
+ throw new CodexError("codex image generation requires a prompt (--prompt).");
668
+ }
669
+ const references = [];
670
+ const ignoredReferences = [];
671
+ for (const candidate of parsed.referenceCandidates) {
672
+ const local = readExplicitLocalFile(candidate);
673
+ if (local) {
674
+ references.push(local.path);
675
+ } else {
676
+ ignoredReferences.push(candidate);
677
+ }
678
+ }
679
+ const requestId = randomBytes(4).toString("hex");
680
+ const workDir = mkdtempSync(path3.join(tmpdir(), "vg-codex-"));
681
+ const filenames = Array.from({ length: parsed.count }, (_, i) => `output-${i}.png`);
682
+ const prompt = buildCodexPrompt(parsed, filenames, references.length > 0);
683
+ const bin = resolveSetting("generate.codex-bin").value;
684
+ const args = codexExecArgs(workDir, references, prompt);
685
+ const storeDir = path3.join(codexHome(), "generated_images");
686
+ const before = new Set(listImages(storeDir));
687
+ const outcome = await spawnCodex(bin, args, workDir);
688
+ if (outcome.notFound) {
689
+ throw new CodexError(
690
+ `The \`codex\` CLI was not found. Install it (npm install -g @openai/codex) and sign in with \`codex login\`, point vg at it with \`vg config set generate.codex-bin <path>\`, or run on vibedgames with --provider vibedgames.`,
691
+ { notInstalled: true }
692
+ );
693
+ }
694
+ if (outcome.code !== 0) {
695
+ throw new CodexError(`codex exec exited with code ${outcome.code}.`, {
696
+ output: outcome.output
697
+ });
698
+ }
699
+ const pinned = new Set(filenames);
700
+ const fromWork = listImages(workDir);
701
+ const pinnedWork = fromWork.filter((p) => pinned.has(path3.basename(p)));
702
+ const fromStore = pickNewest(
703
+ listImages(storeDir).filter((p) => !before.has(p)),
704
+ parsed.count
705
+ );
706
+ let rawFiles = pickNewest(fromWork, parsed.count);
707
+ if (pinnedWork.length > 0) {
708
+ rawFiles = pinnedWork;
709
+ } else if (fromStore.length > 0) {
710
+ rawFiles = fromStore;
711
+ }
712
+ if (rawFiles.length === 0) {
713
+ throw new CodexError(
714
+ `codex produced no image files. It may have declined the request or lack image-generation access on the signed-in plan.`,
715
+ { output: outcome.output }
716
+ );
717
+ }
718
+ return { ignoredReferences, prompt, rawFiles, requestId };
719
+ };
720
+ var placeCodexOutputs = (rawFiles, template, requestId) => {
721
+ const downloaded = [];
722
+ const failed = [];
723
+ const rendered = rawFiles.map((source, index) => {
724
+ const ext = path3.extname(source).slice(1).toLowerCase() || "png";
725
+ return renderLocalTarget(template, index, ext, requestId, rawFiles.length);
726
+ });
727
+ const targets = disambiguateTargets(rendered);
728
+ for (const [index, source] of rawFiles.entries()) {
729
+ const target = targets[index];
730
+ if (target === void 0) {
731
+ continue;
732
+ }
733
+ try {
734
+ if (path3.resolve(source) !== target) {
735
+ mkdirSync2(path3.dirname(target), { recursive: true });
736
+ copyFileSync(source, target);
737
+ }
738
+ downloaded.push(target);
739
+ } catch (error) {
740
+ failed.push({ error: error instanceof Error ? error.message : String(error), url: source });
741
+ }
742
+ }
743
+ return { downloaded, failed };
744
+ };
745
+
746
+ // src/lib/media-poll.ts
747
+ import { setTimeout as sleep } from "node:timers/promises";
748
+ var endpointPath = (endpointId) => endpointId.replaceAll(/^\/+|\/+$/gu, "");
749
+ var QUEUE_APP_NAMESPACES = /* @__PURE__ */ new Set(["workflows", "comfy"]);
750
+ var queueAppId = (endpointId) => {
751
+ const parts = endpointPath(endpointId).split("/").filter(Boolean);
752
+ const take = QUEUE_APP_NAMESPACES.has(parts[0] ?? "") ? 3 : 2;
753
+ return parts.slice(0, take).join("/");
754
+ };
755
+ var POLL_INTERVAL_MS = 2e3;
756
+ var POLL_TIMEOUT_MS = 30 * 60 * 1e3;
757
+ var pickErrorReason = (value) => {
758
+ if (!isJsonObject(value)) {
759
+ return null;
760
+ }
761
+ if (isJsonString(value.error) && value.error.length > 0) {
762
+ return value.error;
763
+ }
764
+ if (isJsonString(value.detail) && value.detail.length > 0) {
765
+ return value.detail;
766
+ }
767
+ if (isJsonObject(value.error) && isJsonString(value.error.message)) {
768
+ return value.error.message;
769
+ }
770
+ if (isJsonObject(value.response)) {
771
+ return pickErrorReason(value.response);
772
+ }
773
+ return null;
774
+ };
775
+ var waitForCompletion = async (client, endpoint_id, request_id, opts) => {
776
+ const ep = queueAppId(endpoint_id);
777
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
778
+ let lastStatus;
779
+ while (true) {
780
+ if (Date.now() > deadline) {
781
+ throw new Error(
782
+ `Job did not complete within ${POLL_TIMEOUT_MS}ms (endpoint=${endpoint_id} request_id=${request_id}). Use \`vg generate status ${endpoint_id} ${request_id} --result\` to check later.`
783
+ );
784
+ }
785
+ const raw = await forwardJson(client, {
786
+ method: "GET",
787
+ path: `/${ep}/requests/${request_id}/status`,
788
+ target: "queue"
789
+ });
790
+ const status = isJsonObject(raw) && isJsonString(raw.status) ? raw.status : "UNKNOWN";
791
+ const upper = status.toUpperCase();
792
+ if (!opts.quiet && upper !== lastStatus) {
793
+ lastStatus = upper;
794
+ const queuePos = isJsonObject(raw) && isJsonNumber(raw.queue_position) ? raw.queue_position : null;
795
+ const tag = queuePos === null ? upper.toLowerCase() : `${upper.toLowerCase()} (queue ${queuePos})`;
796
+ consola.log(` ${tag}`);
797
+ }
798
+ if (upper === "COMPLETED") {
799
+ break;
800
+ }
801
+ if (upper === "FAILED" || upper === "CANCELLED") {
802
+ const reason = pickErrorReason(raw);
803
+ throw new Error(
804
+ reason ? `Job ${upper.toLowerCase()}: ${reason}` : `Job ${upper.toLowerCase()}`
805
+ );
806
+ }
807
+ await sleep(POLL_INTERVAL_MS);
808
+ }
809
+ const result = await forwardJson(client, {
810
+ method: "GET",
811
+ path: `/${ep}/requests/${request_id}`,
812
+ target: "queue"
813
+ });
814
+ return { request_id, result };
815
+ };
816
+
817
+ // src/lib/media-upload.ts
818
+ import { openAsBlob } from "node:fs";
819
+ var pickUrl = (slot, key) => {
820
+ const value = isJsonObject(slot) ? slot[key] : void 0;
821
+ if (!isJsonString(value) || value.length === 0) {
822
+ throw new Error(`fal storage initiate response missing ${key}.`);
823
+ }
824
+ let parsed;
825
+ try {
826
+ parsed = new URL(value);
827
+ } catch {
828
+ throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
829
+ }
830
+ if (parsed.protocol !== "https:") {
831
+ throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
832
+ }
833
+ return value;
834
+ };
835
+ var uploadFile = async (client, file) => {
836
+ const slot = await forwardJson(client, {
837
+ body: { content_type: file.contentType, file_name: file.filename },
838
+ method: "POST",
839
+ path: "/storage/upload/initiate",
840
+ target: "storage"
841
+ });
842
+ const uploadUrl = pickUrl(slot, "upload_url");
843
+ const fileUrl = pickUrl(slot, "file_url");
844
+ const body = await openAsBlob(file.path, { type: file.contentType });
845
+ const res = await fetch(uploadUrl, {
846
+ body,
847
+ headers: { "Content-Type": file.contentType },
848
+ method: "PUT"
849
+ });
850
+ if (!res.ok) {
851
+ const text = await res.text().catch(() => "");
852
+ throw new Error(`Upload failed for ${file.filename}: ${res.status} ${res.statusText} ${text}`);
853
+ }
854
+ return fileUrl;
855
+ };
856
+
857
+ // src/commands/generate.ts
858
+ var buildActionFields = (action, data) => {
859
+ if (action === "result") {
860
+ return { result: data };
861
+ }
862
+ if (action === "status" && isJsonObject(data)) {
863
+ const fields = {};
864
+ if (isJsonString(data.status)) {
865
+ fields.status = data.status;
866
+ }
867
+ if (isJsonNumber(data.queue_position)) {
868
+ fields.queue_position = data.queue_position;
869
+ }
870
+ if (data.logs !== void 0) {
871
+ fields.logs = data.logs;
872
+ }
873
+ return fields;
874
+ }
875
+ return {};
876
+ };
877
+ var isStructuredOutput = (args) => isJsonOutput(args) || Boolean(args.field);
878
+ var extractMediaUrls = (result) => extractMediaRefs(result).map((r) => r.url);
879
+ var warnMislabeled = (mislabeled) => {
880
+ for (const m of mislabeled) {
881
+ consola.warn(` ${m.path} holds ${m.actual.toUpperCase()} data, not what its extension says`);
882
+ }
883
+ };
884
+ var runViaCodex = async (opts) => {
885
+ const { args, finalInput, downloadFlag, endpoint_id } = opts;
886
+ if (args.async) {
887
+ consola.error("--async is not supported with --provider codex (Codex runs synchronously).");
888
+ process.exit(1);
889
+ }
890
+ let result;
891
+ try {
892
+ result = await generateImagesWithCodex({ input: finalInput });
893
+ } catch (error) {
894
+ if (error instanceof CodexError) {
895
+ consola.error(error.message);
896
+ process.exit(1);
897
+ }
898
+ throw error;
899
+ }
900
+ const { requestId, rawFiles, prompt, ignoredReferences } = result;
901
+ for (const ref of ignoredReferences) {
902
+ consola.warn(`Ignored non-local reference (codex needs a local file path): ${ref}`);
903
+ }
904
+ const template = downloadFlag.mode === "on" ? downloadFlag.template : void 0;
905
+ const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId);
906
+ const payload = {
907
+ downloaded_files: downloaded,
908
+ endpoint_id,
909
+ provider: "codex",
910
+ request_id: requestId,
911
+ result: { images: downloaded.map((path4) => ({ path: path4 })), prompt, provider: "codex" },
912
+ status: "completed"
913
+ };
914
+ if (failed.length > 0) {
915
+ payload.download_failures = failed;
916
+ }
917
+ if (ignoredReferences.length > 0) {
918
+ payload.ignored_references = ignoredReferences;
919
+ }
920
+ if (!writeStructured(payload, args)) {
921
+ consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
922
+ for (const path4 of downloaded) {
923
+ consola.log(` ${path4}`);
924
+ }
925
+ for (const f of failed) {
926
+ consola.warn(` failed: ${f.url} (${f.error})`);
927
+ }
928
+ }
929
+ if (failed.length > 0 && downloaded.length === 0) {
930
+ process.exit(1);
931
+ }
932
+ };
933
+ var buildRunPayload = (endpointId, completed, downloaded) => {
934
+ const payload = {
935
+ endpoint_id: endpointId,
936
+ request_id: completed.request_id,
937
+ result: completed.result,
938
+ status: "completed"
939
+ };
940
+ if (!downloaded) {
941
+ return payload;
942
+ }
943
+ payload.downloaded_files = downloaded.downloaded;
944
+ if (downloaded.failed.length > 0) {
945
+ payload.download_failures = downloaded.failed;
946
+ }
947
+ if (downloaded.mislabeled.length > 0) {
948
+ payload.download_format_mismatches = downloaded.mislabeled;
949
+ }
950
+ return payload;
951
+ };
952
+ var reportRun = (completed, downloaded) => {
953
+ consola.success(`Run completed (${completed.request_id})`);
954
+ if (downloaded) {
955
+ for (const file of downloaded.downloaded) {
956
+ consola.log(` ${file}`);
957
+ }
958
+ for (const f of downloaded.failed) {
959
+ consola.warn(` failed: ${f.url} (${f.error})`);
960
+ }
961
+ warnMislabeled(downloaded.mislabeled);
962
+ }
963
+ if (!downloaded?.downloaded.length) {
964
+ for (const url of extractMediaUrls(completed.result)) {
965
+ consola.log(` ${url}`);
966
+ }
967
+ }
968
+ };
969
+ var runCommand = defineCommand({
970
+ args: {
971
+ async: {
972
+ description: "Submit to queue and return request_id without waiting.",
973
+ type: "boolean"
974
+ },
975
+ download: {
976
+ description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
977
+ type: "string"
978
+ },
979
+ endpoint_id: {
980
+ description: "Model endpoint ID, e.g. fal-ai/flux/dev.",
981
+ required: true,
982
+ type: "positional"
983
+ },
984
+ provider: {
985
+ description: "Backend for this run: vibedgames, or codex (image generation through the local Codex CLI and your own Codex plan). Without it, the saved preference applies: `vg config set generate.provider codex` sends OpenAI image runs to Codex. The literal endpoint `codex` implies codex.",
986
+ type: "string"
987
+ },
988
+ ...outputArgs,
989
+ quiet: { description: "Suppress progress output during sync runs.", type: "boolean" }
990
+ },
991
+ meta: { description: "Run a model (waits for result by default).", name: "run" },
992
+ run: async ({ args, rawArgs }) => {
993
+ const downloadFlag = parseDownloadFlag(rawArgs);
994
+ const finalInput = parseRunInput(rawArgs);
995
+ const { endpoint_id } = args;
996
+ const choice = chooseProvider(args.provider, {
997
+ async: Boolean(args.async),
998
+ endpointId: endpoint_id,
999
+ input: finalInput
1000
+ });
1001
+ if (choice.note) {
1002
+ process.stderr.write(`${choice.note}
1003
+ `);
1004
+ }
1005
+ if (choice.provider === "codex") {
1006
+ await runViaCodex({ args, downloadFlag, endpoint_id, finalInput });
1007
+ return;
1008
+ }
1009
+ const client = createClient();
1010
+ const submission = await forwardJson(client, {
1011
+ body: finalInput,
1012
+ method: "POST",
1013
+ path: `/${endpointPath(endpoint_id)}`,
1014
+ target: "queue"
1015
+ });
1016
+ const requestId = isJsonObject(submission) && isJsonString(submission.request_id) ? submission.request_id : null;
1017
+ if (!requestId) {
1018
+ throw new Error("queue submit did not return a request_id.");
1019
+ }
1020
+ if (args.async) {
1021
+ const payload2 = {
1022
+ endpoint_id,
1023
+ hint: `Check status: vg generate status ${endpoint_id} ${requestId}`,
1024
+ request_id: requestId,
1025
+ status: "submitted"
1026
+ };
1027
+ if (!writeStructured(payload2, args)) {
1028
+ consola.success(`Submitted ${endpoint_id}`);
1029
+ consola.log(` request_id: ${requestId}`);
1030
+ }
1031
+ return;
1032
+ }
1033
+ const completed = await waitForCompletion(client, endpoint_id, requestId, {
1034
+ quiet: Boolean(args.quiet) || isStructuredOutput(args)
1035
+ });
1036
+ let downloaded;
1037
+ if (downloadFlag.mode === "on") {
1038
+ const refs = extractMediaRefs(completed.result);
1039
+ downloaded = await downloadMedia({
1040
+ refs,
1041
+ requestId: completed.request_id,
1042
+ template: downloadFlag.template
1043
+ });
1044
+ }
1045
+ const payload = buildRunPayload(endpoint_id, completed, downloaded);
1046
+ if (!writeStructured(payload, args)) {
1047
+ reportRun(completed, downloaded);
1048
+ }
1049
+ if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
1050
+ process.exit(1);
1051
+ }
1052
+ }
1053
+ });
1054
+ var confirmCancelled = async (client, ep, requestId) => {
1055
+ const statusPath = `/${ep}/requests/${requestId}/status`;
1056
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1057
+ await sleep2(1e3);
1058
+ try {
1059
+ const poll = await forwardJson(client, { method: "GET", path: statusPath, target: "queue" });
1060
+ const status = isJsonObject(poll) && isJsonString(poll.status) ? poll.status.toUpperCase() : "";
1061
+ if (["CANCELLED", "FAILED", "COMPLETED"].includes(status)) {
1062
+ break;
1063
+ }
1064
+ } catch {
1065
+ break;
1066
+ }
1067
+ }
1068
+ };
1069
+ var reportStatus = (action, endpointId, requestId, data, downloaded) => {
1070
+ if (action === "status") {
1071
+ const status = isJsonObject(data) && isJsonString(data.status) ? data.status : "?";
1072
+ consola.log(`status: ${status}`);
1073
+ if (isJsonObject(data) && isJsonNumber(data.queue_position)) {
1074
+ consola.log(`queue_position: ${data.queue_position}`);
1075
+ }
1076
+ return;
1077
+ }
1078
+ consola.success(`${action} ${endpointId} ${requestId}`);
1079
+ if (downloaded) {
1080
+ for (const p of downloaded.downloaded) {
1081
+ consola.log(` ${p}`);
1082
+ }
1083
+ for (const f of downloaded.failed) {
1084
+ consola.warn(` failed: ${f.url} (${f.error})`);
1085
+ }
1086
+ warnMislabeled(downloaded.mislabeled);
1087
+ }
1088
+ if (action === "result" && !downloaded?.downloaded.length) {
1089
+ for (const url of extractMediaUrls(data)) {
1090
+ consola.log(` ${url}`);
1091
+ }
1092
+ }
1093
+ };
1094
+ var statusCommand = defineCommand({
1095
+ args: {
1096
+ cancel: { description: "Cancel the job.", type: "boolean" },
1097
+ download: {
1098
+ description: "Download media from the result (implies --result).",
1099
+ type: "string"
1100
+ },
1101
+ endpoint_id: { required: true, type: "positional" },
1102
+ logs: { description: "Include logs.", type: "boolean" },
1103
+ request_id: { required: true, type: "positional" },
1104
+ result: { description: "Fetch the completed result.", type: "boolean" },
1105
+ ...outputArgs
1106
+ },
1107
+ meta: {
1108
+ description: "Check job status, fetch result, or cancel.",
1109
+ name: "status"
1110
+ },
1111
+ run: async ({ args, rawArgs }) => {
1112
+ if (args.result && args.cancel) {
1113
+ consola.error("Pick one of --result or --cancel.");
1114
+ process.exit(1);
1115
+ }
1116
+ const downloadFlag = parseDownloadFlag(rawArgs);
1117
+ const wantResult = args.result || downloadFlag.mode === "on";
1118
+ let action = "status";
1119
+ if (args.cancel) {
1120
+ action = "cancel";
1121
+ } else if (wantResult) {
1122
+ action = "result";
1123
+ }
1124
+ const ep = queueAppId(args.endpoint_id);
1125
+ const client = createClient();
1126
+ const suffixes = { cancel: "/cancel", result: "", status: "/status" };
1127
+ const path4 = `/${ep}/requests/${args.request_id}${suffixes[action]}`;
1128
+ const data = await forwardJson(client, {
1129
+ method: action === "cancel" ? "PUT" : "GET",
1130
+ path: path4,
1131
+ query: action === "status" && args.logs ? { logs: "1" } : void 0,
1132
+ target: "queue"
1133
+ });
1134
+ if (action === "cancel") {
1135
+ await confirmCancelled(client, ep, args.request_id);
1136
+ }
1137
+ let downloaded;
1138
+ if (action === "result" && downloadFlag.mode === "on") {
1139
+ const refs = extractMediaRefs(data);
1140
+ downloaded = await downloadMedia({
1141
+ refs,
1142
+ requestId: args.request_id,
1143
+ template: downloadFlag.template
1144
+ });
1145
+ }
1146
+ const payload = {
1147
+ action,
1148
+ endpoint_id: args.endpoint_id,
1149
+ request_id: args.request_id,
1150
+ ...buildActionFields(action, data)
1151
+ };
1152
+ if (downloaded) {
1153
+ payload.downloaded_files = downloaded.downloaded;
1154
+ if (downloaded.failed.length > 0) {
1155
+ payload.download_failures = downloaded.failed;
1156
+ }
1157
+ if (downloaded.mislabeled.length > 0) {
1158
+ payload.download_format_mismatches = downloaded.mislabeled;
1159
+ }
1160
+ }
1161
+ if (!writeStructured(payload, args)) {
1162
+ reportStatus(action, args.endpoint_id, args.request_id, data, downloaded);
1163
+ }
1164
+ if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
1165
+ process.exit(1);
1166
+ }
1167
+ }
1168
+ });
1169
+ var splitList = (value) => {
1170
+ if (!value) {
1171
+ return [];
1172
+ }
1173
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
1174
+ };
1175
+ var printModels = (data) => {
1176
+ const models = isJsonObject(data) && Array.isArray(data.models) ? data.models : [];
1177
+ for (const m of models) {
1178
+ if (!isJsonObject(m)) {
1179
+ continue;
1180
+ }
1181
+ const id = String(m.endpoint_id ?? "?");
1182
+ const meta = isJsonObject(m.metadata) ? m.metadata : {};
1183
+ const tags = [];
1184
+ if (meta.category) {
1185
+ tags.push(String(meta.category));
1186
+ }
1187
+ if (meta.status) {
1188
+ tags.push(String(meta.status));
1189
+ }
1190
+ consola.log(`${id}${tags.length > 0 ? ` [${tags.join(", ")}]` : ""}`);
1191
+ }
1192
+ if (isJsonObject(data) && data.next_cursor) {
1193
+ consola.log(`
1194
+ next_cursor: ${String(data.next_cursor)}`);
1195
+ }
1196
+ };
1197
+ var modelsCommand = defineCommand({
1198
+ args: {
1199
+ category: { description: "Filter by category.", type: "string" },
1200
+ cursor: { description: "Pagination cursor from a prior response.", type: "string" },
1201
+ endpoint_id: {
1202
+ description: "Specific endpoint id(s); repeat or comma-separate.",
1203
+ type: "string"
1204
+ },
1205
+ expand: {
1206
+ description: "Expand fields: openapi-3.0, enterprise_status. Repeat or comma-separate.",
1207
+ type: "string"
1208
+ },
1209
+ limit: { description: "Max results (default 20).", type: "string" },
1210
+ query: { description: "Search query.", required: false, type: "positional" },
1211
+ status: { description: "active (default) | deprecated | all", type: "string" },
1212
+ ...outputArgs
1213
+ },
1214
+ meta: { description: "Search/list available models.", name: "models" },
1215
+ run: async ({ args }) => {
1216
+ const query = {};
1217
+ if (args.query) {
1218
+ query.q = args.query;
1219
+ }
1220
+ if (args.category) {
1221
+ query.category = args.category;
1222
+ }
1223
+ if (args.status && args.status !== "all") {
1224
+ query.status = args.status;
1225
+ }
1226
+ query.limit = args.limit ?? "20";
1227
+ if (args.cursor) {
1228
+ query.cursor = args.cursor;
1229
+ }
1230
+ const endpointIds = splitList(args.endpoint_id);
1231
+ if (endpointIds.length > 0) {
1232
+ query.endpoint_id = endpointIds;
1233
+ }
1234
+ const expand = splitList(args.expand);
1235
+ if (expand.length > 0) {
1236
+ query.expand = expand;
1237
+ }
1238
+ const client = createClient();
1239
+ const data = await forwardJson(client, {
1240
+ method: "GET",
1241
+ path: "/v1/models",
1242
+ query,
1243
+ target: "platform"
1244
+ });
1245
+ if (!writeStructured(data, args)) {
1246
+ printModels(data);
1247
+ }
1248
+ }
1249
+ });
1250
+ var schemaCommand = defineCommand({
1251
+ args: {
1252
+ endpoint_id: { required: true, type: "positional" },
1253
+ format: { description: "compact (default) | openapi", type: "string" },
1254
+ ...outputArgs
1255
+ },
1256
+ meta: { description: "Fetch a model's input/output schema.", name: "schema" },
1257
+ run: async ({ args }) => {
1258
+ const expand = args.format === "openapi" ? ["openapi-3.0"] : [];
1259
+ const client = createClient();
1260
+ const query = {};
1261
+ query.endpoint_id = args.endpoint_id;
1262
+ query.limit = "1";
1263
+ if (expand.length > 0) {
1264
+ query.expand = expand;
1265
+ }
1266
+ const data = await forwardJson(client, {
1267
+ method: "GET",
1268
+ path: "/v1/models",
1269
+ query,
1270
+ target: "platform"
1271
+ });
1272
+ if (!writeStructured(data, args)) {
1273
+ writeJson(data);
1274
+ }
1275
+ }
1276
+ });
1277
+ var pricingCommand = defineCommand({
1278
+ args: {
1279
+ endpoint_id: { required: true, type: "positional" },
1280
+ ...outputArgs
1281
+ },
1282
+ meta: { description: "Fetch pricing for a model.", name: "pricing" },
1283
+ run: async ({ args }) => {
1284
+ const client = createClient();
1285
+ const data = await forwardJson(client, {
1286
+ method: "GET",
1287
+ path: "/v1/models/pricing",
1288
+ query: { endpoint_id: args.endpoint_id },
1289
+ target: "platform"
1290
+ });
1291
+ if (!writeStructured(data, args)) {
1292
+ writeJson(data);
1293
+ }
1294
+ }
1295
+ });
1296
+ var docsCommand = defineCommand({
1297
+ args: {
1298
+ query: { required: true, type: "positional" },
1299
+ ...outputArgs
1300
+ },
1301
+ meta: { description: "Search generative-model documentation.", name: "docs" },
1302
+ run: async ({ args }) => {
1303
+ const client = createClient();
1304
+ const data = await forwardJson(client, {
1305
+ body: {
1306
+ id: 1,
1307
+ jsonrpc: "2.0",
1308
+ method: "tools/call",
1309
+ params: { arguments: { query: args.query }, name: "search_fal" }
1310
+ },
1311
+ method: "POST",
1312
+ path: "/docs/mcp",
1313
+ target: "docs"
1314
+ });
1315
+ if (!writeStructured(data, args)) {
1316
+ writeJson(data);
1317
+ }
1318
+ }
1319
+ });
1320
+ var uploadCommand = defineCommand({
1321
+ args: {
1322
+ path: { required: true, type: "positional" },
1323
+ ...outputArgs
1324
+ },
1325
+ meta: {
1326
+ description: "Upload a local file. Returns a stable hosted URL.",
1327
+ name: "upload"
1328
+ },
1329
+ run: async ({ args }) => {
1330
+ const stat = readExplicitLocalFile(args.path);
1331
+ if (!stat) {
1332
+ consola.error(`File not found: ${args.path}`);
1333
+ process.exit(1);
1334
+ }
1335
+ const client = createClient();
1336
+ const url = await uploadFile(client, stat);
1337
+ if (!writeStructured({ url }, args)) {
1338
+ process.stdout.write(`${url}
1339
+ `);
1340
+ }
1341
+ }
1342
+ });
1343
+ var generateCommand = defineCommand({
1344
+ meta: {
1345
+ description: "Generate, edit, and inspect images, video, and audio.",
1346
+ name: "generate"
1347
+ },
1348
+ subCommands: {
1349
+ docs: docsCommand,
1350
+ models: modelsCommand,
1351
+ pricing: pricingCommand,
1352
+ run: runCommand,
1353
+ schema: schemaCommand,
1354
+ status: statusCommand,
1355
+ upload: uploadCommand
1356
+ }
1357
+ });
1358
+ export {
1359
+ generateCommand
1360
+ };