mmx-cli 1.0.18 → 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.18",
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
  `);
@@ -737,15 +813,18 @@ function imageEndpoint(baseUrl) {
737
813
  function videoGenerateEndpoint(baseUrl) {
738
814
  return `${baseUrl}/v1/video_generation`;
739
815
  }
816
+ function videoGenerateV2Endpoint(baseUrl) {
817
+ return `${baseUrl}/v2/video_generation`;
818
+ }
740
819
  function videoTaskEndpoint(baseUrl, taskId) {
741
820
  return `${baseUrl}/v1/query/video_generation?task_id=${taskId}`;
742
821
  }
822
+ function videoTaskV2Endpoint(baseUrl, taskId) {
823
+ return `${baseUrl}/v2/query/video_generation/${taskId}`;
824
+ }
743
825
  function fileRetrieveEndpoint(baseUrl, fileId) {
744
826
  return `${baseUrl}/v1/files/retrieve?file_id=${fileId}`;
745
827
  }
746
- function musicEndpoint(baseUrl) {
747
- return `${baseUrl}/v1/music_generation`;
748
- }
749
828
  function searchEndpoint(baseUrl) {
750
829
  return `${baseUrl}/v1/coding_plan/search`;
751
830
  }
@@ -1166,86 +1245,358 @@ function createProgressBar(total, label = "") {
1166
1245
  }
1167
1246
 
1168
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
+ }
1169
1543
  async function downloadFile(url, destPath, opts) {
1170
1544
  const downloadUrl = url.startsWith("http://") ? url.replace("http://", "https://") : url;
1171
- const maxRetries = opts?.retries ?? 3;
1172
- 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);
1173
1560
  let lastError;
1174
- for (let attempt = 0;attempt <= maxRetries; attempt++) {
1175
- try {
1561
+ let retryAfterMs;
1562
+ try {
1563
+ for (let attempt = 0;attempt <= maxRetries; attempt++) {
1176
1564
  if (attempt > 0) {
1177
- const delay = baseDelay * Math.pow(2, attempt - 1);
1178
- if (!opts?.quiet) {
1565
+ const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
1566
+ const delay = Math.max(exponentialDelay, retryAfterMs ?? 0);
1567
+ if (!quiet) {
1179
1568
  process.stderr.write(`
1180
1569
  Retry ${attempt}/${maxRetries} in ${delay}ms...
1181
1570
  `);
1182
1571
  }
1183
- await new Promise((r) => setTimeout(r, delay));
1572
+ await waitForDelay(delay, overallController.signal);
1184
1573
  }
1185
- const res = await fetch(downloadUrl);
1186
- if (!res.ok) {
1187
- throw new CLIError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL);
1188
- }
1189
- const contentLength = Number(res.headers.get("content-length") || 0);
1190
- const reader = res.body?.getReader();
1191
- if (!reader)
1192
- throw new CLIError("No response body", ExitCode.GENERAL);
1193
- const tmpPath = `${destPath}.tmp-${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;
1194
- const writer = createWriteStream(tmpPath);
1195
- const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null;
1196
- let received = 0;
1197
- let readComplete = false;
1198
- let completed = false;
1199
1574
  try {
1200
- const writeError = new Promise((_, reject) => {
1201
- writer.on("error", reject);
1202
- });
1203
- while (true) {
1204
- const { done, value } = await Promise.race([
1205
- reader.read(),
1206
- writeError
1207
- ]);
1208
- if (done)
1209
- break;
1210
- const ok = writer.write(value);
1211
- if (!ok)
1212
- await new Promise((r) => writer.once("drain", r));
1213
- received += value.byteLength;
1214
- progress?.update(received);
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.");
1215
1580
  }
1216
- readComplete = true;
1217
- } finally {
1218
- reader.releaseLock();
1219
- progress?.finish();
1220
- try {
1221
- if (!writer.destroyed) {
1222
- await new Promise((resolve2, reject) => {
1223
- writer.on("finish", resolve2);
1224
- writer.on("error", reject);
1225
- writer.end();
1226
- });
1227
- completed = readComplete;
1228
- }
1229
- } finally {
1230
- if (!completed) {
1231
- try {
1232
- unlinkSync2(tmpPath);
1233
- } catch {}
1234
- }
1235
- }
1236
- }
1237
- renameSync2(tmpPath, destPath);
1238
- return { size: received };
1239
- } catch (err) {
1240
- lastError = err instanceof Error ? err : new Error(String(err));
1241
- if (!opts?.quiet) {
1242
- 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(`
1243
1587
  Download attempt ${attempt + 1} failed: ${lastError.message}
1244
1588
  `);
1589
+ }
1590
+ if (attempt === maxRetries)
1591
+ break;
1245
1592
  }
1246
1593
  }
