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