vibedgames 0.5.0 → 0.6.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/dist/commands/completions.d.ts +1 -1
  3. package/dist/commands/completions.js +21 -20
  4. package/dist/commands/credits.d.ts +5 -5
  5. package/dist/commands/credits.js +43 -33
  6. package/dist/commands/deploy.d.ts +10 -10
  7. package/dist/commands/deploy.js +155 -139
  8. package/dist/commands/factory.d.ts +1 -1
  9. package/dist/commands/factory.js +18 -15
  10. package/dist/commands/fork.d.ts +14 -14
  11. package/dist/commands/fork.js +51 -46
  12. package/dist/commands/generate.js +318 -264
  13. package/dist/commands/init.d.ts +8 -8
  14. package/dist/commands/init.js +31 -24
  15. package/dist/commands/login.js +12 -12
  16. package/dist/commands/logout.js +2 -2
  17. package/dist/commands/new.d.ts +16 -16
  18. package/dist/commands/new.js +153 -142
  19. package/dist/commands/playtest-run.d.ts +62 -0
  20. package/dist/commands/playtest-run.js +258 -0
  21. package/dist/commands/playtest.d.ts +41 -6
  22. package/dist/commands/playtest.js +114 -101
  23. package/dist/commands/update.d.ts +7 -7
  24. package/dist/commands/update.js +20 -17
  25. package/dist/commands/whoami.d.ts +5 -5
  26. package/dist/commands/whoami.js +8 -7
  27. package/dist/index.js +21 -11
  28. package/dist/lib/api.d.ts +4 -4
  29. package/dist/lib/api.js +6 -12
  30. package/dist/lib/archive.d.ts +4 -4
  31. package/dist/lib/archive.js +121 -104
  32. package/dist/lib/codex.d.ts +45 -15
  33. package/dist/lib/codex.js +175 -106
  34. package/dist/lib/config-file.d.ts +6 -6
  35. package/dist/lib/config-file.js +28 -26
  36. package/dist/lib/config.d.ts +8 -8
  37. package/dist/lib/config.js +31 -33
  38. package/dist/lib/manifest.d.ts +3 -3
  39. package/dist/lib/manifest.js +42 -38
  40. package/dist/lib/media-args.d.ts +7 -7
  41. package/dist/lib/media-args.js +113 -95
  42. package/dist/lib/media-download.d.ts +9 -9
  43. package/dist/lib/media-download.js +148 -134
  44. package/dist/lib/media-poll.d.ts +8 -8
  45. package/dist/lib/media-poll.js +32 -27
  46. package/dist/lib/media-upload.d.ts +2 -2
  47. package/dist/lib/media-upload.js +27 -27
  48. package/dist/lib/output.d.ts +27 -12
  49. package/dist/lib/output.js +26 -26
  50. package/dist/lib/package-manager.d.ts +3 -3
  51. package/dist/lib/package-manager.js +27 -22
  52. package/dist/lib/playtest/agent.d.ts +188 -0
  53. package/dist/lib/playtest/agent.js +610 -0
  54. package/dist/lib/playtest/browser.d.ts +109 -0
  55. package/dist/lib/playtest/browser.js +219 -0
  56. package/dist/lib/playtest/controls.d.ts +47 -0
  57. package/dist/lib/playtest/controls.js +218 -0
  58. package/dist/lib/playtest/errors.d.ts +9 -0
  59. package/dist/lib/playtest/errors.js +12 -0
  60. package/dist/lib/playtest/keys.d.ts +41 -0
  61. package/dist/lib/playtest/keys.js +157 -0
  62. package/dist/lib/playtest/run.d.ts +193 -0
  63. package/dist/lib/playtest/run.js +408 -0
  64. package/dist/lib/run.d.ts +4 -4
  65. package/dist/lib/run.js +7 -4
  66. package/dist/lib/strict-args.d.ts +4 -4
  67. package/dist/lib/strict-args.js +28 -18
  68. package/dist/lib/types.d.ts +5 -5
  69. package/dist/lib/types.js +9 -12
  70. package/dist/lib/update.d.ts +4 -4
  71. package/dist/lib/update.js +41 -32
  72. package/dist/lib/upload.d.ts +4 -4
  73. package/dist/lib/upload.js +14 -9
  74. package/package.json +16 -16
@@ -1,80 +1,205 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
1
2
  import { defineCommand } from "citty";
2
- import consola from "consola";
3
+ import { consola } from "consola";
3
4
  import { createClient, forwardJson } from "../lib/api.js";
4
- import { CodexError, generateImagesWithCodex, placeCodexOutputs, resolveProvider, } from "../lib/codex.js";
5
- import { parseDownloadFlag, parseRunInput, readExplicitLocalFile, } from "../lib/media-args.js";
5
+ import { CodexError, generateImagesWithCodex, placeCodexOutputs, chooseProvider, findCodexBinary, } from "../lib/codex.js";
6
+ import { parseDownloadFlag, parseRunInput, readExplicitLocalFile } from "../lib/media-args.js";
6
7
  import { downloadMedia, extractMediaRefs } from "../lib/media-download.js";
