mmx-cli 1.0.19 → 1.0.21

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.
package/dist/sdk.mjs CHANGED
@@ -64,8 +64,6 @@ function parseConfigFile(raw) {
64
64
  out.default_speech_model = obj.default_speech_model;
65
65
  if (typeof obj.default_video_model === "string" && obj.default_video_model.length > 0)
66
66
  out.default_video_model = obj.default_video_model;
67
- if (typeof obj.default_music_model === "string" && obj.default_music_model.length > 0)
68
- out.default_music_model = obj.default_music_model;
69
67
  return out;
70
68
  }
71
69
 
@@ -284,7 +282,6 @@ function loadConfig(flags) {
284
282
  defaultTextModel: file.default_text_model,
285
283
  defaultSpeechModel: file.default_speech_model,
286
284
  defaultVideoModel: file.default_video_model,
287
- defaultMusicModel: file.default_music_model,
288
285
  verbose: flags.verbose || process.env.MINIMAX_VERBOSE === "1",
289
286
  quiet: flags.quiet || false,
290
287
  noColor: flags.noColor || process.env.NO_COLOR !== undefined || !process.stdout.isTTY,
@@ -418,10 +415,6 @@ image-01 requires the Plus plan or above.`;
418
415
  return `
419
416
 
420
417
  Video models (Hailuo-2.3 / 2.3-Fast) require the Max plan or above.`;
421
- if (url.includes("/music_generation"))
422
- return `
423
-
424
- Music-2.6 requires the Max plan or above.`;
425
418
  return "";
426
419
  }
427
420
  function upgradeUrl(url) {
@@ -431,6 +424,7 @@ function upgradeUrl(url) {
431
424
  function mapApiError(status, body, url) {
432
425
  const apiMsg = body.base_resp?.status_msg || body.error?.message || `HTTP ${status}`;
433
426
  const apiCode = body.base_resp?.status_code || body.error?.code;
427
+ const errorType = body.error?.type;
434
428
  if (status === 401 || status === 403) {
435
429
  return new CLIError(`API key rejected (HTTP ${status}).`, ExitCode.AUTH, `Check status: mmx auth status
436
430
  Re-authenticate: mmx auth login`);
@@ -438,11 +432,15 @@ Re-authenticate: mmx auth login`);
438
432
  if (status === 429) {
439
433
  return new CLIError(`Rate limit or quota exceeded. ${apiMsg}`, ExitCode.QUOTA, "Check usage: mmx quota show");
440
434
  }
435
+ if (status === 402 || errorType === "insufficient_balance_error") {
436
+ return new CLIError(`Quota or balance exhausted. ${apiMsg}`, ExitCode.QUOTA, "Check your MiniMax account balance and billing settings.");
437
+ }
441
438
  if (status === 408 || status === 504) {
442
439
  return new CLIError(`Request timed out (HTTP ${status}).`, ExitCode.TIMEOUT, "Try increasing --timeout or retry later.");
443
440
  }