1594
+ } finally {
1595
+ clearTimeout(overallTimer);
1596
+ opts?.signal?.removeEventListener("abort", abortFromCaller);
1247
1597
  }
1248
- 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);
1249
1600
  }
1250
1601
 
1251
1602
  // src/sdk/image/index.ts
@@ -1347,7 +1698,9 @@ async function poll(config, opts) {
1347
1698
  if (opts.isFailed(data)) {
1348
1699
  spinner.stop("Failed.");
1349
1700
  const status = opts.getStatus ? opts.getStatus(data) : "failed";
1350
- 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})` : "";
1351
1704
  throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1352
1705
  }
1353
1706
  await new Promise((r) => setTimeout(r, opts.intervalSec * 1000));
@@ -1358,11 +1711,176 @@ async function poll(config, opts) {
1358
1711
  throw new CLIError("Polling timed out.", ExitCode.TIMEOUT, "Try increasing --timeout or check task status manually.");
1359
1712
  }
1360
1713
 
1714
+ // src/utils/media.ts
1715
+ var VIDEO_V2_MEDIA_SIZE_LIMITS = {
1716
+ image: 30 * 1024 * 1024,
1717
+ video: 50 * 1024 * 1024,
1718
+ audio: 15 * 1024 * 1024
1719
+ };
1720
+ var VIDEO_V2_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
1721
+ function dataUriDecodedSize(input) {
1722
+ const match = /^data:[^;,]+;base64,([\s\S]*)$/.exec(input);
1723
+ if (!match)
1724
+ return;
1725
+ const base64 = match[1].replace(/\s/g, "");
1726
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
1727
+ return Math.max(0, Math.floor(base64.length * 3 / 4) - padding);
1728
+ }
1729
+
1730
+ // src/video/v2.ts
1731
+ var VIDEO_V2_MODEL = "MiniMax-H3";
1732
+ var VIDEO_V2_RATIOS = new Set([
1733
+ "adaptive",
1734
+ "21:9",
1735
+ "16:9",
1736
+ "4:3",
1737
+ "1:1",
1738
+ "3:4",
1739
+ "9:16"
1740
+ ]);
1741
+ var VIDEO_V2_IMAGE_ROLES = new Set([
1742
+ "first_frame",
1743
+ "last_frame",
1744
+ "reference_image"
1745
+ ]);
1746
+
1747
+ class VideoV2InputError extends Error {
1748
+ constructor(message) {
1749
+ super(message);
1750
+ this.name = "VideoV2InputError";
1751
+ }
1752
+ }
1753
+ function isVideoV2Model(model) {
1754
+ return model === VIDEO_V2_MODEL;
1755
+ }
1756
+ function isVideoV2Request(request2) {
1757
+ return isVideoV2Model(request2.model);
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
+ }
1766
+ function buildVideoV2Request(options) {
1767
+ const images = options.images ?? [];
1768
+ if (images.length > 1 && images.some((image) => !image.role)) {
1769
+ throw new VideoV2InputError("Each image must specify a role when multiple images are provided.");
1770
+ }
1771
+ const content = [
1772
+ { type: "text", text: options.prompt },
1773
+ ...images.map((image) => ({
1774
+ type: "image_url",
1775
+ image_url: { url: image.url },
1776
+ role: image.role ?? "first_frame"
1777
+ })),
1778
+ ...(options.referenceVideos ?? []).map((url) => ({
1779
+ type: "video_url",
1780
+ video_url: { url },
1781
+ role: "reference_video"
1782
+ })),
1783
+ ...(options.referenceAudios ?? []).map((url) => ({
1784
+ type: "audio_url",
1785
+ audio_url: { url },
1786
+ role: "reference_audio"
1787
+ }))
1788
+ ];
1789
+ const hasFrameInput = content.some((item) => item.type === "image_url" && (item.role === "first_frame" || item.role === "last_frame"));
1790
+ const hasReferenceInput = content.some((item) => item.type !== "text" && item.role?.startsWith("reference_"));
1791
+ const request2 = {
1792
+ model: VIDEO_V2_MODEL,
1793
+ content,
1794
+ resolution: options.resolution ?? "2K",
1795
+ duration: options.duration ?? 5,
1796
+ ratio: hasFrameInput ? "adaptive" : options.ratio ?? (hasReferenceInput ? "adaptive" : "16:9")
1797
+ };
1798
+ if (options.callbackUrl)
1799
+ request2.callback_url = options.callbackUrl;
1800
+ validateVideoV2Request(request2);
1801
+ return request2;
1802
+ }
1803
+ function validateVideoV2Request(request2) {
1804
+ if (!isVideoV2Model(request2.model)) {
1805
+ throw new VideoV2InputError(`Video Generation V2 only supports ${VIDEO_V2_MODEL}.`);
1806
+ }
1807
+ const textItems = request2.content.filter((item) => item.type === "text");
1808
+ if (!textItems.some((item) => item.text.trim().length > 0)) {
1809
+ throw new VideoV2InputError("MiniMax-H3 requires a non-empty text content item.");
1810
+ }
1811
+ if (textItems.some((item) => item.text.length > 7000)) {
1812
+ throw new VideoV2InputError("MiniMax-H3 text content must not exceed 7000 characters.");
1813
+ }
1814
+ if (request2.resolution !== "2K") {
1815
+ throw new VideoV2InputError("MiniMax-H3 currently only supports 2K resolution.");
1816
+ }
1817
+ if (!Number.isInteger(request2.duration) || request2.duration < 4 || request2.duration > 15) {
1818
+ throw new VideoV2InputError("MiniMax-H3 duration must be an integer from 4 to 15 seconds.");
1819
+ }
1820
+ if (request2.ratio && !VIDEO_V2_RATIOS.has(request2.ratio)) {
1821
+ throw new VideoV2InputError("MiniMax-H3 ratio must be one of: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16.");
1822
+ }
1823
+ const images = request2.content.filter((item) => item.type === "image_url");
1824
+ const videos = request2.content.filter((item) => item.type === "video_url");
1825
+ const audios = request2.content.filter((item) => item.type === "audio_url");
1826
+ if (images.some((item) => item.role && !VIDEO_V2_IMAGE_ROLES.has(item.role))) {
1827
+ throw new VideoV2InputError("MiniMax-H3 image role must be one of: first_frame, last_frame, reference_image.");
1828
+ }
1829
+ if (videos.some((item) => item.role !== "reference_video")) {
1830
+ throw new VideoV2InputError("MiniMax-H3 video role must be reference_video.");
1831
+ }
1832
+ if (audios.some((item) => item.role !== "reference_audio")) {
1833
+ throw new VideoV2InputError("MiniMax-H3 audio role must be reference_audio.");
1834
+ }
1835
+ for (const image of images) {
1836
+ validateDataUriSize(image.image_url.url, "image");
1837
+ }
1838
+ for (const video of videos) {
1839
+ validateDataUriSize(video.video_url.url, "video");
1840
+ }
1841
+ for (const audio of audios) {
1842
+ validateDataUriSize(audio.audio_url.url, "audio");
1843
+ }
1844
+ const requestBodyBytes = Buffer.byteLength(JSON.stringify(request2));
1845
+ if (requestBodyBytes > VIDEO_V2_MAX_REQUEST_BODY_BYTES) {
1846
+ throw new VideoV2InputError(`MiniMax-H3 request body is ${(requestBodyBytes / 1024 / 1024).toFixed(1)} MB; the maximum is 64 MB. Use public URLs or mm_file:// file IDs instead of Base64.`);
1847
+ }
1848
+ const firstFrames = images.filter((item) => !item.role || item.role === "first_frame");
1849
+ const lastFrames = images.filter((item) => item.role === "last_frame");
1850
+ const referenceImages = images.filter((item) => item.role === "reference_image");
1851
+ const hasFrameInput = firstFrames.length > 0 || lastFrames.length > 0;
1852
+ const hasReferenceInput = referenceImages.length > 0 || videos.length > 0 || audios.length > 0;
1853
+ if (firstFrames.length > 1 || lastFrames.length > 1) {
1854
+ throw new VideoV2InputError("MiniMax-H3 accepts at most one first frame and one last frame.");
1855
+ }
1856
+ if (referenceImages.length > 9 || videos.length > 3 || audios.length > 3) {
1857
+ throw new VideoV2InputError("MiniMax-H3 accepts up to 9 reference images, 3 reference videos, and 3 reference audios.");
1858
+ }
1859
+ if (hasFrameInput && hasReferenceInput) {
1860
+ throw new VideoV2InputError("MiniMax-H3 frame inputs and reference inputs cannot be used together.");
1861
+ }
1862
+ if (audios.length > 0 && referenceImages.length === 0 && videos.length === 0) {
1863
+ throw new VideoV2InputError("MiniMax-H3 reference audio requires at least one reference image or reference video.");
1864
+ }
1865
+ const isTextOnly = request2.content.every((item) => item.type === "text");
1866
+ if (isTextOnly && (!request2.ratio || request2.ratio === "adaptive")) {
1867
+ throw new VideoV2InputError("MiniMax-H3 text-to-video requires a concrete ratio; adaptive is not supported.");
1868
+ }
1869
+ }
1870
+ function validateDataUriSize(url, kind) {
1871
+ const size = dataUriDecodedSize(url);
1872
+ const maxBytes = VIDEO_V2_MEDIA_SIZE_LIMITS[kind];
1873
+ if (size !== undefined && size > maxBytes) {
1874
+ throw new VideoV2InputError(`MiniMax-H3 ${kind} input is ${(size / 1024 / 1024).toFixed(1)} MB; the maximum is ${maxBytes / 1024 / 1024} MB.`);
1875
+ }
1876
+ }
1877
+
1361
1878
  // src/sdk/video/index.ts