7
8
  import { endpointPath, queueAppId, waitForCompletion } from "../lib/media-poll.js";
8
9
  import { uploadFile } from "../lib/media-upload.js";
9
10
  import { isJsonOutput, outputArgs, writeJson, writeStructured } from "../lib/output.js";
10
- import { isJsonNumber, isJsonObject, isJsonString, } from "../lib/types.js";
11
- function buildActionFields(action, data) {
12
- if (action === "result")
11
+ import { isJsonNumber, isJsonObject, isJsonString } from "../lib/types.js";
12
+ const buildActionFields = (action, data) => {
13
+ if (action === "result") {
13
14
  return { result: data };
15
+ }
14
16
  if (action === "status" && isJsonObject(data)) {
15
17
  const fields = {};
16
- if (isJsonString(data.status))
18
+ if (isJsonString(data.status)) {
17
19
  fields.status = data.status;
18
- if (isJsonNumber(data.queue_position))
20
+ }
21
+ if (isJsonNumber(data.queue_position)) {
19
22
  fields.queue_position = data.queue_position;
20
- if (data.logs !== undefined)
23
+ }
24
+ if (data.logs !== undefined) {
21
25
  fields.logs = data.logs;
26
+ }
22
27
  return fields;
23
28
  }
24
29
  return {};
25
- }
30
+ };
26
31
  /**
27
32
  * True when stdout is carrying data rather than a progress narrative, so
28
33
  * spinners and status lines must stay off it. `--field` counts: its whole
29
34
  * point is that the output can be captured by a shell verbatim.
30
35
  */
31
- function isStructuredOutput(args) {
32
- return isJsonOutput(args) || Boolean(args.field);
33
- }
34
- function extractMediaUrls(result) {
35
- return extractMediaRefs(result).map((r) => r.url);
36
- }
36
+ const isStructuredOutput = (args) => isJsonOutput(args) || Boolean(args.field);
37
+ const extractMediaUrls = (result) => extractMediaRefs(result).map((r) => r.url);
37
38
  // ---- run --------------------------------------------------------------------