444
- if (apiCode === 1002 || apiCode === 1039) {
445
- const filterType = body.base_resp?.status_msg || "content sensitivity";
441
+ const isV2ContentFilter = status === 422 && errorType === "unprocessable_entity_error" && (/sensitive content/i.test(apiMsg) || /(?:^|\D)1026(?:\D|$)/.test(apiMsg));
442
+ if (apiCode === 1002 || apiCode === 1039 || isV2ContentFilter) {
443
+ const filterType = body.base_resp?.status_msg || body.error?.message || "content sensitivity";
446
444
  return new CLIError(`Input content flagged by sensitivity filter (${filterType}).`, ExitCode.CONTENT_FILTER);
447
445
  }
448
446
  if (apiCode === 1028 || apiCode === 1030) {
@@ -496,7 +494,7 @@ function maybeShowStatusBar(config, token, model) {
496
494
  // package.json
497
495
  var package_default = {
498
496
  name: "mmx-cli",
499
- version: "1.0.19",
497
+ version: "1.0.21",
500
498
  description: "CLI for the MiniMax AI Platform",
501
499
  type: "module",
502
500
  repository: {
@@ -554,6 +552,71 @@ var package_default = {
554
552
  var CLI_VERSION = process.env.CLI_VERSION ?? package_default.version;
555
553
 
556
554
  // src/client/http.ts
555
+ function timeoutError(message) {
556
+ return new DOMException(message, "TimeoutError");
557
+ }
558
+ function withIdleTimeout(response, timeoutMs, abortController) {
559
+ if (!response.body)
560
+ return response;
561
+ const reader = response.body.getReader();
562
+ let released = false;
563
+ const releaseReader = () => {
564
+ if (released)
565
+ return;
566
+ released = true;
567
+ reader.releaseLock();
568
+ };
569
+ const cancelRequest = async (reason) => {
570
+ if (!abortController.signal.aborted)
571
+ abortController.abort(reason);
572
+ try {
573
+ await reader.cancel(reason);
574
+ } finally {
575
+ releaseReader();
576
+ }
577
+ };
578
+ const body = new ReadableStream({
579
+ async pull(controller) {
580
+ let timer;
581
+ try {
582
+ const result = await new Promise((resolve, reject) => {
583
+ timer = setTimeout(() => {
584
+ const error = timeoutError(`Stream received no data for ${timeoutMs}ms.`);
585
+ abortController.abort(error);
586
+ reject(error);
587
+ }, timeoutMs);
588
+ reader.read().then(resolve, reject);
589
+ });
590
+ if (result.done) {
591
+ releaseReader();
592
+ controller.close();
593
+ } else {
594
+ controller.enqueue(result.value);
595
+ }
596
+ } catch (error) {
597
+ await cancelRequest(error).catch(() => {});
598
+ controller.error(error);
599
+ } finally {
600
+ if (timer)
601
+ clearTimeout(timer);
602
+ }
603
+ },
604
+ cancel(reason) {
605
+ return cancelRequest(reason);
606
+ }
607
+ });
608
+ const timedResponse = new Response(body, {
609
+ status: response.status,
610
+ statusText: response.statusText,
611
+ headers: response.headers
612
+ });
613
+ Object.defineProperties(timedResponse, {
614
+ url: { value: response.url },
615
+ redirected: { value: response.redirected },
616
+ type: { value: response.type }
617
+ });
618
+ return timedResponse;
619
+ }
557
620
  async function request(config, opts) {
558
621
  const isFormData = typeof FormData !== "undefined" && opts.body instanceof FormData;
559
622
  const headers = {
@@ -580,12 +643,25 @@ async function request(config, opts) {
580
643
  maybeShowStatusBar(config, credential.token, model);
581
644
  }
582
645
  const timeoutMs = (opts.timeout ?? config.timeout) * 1000;
583
- const res = await fetch(opts.url, {
584
- method: opts.method ?? "GET",
585
- headers,
586
- body: opts.body ? isFormData ? opts.body : JSON.stringify(opts.body) : undefined,
587
- signal: opts.stream ? undefined : AbortSignal.timeout(timeoutMs)
588
- });
646
+ const streamAbortController = opts.stream ? new AbortController : undefined;
647
+ const headerTimeout = streamAbortController ? setTimeout(() => {
648
+ streamAbortController.abort(timeoutError(`Request headers were not received within ${timeoutMs}ms.`));
649
+ }, timeoutMs) : undefined;
650
+ let res;
651
+ try {
652
+ res = await fetch(opts.url, {
653
+ method: opts.method ?? "GET",
654
+ headers,
655
+ body: opts.body ? isFormData ? opts.body : JSON.stringify(opts.body) : undefined,
656
+ signal: streamAbortController?.signal ?? AbortSignal.timeout(timeoutMs)
657
+ });
658
+ } finally {
659
+ if (headerTimeout)
660
+ clearTimeout(headerTimeout);
661
+ }
662
+ if (streamAbortController) {
663
+ res = withIdleTimeout(res, timeoutMs, streamAbortController);
664
+ }
589
665
  if (config.verbose) {
590
666
  process.stderr.write(`< ${res.status} ${res.statusText}
591
667
  `);
@@ -749,9 +825,6 @@ function videoTaskV2Endpoint(baseUrl, taskId) {
749
825
  function fileRetrieveEndpoint(baseUrl, fileId) {
750
826
  return `${baseUrl}/v1/files/retrieve?file_id=${fileId}`;
751
827
  }
752
- function musicEndpoint(baseUrl) {
753
- return `${baseUrl}/v1/music_generation`;
754
- }
755
828
  function searchEndpoint(baseUrl) {
756
829
  return `${baseUrl}/v1/coding_plan/search`;
757
830
  }
@@ -1172,89 +1245,358 @@ function createProgressBar(total, label = "") {
1172
1245
  }
1173
1246
 
1174
1247
  // src/files/download.ts
1248
+ var DEFAULT_OVERALL_TIMEOUT_MS = 30 * 60 * 1000;
1249
+ var DEFAULT_IDLE_TIMEOUT_MS = 60 * 1000;
1250
+ var DEFAULT_MAX_BYTES = 5 * 1024 * 1024 * 1024;
1251
+ var CLEANUP_TIMEOUT_MS = 1000;
1252
+
1253
+ class RetryableDownloadError extends CLIError {
1254
+ retryAfterMs;
1255
+ constructor(message, exitCode = ExitCode.NETWORK, retryAfterMs) {
1256
+ super(message, exitCode);
1257
+ this.retryAfterMs = retryAfterMs;
1258
+ }
1259
+ }
1260
+
1261
+ class DownloadHttpError extends CLIError {
1262
+ retryable;
1263
+ retryAfterMs;
1264
+ constructor(status, retryAfterMs) {
1265
+ super(`Download failed: HTTP ${status}`, ExitCode.GENERAL);
1266
+ this.retryable = status === 408 || status === 429 || status >= 500;
1267
+ this.retryAfterMs = retryAfterMs;
1268
+ }
1269
+ }
1270
+ function positiveNumber(value, name) {
1271
+ if (!Number.isFinite(value) || value <= 0) {
1272
+ throw new CLIError(`${name} must be a positive number.`, ExitCode.USAGE);
1273
+ }
1274
+ return value;
1275
+ }
1276
+ function nonNegativeInteger(value, name) {
1277
+ if (!Number.isInteger(value) || value < 0) {
1278
+ throw new CLIError(`${name} must be a non-negative integer.`, ExitCode.USAGE);
1279
+ }
1280
+ return value;
1281
+ }
1282
+ function nonNegativeNumber(value, name) {
1283
+ if (!Number.isFinite(value) || value < 0) {
1284
+ throw new CLIError(`${name} must be a non-negative number.`, ExitCode.USAGE);
1285
+ }
1286
+ return value;
1287
+ }
1288
+ function abortReason(signal, fallback) {
1289
+ return signal.reason instanceof Error ? signal.reason : new CLIError(fallback, ExitCode.GENERAL);
1290
+ }
1291
+ function parseRetryAfter(value) {
1292
+ if (!value)
1293
+ return;
1294
+ const seconds = Number(value);
1295
+ if (Number.isFinite(seconds) && seconds >= 0)
1296
+ return seconds * 1000;
1297
+ const timestamp = Date.parse(value);
1298
+ if (!Number.isFinite(timestamp))
1299
+ return;
1300
+ return Math.max(0, timestamp - Date.now());
1301
+ }
1302
+ function parseContentLength(value) {
1303
+ if (!value || !/^\d+$/.test(value))
1304
+ return;
1305
+ const length = BigInt(value);
1306
+ return length <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(length) : Number.POSITIVE_INFINITY;
1307
+ }
1308
+ async function waitForDelay(delayMs, signal) {
1309
+ if (signal.aborted)
1310
+ throw abortReason(signal, "Download aborted.");
1311
+ if (delayMs <= 0)
1312
+ return;
1313
+ await new Promise((resolve2, reject) => {
1314
+ const timer = setTimeout(() => {
1315
+ signal.removeEventListener("abort", onAbort);
1316
+ resolve2();
1317
+ }, delayMs);
1318
+ const onAbort = () => {
1319
+ clearTimeout(timer);
1320
+ reject(abortReason(signal, "Download aborted."));
1321
+ };
1322
+ signal.addEventListener("abort", onAbort, { once: true });
1323
+ });
1324
+ }
1325
+ async function withIdleTimeout2(operation, controller, idleTimeoutMs, phase, retryable = true) {
1326
+ if (controller.signal.aborted) {
1327
+ throw abortReason(controller.signal, "Download aborted.");
1328
+ }
1329
+ let timer;
1330
+ let onAbort;
1331
+ const timeout = new Promise((_, reject) => {
1332
+ timer = setTimeout(() => {
1333
+ const error = retryable ? new RetryableDownloadError(`Download idle timeout while ${phase} after ${idleTimeoutMs}ms.`, ExitCode.TIMEOUT) : new CLIError(`Download idle timeout while ${phase} after ${idleTimeoutMs}ms.`, ExitCode.TIMEOUT);
1334
+ controller.abort(error);
1335
+ reject(error);
1336
+ }, idleTimeoutMs);
1337
+ });
1338
+ const aborted = new Promise((_, reject) => {
1339
+ onAbort = () => reject(abortReason(controller.signal, "Download aborted."));
1340
+ controller.signal.addEventListener("abort", onAbort, { once: true });
1341
+ });
1342
+ try {
1343
+ return await Promise.race([operation, timeout, aborted]);
1344
+ } catch (error) {
1345
+ if (controller.signal.aborted) {
1346
+ throw abortReason(controller.signal, "Download aborted.");
1347
+ }
1348
+ throw error;
1349
+ } finally {
1350
+ if (timer)
1351
+ clearTimeout(timer);
1352
+ if (onAbort)
1353
+ controller.signal.removeEventListener("abort", onAbort);
1354
+ }
1355
+ }
1356
+ async function waitForDrain(writer, controller, idleTimeoutMs) {
1357
+ const drain = new Promise((resolve2, reject) => {
1358
+ const onDrain = () => finish(resolve2);
1359
+ const onError = (error) => finish(() => reject(error));
1360
+ const onClose = () => finish(() => reject(new Error("File writer closed before draining.")));
1361
+ const finish = (done) => {
1362
+ writer.off("drain", onDrain);
1363
+ writer.off("error", onError);
1364
+ writer.off("close", onClose);
1365
+ done();
1366
+ };
1367
+ writer.once("drain", onDrain);
1368
+ writer.once("error", onError);
1369
+ writer.once("close", onClose);
1370
+ });
1371
+ try {
1372
+ await withIdleTimeout2(drain, controller, idleTimeoutMs, "waiting for disk writes", false);
1373
+ } catch (error) {
1374
+ if (error instanceof CLIError)
1375
+ throw error;
1376
+ throw new CLIError(`Could not write download: ${error instanceof Error ? error.message : String(error)}`, ExitCode.GENERAL);
1377
+ }
1378
+ }
1379
+ async function finishWriter(writer, controller, idleTimeoutMs) {
1380
+ const finished = new Promise((resolve2, reject) => {
1381
+ const onFinish = () => finish(resolve2);
1382
+ const onError = (error) => finish(() => reject(error));
1383
+ const onClose = () => {
1384
+ if (!writer.writableFinished)
1385
+ finish(() => reject(new Error("File writer closed early.")));
1386
+ };
1387
+ const finish = (done) => {
1388
+ writer.off("finish", onFinish);
1389
+ writer.off("error", onError);
1390
+ writer.off("close", onClose);
1391
+ done();
1392
+ };
1393
+ writer.once("finish", onFinish);
1394
+ writer.once("error", onError);
1395
+ writer.once("close", onClose);
1396
+ writer.end();
1397
+ });
1398
+ try {
1399
+ await withIdleTimeout2(finished, controller, idleTimeoutMs, "finishing disk writes", false);
1400
+ } catch (error) {
1401
+ if (error instanceof CLIError)
1402
+ throw error;
1403
+ throw new CLIError(`Could not write download: ${error instanceof Error ? error.message : String(error)}`, ExitCode.GENERAL);
1404
+ }
1405
+ }
1406
+ async function destroyWriter(writer) {
1407
+ if (writer.closed)
1408
+ return;
1409
+ await new Promise((resolve2) => {
1410
+ const timer = setTimeout(() => {
1411
+ writer.off("close", onClose);
1412
+ resolve2();
1413
+ }, CLEANUP_TIMEOUT_MS);
1414
+ const onClose = () => {
1415
+ clearTimeout(timer);
1416
+ resolve2();
1417
+ };
1418
+ writer.once("close", onClose);
1419
+ writer.destroy();
1420
+ });
1421
+ }
1422
+ async function settleCleanup(operation) {
1423
+ let timer;
1424
+ await Promise.race([
1425
+ operation.catch(() => {
1426
+ return;
1427
+ }),
1428
+ new Promise((resolve2) => {
1429
+ timer = setTimeout(resolve2, CLEANUP_TIMEOUT_MS);
1430
+ })
1431
+ ]);
1432
+ if (timer)
1433
+ clearTimeout(timer);
1434
+ }
1435
+ async function attemptDownload(downloadUrl, destPath, attempt, opts, overallSignal) {
1436
+ const controller = new AbortController;
1437
+ const abortAttempt = () => controller.abort(abortReason(overallSignal, "Download aborted."));
1438
+ if (overallSignal.aborted)
1439
+ abortAttempt();
1440
+ else
1441
+ overallSignal.addEventListener("abort", abortAttempt, { once: true });
1442
+ let response;
1443
+ let reader;
1444
+ let writer;
1445
+ let tmpPath;
1446
+ let progress = null;
1447
+ let succeeded = false;
1448
+ try {
1449
+ try {
1450
+ response = await withIdleTimeout2(fetch(downloadUrl, { signal: controller.signal }), controller, opts.idleTimeoutMs, "waiting for response headers");
1451
+ } catch (error) {
1452
+ if (error instanceof CLIError)
1453
+ throw error;
1454
+ throw new RetryableDownloadError(`Download request failed: ${error instanceof Error ? error.message : String(error)}`);
1455
+ }
1456
+ if (!response.ok) {
1457
+ throw new DownloadHttpError(response.status, parseRetryAfter(response.headers.get("retry-after")));
1458
+ }
1459
+ const declaredLength = parseContentLength(response.headers.get("content-length"));
1460
+ if (declaredLength !== undefined && declaredLength > opts.maxBytes) {
1461
+ throw new CLIError(`Download exceeds maximum size of ${opts.maxBytes} bytes (Content-Length: ${declaredLength}).`, ExitCode.GENERAL);
1462
+ }
1463
+ reader = response.body?.getReader();
1464
+ if (!reader)
1465
+ throw new CLIError("Download response has no body.", ExitCode.GENERAL);
1466
+ const expectedLength = response.headers.get("content-encoding") ? undefined : declaredLength;
1467
+ tmpPath = `${destPath}.tmp-${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;
1468
+ writer = createWriteStream(tmpPath);
1469
+ progress = expectedLength && !opts.quiet ? createProgressBar(expectedLength, "Downloading") : null;
1470
+ let writerError;
1471
+ const writerFailed = new Promise((_, reject) => {
1472
+ writer.once("error", (error) => {
1473
+ writerError = error;
1474
+ reject(error);
1475
+ });
1476
+ });
1477
+ writerFailed.catch(() => {
1478
+ return;
1479
+ });
1480
+ let received = 0;
1481
+ while (true) {
1482
+ let result;
1483
+ try {
1484
+ result = await withIdleTimeout2(Promise.race([reader.read(), writerFailed]), controller, opts.idleTimeoutMs, "waiting for response data");
1485
+ } catch (error) {
1486
+ if (writerError) {
1487
+ throw new CLIError(`Could not write download: ${writerError.message}`, ExitCode.GENERAL);
1488
+ }
1489
+ if (error instanceof CLIError)
1490
+ throw error;
1491
+ throw new RetryableDownloadError(`Download stream failed: ${error instanceof Error ? error.message : String(error)}`);
1492
+ }
1493
+ if (result.done)
1494
+ break;
1495
+ const nextSize = received + result.value.byteLength;
1496
+ if (nextSize > opts.maxBytes) {
1497
+ throw new CLIError(`Download exceeds maximum size of ${opts.maxBytes} bytes.`, ExitCode.GENERAL);
1498
+ }
1499
+ let accepted;
1500
+ try {
1501
+ accepted = writer.write(result.value);
1502
+ } catch (error) {
1503
+ throw new CLIError(`Could not write download: ${error instanceof Error ? error.message : String(error)}`, ExitCode.GENERAL);
1504
+ }
1505
+ if (!accepted)
1506
+ await waitForDrain(writer, controller, opts.idleTimeoutMs);
1507
+ received = nextSize;
1508
+ progress?.update(received);
1509
+ }
1510
+ if (expectedLength !== undefined && received !== expectedLength) {
1511
+ throw new RetryableDownloadError(`Download truncated: expected ${expectedLength} bytes, received ${received}.`);
1512
+ }
1513
+ await finishWriter(writer, controller, opts.idleTimeoutMs);
1514
+ writer = undefined;
1515
+ reader.releaseLock();
1516
+ reader = undefined;
1517
+ renameSync2(tmpPath, destPath);
1518
+ tmpPath = undefined;
1519
+ succeeded = true;
1520
+ return { size: received };
1521
+ } finally {
1522
+ overallSignal.removeEventListener("abort", abortAttempt);
1523
+ progress?.finish();
1524
+ if (!succeeded) {
1525
+ if (reader) {
1526
+ await settleCleanup(reader.cancel(controller.signal.reason));
1527
+ try {
1528
+ reader.releaseLock();
1529
+ } catch {}
1530
+ } else if (response?.body) {
1531
+ await settleCleanup(response.body.cancel(controller.signal.reason));
1532
+ }
1533
+ if (writer)
1534
+ await destroyWriter(writer);
1535
+ if (tmpPath) {
1536
+ try {
1537
+ unlinkSync2(tmpPath);
1538
+ } catch {}
1539
+ }
1540
+ }
1541
+ }
1542
+ }
1175
1543
  async function downloadFile(url, destPath, opts) {
1176
1544
  const downloadUrl = url.startsWith("http://") ? url.replace("http://", "https://") : url;
1177
- const maxRetries = opts?.retries ?? 3;
1178
- const baseDelay = opts?.retryDelayMs ?? 1000;
1545
+ const maxRetries = nonNegativeInteger(opts?.retries ?? 3, "retries");
1546
+ const baseDelay = nonNegativeNumber(opts?.retryDelayMs ?? 1000, "retryDelayMs");
1547
+ const overallTimeoutMs = positiveNumber(opts?.overallTimeoutMs ?? DEFAULT_OVERALL_TIMEOUT_MS, "overallTimeoutMs");
1548
+ const idleTimeoutMs = positiveNumber(opts?.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS, "idleTimeoutMs");
1549
+ const maxBytes = positiveNumber(opts?.maxBytes ?? DEFAULT_MAX_BYTES, "maxBytes");
1550
+ const quiet = opts?.quiet ?? false;
1551
+ const overallController = new AbortController;
1552
+ const abortFromCaller = () => overallController.abort(abortReason(opts.signal, "Download aborted by caller."));
1553
+ if (opts?.signal?.aborted)
1554
+ abortFromCaller();
1555
+ else
1556
+ opts?.signal?.addEventListener("abort", abortFromCaller, { once: true });
1557
+ const overallTimer = setTimeout(() => {
1558
+ overallController.abort(new CLIError(`Download timed out after ${overallTimeoutMs}ms.`, ExitCode.TIMEOUT));
1559
+ }, overallTimeoutMs);
1179
1560
  let lastError;
1180
- for (let attempt = 0;attempt <= maxRetries; attempt++) {
1181
- try {
1561
+ let retryAfterMs;
1562
+ try {
1563
+ for (let attempt = 0;attempt <= maxRetries; attempt++) {
1182
1564
  if (attempt > 0) {
1183
- const delay = baseDelay * Math.pow(2, attempt - 1);
1184
- if (!opts?.quiet) {
1565
+ const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
1566
+ const delay = Math.max(exponentialDelay, retryAfterMs ?? 0);
1567
+ if (!quiet) {
1185
1568
  process.stderr.write(`
1186
1569
  Retry ${attempt}/${maxRetries} in ${delay}ms...
1187
1570
  `);
1188
1571
  }
1189
- await new Promise((r) => setTimeout(r, delay));
1190
- }
1191
- const res = await fetch(downloadUrl);
1192
- if (!res.ok) {
1193
- throw new CLIError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL);
1572
+ await waitForDelay(delay, overallController.signal);
1194
1573
  }
1195
- const contentLength = res.headers.get("content-encoding") ? 0 : Number(res.headers.get("content-length") || 0);
1196
- const reader = res.body?.getReader();
1197
- if (!reader)
1198
- throw new CLIError("No response body", ExitCode.GENERAL);
1199
- const tmpPath = `${destPath}.tmp-${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;
1200
- const writer = createWriteStream(tmpPath);
1201
- const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null;
1202
- let received = 0;
1203
- let readComplete = false;
1204
- let completed = false;
1205
1574
  try {
1206
- const writeError = new Promise((_, reject) => {
1207
- writer.on("error", reject);
1208
- });
1209
- while (true) {
1210
- const { done, value } = await Promise.race([
1211
- reader.read(),
1212
- writeError
1213
- ]);
1214
- if (done)
1215
- break;
1216
- const ok = writer.write(value);
1217
- if (!ok)
1218
- await new Promise((r) => writer.once("drain", r));
1219
- received += value.byteLength;
1220
- progress?.update(received);
1221
- }
1222
- if (contentLength > 0 && received !== contentLength) {
1223
- throw new CLIError(`Download truncated: expected ${contentLength} bytes, received ${received}.`, ExitCode.NETWORK);
1224
- }
1225
- readComplete = true;
1226
- } finally {
1227
- reader.releaseLock();
1228
- progress?.finish();
1229
- try {
1230
- if (!writer.destroyed) {
1231
- await new Promise((resolve2, reject) => {
1232
- writer.on("finish", resolve2);
1233
- writer.on("error", reject);
1234
- writer.end();
1235
- });
1236
- completed = readComplete;
1237
- }
1238
- } finally {
1239
- if (!completed) {
1240
- try {
1241
- unlinkSync2(tmpPath);
1242
- } catch {}
1243
- }
1575
+ return await attemptDownload(downloadUrl, destPath, attempt, { quiet, idleTimeoutMs, maxBytes }, overallController.signal);
1576
+ } catch (error) {
1577
+ lastError = error instanceof Error ? error : new Error(String(error));
1578
+ if (overallController.signal.aborted) {
1579
+ throw abortReason(overallController.signal, "Download aborted.");
1244
1580
  }
1245
- }
1246
- renameSync2(tmpPath, destPath);
1247
- return { size: received };
1248
- } catch (err) {
1249
- lastError = err instanceof Error ? err : new Error(String(err));
1250
- if (!opts?.quiet) {
1251
- process.stderr.write(`
1581
+ const retryable = error instanceof RetryableDownloadError || error instanceof DownloadHttpError && error.retryable;
1582
+ if (!retryable)
1583
+ throw error;
1584
+ retryAfterMs = error instanceof DownloadHttpError || error instanceof RetryableDownloadError ? error.retryAfterMs : undefined;
1585
+ if (!quiet) {
1586
+ process.stderr.write(`
1252
1587
  Download attempt ${attempt + 1} failed: ${lastError.message}
1253
1588
  `);
1589
+ }
1590
+ if (attempt === maxRetries)
1591
+ break;
1254
1592
  }
1255
1593
  }
1594
+ } finally {
1595
+ clearTimeout(overallTimer);
1596
+ opts?.signal?.removeEventListener("abort", abortFromCaller);
1256
1597
  }
1257
- throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, ExitCode.NETWORK, "Check your network connection and proxy settings.");
1598
+ const exitCode = lastError instanceof CLIError ? lastError.exitCode : ExitCode.NETWORK;
1599
+ throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, exitCode, exitCode === ExitCode.NETWORK ? "Check your network connection and proxy settings." : undefined);
1258
1600
  }
1259
1601
 
1260
1602
  // src/sdk/image/index.ts
@@ -1356,7 +1698,9 @@ async function poll(config, opts) {
1356
1698
  if (opts.isFailed(data)) {
1357
1699
  spinner.stop("Failed.");
1358
1700
  const status = opts.getStatus ? opts.getStatus(data) : "failed";
1359
- const extra = data?.base_resp ? ` (${data.base_resp.status_msg})` : "";
1701
+ const baseResponseMessage = data.base_resp?.status_msg;
1702
+ const failureReason = opts.getFailureReason?.(data) ?? baseResponseMessage;
1703
+ const extra = failureReason ? ` (${failureReason})` : "";
1360
1704
  throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1361
1705
  }
1362
1706
  await new Promise((r) => setTimeout(r, opts.intervalSec * 1000));
@@ -1412,6 +1756,13 @@ function isVideoV2Model(model) {
1412
1756
  function isVideoV2Request(request2) {
1413
1757
  return isVideoV2Model(request2.model);
1414
1758
  }
1759
+ function getVideoV2FailureReason(task) {
1760
+ const code = task.error?.code?.trim();
1761
+ const message = task.error?.message?.trim();
1762
+ if (code && message)
1763
+ return `${code}: ${message}`;
1764
+ return message || code;
1765
+ }
1415
1766
  function buildVideoV2Request(options) {
1416
1767
  const images = options.images ?? [];
1417
1768
  if (images.length > 1 && images.some((image) => !image.role)) {
@@ -1547,7 +1898,8 @@ class VideoSDK extends Client {
1547
1898
  timeoutSec: request2.timeout ?? this.config.timeout,
1548
1899
  isComplete: (d) => d.task.status === "succeeded",
1549
1900
  isFailed: (d) => ["failed", "cancelled", "expired"].includes(d.task.status),
1550
- getStatus: (d) => d.task.status
1901
+ getStatus: (d) => d.task.status,
1902
+ getFailureReason: (d) => getVideoV2FailureReason(d.task)
1551
1903
  });
1552
1904
  return result.task;
1553
1905
  }
@@ -1595,6 +1947,15 @@ class VideoSDK extends Client {
1595
1947
  if (params.model && !isVideoV2Model(params.model)) {
1596
1948
  throw new VideoV2InputError("content is only supported with model MiniMax-H3");
1597
1949
  }
1950
+ const conflictingFields = [
1951
+ "prompt",
1952
+ "first_frame_image",
1953
+ "last_frame_image",
1954
+ "subject_reference"
1955
+ ].filter((field) => params[field] !== undefined);
1956
+ if (conflictingFields.length > 0) {
1957
+ throw new VideoV2InputError(`content cannot be combined with legacy video fields: ${conflictingFields.join(", ")}`);
1958
+ }
1598
1959
  const content = params.content;
1599
1960
  const hasFrameInput = content.some((item) => item.type === "image_url" && (!item.role || item.role === "first_frame" || item.role === "last_frame"));
1600
1961
  const hasReferenceInput = content.some((item) => item.type !== "text" && item.role?.startsWith("reference_"));
@@ -1612,6 +1973,9 @@ class VideoSDK extends Client {
1612
1973
  if (!prompt2) {
1613
1974
  throw new VideoV2InputError("prompt or content is required");
1614
1975
  }
1976
+ if (params.subject_reference !== undefined) {
1977
+ throw new VideoV2InputError("subject_reference is only supported by legacy video models. Use content with role reference_image for MiniMax-H3.");
1978
+ }
1615
1979
  return buildVideoV2Request({
1616
1980
  prompt: prompt2,
1617
1981
  images: [
@@ -1663,321 +2027,6 @@ class VideoSDK extends Client {
1663
2027
  }
1664
2028
  }
1665
2029
 
1666
- // src/sdk/music/index.ts
1667
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "node:fs";
1668
- import { resolve as resolve3, dirname as dirname3 } from "node:path";
1669
-
1670
- // src/commands/music/models.ts
1671
- var MUSIC_GENERATE_MODELS = [
1672
- "music-3.0",
1673
- "music-2.6",
1674
- "music-2.6-free",
1675
- "music-2.5+",
1676
- "music-2.5"
1677
- ];
1678
- var MUSIC_COVER_MODELS = ["music-cover", "music-cover-free"];
1679
- function includesModel(models, model) {
1680
- return models.includes(model);
1681
- }
1682
- function musicGenerateModel(config) {
1683
- if (config.defaultMusicModel && includesModel(MUSIC_GENERATE_MODELS, config.defaultMusicModel)) {
1684
- return config.defaultMusicModel;
1685
- }
1686
- return "music-3.0";
1687
- }
1688
-
1689
- // src/utils/audio-stream.ts
1690
- function decodeHexAudio(hex) {
1691
- if (!/^[0-9a-fA-F]+$/.test(hex)) {
1692
- throw new CLIError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
1693
- }
1694
- if (hex.length % 2 !== 0) {
1695
- throw new CLIError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
1696
- }
1697
- return Uint8Array.from(Buffer.from(hex, "hex"));
1698
- }
1699
- function throwIfApiError(response, payload) {
1700
- const statusCode = payload.base_resp?.status_code;
1701
- if (statusCode !== undefined && statusCode !== 0 || payload.error) {
1702
- throw mapApiError(response.status, payload, response.url || undefined);
1703
- }
1704
- }
1705
- function missingAudioError() {
1706
- return new CLIError("API stream ended without audio data.", ExitCode.GENERAL);
1707
- }
1708
- async function* decodeAudioStream(response) {
1709
- const contentType = response.headers.get("content-type") || "";
1710
- if (!contentType.toLowerCase().includes("text/event-stream")) {
1711
- let payload;
1712
- try {
1713
- payload = await response.json();
1714
- } catch {
1715
- throw new CLIError(`Expected SSE audio stream but got content-type "${contentType || "unknown"}".`, ExitCode.GENERAL);
1716
- }
1717
- throwIfApiError(response, payload);
1718
- const hex = payload.data?.audio;
1719
- if (!hex)
1720
- throw missingAudioError();
1721
- yield decodeHexAudio(hex);
1722
- return;
1723
- }
1724
- let receivedAudio = false;
1725
- for await (const event of parseSSE(response)) {
1726
- if (!event.data || event.data === "[DONE]")
1727
- break;
1728
- let parsed;
1729
- try {
1730
- parsed = JSON.parse(event.data);
1731
- } catch (error) {
1732
- throw new CLIError(`Failed to parse audio stream chunk: ${error instanceof Error ? error.message : String(error)}`, ExitCode.GENERAL);
1733
- }
1734
- throwIfApiError(response, parsed);
1735
- const hex = parsed.data?.audio;
1736
- if (hex) {
1737
- receivedAudio = true;
1738
- yield decodeHexAudio(hex);
1739
- }
1740
- if (parsed.data?.status === 2)
1741
- break;
1742
- }
1743
- if (!receivedAudio)
1744
- throw missingAudioError();
1745
- }
1746
-
1747
- // src/sdk/music/index.ts
1748
- function hexToBuffer2(hex) {
1749
- if (!/^[0-9a-fA-F]*$/.test(hex)) {
1750
- throw new SDKError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
1751
- }
1752
- if (hex.length % 2 !== 0) {
1753
- throw new SDKError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
1754
- }
1755
- return Buffer.from(hex, "hex");
1756
- }
1757
- function defaultFilename2(prefix, ext) {
1758
- const ts = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-");
1759
- return `${prefix}_${ts}.${ext}`;
1760
- }
1761
-
1762
- class MusicSDK extends Client {
1763
- async* generateStream(body, url) {
1764
- const res = await this.request({
1765
- url,
1766
- method: "POST",
1767
- body,
1768
- stream: true
1769
- });
1770
- if (!res.body) {
1771
- throw new SDKError("No response body", ExitCode.GENERAL);
1772
- }
1773
- yield* decodeAudioStream(res);
1774
- }
1775
- async generate(request2) {
1776
- const body = this.validateParams(request2);
1777
- const url = musicEndpoint(this.config.baseUrl);
1778
- if (request2.stream) {
1779
- return this.generateStream(body, url);
1780
- }
1781
- return await this.requestJson({
1782
- url,
1783
- method: "POST",
1784
- body
1785
- });
1786
- }
1787
- save(response, outPath, ext = "mp3") {
1788
- const dest = resolve3(outPath || defaultFilename2("music", ext));
1789
- const audioHex = response.data.audio;
1790
- if (!audioHex) {
1791
- throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1792
- }
1793
- const dir = dirname3(dest);
1794
- if (!existsSync4(dir))
1795
- mkdirSync3(dir, { recursive: true });
1796
- try {
1797
- writeFileSync4(dest, hexToBuffer2(audioHex));
1798
- } catch (err) {
1799
- if (err.code === "ENOSPC") {
1800
- throw new SDKError("Disk full — cannot write audio file.", ExitCode.GENERAL);
1801
- }
1802
- throw err;
1803
- }
1804
- return dest;
1805
- }
1806
- buildPrompt(request2) {
1807
- const structuredParts = [];
1808
- if (request2.vocals)
1809
- structuredParts.push(`Vocals: ${request2.vocals}`);
1810
- if (request2.genre)
1811
- structuredParts.push(`Genre: ${request2.genre}`);
1812
- if (request2.mood)
1813
- structuredParts.push(`Mood: ${request2.mood}`);
1814
- if (request2.instruments)
1815
- structuredParts.push(`Instruments: ${request2.instruments}`);
1816
- if (request2.tempo)
1817
- structuredParts.push(`Tempo: ${request2.tempo}`);
1818
- if (request2.bpm)
1819
- structuredParts.push(`BPM: ${request2.bpm}`);
1820
- if (request2.key)
1821
- structuredParts.push(`Key: ${request2.key}`);
1822
- if (request2.avoid)
1823
- structuredParts.push(`Avoid: ${request2.avoid}`);
1824
- const useCase = request2.useCase || request2.use_case;
1825
- if (useCase)
1826
- structuredParts.push(`Use case: ${useCase}`);
1827
- if (request2.structure)
1828
- structuredParts.push(`Structure: ${request2.structure}`);
1829
- if (request2.references)
1830
- structuredParts.push(`References: ${request2.references}`);
1831
- if (request2.extra)
1832
- structuredParts.push(`Extra: ${request2.extra}`);
1833
- let prompt = request2.prompt;
1834
- if (request2.is_instrumental || request2.instrumental) {
1835
- structuredParts.push("Style: instrumental, no vocals, pure music");
1836
- }
1837
- if (structuredParts.length > 0) {
1838
- const structured = structuredParts.join(". ");
1839
- prompt = prompt ? `${prompt}. ${structured}` : structured;
1840
- }
1841
- return prompt;
1842
- }
1843
- validateParams(params) {
1844
- const instrumental = params.instrumental;
1845
- const apiParams = { ...params };
1846
- const sdkOnlyFields = [
1847
- "instrumental",
1848
- "vocals",
1849
- "genre",
1850
- "mood",
1851
- "instruments",
1852
- "tempo",
1853
- "bpm",
1854
- "key",
1855
- "avoid",
1856
- "use_case",
1857
- "useCase",
1858
- "structure",
1859
- "references",
1860
- "extra"
1861
- ];
1862
- for (const field of sdkOnlyFields)
1863
- delete apiParams[field];
1864
- if (instrumental !== undefined && params.is_instrumental !== undefined && instrumental !== params.is_instrumental) {
1865
- throw new SDKError("instrumental and is_instrumental must not conflict", ExitCode.USAGE);
1866
- }
1867
- const normalized = {
1868
- ...apiParams,
1869
- is_instrumental: params.is_instrumental ?? instrumental
1870
- };
1871
- const {
1872
- model,
1873
- output_format,
1874
- stream,
1875
- prompt,
1876
- lyrics,
1877
- is_instrumental,
1878
- lyrics_optimizer
1879
- } = normalized;
1880
- const effectiveModel = model ?? musicGenerateModel(this.config);
1881
- const isGenerateModel = MUSIC_GENERATE_MODELS.includes(effectiveModel);
1882
- const isCoverModel = MUSIC_COVER_MODELS.includes(effectiveModel);
1883
- if (!isGenerateModel && !isCoverModel) {
1884
- throw new SDKError(`Invalid model: ${effectiveModel}. Valid models are ${[
1885
- ...MUSIC_GENERATE_MODELS,
1886
- ...MUSIC_COVER_MODELS
1887
- ].join(", ")}.`, ExitCode.USAGE);
1888
- }
1889
- const VALID_OUTPUT_FORMATS = ["hex", "url"];
1890
- if (output_format && !VALID_OUTPUT_FORMATS.includes(output_format)) {
1891
- throw new SDKError(`Invalid output format: ${output_format}. Valid formats are ${VALID_OUTPUT_FORMATS.join(", ")}.`, ExitCode.USAGE);
1892
- }
1893
- if (stream && output_format === "url") {
1894
- throw new SDKError(`stream and output_format url cannot be used together. Streaming requires hex format.`, ExitCode.USAGE);
1895
- }
1896
- let targetPrompt = this.buildPrompt({
1897
- ...params,
1898
- is_instrumental
1899
- });
1900
- if (isCoverModel) {
1901
- if (is_instrumental) {
1902
- throw new SDKError("is_instrumental is only supported by music generation models", ExitCode.USAGE);
1903
- }
1904
- if (lyrics_optimizer) {
1905
- throw new SDKError("lyrics_optimizer is only supported by music generation models", ExitCode.USAGE);
1906
- }
1907
- delete normalized.is_instrumental;
1908
- delete normalized.lyrics_optimizer;
1909
- targetPrompt = targetPrompt?.trim();
1910
- const coverPromptLength = targetPrompt?.length ?? 0;
1911
- if (coverPromptLength < 10 || coverPromptLength > 300) {
1912
- throw new SDKError("prompt must be between 10 and 300 characters for music cover models", ExitCode.USAGE);
1913
- }
1914
- const hasAudioUrl = Boolean(normalized.audio_url?.trim());
1915
- const hasAudioBase64 = Boolean(normalized.audio_base64?.trim());
1916
- const hasCoverFeatureId = Boolean(normalized.cover_feature_id?.trim());
1917
- const sourceCount = [hasAudioUrl, hasAudioBase64, hasCoverFeatureId].filter(Boolean).length;
1918
- if (sourceCount !== 1) {
1919
- throw new SDKError("Exactly one of audio_url, audio_base64, or cover_feature_id is required for music cover models", ExitCode.USAGE);
1920
- }
1921
- if (hasAudioUrl)
1922
- normalized.audio_url = normalized.audio_url?.trim();
1923
- else
1924
- delete normalized.audio_url;
1925
- if (hasAudioBase64)
1926
- normalized.audio_base64 = normalized.audio_base64?.trim();
1927
- else
1928
- delete normalized.audio_base64;
1929
- if (hasCoverFeatureId) {
1930
- normalized.cover_feature_id = normalized.cover_feature_id?.trim();
1931
- } else {
1932
- delete normalized.cover_feature_id;
1933
- }
1934
- const coverLyrics = lyrics?.trim();
1935
- const lyricsLength = coverLyrics?.length ?? 0;
1936
- if (hasCoverFeatureId && lyricsLength === 0) {
1937
- throw new SDKError("lyrics is required with cover_feature_id", ExitCode.USAGE);
1938
- }
1939
- if (coverLyrics)
1940
- normalized.lyrics = coverLyrics;
1941
- else
1942
- delete normalized.lyrics;
1943
- if (lyricsLength > 0 && (lyricsLength < 10 || lyricsLength > 1000)) {
1944
- throw new SDKError("lyrics must be between 10 and 1000 characters for music cover models", ExitCode.USAGE);
1945
- }
1946
- } else {
1947
- if (normalized.audio_url || normalized.audio_base64 || normalized.cover_feature_id) {
1948
- throw new SDKError("audio_url, audio_base64, and cover_feature_id are only supported by music cover models", ExitCode.USAGE);
1949
- }
1950
- if (is_instrumental && lyrics) {
1951
- throw new SDKError("Cannot use is_instrumental with lyrics", ExitCode.USAGE);
1952
- }
1953
- if (lyrics_optimizer && (lyrics || is_instrumental)) {
1954
- throw new SDKError("Cannot use lyrics_optimizer with lyrics or is_instrumental", ExitCode.USAGE);
1955
- }
1956
- if (!prompt && !lyrics && !is_instrumental && !lyrics_optimizer) {
1957
- throw new SDKError("At least one of prompt or lyrics or is_instrumental or lyrics_optimizer is required", ExitCode.USAGE);
1958
- }
1959
- if ((is_instrumental || lyrics_optimizer) && !prompt?.trim()) {
1960
- throw new SDKError("prompt is required with is_instrumental or lyrics_optimizer", ExitCode.USAGE);
1961
- }
1962
- if (!is_instrumental && !lyrics_optimizer && !lyrics?.trim()) {
1963
- throw new SDKError("lyrics is required", ExitCode.USAGE);
1964
- }
1965
- }
1966
- return toMerged({
1967
- model: effectiveModel,
1968
- audio_setting: {
1969
- format: "mp3",
1970
- sample_rate: 44100,
1971
- bitrate: 256000
1972
- },
1973
- output_format: "hex"
1974
- }, {
1975
- ...normalized,
1976
- prompt: targetPrompt
1977
- });
1978
- }
1979
- }
1980
-
1981
2030
  // src/sdk/search/index.ts
1982
2031
  class SearchSDK extends Client {
1983
2032
  async query(query) {
@@ -1992,7 +2041,7 @@ class SearchSDK extends Client {
1992
2041
  }
1993
2042
 
1994
2043
  // src/utils/image.ts
1995
- import { readFileSync as readFileSync2, existsSync as existsSync5, statSync } from "fs";
2044
+ import { readFileSync as readFileSync2, existsSync as existsSync4, statSync } from "fs";
1996
2045
  import { extname } from "path";
1997
2046
  var IMAGE_MIME_TYPES = {
1998
2047
  ".jpg": "image/jpeg",
@@ -2030,7 +2079,7 @@ async function toDataUri(image) {
2030
2079
  }
2031
2080
  return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
2032
2081
  }
2033
- if (!existsSync5(image))
2082
+ if (!existsSync4(image))
2034
2083
  throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
2035
2084
  const ext = extname(image).toLowerCase();
2036
2085
  if (!IMAGE_MIME_TYPES[ext])
@@ -2065,13 +2114,13 @@ class QuotaSDK extends Client {
2065
2114
  }
2066
2115
 
2067
2116
  // src/sdk/file/index.ts
2068
- import { existsSync as existsSync6 } from "node:fs";
2117
+ import { existsSync as existsSync5 } from "node:fs";
2069
2118
  import { readFile } from "node:fs/promises";
2070
- import { resolve as resolve4, basename } from "node:path";
2119
+ import { resolve as resolve3, basename } from "node:path";
2071
2120
  class FileSDK extends Client {
2072
2121
  async upload(filePath, purpose = "retrieval") {
2073
- const fullPath = resolve4(filePath);
2074
- if (!existsSync6(fullPath)) {
2122
+ const fullPath = resolve3(filePath);
2123
+ if (!existsSync5(fullPath)) {
2075
2124
  throw new SDKError(`File not found: ${fullPath}`, ExitCode.USAGE);
2076
2125
  }
2077
2126
  const fileData = await readFile(fullPath);
@@ -2110,7 +2159,6 @@ class MiniMaxSDK extends Client {
2110
2159
  speech;
2111
2160
  image;
2112
2161
  video;
2113
- music;
2114
2162
  search;
2115
2163
  vision;
2116
2164
  quota;
@@ -2121,7 +2169,6 @@ class MiniMaxSDK extends Client {
2121
2169
  this.speech = new SpeechSDK(options);
2122
2170
  this.image = new ImageSDK(options);
2123
2171
  this.video = new VideoSDK(options);
2124
- this.music = new MusicSDK(options);
2125
2172
  this.search = new SearchSDK(options);
2126
2173
  this.vision = new VisionSDK(options);
2127
2174
  this.quota = new QuotaSDK(options);