@5y/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,887 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { parseArgs } from './args.mjs';
6
+ import { deliverCallback } from './callback.mjs';
7
+ import {
8
+ keyPrefix,
9
+ loadRuntimeConfig,
10
+ normalizeBaseUrl,
11
+ saveConfig,
12
+ } from './config.mjs';
13
+ import {
14
+ downloadToFile,
15
+ extensionForContentType,
16
+ makeMultipart,
17
+ openApi,
18
+ redactUrl,
19
+ } from './http.mjs';
20
+ import {
21
+ CliError,
22
+ EXIT,
23
+ UsageError,
24
+ emitFailure,
25
+ emitSuccess,
26
+ log,
27
+ } from './output.mjs';
28
+ import { VERSION } from './version.mjs';
29
+
30
+ const TERMINAL_STATUSES = new Set(['succeeded', 'failed', 'cancelled']);
31
+
32
+ const USAGE = `5y <command> [options]
33
+
34
+ Commands:
35
+ login --key <API_KEY> [--base-url URL]
36
+ whoami
37
+ models [--type image|video]
38
+ upload <file> [--name <name>]
39
+ assets list [--type T] [--limit N] [--cursor C]
40
+ assets get <asset_id>
41
+ assets delete <asset_id>
42
+ image|video --prompt <text> [--model M]
43
+ [--asset source_video=<id>] [--asset image=<id>] [--asset video=<id>]
44
+ [--param k=v ...] [--idempotency-key K]
45
+ [--wait | --no-wait | --callback URL]
46
+ [--out <dir>] [--interval <seconds>] [--timeout <seconds>]
47
+ job list [--limit N] [--cursor C]
48
+ job get <job_id>
49
+ job wait <job_id> [--interval <seconds>] [--timeout <seconds>]
50
+ job cancel <job_id>
51
+ job replay <job_id> --callback URL
52
+ download <job_id> [--out <dir>]
53
+
54
+ Output: stdout is exactly one line of JSON; progress goes to stderr.
55
+ Exit codes: 0 ok / 2 usage / 3 auth / 4 business failure / 5 network or upstream.`;
56
+
57
+ function requireAuth(cfg) {
58
+ if (!cfg.apiKey) {
59
+ throw new CliError({
60
+ code: 'UNAUTHORIZED',
61
+ message: 'no API key configured; run: 5y login --key <API_KEY>',
62
+ retryable: false,
63
+ exitCode: EXIT.AUTH,
64
+ });
65
+ }
66
+ }
67
+
68
+ function expectPositionals(rest, min, max, usage) {
69
+ if (rest.length < min) throw new UsageError(`missing argument. usage: ${usage}`);
70
+ if (rest.length > max) throw new UsageError(`unexpected argument "${rest[max]}". usage: ${usage}`);
71
+ }
72
+
73
+ function validateBaseUrl(value) {
74
+ let parsed;
75
+ try {
76
+ parsed = new URL(value);
77
+ } catch {
78
+ throw new UsageError(`invalid --base-url: ${redactUrl(value)}`);
79
+ }
80
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
81
+ throw new UsageError('--base-url must be http:// or https://');
82
+ }
83
+ return normalizeBaseUrl(value);
84
+ }
85
+
86
+ function validateCallbackUrl(value) {
87
+ let parsed;
88
+ try {
89
+ parsed = new URL(value);
90
+ } catch {
91
+ throw new UsageError(`invalid --callback URL: ${redactUrl(value)}`);
92
+ }
93
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
94
+ throw new UsageError('--callback must be http:// or https://');
95
+ }
96
+ return value;
97
+ }
98
+
99
+ function parseInterval(flags) {
100
+ if (flags.interval === undefined) return 5;
101
+ const seconds = Number(flags.interval);
102
+ if (!Number.isFinite(seconds) || seconds <= 0) {
103
+ throw new UsageError('--interval must be a positive number of seconds');
104
+ }
105
+ return seconds;
106
+ }
107
+
108
+ function parseTimeout(flags) {
109
+ if (flags.timeout === undefined) return 0;
110
+ const seconds = Number(flags.timeout);
111
+ if (!Number.isFinite(seconds) || seconds < 0) {
112
+ throw new UsageError('--timeout must be a non-negative number of seconds');
113
+ }
114
+ return seconds;
115
+ }
116
+
117
+ function parseScalar(raw) {
118
+ if (raw === 'true') return true;
119
+ if (raw === 'false') return false;
120
+ if (raw === 'null') return null;
121
+ if (raw !== '' && /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(raw)) return Number(raw);
122
+ const trimmed = raw.trim();
123
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
124
+ try {
125
+ return JSON.parse(trimmed);
126
+ } catch {
127
+ return raw;
128
+ }
129
+ }
130
+ return raw;
131
+ }
132
+
133
+ function parseParams(entries) {
134
+ const params = Object.create(null);
135
+ for (const entry of entries) {
136
+ const eq = entry.indexOf('=');
137
+ if (eq <= 0) throw new UsageError(`--param expects key=value, got "${entry}"`);
138
+ const key = entry.slice(0, eq);
139
+ params[key] = parseScalar(entry.slice(eq + 1));
140
+ }
141
+ return params;
142
+ }
143
+
144
+ function parseAssets(entries) {
145
+ const assets = Object.create(null);
146
+ for (const entry of entries) {
147
+ const eq = entry.indexOf('=');
148
+ if (eq <= 0) throw new UsageError(`--asset expects key=asset_id, got "${entry}"`);
149
+ const key = entry.slice(0, eq);
150
+ const id = entry.slice(eq + 1);
151
+ if (!id) throw new UsageError(`--asset ${key}= is missing an asset id`);
152
+
153
+ if (key === 'image') {
154
+ if (!assets.images) assets.images = [];
155
+ assets.images.push(id);
156
+ } else if (key === 'video') {
157
+ if (!assets.videos) assets.videos = [];
158
+ assets.videos.push(id);
159
+ } else if (key === 'images' || key === 'videos') {
160
+ if (!assets[key]) assets[key] = [];
161
+ assets[key].push(id);
162
+ } else {
163
+ assets[key] = id;
164
+ }
165
+ }
166
+ return assets;
167
+ }
168
+
169
+ /** Copy known scalar fields to the top level while keeping the full nested object. */
170
+ function pickDefined(source, keys) {
171
+ const out = {};
172
+ if (!source || typeof source !== 'object') return out;
173
+ for (const key of keys) {
174
+ if (Object.prototype.hasOwnProperty.call(source, key)) out[key] = source[key];
175
+ }
176
+ return out;
177
+ }
178
+
179
+ function normalizeList(data, keys) {
180
+ if (Array.isArray(data)) return data;
181
+ if (data && typeof data === 'object') {
182
+ for (const key of keys) {
183
+ if (Array.isArray(data[key])) return data[key];
184
+ }
185
+ }
186
+ return [];
187
+ }
188
+
189
+ function normalizePage(data, keys) {
190
+ if (Array.isArray(data)) return { items: data, next_cursor: null };
191
+ if (!data || typeof data !== 'object') return { items: [], next_cursor: null };
192
+ const items = normalizeList(data, keys);
193
+ const next = data.next_cursor ?? data.nextCursor ?? data.cursor ?? null;
194
+ return { items, next_cursor: next === undefined ? null : next };
195
+ }
196
+
197
+ function resultUrl(job) {
198
+ const result = job && job.result;
199
+ if (!result || typeof result !== 'object') return null;
200
+ return result.url || result.video_url || result.image_url || null;
201
+ }
202
+
203
+ /** The open API returns absolute URLs today; tolerate relative ones without a crash. */
204
+ function absoluteUrl(url, baseUrl) {
205
+ try {
206
+ return new URL(url).toString();
207
+ } catch {
208
+ try {
209
+ return new URL(url, `${normalizeBaseUrl(baseUrl)}/`).toString();
210
+ } catch {
211
+ return url;
212
+ }
213
+ }
214
+ }
215
+
216
+ function chooseFilename(jobId, url, contentType) {
217
+ let base = '';
218
+ try {
219
+ base = path.basename(decodeURIComponent(new URL(url).pathname));
220
+ } catch {
221
+ base = '';
222
+ }
223
+ base = base.replace(/[\\/\0]/g, '').replace(/^\.+/, '');
224
+ if (base && base !== '.' && path.extname(base)) return base;
225
+
226
+ const ext = extensionForContentType(contentType) || 'bin';
227
+ return `${jobId}.${ext}`;
228
+ }
229
+
230
+ async function downloadToDir(url, outDir, jobId) {
231
+ const resolvedDir = path.resolve(outDir);
232
+ fs.mkdirSync(resolvedDir, { recursive: true });
233
+
234
+ const tempPath = path.join(resolvedDir, `.${jobId}.${process.pid}.part`);
235
+ try {
236
+ const result = await downloadToFile(url, tempPath, { timeoutMs: 60000 });
237
+ const filename = chooseFilename(jobId, url, result.contentType);
238
+ const finalPath = path.join(resolvedDir, filename);
239
+ fs.renameSync(tempPath, finalPath);
240
+ return { path: finalPath, bytes: result.bytes, content_type: result.contentType || null };
241
+ } catch (err) {
242
+ try {
243
+ fs.rmSync(tempPath, { force: true });
244
+ } catch {
245
+ // ignore
246
+ }
247
+ throw err;
248
+ }
249
+ }
250
+
251
+ async function pollJob(cfg, jobId, options = {}) {
252
+ const { interval = 5, timeout = 0 } = options;
253
+ const startedAt = Date.now();
254
+ let lastStatus = null;
255
+
256
+ for (;;) {
257
+ const { data, requestId } = await openApi(cfg, {
258
+ path: `/generations/${encodeURIComponent(jobId)}`,
259
+ timeoutMs: 10000,
260
+ label: `GET /generations/${jobId}`,
261
+ });
262
+
263
+ if (!data || typeof data !== 'object') {
264
+ throw new CliError({
265
+ code: 'INTERNAL',
266
+ message: 'invalid job response from server',
267
+ retryable: false,
268
+ requestId,
269
+ exitCode: EXIT.UPSTREAM,
270
+ });
271
+ }
272
+
273
+ const status = data.status || 'unknown';
274
+ if (status !== lastStatus) {
275
+ const progress =
276
+ typeof data.progress === 'number'
277
+ ? ` (${Math.round(data.progress * 100)}%)`
278
+ : '';
279
+ log(`job ${jobId}: ${status}${progress}`);
280
+ lastStatus = status;
281
+ }
282
+
283
+ if (TERMINAL_STATUSES.has(status)) return data;
284
+
285
+ if (timeout > 0 && (Date.now() - startedAt) / 1000 >= timeout) {
286
+ throw new CliError({
287
+ code: 'JOB_TIMEOUT',
288
+ message: `job ${jobId} did not reach a terminal state within ${timeout}s`,
289
+ retryable: true,
290
+ requestId,
291
+ exitCode: EXIT.UPSTREAM,
292
+ details: { job_id: jobId, last_status: status },
293
+ });
294
+ }
295
+
296
+ await new Promise((resolve) => setTimeout(resolve, interval * 1000));
297
+ }
298
+ }
299
+
300
+ function buildCallbackPayload(jobId, job) {
301
+ return {
302
+ event: 'job.finished',
303
+ job_id: jobId,
304
+ status: (job && job.status) || null,
305
+ result: (job && job.result) || null,
306
+ cost: (job && job.cost) || null,
307
+ error: (job && job.error) || null,
308
+ delivered_at: new Date().toISOString(),
309
+ };
310
+ }
311
+
312
+ function getOrCreateCallbackSecret(cfg) {
313
+ if (cfg.callbackSecret) return { secret: cfg.callbackSecret, created: false };
314
+
315
+ const secret = crypto.randomBytes(32).toString('hex');
316
+ saveConfig({ callback_secret: secret });
317
+ log(`callback secret generated (saved to ${cfg.configPath}): ${secret}`);
318
+ return { secret, created: true };
319
+ }
320
+
321
+ async function sendCallback(cfg, callbackUrl, payload) {
322
+ const { secret, created } = getOrCreateCallbackSecret(cfg);
323
+ const result = await deliverCallback(callbackUrl, payload, { secret });
324
+
325
+ if (!result.delivered) {
326
+ log(
327
+ `callback delivery failed after ${result.attempts} attempt(s); job ${payload.job_id} is kept. ` +
328
+ `Replay with: 5y job replay ${payload.job_id} --callback ${redactUrl(callbackUrl)}`,
329
+ );
330
+ }
331
+
332
+ return {
333
+ delivered: result.delivered,
334
+ attempts: result.attempts,
335
+ url: redactUrl(callbackUrl),
336
+ secret_created: created || undefined,
337
+ error: result.delivered
338
+ ? undefined
339
+ : result.error && result.error.message
340
+ ? result.error.message
341
+ : 'callback delivery failed',
342
+ };
343
+ }
344
+
345
+ function jobFailureResult(jobId, job) {
346
+ if (job.status === 'failed') {
347
+ const error = job.error || {};
348
+ const retryable = Boolean(error.retryable);
349
+ return {
350
+ exitCode: retryable ? EXIT.UPSTREAM : EXIT.BUSINESS,
351
+ error: new CliError({
352
+ code: error.code || 'JOB_FAILED',
353
+ message: error.message || 'job failed',
354
+ retryable,
355
+ requestId: error.request_id || null,
356
+ exitCode: retryable ? EXIT.UPSTREAM : EXIT.BUSINESS,
357
+ details: { job_id: jobId, status: job.status },
358
+ }),
359
+ };
360
+ }
361
+
362
+ return {
363
+ exitCode: EXIT.BUSINESS,
364
+ error: new CliError({
365
+ code: 'JOB_CANCELLED',
366
+ message: 'job was cancelled',
367
+ retryable: false,
368
+ exitCode: EXIT.BUSINESS,
369
+ details: { job_id: jobId, status: job.status },
370
+ }),
371
+ };
372
+ }
373
+
374
+ async function runGeneration(cfg, flags, parsed, type) {
375
+ requireAuth(cfg);
376
+
377
+ const prompt = flags.prompt;
378
+ if (typeof prompt !== 'string' || prompt.length === 0) {
379
+ throw new UsageError(`${type} requires --prompt`);
380
+ }
381
+ if (flags.wait === false && flags.callback) {
382
+ throw new UsageError('--no-wait cannot be combined with --callback');
383
+ }
384
+
385
+ const callbackUrl = flags.callback ? validateCallbackUrl(flags.callback) : null;
386
+ const idempotencyKey = flags['idempotency-key'] || crypto.randomUUID();
387
+ if (!idempotencyKey) throw new UsageError('--idempotency-key must not be empty');
388
+
389
+ const body = { type, prompt };
390
+ if (flags.model) body.model = flags.model;
391
+
392
+ const params = parseParams(parsed.params);
393
+ if (Object.keys(params).length) body.params = params;
394
+
395
+ const assets = parseAssets(parsed.assets);
396
+ if (Object.keys(assets).length) body.assets = assets;
397
+
398
+ body.idempotency_key = idempotencyKey;
399
+
400
+ const submit = await openApi(cfg, {
401
+ method: 'POST',
402
+ path: '/generations',
403
+ json: body,
404
+ timeoutMs: 30000,
405
+ label: 'POST /generations',
406
+ });
407
+
408
+ const data = submit.data && typeof submit.data === 'object' ? submit.data : {};
409
+ const jobId = data.job_id || data.id || (data.job && data.job.job_id);
410
+ if (!jobId) {
411
+ throw new CliError({
412
+ code: 'INTERNAL',
413
+ message: 'server response missing job_id',
414
+ retryable: false,
415
+ requestId: submit.requestId,
416
+ exitCode: EXIT.UPSTREAM,
417
+ });
418
+ }
419
+
420
+ let notice = data.notice ? String(data.notice) : null;
421
+ if (!flags.model && data.model) {
422
+ notice = `未指定模型,已使用默认 ${data.model}(可用 --model 指定)`;
423
+ }
424
+ if (notice) log(notice);
425
+
426
+ if (flags.wait === false) {
427
+ emitSuccess({
428
+ job_id: jobId,
429
+ status: data.status || 'queued',
430
+ model: data.model || null,
431
+ estimated_cost: data.estimated_cost ?? null,
432
+ notice: notice || undefined,
433
+ });
434
+ return EXIT.OK;
435
+ }
436
+
437
+ const interval = parseInterval(flags);
438
+ const timeout = parseTimeout(flags);
439
+ const job = await pollJob(cfg, jobId, { interval, timeout });
440
+
441
+ let callbackInfo;
442
+ if (callbackUrl) {
443
+ callbackInfo = await sendCallback(cfg, callbackUrl, buildCallbackPayload(jobId, job));
444
+ }
445
+
446
+ if (job.status === 'succeeded') {
447
+ let downloaded;
448
+ if (flags.out) {
449
+ const url = resultUrl(job);
450
+ if (url) {
451
+ try {
452
+ downloaded = await downloadToDir(absoluteUrl(url, cfg.baseUrl), flags.out, jobId);
453
+ } catch (err) {
454
+ if (err instanceof CliError && err.details === undefined) err.details = { job_id: jobId };
455
+ throw err;
456
+ }
457
+ } else {
458
+ log('job succeeded but the response has no result URL; nothing downloaded');
459
+ }
460
+ }
461
+
462
+ const result = job.result && typeof job.result === 'object' ? { ...job.result } : null;
463
+ if (result && downloaded) result.path = downloaded.path;
464
+
465
+ emitSuccess({
466
+ job_id: jobId,
467
+ status: job.status,
468
+ model: job.model || data.model || null,
469
+ result,
470
+ cost: job.cost || null,
471
+ notice: notice || undefined,
472
+ downloaded: downloaded || undefined,
473
+ callback: callbackInfo,
474
+ });
475
+ return EXIT.OK;
476
+ }
477
+
478
+ const failure = jobFailureResult(jobId, job);
479
+ emitFailure(failure.error);
480
+ return failure.exitCode;
481
+ }
482
+
483
+ function handleHelp() {
484
+ process.stderr.write(`${USAGE}\n`);
485
+ emitSuccess({ usage: USAGE });
486
+ return EXIT.OK;
487
+ }
488
+
489
+ function fail(err) {
490
+ if (err instanceof UsageError) {
491
+ log(err.message);
492
+ process.stderr.write(`${USAGE}\n`);
493
+ emitFailure(
494
+ new CliError({
495
+ code: 'INVALID_ARGS',
496
+ message: err.message,
497
+ retryable: false,
498
+ exitCode: EXIT.USAGE,
499
+ }),
500
+ );
501
+ return EXIT.USAGE;
502
+ }
503
+
504
+ const cliError =
505
+ err instanceof CliError
506
+ ? err
507
+ : new CliError({
508
+ code: 'INTERNAL',
509
+ message: err && err.message ? err.message : String(err),
510
+ retryable: false,
511
+ exitCode: EXIT.BUSINESS,
512
+ });
513
+
514
+ log(`error: ${cliError.message}`);
515
+ if (cliError.requestId) log(`request_id: ${cliError.requestId}`);
516
+ emitFailure(cliError);
517
+ return cliError.exitCode || EXIT.BUSINESS;
518
+ }
519
+
520
+ export async function run(argv) {
521
+ let parsed;
522
+ try {
523
+ parsed = parseArgs(argv);
524
+ const { flags, positionals } = parsed;
525
+
526
+ if (flags.version) {
527
+ emitSuccess({ version: VERSION });
528
+ return EXIT.OK;
529
+ }
530
+ if (flags.help || positionals.length === 0 || positionals[0] === 'help') {
531
+ return handleHelp();
532
+ }
533
+
534
+ const cfg = loadRuntimeConfig(flags);
535
+ const [command, ...rest] = positionals;
536
+
537
+ switch (command) {
538
+ case 'login': {
539
+ expectPositionals(rest, 0, 0, '5y login --key <API_KEY>');
540
+ if (!flags.key || !String(flags.key).trim()) {
541
+ throw new UsageError('login requires --key <API_KEY>');
542
+ }
543
+ const updates = { api_key: String(flags.key).trim() };
544
+ let baseUrl = cfg.baseUrl;
545
+ if (flags['base-url']) {
546
+ baseUrl = validateBaseUrl(flags['base-url']);
547
+ updates.base_url = baseUrl;
548
+ }
549
+ saveConfig(updates);
550
+ emitSuccess({
551
+ config_path: cfg.configPath,
552
+ base_url: baseUrl,
553
+ key_prefix: keyPrefix(updates.api_key),
554
+ });
555
+ return EXIT.OK;
556
+ }
557
+
558
+ case 'whoami': {
559
+ expectPositionals(rest, 0, 0, '5y whoami');
560
+ requireAuth(cfg);
561
+ // 服务端 `/open/v1/me` 是真相(身份/工作区/限流);离线时退回本地配置。
562
+ let server = null;
563
+ let offline = false;
564
+ try {
565
+ const me = await openApi(cfg, { path: '/me', timeoutMs: 10000 });
566
+ server = me && (me.data || me);
567
+ } catch (err) {
568
+ // 只有「鉴权失败」要往上抛(key 无效就是无效);
569
+ // 其余(网络/5xx/端点暂不可用)都退回本地信息,whoami 不该因后端掉线而失败。
570
+ if (err instanceof CliError && err.exitCode === EXIT.AUTH) throw err;
571
+ offline = true;
572
+ }
573
+ emitSuccess({
574
+ key_prefix: keyPrefix(cfg.apiKey),
575
+ base_url: cfg.baseUrl,
576
+ config_path: cfg.configPath,
577
+ callback_configured: Boolean(cfg.callbackSecret),
578
+ offline,
579
+ user: server ? server.user : null,
580
+ key: server ? server.key : null,
581
+ });
582
+ return EXIT.OK;
583
+ }
584
+
585
+ case 'models': {
586
+ expectPositionals(rest, 0, 0, '5y models [--type image|video]');
587
+ requireAuth(cfg);
588
+ const type = flags.type;
589
+ if (type !== undefined && type !== 'image' && type !== 'video') {
590
+ throw new UsageError('--type must be image or video');
591
+ }
592
+ const { data } = await openApi(cfg, { path: '/models', timeoutMs: 10000 });
593
+ let models = normalizeList(data, ['models', 'data', 'items']);
594
+ if (type) {
595
+ models = models.filter((model) => (model && (model.type || model.task_type)) === type);
596
+ }
597
+ emitSuccess({ models, count: models.length, type: type || null });
598
+ return EXIT.OK;
599
+ }
600
+
601
+ case 'upload': {
602
+ expectPositionals(rest, 1, 1, '5y upload <file> [--name <name>]');
603
+ requireAuth(cfg);
604
+ const filePath = rest[0];
605
+ let stat;
606
+ try {
607
+ stat = fs.statSync(filePath);
608
+ } catch {
609
+ throw new UsageError(`file not found: ${filePath}`);
610
+ }
611
+ if (!stat.isFile()) throw new UsageError(`not a file: ${filePath}`);
612
+
613
+ const fields = {};
614
+ if (flags.name) fields.name = flags.name;
615
+
616
+ const { data } = await openApi(cfg, {
617
+ method: 'POST',
618
+ path: '/assets',
619
+ multipart: makeMultipart(filePath, {
620
+ fieldName: 'file',
621
+ filename: flags.name || path.basename(filePath),
622
+ fields,
623
+ }),
624
+ timeoutMs: 60000,
625
+ label: 'POST /assets',
626
+ });
627
+ emitSuccess({
628
+ ...pickDefined(data, [
629
+ 'asset_id',
630
+ 'url',
631
+ 'type',
632
+ 'thumbnail_url',
633
+ 'width',
634
+ 'height',
635
+ 'duration_seconds',
636
+ 'size_bytes',
637
+ ]),
638
+ asset: data,
639
+ });
640
+ return EXIT.OK;
641
+ }
642
+
643
+ case 'assets': {
644
+ requireAuth(cfg);
645
+ const [sub, ...args] = rest;
646
+ if (!sub) {
647
+ throw new UsageError('usage: 5y assets list|get|delete');
648
+ }
649
+
650
+ if (sub === 'list') {
651
+ expectPositionals(args, 0, 0, '5y assets list [--type T] [--limit N] [--cursor C]');
652
+ const { data } = await openApi(cfg, {
653
+ path: '/assets',
654
+ query: { type: flags.type, limit: flags.limit, cursor: flags.cursor },
655
+ timeoutMs: 10000,
656
+ });
657
+ const page = normalizePage(data, ['assets', 'items', 'data']);
658
+ emitSuccess({ assets: page.items, next_cursor: page.next_cursor });
659
+ return EXIT.OK;
660
+ }
661
+
662
+ if (sub === 'get') {
663
+ expectPositionals(args, 1, 1, '5y assets get <asset_id>');
664
+ const { data } = await openApi(cfg, {
665
+ path: `/assets/${encodeURIComponent(args[0])}`,
666
+ timeoutMs: 10000,
667
+ });
668
+ emitSuccess({
669
+ ...pickDefined(data, [
670
+ 'asset_id',
671
+ 'url',
672
+ 'type',
673
+ 'thumbnail_url',
674
+ 'width',
675
+ 'height',
676
+ 'size_bytes',
677
+ 'created_at',
678
+ ]),
679
+ asset: data,
680
+ });
681
+ return EXIT.OK;
682
+ }
683
+
684
+ if (sub === 'delete') {
685
+ expectPositionals(args, 1, 1, '5y assets delete <asset_id>');
686
+ const { data } = await openApi(cfg, {
687
+ method: 'DELETE',
688
+ path: `/assets/${encodeURIComponent(args[0])}`,
689
+ timeoutMs: 10000,
690
+ });
691
+ emitSuccess({ asset_id: args[0], deleted: true, asset: data || null });
692
+ return EXIT.OK;
693
+ }
694
+
695
+ throw new UsageError(`unknown assets subcommand "${sub}". usage: list|get|delete`);
696
+ }
697
+
698
+ case 'image':
699
+ case 'video': {
700
+ expectPositionals(rest, 0, 0, `5y ${command} --prompt <text>`);
701
+ return await runGeneration(cfg, flags, parsed, command);
702
+ }
703
+
704
+ case 'job': {
705
+ requireAuth(cfg);
706
+ const [sub, ...args] = rest;
707
+ if (!sub) throw new UsageError('usage: 5y job list|get|wait|cancel|replay');
708
+
709
+ if (sub === 'list') {
710
+ expectPositionals(args, 0, 0, '5y job list [--limit N] [--cursor C]');
711
+ const { data } = await openApi(cfg, {
712
+ path: '/generations',
713
+ query: { limit: flags.limit, cursor: flags.cursor },
714
+ timeoutMs: 10000,
715
+ });
716
+ const page = normalizePage(data, ['jobs', 'generations', 'items', 'data']);
717
+ emitSuccess({ jobs: page.items, next_cursor: page.next_cursor });
718
+ return EXIT.OK;
719
+ }
720
+
721
+ if (sub === 'get') {
722
+ expectPositionals(args, 1, 1, '5y job get <job_id>');
723
+ const { data } = await openApi(cfg, {
724
+ path: `/generations/${encodeURIComponent(args[0])}`,
725
+ timeoutMs: 10000,
726
+ });
727
+ emitSuccess({
728
+ ...pickDefined(data, [
729
+ 'job_id',
730
+ 'status',
731
+ 'progress',
732
+ 'model',
733
+ 'result',
734
+ 'cost',
735
+ 'error',
736
+ 'created_at',
737
+ 'completed_at',
738
+ ]),
739
+ job: data,
740
+ });
741
+ return EXIT.OK;
742
+ }
743
+
744
+ if (sub === 'wait') {
745
+ expectPositionals(args, 1, 1, '5y job wait <job_id> [--interval S] [--timeout S]');
746
+ const jobId = args[0];
747
+ const job = await pollJob(cfg, jobId, {
748
+ interval: parseInterval(flags),
749
+ timeout: parseTimeout(flags),
750
+ });
751
+ if (job.status === 'succeeded') {
752
+ emitSuccess({
753
+ ...pickDefined(job, [
754
+ 'job_id',
755
+ 'status',
756
+ 'progress',
757
+ 'model',
758
+ 'result',
759
+ 'cost',
760
+ 'error',
761
+ 'created_at',
762
+ 'completed_at',
763
+ ]),
764
+ job,
765
+ });
766
+ return EXIT.OK;
767
+ }
768
+ const failure = jobFailureResult(jobId, job);
769
+ emitFailure(failure.error);
770
+ return failure.exitCode;
771
+ }
772
+
773
+ if (sub === 'cancel') {
774
+ expectPositionals(args, 1, 1, '5y job cancel <job_id>');
775
+ const jobId = args[0];
776
+ const { data } = await openApi(cfg, {
777
+ method: 'POST',
778
+ path: `/generations/${encodeURIComponent(jobId)}/cancel`,
779
+ timeoutMs: 10000,
780
+ });
781
+ emitSuccess({ job_id: jobId, cancelled: true, job: data || null });
782
+ return EXIT.OK;
783
+ }
784
+
785
+ if (sub === 'replay') {
786
+ expectPositionals(args, 1, 1, '5y job replay <job_id> --callback URL');
787
+ if (!flags.callback) throw new UsageError('job replay requires --callback URL');
788
+ const callbackUrl = validateCallbackUrl(flags.callback);
789
+ const jobId = args[0];
790
+ const { data: job } = await openApi(cfg, {
791
+ path: `/generations/${encodeURIComponent(jobId)}`,
792
+ timeoutMs: 10000,
793
+ });
794
+
795
+ if (!job || typeof job !== 'object' || !TERMINAL_STATUSES.has(job.status)) {
796
+ throw new CliError({
797
+ code: 'JOB_NOT_FINISHED',
798
+ message: `job ${jobId} is not in a terminal state`,
799
+ retryable: false,
800
+ exitCode: EXIT.BUSINESS,
801
+ details: { job_id: jobId, status: job && job.status },
802
+ });
803
+ }
804
+
805
+ const info = await sendCallback(cfg, callbackUrl, buildCallbackPayload(jobId, job));
806
+ if (!info.delivered) {
807
+ throw new CliError({
808
+ code: 'CALLBACK_FAILED',
809
+ message: `callback delivery failed after ${info.attempts} attempt(s)`,
810
+ retryable: true,
811
+ exitCode: EXIT.UPSTREAM,
812
+ details: { job_id: jobId, callback_url: info.url },
813
+ });
814
+ }
815
+
816
+ emitSuccess({
817
+ job_id: jobId,
818
+ delivered: true,
819
+ attempts: info.attempts,
820
+ callback_url: info.url,
821
+ secret_created: info.secret_created,
822
+ });
823
+ return EXIT.OK;
824
+ }
825
+
826
+ throw new UsageError(`unknown job subcommand "${sub}". usage: list|get|wait|cancel|replay`);
827
+ }
828
+
829
+ case 'download': {
830
+ expectPositionals(rest, 1, 1, '5y download <job_id> [--out <dir>]');
831
+ requireAuth(cfg);
832
+ const jobId = rest[0];
833
+ const outDir = flags.out || './5y-output';
834
+
835
+ const { data: job } = await openApi(cfg, {
836
+ path: `/generations/${encodeURIComponent(jobId)}`,
837
+ timeoutMs: 10000,
838
+ });
839
+
840
+ if (!job || typeof job !== 'object' || job.status !== 'succeeded') {
841
+ throw new CliError({
842
+ code: 'JOB_NOT_READY',
843
+ message: `job ${jobId} is not succeeded; nothing to download`,
844
+ retryable: false,
845
+ exitCode: EXIT.BUSINESS,
846
+ details: { job_id: jobId, status: job && job.status },
847
+ });
848
+ }
849
+
850
+ const rawUrl = resultUrl(job);
851
+ if (!rawUrl) {
852
+ throw new CliError({
853
+ code: 'NO_RESULT_URL',
854
+ message: `job ${jobId} has no result URL`,
855
+ retryable: false,
856
+ exitCode: EXIT.BUSINESS,
857
+ details: { job_id: jobId },
858
+ });
859
+ }
860
+ const url = absoluteUrl(rawUrl, cfg.baseUrl);
861
+
862
+ let downloaded;
863
+ try {
864
+ downloaded = await downloadToDir(url, outDir, jobId);
865
+ } catch (err) {
866
+ if (err instanceof CliError && err.details === undefined) err.details = { job_id: jobId };
867
+ throw err;
868
+ }
869
+ emitSuccess({
870
+ job_id: jobId,
871
+ url,
872
+ path: downloaded.path,
873
+ bytes: downloaded.bytes,
874
+ content_type: downloaded.content_type,
875
+ });
876
+ return EXIT.OK;
877
+ }
878
+
879
+ default:
880
+ throw new UsageError(`unknown command "${command}"`);
881
+ }
882
+ } catch (err) {
883
+ return fail(err);
884
+ }
885
+ }
886
+
887
+ export { USAGE };