39
+ /**
40
+ * A downloaded file whose extension does not match the bytes inside it.
41
+ *
42
+ * The model, not the CLI, picks the output format, so asking for `board.png`
43
+ * from an endpoint that returns JPEG produces a `.png` full of JPEG. The next
44
+ * tool in the pipeline reports "bad signature" with no hint of where it came
45
+ * from, so name it here while the cause is still on screen.
46
+ */
47
+ const warnMislabeled = (mislabeled) => {
48
+ for (const m of mislabeled) {
49
+ consola.warn(` ${m.path} holds ${m.actual.toUpperCase()} data, not what its extension says`);
50
+ }
51
+ };
52
+ // Delegate image generation to the local Codex CLI instead of the
53
+ // vibedgames model runner. Produces local files directly (Codex writes
54
+ // to disk), so there's no queue, no request polling, and no vibedgames
55
+ // backend call. The `--download` template still controls output naming;
56
+ // without it we default to cwd.
57
+ const runViaCodex = async (opts) => {
58
+ const { args, finalInput, downloadFlag, endpoint_id } = opts;
59
+ if (args.async) {
60
+ consola.error("--async is not supported with --provider codex (Codex runs synchronously).");
61
+ process.exit(1);
62
+ }
63
+ let result;
64
+ try {
65
+ result = await generateImagesWithCodex({ input: finalInput });
66
+ }
67
+ catch (error) {
68
+ if (error instanceof CodexError) {
69
+ // Expected, user-facing failure (codex missing / declined / exec
70
+ // error). Present it cleanly with a deterministic exit code instead
71
+ // of an unhandled stack trace — consola.error goes to stderr, so it
72
+ // never corrupts a --json consumer's stdout. Codex's own output
73
+ // already streamed straight to stderr as it ran (and the message
74
+ // already names the vibedgames fallback), so we don't reprint here.
75
+ consola.error(error.message);
76
+ process.exit(1);
77
+ }
78
+ throw error;
79
+ }
80
+ const { requestId, rawFiles, prompt, ignoredReferences } = result;
81
+ // Warn about dropped (non-local) references on stderr regardless of
82
+ // --json/--quiet — stderr never corrupts the JSON payload — and also
83
+ // record them in the JSON so an agent parsing stdout sees the signal.
84
+ for (const ref of ignoredReferences) {
85
+ consola.warn(`Ignored non-local reference (codex needs a local file path): ${ref}`);
86
+ }
87
+ const template = downloadFlag.mode === "on" ? downloadFlag.template : undefined;
88
+ const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId);
89
+ const payload = {
90
+ downloaded_files: downloaded,
91
+ endpoint_id,
92
+ provider: "codex",
93
+ request_id: requestId,
94
+ result: { images: downloaded.map((path) => ({ path })), prompt, provider: "codex" },
95
+ status: "completed",
96
+ };
97
+ if (failed.length > 0) {
98
+ payload.download_failures = failed;
99
+ }
100
+ if (ignoredReferences.length > 0) {
101
+ payload.ignored_references = ignoredReferences;
102
+ }
103
+ if (!writeStructured(payload, args)) {
104
+ consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
105
+ for (const path of downloaded) {
106
+ consola.log(` ${path}`);
107
+ }
108
+ for (const f of failed) {
109
+ consola.warn(` failed: ${f.url} (${f.error})`);
110
+ }
111
+ }
112
+ if (failed.length > 0 && downloaded.length === 0) {
113
+ process.exit(1);
114
+ }
115
+ };
116
+ const buildRunPayload = (endpointId, completed, downloaded) => {
117
+ const payload = {
118
+ endpoint_id: endpointId,
119
+ request_id: completed.request_id,
120
+ result: completed.result,
121
+ status: "completed",
122
+ };
123
+ if (!downloaded) {
124
+ return payload;
125
+ }
126
+ payload.downloaded_files = downloaded.downloaded;
127
+ if (downloaded.failed.length > 0) {
128
+ payload.download_failures = downloaded.failed;
129
+ }
130
+ if (downloaded.mislabeled.length > 0) {
131
+ payload.download_format_mismatches = downloaded.mislabeled;
132
+ }
133
+ return payload;
134
+ };
135
+ const reportRun = (completed, downloaded) => {
136
+ consola.success(`Run completed (${completed.request_id})`);
137
+ if (downloaded) {
138
+ for (const file of downloaded.downloaded) {
139
+ consola.log(` ${file}`);
140
+ }
141
+ for (const f of downloaded.failed) {
142
+ consola.warn(` failed: ${f.url} (${f.error})`);
143
+ }
144
+ warnMislabeled(downloaded.mislabeled);
145
+ }
146
+ if (!downloaded?.downloaded.length) {
147
+ for (const url of extractMediaUrls(completed.result)) {
148
+ consola.log(` ${url}`);
149
+ }
150
+ }
151
+ };
38
152
  const runCommand = defineCommand({
39
- meta: { name: "run", description: "Run a model (waits for result by default)." },
40
153
  args: {
41
- endpoint_id: {
42
- type: "positional",
43
- required: true,
44
- description: "Model endpoint ID, e.g. fal-ai/flux/dev.",
45
- },
46
154
  async: {
47
- type: "boolean",
48
155
  description: "Submit to queue and return request_id without waiting.",
156
+ type: "boolean",
49
157
  },
50
- provider: {
158
+ download: {
159
+ description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
51
160
  type: "string",
52
- description: "Execution backend: vibedgames (default) or codex (delegate image generation to the local Codex CLI / your Codex plan). Also settable via VG_GENERATE_PROVIDER.",
53
161
  },
54
- download: {
162
+ endpoint_id: {
163
+ description: "Model endpoint ID, e.g. fal-ai/flux/dev.",
164
+ required: true,
165
+ type: "positional",
166
+ },
167
+ provider: {
168
+ description: "Execution backend: vibedgames or codex (delegate image generation to the local Codex CLI / your Codex plan). Unset, OpenAI image models (openai/gpt-image-*) use codex when it is installed; everything else uses vibedgames. Also settable via VG_GENERATE_PROVIDER.",
55
169
  type: "string",
56
- description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
57
170
  },
58
171
  ...outputArgs,
59
- quiet: { type: "boolean", description: "Suppress progress output during sync runs." },
172
+ quiet: { description: "Suppress progress output during sync runs.", type: "boolean" },
60
173
  },
174
+ meta: { description: "Run a model (waits for result by default).", name: "run" },
61
175
  run: async ({ args, rawArgs }) => {
62
176
  const downloadFlag = parseDownloadFlag(rawArgs);
63
177
  // parseRunInput already skips non-`--` tokens, so the positional
64
178
  // endpoint_id and any subcommand name in argv are no-ops.
65
179
  const finalInput = parseRunInput(rawArgs);
66
- const endpoint_id = args.endpoint_id;
67
- const provider = resolveProvider(args.provider);
68
- if (provider === "codex") {
69
- await runViaCodex({ args, finalInput, downloadFlag, endpoint_id });
180
+ const { endpoint_id } = args;
181
+ const choice = chooseProvider(args.provider, {
182
+ async: Boolean(args.async),
183
+ codexInstalled: findCodexBinary() !== null,
184
+ endpointId: endpoint_id,
185
+ input: finalInput,
186
+ });
187
+ if (choice.provider === "codex") {
188
+ if (choice.auto) {
189
+ // stderr directly: consola.info targets stdout, which a --json
190
+ // consumer owns
191
+ process.stderr.write(`Running ${endpoint_id} through your local codex CLI (OpenAI image model, your own plan). ` +
192
+ `Pass --provider vibedgames to run it on vibedgames instead.\n`);
193
+ }
194
+ await runViaCodex({ args, downloadFlag, endpoint_id, finalInput });
70
195
  return;
71
196
  }
72
197
  const client = createClient();
73
198
  const submission = await forwardJson(client, {
74
- target: "queue",
199
+ body: finalInput,
75
200
  method: "POST",
76
201
  path: `/${endpointPath(endpoint_id)}`,
77
- body: finalInput,
202
+ target: "queue",
78
203
  });
79
204
  const requestId = isJsonObject(submission) && isJsonString(submission.request_id)
80
205
  ? submission.request_id
@@ -84,10 +209,10 @@ const runCommand = defineCommand({
84
209
  }
85
210
  if (args.async) {
86
211
  const payload = {
87
- status: "submitted",
88
212
  endpoint_id,
89
- request_id: requestId,
90
213
  hint: `Check status: vg generate status ${endpoint_id} ${requestId}`,
214
+ request_id: requestId,
215
+ status: "submitted",
91
216
  };
92
217
  if (!writeStructured(payload, args)) {
93
218
  consola.success(`Submitted ${endpoint_id}`);
@@ -103,133 +228,82 @@ const runCommand = defineCommand({
103
228
  const refs = extractMediaRefs(completed.result);
104
229
  downloaded = await downloadMedia({
105
230
  refs,
106
- template: downloadFlag.template,
107
231
  requestId: completed.request_id,
232
+ template: downloadFlag.template,
108
233
  });
109
234
  }
110
- const payload = {
111
- status: "completed",
112
- endpoint_id,
113
- request_id: completed.request_id,
114
- result: completed.result,
115
- };
116
- if (downloaded) {
117
- payload.downloaded_files = downloaded.downloaded;
118
- if (downloaded.failed.length > 0)
119
- payload.download_failures = downloaded.failed;
120
- if (downloaded.mislabeled.length > 0) {
121
- payload.download_format_mismatches = downloaded.mislabeled;
122
- }
123
- }
235
+ const payload = buildRunPayload(endpoint_id, completed, downloaded);
124
236
  if (!writeStructured(payload, args)) {
125
- consola.success(`Run completed (${completed.request_id})`);
126
- if (downloaded) {
127
- for (const path of downloaded.downloaded)
128
- consola.log(` ${path}`);
129
- for (const f of downloaded.failed)
130
- consola.warn(` failed: ${f.url} (${f.error})`);
131
- warnMislabeled(downloaded.mislabeled);
132
- }
133
- if (!downloaded?.downloaded.length) {
134
- for (const url of extractMediaUrls(completed.result))
135
- consola.log(` ${url}`);
136
- }
237
+ reportRun(completed, downloaded);
137
238
  }
138
239
  if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
139
240
  process.exit(1);
140
241
  }
141
242
  },
142
243
  });
143
- /**
144
- * A downloaded file whose extension does not match the bytes inside it.
145
- *
146
- * The model, not the CLI, picks the output format, so asking for `board.png`
147
- * from an endpoint that returns JPEG produces a `.png` full of JPEG. The next
148
- * tool in the pipeline reports "bad signature" with no hint of where it came
149
- * from, so name it here while the cause is still on screen.
150
- */
151
- function warnMislabeled(mislabeled) {
152
- for (const m of mislabeled) {
153
- consola.warn(` ${m.path} holds ${m.actual.toUpperCase()} data, not what its extension says`);
154
- }
155
- }
156
- // Delegate image generation to the local Codex CLI instead of the
157
- // vibedgames model runner. Produces local files directly (Codex writes
158
- // to disk), so there's no queue, no request polling, and no vibedgames
159
- // backend call. The `--download` template still controls output naming;
160
- // without it we default to cwd.
161
- async function runViaCodex(opts) {
162
- const { args, finalInput, downloadFlag, endpoint_id } = opts;
163
- if (args.async) {
164
- consola.error("--async is not supported with --provider codex (Codex runs synchronously).");
165
- process.exit(1);
166
- }
167
- let result;
168
- try {
169
- result = await generateImagesWithCodex({ input: finalInput });
170
- }
171
- catch (err) {
172
- if (err instanceof CodexError) {
173
- // Expected, user-facing failure (codex missing / declined / exec
174
- // error). Present it cleanly with a deterministic exit code instead
175
- // of an unhandled stack trace — consola.error goes to stderr, so it
176
- // never corrupts a --json consumer's stdout. Codex's own output
177
- // already streamed straight to stderr as it ran (and the message
178
- // already names the vibedgames fallback), so we don't reprint here.
179
- consola.error(err.message);
180
- process.exit(1);
244
+ // ---- status -----------------------------------------------------------------
245
+ /** Cancellation is confirmed asynchronously, and the platform refunds a
246
+ * cancelled job's credit hold when a status poll reports the terminal state —
247
+ * so confirm with a few polls instead of leaving the refund to whenever the
248
+ * user next checks. Best-effort: a miss just defers it. */
249
+ const confirmCancelled = async (client, ep, requestId) => {
250
+ const statusPath = `/${ep}/requests/${requestId}/status`;
251
+ for (let attempt = 0; attempt < 3; attempt += 1) {
252
+ await sleep(1000);
253
+ try {
254
+ const poll = await forwardJson(client, { method: "GET", path: statusPath, target: "queue" });
255
+ const status = isJsonObject(poll) && isJsonString(poll.status) ? poll.status.toUpperCase() : "";
256
+ if (["CANCELLED", "FAILED", "COMPLETED"].includes(status)) {
257
+ break;
258
+ }
259
+ }
260
+ catch {
261
+ break;
181
262
  }
182
- throw err;
183
263
  }
184
- const { requestId, rawFiles, prompt, ignoredReferences } = result;
185
- // Warn about dropped (non-local) references on stderr regardless of
186
- // --json/--quiet — stderr never corrupts the JSON payload — and also
187
- // record them in the JSON so an agent parsing stdout sees the signal.
188
- for (const ref of ignoredReferences) {
189
- consola.warn(`Ignored non-local reference (codex needs a local file path): ${ref}`);
264
+ };
265
+ const reportStatus = (action, endpointId, requestId, data, downloaded) => {
266
+ if (action === "status") {
267
+ const status = isJsonObject(data) && isJsonString(data.status) ? data.status : "?";
268
+ consola.log(`status: ${status}`);
269
+ if (isJsonObject(data) && isJsonNumber(data.queue_position)) {
270
+ consola.log(`queue_position: ${data.queue_position}`);
271
+ }
272
+ return;
190
273
  }
191
- const template = downloadFlag.mode === "on" ? downloadFlag.template : undefined;
192
- const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId);
193
- const payload = {
194
- status: "completed",
195
- provider: "codex",
196
- endpoint_id,
197
- request_id: requestId,
198
- result: { provider: "codex", prompt, images: downloaded.map((path) => ({ path })) },
199
- downloaded_files: downloaded,
200
- };
201
- if (failed.length > 0)
202
- payload.download_failures = failed;
203
- if (ignoredReferences.length > 0)
204
- payload.ignored_references = ignoredReferences;
205
- if (!writeStructured(payload, args)) {
206
- consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
207
- for (const path of downloaded)
208
- consola.log(` ${path}`);
209
- for (const f of failed)
274
+ consola.success(`${action} ${endpointId} ${requestId}`);
275
+ if (downloaded) {
276
+ for (const p of downloaded.downloaded) {
277
+ consola.log(` ${p}`);
278
+ }
279
+ for (const f of downloaded.failed) {
210
280
  consola.warn(` failed: ${f.url} (${f.error})`);
281
+ }
282
+ warnMislabeled(downloaded.mislabeled);
211
283
  }
212
- if (failed.length > 0 && downloaded.length === 0)
213
- process.exit(1);
214
- }
215
- // ---- status -----------------------------------------------------------------
284
+ if (action === "result" && !downloaded?.downloaded.length) {
285
+ for (const url of extractMediaUrls(data)) {
286
+ consola.log(` ${url}`);
287
+ }
288
+ }
289
+ };
216
290
  const statusCommand = defineCommand({
217
- meta: {
218
- name: "status",
219
- description: "Check job status, fetch result, or cancel.",
220
- },
221
291
  args: {
222
- endpoint_id: { type: "positional", required: true },
223
- request_id: { type: "positional", required: true },
224
- result: { type: "boolean", description: "Fetch the completed result." },
225
- cancel: { type: "boolean", description: "Cancel the job." },
226
- logs: { type: "boolean", description: "Include logs." },
292
+ cancel: { description: "Cancel the job.", type: "boolean" },
227
293
  download: {
228
- type: "string",
229
294
  description: "Download media from the result (implies --result).",
295
+ type: "string",
230
296
  },
297
+ endpoint_id: { required: true, type: "positional" },
298
+ logs: { description: "Include logs.", type: "boolean" },
299
+ request_id: { required: true, type: "positional" },
300
+ result: { description: "Fetch the completed result.", type: "boolean" },
231
301
  ...outputArgs,
232
302
  },
303
+ meta: {
304
+ description: "Check job status, fetch result, or cancel.",
305
+ name: "status",
306
+ },
233
307
  run: async ({ args, rawArgs }) => {
234
308
  if (args.result && args.cancel) {
235
309
  consola.error("Pick one of --result or --cancel.");
@@ -237,54 +311,37 @@ const statusCommand = defineCommand({
237
311
  }
238
312
  const downloadFlag = parseDownloadFlag(rawArgs);
239
313
  const wantResult = args.result || downloadFlag.mode === "on";
240
- const action = args.cancel
241
- ? "cancel"
242
- : wantResult
243
- ? "result"
244
- : "status";
314
+ let action = "status";
315
+ if (args.cancel) {
316
+ action = "cancel";
317
+ }
318
+ else if (wantResult) {
319
+ action = "result";
320
+ }
245
321
  const ep = queueAppId(args.endpoint_id);
246
322
  const client = createClient();
247
- const path = action === "cancel"
248
- ? `/${ep}/requests/${args.request_id}/cancel`
249
- : action === "result"
250
- ? `/${ep}/requests/${args.request_id}`
251
- : `/${ep}/requests/${args.request_id}/status`;
323
+ const suffixes = { cancel: "/cancel", result: "", status: "/status" };
324
+ const path = `/${ep}/requests/${args.request_id}${suffixes[action]}`;
252
325
  const data = await forwardJson(client, {
253
- target: "queue",
254
326
  method: action === "cancel" ? "PUT" : "GET",
255
327
  path,
256
328
  query: action === "status" && args.logs ? { logs: "1" } : undefined,
329
+ target: "queue",
257
330
  });
258
331
  // Cancellation is confirmed asynchronously, and the platform refunds a
259
332
  // cancelled job's credit hold when a status poll reports the terminal
260
333
  // state — so confirm with a few polls instead of leaving the refund to
261
334
  // whenever the user next checks. Best-effort: a miss just defers it.
262
335
  if (action === "cancel") {
263
- const statusPath = `/${ep}/requests/${args.request_id}/status`;
264
- for (let attempt = 0; attempt < 3; attempt++) {
265
- await new Promise((resolve) => setTimeout(resolve, 1_000));
266
- try {
267
- const poll = await forwardJson(client, {
268
- target: "queue",
269
- method: "GET",
270
- path: statusPath,
271
- });
272
- const status = isJsonObject(poll) && isJsonString(poll.status) ? poll.status.toUpperCase() : "";
273
- if (["CANCELLED", "FAILED", "COMPLETED"].includes(status))
274
- break;
275
- }
276
- catch {
277
- break;
278
- }
279
- }
336
+ await confirmCancelled(client, ep, args.request_id);
280
337
  }
281
338
  let downloaded;
282
339
  if (action === "result" && downloadFlag.mode === "on") {
283
340
  const refs = extractMediaRefs(data);
284
341
  downloaded = await downloadMedia({
285
342
  refs,
286
- template: downloadFlag.template,
287
343
  requestId: args.request_id,
344
+ template: downloadFlag.template,
288
345
  });
289
346
  }
290
347
  const payload = {
@@ -295,34 +352,15 @@ const statusCommand = defineCommand({
295
352
  };
296
353
  if (downloaded) {
297
354
  payload.downloaded_files = downloaded.downloaded;
298
- if (downloaded.failed.length > 0)
355
+ if (downloaded.failed.length > 0) {
299
356
  payload.download_failures = downloaded.failed;
357
+ }
300
358
  if (downloaded.mislabeled.length > 0) {
301
359
  payload.download_format_mismatches = downloaded.mislabeled;
302
360
  }
303
361
  }
304
362
  if (!writeStructured(payload, args)) {
305
- if (action === "status") {
306
- const status = isJsonObject(data) && isJsonString(data.status) ? data.status : "?";
307
- consola.log(`status: ${status}`);
308
- if (isJsonObject(data) && isJsonNumber(data.queue_position)) {
309
- consola.log(`queue_position: ${data.queue_position}`);
310
- }
311
- }
312
- else {
313
- consola.success(`${action} ${args.endpoint_id} ${args.request_id}`);
314
- if (downloaded) {
315
- for (const p of downloaded.downloaded)
316
- consola.log(` ${p}`);
317
- for (const f of downloaded.failed)
318
- consola.warn(` failed: ${f.url} (${f.error})`);
319
- warnMislabeled(downloaded.mislabeled);
320
- }
321
- if (action === "result" && !downloaded?.downloaded.length) {
322
- for (const url of extractMediaUrls(data))
323
- consola.log(` ${url}`);
324
- }
325
- }
363
+ reportStatus(action, args.endpoint_id, args.request_id, data, downloaded);
326
364
  }
327
365
  if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
328
366
  process.exit(1);
@@ -330,157 +368,172 @@ const statusCommand = defineCommand({
330
368
  },
331
369
  });
332
370
  // ---- models -----------------------------------------------------------------
371
+ const splitList = (value) => {
372
+ if (!value) {
373
+ return [];
374
+ }
375
+ return value
376
+ .split(",")
377
+ .map((s) => s.trim())
378
+ .filter(Boolean);
379
+ };
380
+ const printModels = (data) => {
381
+ const models = isJsonObject(data) && Array.isArray(data.models) ? data.models : [];
382
+ for (const m of models) {
383
+ if (!isJsonObject(m)) {
384
+ continue;
385
+ }
386
+ const id = String(m.endpoint_id ?? "?");
387
+ const meta = isJsonObject(m.metadata) ? m.metadata : {};
388
+ const tags = [];
389
+ if (meta.category) {
390
+ tags.push(String(meta.category));
391
+ }
392
+ if (meta.status) {
393
+ tags.push(String(meta.status));
394
+ }
395
+ consola.log(`${id}${tags.length > 0 ? ` [${tags.join(", ")}]` : ""}`);
396
+ }
397
+ if (isJsonObject(data) && data.next_cursor) {
398
+ consola.log(`\nnext_cursor: ${String(data.next_cursor)}`);
399
+ }
400
+ };
333
401
  const modelsCommand = defineCommand({
334
- meta: { name: "models", description: "Search/list available models." },
335
402
  args: {
336
- query: { type: "positional", required: false, description: "Search query." },
337
- category: { type: "string", description: "Filter by category." },
338
- status: { type: "string", description: "active (default) | deprecated | all" },
339
- limit: { type: "string", description: "Max results (default 20)." },
340
- cursor: { type: "string", description: "Pagination cursor from a prior response." },
403
+ category: { description: "Filter by category.", type: "string" },
404
+ cursor: { description: "Pagination cursor from a prior response.", type: "string" },
341
405
  endpoint_id: {
342
- type: "string",
343
406
  description: "Specific endpoint id(s); repeat or comma-separate.",
407
+ type: "string",
344
408
  },
345
409
  expand: {
346
- type: "string",
347
410
  description: "Expand fields: openapi-3.0, enterprise_status. Repeat or comma-separate.",
411
+ type: "string",
348
412
  },
413
+ limit: { description: "Max results (default 20).", type: "string" },
414
+ query: { description: "Search query.", required: false, type: "positional" },
415
+ status: { description: "active (default) | deprecated | all", type: "string" },
349
416
  ...outputArgs,
350
417
  },
418
+ meta: { description: "Search/list available models.", name: "models" },
351
419
  run: async ({ args }) => {
352
420
  const query = {};
353
- if (args.query)
421
+ if (args.query) {
354
422
  query.q = args.query;
355
- if (args.category)
423
+ }
424
+ if (args.category) {
356
425
  query.category = args.category;
357
- if (args.status && args.status !== "all")
426
+ }
427
+ if (args.status && args.status !== "all") {
358
428
  query.status = args.status;
429
+ }
359
430
  query.limit = args.limit ?? "20";
360
- if (args.cursor)
431
+ if (args.cursor) {
361
432
  query.cursor = args.cursor;
433
+ }
362
434
  const endpointIds = splitList(args.endpoint_id);
363
- if (endpointIds.length > 0)
435
+ if (endpointIds.length > 0) {
364
436
  query.endpoint_id = endpointIds;
437
+ }
365
438
  const expand = splitList(args.expand);
366
- if (expand.length > 0)
439
+ if (expand.length > 0) {
367
440
  query.expand = expand;
441
+ }
368
442
  const client = createClient();
369
443
  const data = await forwardJson(client, {
370
- target: "platform",
371
444
  method: "GET",
372
445
  path: "/v1/models",
373
446
  query,
447
+ target: "platform",
374
448
  });
375
- if (!writeStructured(data, args))
449
+ if (!writeStructured(data, args)) {
376
450
  printModels(data);
451
+ }
377
452
  },
378
453
  });
379
- function splitList(value) {
380
- if (!value)
381
- return [];
382
- return value
383
- .split(",")
384
- .map((s) => s.trim())
385
- .filter(Boolean);
386
- }
387
- function printModels(data) {
388
- const models = isJsonObject(data) && Array.isArray(data.models) ? data.models : [];
389
- for (const m of models) {
390
- if (!isJsonObject(m))
391
- continue;
392
- const id = String(m.endpoint_id ?? "?");
393
- const meta = isJsonObject(m.metadata) ? m.metadata : {};
394
- const tags = [];
395
- if (meta.category)
396
- tags.push(String(meta.category));
397
- if (meta.status)
398
- tags.push(String(meta.status));
399
- consola.log(`${id}${tags.length > 0 ? ` [${tags.join(", ")}]` : ""}`);
400
- }
401
- if (isJsonObject(data) && data.next_cursor) {
402
- consola.log(`\nnext_cursor: ${String(data.next_cursor)}`);
403
- }
404
- }
405
454
  // ---- schema -----------------------------------------------------------------
406
455
  const schemaCommand = defineCommand({
407
- meta: { name: "schema", description: "Fetch a model's input/output schema." },
408
456
  args: {
409
- endpoint_id: { type: "positional", required: true },
410
- format: { type: "string", description: "compact (default) | openapi" },
457
+ endpoint_id: { required: true, type: "positional" },
458
+ format: { description: "compact (default) | openapi", type: "string" },
411
459
  ...outputArgs,
412
460
  },
461
+ meta: { description: "Fetch a model's input/output schema.", name: "schema" },
413
462
  run: async ({ args }) => {
414
463
  const expand = args.format === "openapi" ? ["openapi-3.0"] : [];
415
464
  const client = createClient();
416
465
  const query = {};
417
466
  query.endpoint_id = args.endpoint_id;
418
467
  query.limit = "1";
419
- if (expand.length > 0)
468
+ if (expand.length > 0) {
420
469
  query.expand = expand;
470
+ }
421
471
  const data = await forwardJson(client, {
422
- target: "platform",
423
472
  method: "GET",
424
473
  path: "/v1/models",
425
474
  query,
475
+ target: "platform",
426
476
  });
427
- if (!writeStructured(data, args))
477
+ if (!writeStructured(data, args)) {
428
478
  writeJson(data);
479
+ }
429
480
  },
430
481
  });
431
482
  // ---- pricing ----------------------------------------------------------------
432
483
  const pricingCommand = defineCommand({
433
- meta: { name: "pricing", description: "Fetch pricing for a model." },
434
484
  args: {
435
- endpoint_id: { type: "positional", required: true },
485
+ endpoint_id: { required: true, type: "positional" },
436
486
  ...outputArgs,
437
487
  },
488
+ meta: { description: "Fetch pricing for a model.", name: "pricing" },
438
489
  run: async ({ args }) => {
439
490
  const client = createClient();
440
491
  const data = await forwardJson(client, {
441
- target: "platform",
442
492
  method: "GET",
443
493
  path: "/v1/models/pricing",
444
494
  query: { endpoint_id: args.endpoint_id },
495
+ target: "platform",
445
496
  });
446
- if (!writeStructured(data, args))
497
+ if (!writeStructured(data, args)) {
447
498
  writeJson(data);
499
+ }
448
500
  },
449
501
  });
450
502
  // ---- docs -------------------------------------------------------------------
451
503
  const docsCommand = defineCommand({
452
- meta: { name: "docs", description: "Search generative-model documentation." },
453
504
  args: {
454
- query: { type: "positional", required: true },
505
+ query: { required: true, type: "positional" },
455
506
  ...outputArgs,
456
507
  },
508
+ meta: { description: "Search generative-model documentation.", name: "docs" },
457
509
  run: async ({ args }) => {
458
510
  const client = createClient();
459
511
  const data = await forwardJson(client, {
460
- target: "docs",
461
- method: "POST",
462
- path: "/docs/mcp",
463
512
  body: {
464
- jsonrpc: "2.0",
465
513
  id: 1,
514
+ jsonrpc: "2.0",
466
515
  method: "tools/call",
467
- params: { name: "search_fal", arguments: { query: args.query } },
516
+ params: { arguments: { query: args.query }, name: "search_fal" },
468
517
  },
518
+ method: "POST",
519
+ path: "/docs/mcp",
520
+ target: "docs",
469
521
  });
470
- if (!writeStructured(data, args))
522
+ if (!writeStructured(data, args)) {
471
523
  writeJson(data);
524
+ }
472
525
  },
473
526
  });
474
527
  // ---- upload -----------------------------------------------------------------
475
528
  const uploadCommand = defineCommand({
476
- meta: {
477
- name: "upload",
478
- description: "Upload a local file. Returns a stable hosted URL.",
479
- },
480
529
  args: {
481
- path: { type: "positional", required: true },
530
+ path: { required: true, type: "positional" },
482
531
  ...outputArgs,
483
532
  },
533
+ meta: {
534
+ description: "Upload a local file. Returns a stable hosted URL.",
535
+ name: "upload",
536
+ },
484
537
  run: async ({ args }) => {
485
538
  const stat = readExplicitLocalFile(args.path);
486
539
  if (!stat) {
@@ -489,23 +542,24 @@ const uploadCommand = defineCommand({
489
542
  }
490
543
  const client = createClient();
491
544
  const url = await uploadFile(client, stat);
492
- if (!writeStructured({ url }, args))
493
- process.stdout.write(url + "\n");
545
+ if (!writeStructured({ url }, args)) {
546
+ process.stdout.write(`${url}\n`);
547
+ }
494
548
  },
495
549
  });
496
550
  // ---- top-level --------------------------------------------------------------
497
551
  export const generateCommand = defineCommand({
498
552
  meta: {
499
- name: "generate",
500
553
  description: "Generate, edit, and inspect images, video, and audio.",
554
+ name: "generate",
501
555
  },
502
556
  subCommands: {
503
- run: runCommand,
504
- status: statusCommand,
557
+ docs: docsCommand,
505
558
  models: modelsCommand,
506
- schema: schemaCommand,
507
559
  pricing: pricingCommand,
508
- docs: docsCommand,
560
+ run: runCommand,
561
+ schema: schemaCommand,
562
+ status: statusCommand,
509
563
  upload: uploadCommand,
510
564
  },
511
565
  });