1362
1879
  class VideoSDK extends Client {
1363
1880
  async generate(request2) {
1364
1881
  const body = this.validateParams(request2);
1365
- const url = videoGenerateEndpoint(this.config.baseUrl);
1882
+ const usesV2 = isVideoV2Request(body);
1883
+ const url = usesV2 ? videoGenerateV2Endpoint(this.config.baseUrl) : videoGenerateEndpoint(this.config.baseUrl);
1366
1884
  const res = await this.requestJson({
1367
1885
  url,
1368
1886
  method: "POST",
@@ -1372,8 +1890,21 @@ class VideoSDK extends Client {
1372
1890
  if (request2.async) {
1373
1891
  return { taskId };
1374
1892
  }
1893
+ if (usesV2) {
1894
+ const taskUrl2 = videoTaskV2Endpoint(this.config.baseUrl, taskId);
1895
+ const result = await poll(this.config, {
1896
+ url: taskUrl2,
1897
+ intervalSec: request2.pollInterval ?? 5,
1898
+ timeoutSec: request2.timeout ?? this.config.timeout,
1899
+ isComplete: (d) => d.task.status === "succeeded",
1900
+ isFailed: (d) => ["failed", "cancelled", "expired"].includes(d.task.status),
1901
+ getStatus: (d) => d.task.status,
1902
+ getFailureReason: (d) => getVideoV2FailureReason(d.task)
1903
+ });
1904
+ return result.task;
1905
+ }
1375
1906
  const taskUrl = videoTaskEndpoint(this.config.baseUrl, taskId);
1376
- const result = await poll(this.config, {
1907
+ return await poll(this.config, {
1377
1908
  url: taskUrl,
1378
1909
  intervalSec: request2.pollInterval ?? 5,
1379
1910
  timeoutSec: request2.timeout ?? this.config.timeout,
@@ -1381,9 +1912,13 @@ class VideoSDK extends Client {
1381
1912
  isFailed: (d) => d.status === "Failed",
1382
1913
  getStatus: (d) => d.status
1383
1914
  });
1384
- return result;
1385
1915
  }
1386
- async getTask({ taskId }) {
1916
+ async getTask({ taskId, model }) {
1917
+ if (isVideoV2Model(model)) {
1918
+ const url2 = videoTaskV2Endpoint(this.config.baseUrl, taskId);
1919
+ const result = await this.requestJson({ url: url2 });
1920
+ return result.task;
1921
+ }
1387
1922
  const url = videoTaskEndpoint(this.config.baseUrl, taskId);
1388
1923
  return await this.requestJson({ url });
1389
1924
  }
@@ -1402,7 +1937,67 @@ class VideoSDK extends Client {
1402
1937
  };
1403
1938
  }
1404
1939
  validateParams(request2) {
1405
- const { prompt, model, first_frame_image, last_frame_image, subject_reference } = request2;
1940
+ const params = { ...request2 };
1941
+ delete params.async;
1942
+ delete params.pollInterval;
1943
+ delete params.timeout;
1944
+ if ("content" in params || isVideoV2Model(params.model)) {
1945
+ try {
1946
+ if ("content" in params) {
1947
+ if (params.model && !isVideoV2Model(params.model)) {
1948
+ throw new VideoV2InputError("content is only supported with model MiniMax-H3");
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
+ }
1959
+ const content = params.content;
1960
+ const hasFrameInput = content.some((item) => item.type === "image_url" && (!item.role || item.role === "first_frame" || item.role === "last_frame"));
1961
+ const hasReferenceInput = content.some((item) => item.type !== "text" && item.role?.startsWith("reference_"));
1962
+ const body = {
1963
+ ...params,
1964
+ model: VIDEO_V2_MODEL,
1965
+ resolution: params.resolution ?? "2K",
1966
+ duration: params.duration ?? 5,
1967
+ ratio: params.ratio ?? (hasFrameInput || hasReferenceInput ? "adaptive" : "16:9")
1968
+ };
1969
+ validateVideoV2Request(body);
1970
+ return body;
1971
+ }
1972
+ const prompt2 = params.prompt;
1973
+ if (!prompt2) {
1974
+ throw new VideoV2InputError("prompt or content is required");
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
+ }
1979
+ return buildVideoV2Request({
1980
+ prompt: prompt2,
1981
+ images: [
1982
+ ...params.first_frame_image ? [{ url: params.first_frame_image, role: "first_frame" }] : [],
1983
+ ...params.last_frame_image ? [{ url: params.last_frame_image, role: "last_frame" }] : []
1984
+ ],
1985
+ resolution: params.resolution,
1986
+ duration: params.duration,
1987
+ ratio: params.ratio,
1988
+ callbackUrl: params.callback_url
1989
+ });
1990
+ } catch (error) {
1991
+ if (error instanceof VideoV2InputError) {
1992
+ throw new SDKError(error.message, ExitCode.USAGE);
1993
+ }
1994
+ throw error;
1995
+ }
1996
+ }
1997
+ if ("resolution" in params || "duration" in params || "ratio" in params) {
1998
+ throw new SDKError("resolution, duration, and ratio require model MiniMax-H3", ExitCode.USAGE);
1999
+ }
2000
+ const { prompt, model, first_frame_image, last_frame_image, subject_reference } = params;
1406
2001
  if (!prompt) {
1407
2002
  throw new SDKError("prompt is required", ExitCode.USAGE);
1408
2003
  }
@@ -1425,324 +2020,10 @@ class VideoSDK extends Client {
1425
2020
  if (last_frame_image && subject_reference) {
1426
2021
  throw new SDKError("last_frame_image and subject_reference cannot be used together (SEF and S2V are different modes).", ExitCode.USAGE);
1427
2022
  }
1428
- return toMerged({
2023
+ return {
2024
+ ...params,
1429
2025
  model: resolvedModel
1430
- }, request2);
1431
- }
1432
- }
1433
-
1434
- // src/sdk/music/index.ts
1435
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "node:fs";
1436
- import { resolve as resolve3, dirname as dirname3 } from "node:path";
1437
-
1438
- // src/commands/music/models.ts
1439
- var MUSIC_GENERATE_MODELS = [
1440
- "music-3.0",
1441
- "music-2.6",
1442
- "music-2.6-free",
1443
- "music-2.5+",
1444
- "music-2.5"
1445
- ];
1446
- var MUSIC_COVER_MODELS = ["music-cover", "music-cover-free"];
1447
- function includesModel(models, model) {
1448
- return models.includes(model);
1449
- }
1450
- function musicGenerateModel(config) {
1451
- if (config.defaultMusicModel && includesModel(MUSIC_GENERATE_MODELS, config.defaultMusicModel)) {
1452
- return config.defaultMusicModel;
1453
- }
1454
- return "music-3.0";
1455
- }
1456
-
1457
- // src/utils/audio-stream.ts
1458
- function decodeHexAudio(hex) {
1459
- if (!/^[0-9a-fA-F]+$/.test(hex)) {
1460
- throw new CLIError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
1461
- }
1462
- if (hex.length % 2 !== 0) {
1463
- throw new CLIError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
1464
- }
1465
- return Uint8Array.from(Buffer.from(hex, "hex"));
1466
- }
1467
- function throwIfApiError(response, payload) {
1468
- const statusCode = payload.base_resp?.status_code;
1469
- if (statusCode !== undefined && statusCode !== 0 || payload.error) {
1470
- throw mapApiError(response.status, payload, response.url || undefined);
1471
- }
1472
- }
1473
- function missingAudioError() {
1474
- return new CLIError("API stream ended without audio data.", ExitCode.GENERAL);
1475
- }
1476
- async function* decodeAudioStream(response) {
1477
- const contentType = response.headers.get("content-type") || "";
1478
- if (!contentType.toLowerCase().includes("text/event-stream")) {
1479
- let payload;
1480
- try {
1481
- payload = await response.json();
1482
- } catch {
1483
- throw new CLIError(`Expected SSE audio stream but got content-type "${contentType || "unknown"}".`, ExitCode.GENERAL);
1484
- }
1485
- throwIfApiError(response, payload);
1486
- const hex = payload.data?.audio;
1487
- if (!hex)
1488
- throw missingAudioError();
1489
- yield decodeHexAudio(hex);
1490
- return;
1491
- }
1492
- let receivedAudio = false;
1493
- for await (const event of parseSSE(response)) {
1494
- if (!event.data || event.data === "[DONE]")
1495
- break;
1496
- let parsed;
1497
- try {
1498
- parsed = JSON.parse(event.data);
1499
- } catch (error) {
1500
- throw new CLIError(`Failed to parse audio stream chunk: ${error instanceof Error ? error.message : String(error)}`, ExitCode.GENERAL);
1501
- }
1502
- throwIfApiError(response, parsed);
1503
- const hex = parsed.data?.audio;
1504
- if (hex) {
1505
- receivedAudio = true;
1506
- yield decodeHexAudio(hex);
1507
- }
1508
- if (parsed.data?.status === 2)
1509
- break;
1510
- }
1511
- if (!receivedAudio)
1512
- throw missingAudioError();
1513
- }
1514
-
1515
- // src/sdk/music/index.ts
1516
- function hexToBuffer2(hex) {
1517
- if (!/^[0-9a-fA-F]*$/.test(hex)) {
1518
- throw new SDKError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
1519
- }
1520
- if (hex.length % 2 !== 0) {
1521
- throw new SDKError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
1522
- }
1523
- return Buffer.from(hex, "hex");
1524
- }
1525
- function defaultFilename2(prefix, ext) {
1526
- const ts = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-");
1527
- return `${prefix}_${ts}.${ext}`;
1528
- }
1529
-
1530
- class MusicSDK extends Client {
1531
- async* generateStream(body, url) {
1532
- const res = await this.request({
1533
- url,
1534
- method: "POST",
1535
- body,
1536
- stream: true
1537
- });
1538
- if (!res.body) {
1539
- throw new SDKError("No response body", ExitCode.GENERAL);
1540
- }
1541
- yield* decodeAudioStream(res);
1542
- }
1543
- async generate(request2) {
1544
- const body = this.validateParams(request2);
1545
- const url = musicEndpoint(this.config.baseUrl);
1546
- if (request2.stream) {
1547
- return this.generateStream(body, url);
1548
- }
1549
- return await this.requestJson({
1550
- url,
1551
- method: "POST",
1552
- body
1553
- });
1554
- }
1555
- save(response, outPath, ext = "mp3") {
1556
- const dest = resolve3(outPath || defaultFilename2("music", ext));
1557
- const audioHex = response.data.audio;
1558
- if (!audioHex) {
1559
- throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1560
- }
1561
- const dir = dirname3(dest);
1562
- if (!existsSync4(dir))
1563
- mkdirSync3(dir, { recursive: true });
1564
- try {
1565
- writeFileSync4(dest, hexToBuffer2(audioHex));
1566
- } catch (err) {
1567
- if (err.code === "ENOSPC") {
1568
- throw new SDKError("Disk full — cannot write audio file.", ExitCode.GENERAL);
1569
- }
1570
- throw err;
1571
- }
1572
- return dest;
1573
- }
1574
- buildPrompt(request2) {
1575
- const structuredParts = [];
1576
- if (request2.vocals)
1577
- structuredParts.push(`Vocals: ${request2.vocals}`);
1578
- if (request2.genre)
1579
- structuredParts.push(`Genre: ${request2.genre}`);
1580
- if (request2.mood)
1581
- structuredParts.push(`Mood: ${request2.mood}`);
1582
- if (request2.instruments)
1583
- structuredParts.push(`Instruments: ${request2.instruments}`);
1584
- if (request2.tempo)
1585
- structuredParts.push(`Tempo: ${request2.tempo}`);
1586
- if (request2.bpm)
1587
- structuredParts.push(`BPM: ${request2.bpm}`);
1588
- if (request2.key)
1589
- structuredParts.push(`Key: ${request2.key}`);
1590
- if (request2.avoid)
1591
- structuredParts.push(`Avoid: ${request2.avoid}`);
1592
- const useCase = request2.useCase || request2.use_case;
1593
- if (useCase)
1594
- structuredParts.push(`Use case: ${useCase}`);
1595
- if (request2.structure)
1596
- structuredParts.push(`Structure: ${request2.structure}`);
1597
- if (request2.references)
1598
- structuredParts.push(`References: ${request2.references}`);
1599
- if (request2.extra)
1600
- structuredParts.push(`Extra: ${request2.extra}`);
1601
- let prompt = request2.prompt;
1602
- if (request2.is_instrumental || request2.instrumental) {
1603
- structuredParts.push("Style: instrumental, no vocals, pure music");
1604
- }
1605
- if (structuredParts.length > 0) {
1606
- const structured = structuredParts.join(". ");
1607
- prompt = prompt ? `${prompt}. ${structured}` : structured;
1608
- }
1609
- return prompt;
1610
- }
1611
- validateParams(params) {
1612
- const instrumental = params.instrumental;
1613
- const apiParams = { ...params };
1614
- const sdkOnlyFields = [
1615
- "instrumental",
1616
- "vocals",
1617
- "genre",
1618
- "mood",
1619
- "instruments",
1620
- "tempo",
1621
- "bpm",
1622
- "key",
1623
- "avoid",
1624
- "use_case",
1625
- "useCase",
1626
- "structure",
1627
- "references",
1628
- "extra"
1629
- ];
1630
- for (const field of sdkOnlyFields)
1631
- delete apiParams[field];
1632
- if (instrumental !== undefined && params.is_instrumental !== undefined && instrumental !== params.is_instrumental) {
1633
- throw new SDKError("instrumental and is_instrumental must not conflict", ExitCode.USAGE);
1634
- }
1635
- const normalized = {
1636
- ...apiParams,
1637
- is_instrumental: params.is_instrumental ?? instrumental
1638
2026
  };
1639
- const {
1640
- model,
1641
- output_format,
1642
- stream,
1643
- prompt,
1644
- lyrics,
1645
- is_instrumental,
1646
- lyrics_optimizer
1647
- } = normalized;
1648
- const effectiveModel = model ?? musicGenerateModel(this.config);
1649
- const isGenerateModel = MUSIC_GENERATE_MODELS.includes(effectiveModel);
1650
- const isCoverModel = MUSIC_COVER_MODELS.includes(effectiveModel);
1651
- if (!isGenerateModel && !isCoverModel) {
1652
- throw new SDKError(`Invalid model: ${effectiveModel}. Valid models are ${[
1653
- ...MUSIC_GENERATE_MODELS,
1654
- ...MUSIC_COVER_MODELS
1655
- ].join(", ")}.`, ExitCode.USAGE);
1656
- }
1657
- const VALID_OUTPUT_FORMATS = ["hex", "url"];
1658
- if (output_format && !VALID_OUTPUT_FORMATS.includes(output_format)) {
1659
- throw new SDKError(`Invalid output format: ${output_format}. Valid formats are ${VALID_OUTPUT_FORMATS.join(", ")}.`, ExitCode.USAGE);
1660
- }
1661
- if (stream && output_format === "url") {
1662
- throw new SDKError(`stream and output_format url cannot be used together. Streaming requires hex format.`, ExitCode.USAGE);
1663
- }
1664
- let targetPrompt = this.buildPrompt({
1665
- ...params,
1666
- is_instrumental
1667
- });
1668
- if (isCoverModel) {
1669
- if (is_instrumental) {
1670
- throw new SDKError("is_instrumental is only supported by music generation models", ExitCode.USAGE);
1671
- }
1672
- if (lyrics_optimizer) {
1673
- throw new SDKError("lyrics_optimizer is only supported by music generation models", ExitCode.USAGE);
1674
- }
1675
- delete normalized.is_instrumental;
1676
- delete normalized.lyrics_optimizer;
1677
- targetPrompt = targetPrompt?.trim();
1678
- const coverPromptLength = targetPrompt?.length ?? 0;
1679
- if (coverPromptLength < 10 || coverPromptLength > 300) {
1680
- throw new SDKError("prompt must be between 10 and 300 characters for music cover models", ExitCode.USAGE);
1681
- }
1682
- const hasAudioUrl = Boolean(normalized.audio_url?.trim());
1683
- const hasAudioBase64 = Boolean(normalized.audio_base64?.trim());
1684
- const hasCoverFeatureId = Boolean(normalized.cover_feature_id?.trim());
1685
- const sourceCount = [hasAudioUrl, hasAudioBase64, hasCoverFeatureId].filter(Boolean).length;
1686
- if (sourceCount !== 1) {
1687
- throw new SDKError("Exactly one of audio_url, audio_base64, or cover_feature_id is required for music cover models", ExitCode.USAGE);
1688
- }
1689
- if (hasAudioUrl)
1690
- normalized.audio_url = normalized.audio_url?.trim();
1691
- else
1692
- delete normalized.audio_url;
1693
- if (hasAudioBase64)
1694
- normalized.audio_base64 = normalized.audio_base64?.trim();
1695
- else
1696
- delete normalized.audio_base64;
1697
- if (hasCoverFeatureId) {
1698
- normalized.cover_feature_id = normalized.cover_feature_id?.trim();
1699
- } else {
1700
- delete normalized.cover_feature_id;
1701
- }
1702
- const coverLyrics = lyrics?.trim();
1703
- const lyricsLength = coverLyrics?.length ?? 0;
1704
- if (hasCoverFeatureId && lyricsLength === 0) {
1705
- throw new SDKError("lyrics is required with cover_feature_id", ExitCode.USAGE);
1706
- }
1707
- if (coverLyrics)
1708
- normalized.lyrics = coverLyrics;
1709
- else
1710
- delete normalized.lyrics;
1711
- if (lyricsLength > 0 && (lyricsLength < 10 || lyricsLength > 1000)) {
1712
- throw new SDKError("lyrics must be between 10 and 1000 characters for music cover models", ExitCode.USAGE);
1713
- }
1714
- } else {
1715
- if (normalized.audio_url || normalized.audio_base64 || normalized.cover_feature_id) {
1716
- throw new SDKError("audio_url, audio_base64, and cover_feature_id are only supported by music cover models", ExitCode.USAGE);
1717
- }
1718
- if (is_instrumental && lyrics) {
1719
- throw new SDKError("Cannot use is_instrumental with lyrics", ExitCode.USAGE);
1720
- }
1721
- if (lyrics_optimizer && (lyrics || is_instrumental)) {
1722
- throw new SDKError("Cannot use lyrics_optimizer with lyrics or is_instrumental", ExitCode.USAGE);
1723
- }
1724
- if (!prompt && !lyrics && !is_instrumental && !lyrics_optimizer) {
1725
- throw new SDKError("At least one of prompt or lyrics or is_instrumental or lyrics_optimizer is required", ExitCode.USAGE);
1726
- }
1727
- if ((is_instrumental || lyrics_optimizer) && !prompt?.trim()) {
1728
- throw new SDKError("prompt is required with is_instrumental or lyrics_optimizer", ExitCode.USAGE);
1729
- }
1730
- if (!is_instrumental && !lyrics_optimizer && !lyrics?.trim()) {
1731
- throw new SDKError("lyrics is required", ExitCode.USAGE);
1732
- }
1733
- }
1734
- return toMerged({
1735
- model: effectiveModel,
1736
- audio_setting: {
1737
- format: "mp3",
1738
- sample_rate: 44100,
1739
- bitrate: 256000
1740
- },
1741
- output_format: "hex"
1742
- }, {
1743
- ...normalized,
1744
- prompt: targetPrompt
1745
- });
1746
2027
  }
1747
2028
  }
1748
2029
 
@@ -1760,15 +2041,23 @@ class SearchSDK extends Client {
1760
2041
  }
1761
2042
 
1762
2043
  // src/utils/image.ts
1763
- import { readFileSync as readFileSync2, existsSync as existsSync5 } from "fs";
2044
+ import { readFileSync as readFileSync2, existsSync as existsSync4, statSync } from "fs";
1764
2045
  import { extname } from "path";
1765
2046
  var IMAGE_MIME_TYPES = {
1766
2047
  ".jpg": "image/jpeg",
1767
2048
  ".jpeg": "image/jpeg",
1768
2049
  ".png": "image/png",
1769
- ".webp": "image/webp"
2050
+ ".webp": "image/webp",
2051
+ ".heic": "image/heic",
2052
+ ".heif": "image/heif"
1770
2053
  };
1771
- function localFileToDataUri(filePath) {
2054
+ function localFileToDataUri(filePath, maxBytes) {
2055
+ if (maxBytes !== undefined) {
2056
+ const size = statSync(filePath).size;
2057
+ if (size > maxBytes) {
2058
+ throw new CLIError(`Image file is ${(size / 1024 / 1024).toFixed(1)} MB; MiniMax-H3 allows at most ${maxBytes / 1024 / 1024} MB.`, ExitCode.USAGE, "Use a public URL or mm_file:// file ID for large images.");
2059
+ }
2060
+ }
1772
2061
  const ext = extname(filePath).toLowerCase();
1773
2062
  const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
1774
2063
  const data = readFileSync2(filePath);
@@ -1790,7 +2079,7 @@ async function toDataUri(image) {
1790
2079
  }
1791
2080
  return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
1792
2081
  }
1793
- if (!existsSync5(image))
2082
+ if (!existsSync4(image))
1794
2083
  throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
1795
2084
  const ext = extname(image).toLowerCase();
1796
2085
  if (!IMAGE_MIME_TYPES[ext])
@@ -1825,13 +2114,13 @@ class QuotaSDK extends Client {
1825
2114
  }
1826
2115
 
1827
2116
  // src/sdk/file/index.ts
1828
- import { existsSync as existsSync6 } from "node:fs";
2117
+ import { existsSync as existsSync5 } from "node:fs";
1829
2118
  import { readFile } from "node:fs/promises";
1830
- import { resolve as resolve4, basename } from "node:path";
2119
+ import { resolve as resolve3, basename } from "node:path";
1831
2120
  class FileSDK extends Client {
1832
2121
  async upload(filePath, purpose = "retrieval") {
1833
- const fullPath = resolve4(filePath);
1834
- if (!existsSync6(fullPath)) {
2122
+ const fullPath = resolve3(filePath);
2123
+ if (!existsSync5(fullPath)) {
1835
2124
  throw new SDKError(`File not found: ${fullPath}`, ExitCode.USAGE);
1836
2125
  }
1837
2126
  const fileData = await readFile(fullPath);
@@ -1870,7 +2159,6 @@ class MiniMaxSDK extends Client {
1870
2159
  speech;
1871
2160
  image;
1872
2161
  video;
1873
- music;
1874
2162
  search;
1875
2163
  vision;
1876
2164
  quota;
@@ -1881,7 +2169,6 @@ class MiniMaxSDK extends Client {
1881
2169
  this.speech = new SpeechSDK(options);
1882
2170
  this.image = new ImageSDK(options);
1883
2171
  this.video = new VideoSDK(options);
1884
- this.music = new MusicSDK(options);
1885
2172
  this.search = new SearchSDK(options);
1886
2173
  this.vision = new VisionSDK(options);
1887
2174
  this.quota = new QuotaSDK(options);