mmx-cli 1.0.27 → 1.0.29

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
@@ -1,5 +1,6 @@
1
1
  // src/config/loader.ts
2
2
  import { copyFileSync, existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
3
+ import { dirname } from "path";
3
4
 
4
5
  // src/config/schema.ts
5
6
  var REGIONS = {
@@ -76,8 +77,7 @@ function getConfigDir() {
76
77
  function getConfigPath() {
77
78
  return join(getConfigDir(), "config.json");
78
79
  }
79
- async function ensureConfigDir() {
80
- const dir = getConfigDir();
80
+ async function ensureConfigDir(dir = getConfigDir()) {
81
81
  const fs = await import("fs/promises");
82
82
  await fs.mkdir(dir, { recursive: true, mode: 448 });
83
83
  }
@@ -227,8 +227,7 @@ function renameWithCrossDeviceFallback(from, to, ops = {
227
227
  ops.unlink(from);
228
228
  }
229
229
  }
230
- function readConfigFile() {
231
- const path = getConfigPath();
230
+ function readConfigFile(path = getConfigPath()) {
232
231
  if (!existsSync(path))
233
232
  return {};
234
233
  try {
@@ -242,9 +241,8 @@ function readConfigFile() {
242
241
  return {};
243
242
  }
244
243
  }
245
- async function writeConfigFile(data, renameOps) {
246
- await ensureConfigDir();
247
- const path = getConfigPath();
244
+ async function writeConfigFile(data, renameOps, path = getConfigPath()) {
245
+ await ensureConfigDir(dirname(path));
248
246
  const tmp = path + ".tmp";
249
247
  writeFileSync(tmp, JSON.stringify(data, null, 2) + `
250
248
  `, { mode: 384 });
@@ -262,7 +260,7 @@ function loadConfig(flags) {
262
260
  const region = explicitRegion || cachedRegion || "global";
263
261
  const activeKey = apiKey || fileApiKey;
264
262
  const needsRegionDetection = !explicitRegion && (!cachedRegion || activeKey !== undefined && activeKey !== file.api_key);
265
- const baseUrl = flags.baseUrl || process.env.MINIMAX_BASE_URL || file.base_url || file.oauth?.resource_url || REGIONS[region] || REGIONS.global;
263
+ const baseUrl = flags.baseUrl || process.env.MINIMAX_BASE_URL || file.base_url || (!apiKey ? file.oauth?.resource_url : undefined) || REGIONS[region] || REGIONS.global;
266
264
  const output = detectOutputFormat(flags.output || process.env.MINIMAX_OUTPUT || file.output);
267
265
  const envTimeout = process.env.MINIMAX_TIMEOUT ? Number(process.env.MINIMAX_TIMEOUT) : undefined;
268
266
  const validEnvTimeout = envTimeout !== undefined && Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : undefined;
@@ -295,18 +293,20 @@ async function loadCredentials() {
295
293
  const cfg = readConfigFile();
296
294
  return cfg.oauth ?? null;
297
295
  }
298
- async function saveCredentials(creds) {
299
- const existing = readConfigFile();
296
+ async function saveCredentials(creds, path = getConfigPath()) {
297
+ const existing = readConfigFile(path);
300
298
  existing.oauth = creds;
301
- await writeConfigFile(existing);
299
+ await writeConfigFile(existing, undefined, path);
302
300
  }
303
301
 
304
302
  // src/auth/refresh.ts
303
+ import { resolve } from "path";
305
304
  var CLIENT_ID = "659cf4c1-615c-45f6-a5f6-4bf15eb476e5";
306
305
  var MAX_RETRIES = 2;
307
306
  var RETRY_DELAY_MS = 500;
308
307
  var REQUEST_TIMEOUT_MS = 1e4;
309
308
  var REFRESH_BUFFER_MS = 5 * 60 * 1000;
309
+ var pendingRefreshes = new Map;
310
310
  async function refreshAccessToken(refreshToken, region = "global") {
311
311
  const tokenUrl = `${OAUTH_HOSTS[region]}/oauth2/token`;
312
312
  let lastErr = null;
@@ -355,17 +355,30 @@ async function ensureFreshToken(creds) {
355
355
  const expiresAt = new Date(creds.expires_at).getTime();
356
356
  if (Date.now() < expiresAt - REFRESH_BUFFER_MS)
357
357
  return creds.access_token;
358
- const fresh = await refreshAccessToken(creds.refresh_token, creds.region ?? "global");
359
- const updated = {
360
- access_token: fresh.access_token,
361
- refresh_token: fresh.refresh_token,
362
- expires_at: fresh.expires_at,
363
- region: creds.region,
364
- resource_url: fresh.resource_url ?? creds.resource_url,
365
- account: creds.account
366
- };
367
- await saveCredentials(updated);
368
- return updated.access_token;
358
+ const path = resolve(getConfigPath());
359
+ const key = JSON.stringify([path, creds.region ?? "global", creds.refresh_token]);
360
+ const existing = pendingRefreshes.get(key);
361
+ if (existing)
362
+ return existing;
363
+ const pending = (async () => {
364
+ const fresh = await refreshAccessToken(creds.refresh_token, creds.region ?? "global");
365
+ const updated = {
366
+ access_token: fresh.access_token,
367
+ refresh_token: fresh.refresh_token,
368
+ expires_at: fresh.expires_at,
369
+ region: creds.region,
370
+ resource_url: fresh.resource_url ?? creds.resource_url,
371
+ account: creds.account
372
+ };
373
+ await saveCredentials(updated, path);
374
+ return updated.access_token;
375
+ })();
376
+ pendingRefreshes.set(key, pending);
377
+ try {
378
+ return await pending;
379
+ } finally {
380
+ pendingRefreshes.delete(key);
381
+ }
369
382
  }
370
383
 
371
384
  // src/auth/hints.ts
@@ -418,17 +431,38 @@ function upgradeUrl(url) {
418
431
  const host = url?.includes("api.minimax.cn") || url?.includes("api.minimaxi.com") ? "https://platform.minimax.cn" : "https://platform.minimax.io";
419
432
  return `${host}/subscribe/token-plan`;
420
433
  }
434
+ function imageFailureDetails(body) {
435
+ if (!Array.isArray(body.data))
436
+ return;
437
+ const items = body.data;
438
+ const lines = items.flatMap((item, index) => item?.error ? [`Image ${index + 1}${item.error.code !== undefined ? ` (${item.error.code})` : ""}: ${item.error.message ?? "unknown error"}`] : []);
439
+ return lines.length > 0 ? lines.join(`
440
+ `) : undefined;
441
+ }
421
442
  function mapApiError(status, body, url) {
443
+ const error = mapApiErrorBase(status, body, url);
444
+ const details = url?.includes("/v1/images/") ? imageFailureDetails(body) : undefined;
445
+ if (!details)
446
+ return error;
447
+ return new CLIError(error.message, error.exitCode, error.hint ? `${details}
448
+ ${error.hint}` : details);
449
+ }
450
+ function mapApiErrorBase(status, body, url) {
422
451
  const apiMsg = body.base_resp?.status_msg || body.error?.message || `HTTP ${status}`;
423
- const apiCode = body.base_resp?.status_code || body.error?.code;
452
+ const trailingCode = url?.includes("/v1/images/") ? body.error?.message?.match(/\((\d{4})\)\s*$/)?.[1] : undefined;
453
+ const apiCode = body.base_resp?.status_code || body.error?.code || (trailingCode ? Number(trailingCode) : undefined);
424
454
  const errorType = body.error?.type;
425
455
  if (status === 401 || status === 403) {
426
456
  return new CLIError(`API key rejected (HTTP ${status}).`, ExitCode.AUTH, `Check status: mmx auth status
427
457
  Re-authenticate: mmx auth login`);
428
458
  }
429
- if (status === 429) {
459
+ if (status === 429 || apiCode === 1002 && url?.includes("/v1/images/")) {
430
460
  return new CLIError(`Rate limit or quota exceeded. ${apiMsg}`, ExitCode.QUOTA, "Check usage: mmx quota show");
431
461
  }
462
+ if (apiCode === 2068 && url?.includes("/v1/images/")) {
463
+ return new CLIError(`This model is not available on your current plan. ${apiMsg}`, ExitCode.QUOTA, `Check usage: mmx quota show
464
+ Upgrade plan: ${upgradeUrl(url)}`);
465
+ }
432
466
  if (status === 402 || errorType === "insufficient_balance_error") {
433
467
  return new CLIError(`Quota or balance exhausted. ${apiMsg}`, ExitCode.QUOTA, "Check your MiniMax account balance and billing settings.");
434
468
  }
@@ -824,6 +858,12 @@ function voicesEndpoint(baseUrl) {
824
858
  function imageEndpoint(baseUrl) {
825
859
  return `${baseUrl}/v1/image_generation`;
826
860
  }
861
+ function imageGenerationsEndpoint(baseUrl) {
862
+ return `${baseUrl}/v1/images/generations`;
863
+ }
864
+ function imageEditsEndpoint(baseUrl) {
865
+ return `${baseUrl}/v1/images/edits`;
866
+ }
827
867
  function videoGenerateEndpoint(baseUrl) {
828
868
  return `${baseUrl}/v1/video_generation`;
829
869
  }
@@ -876,6 +916,9 @@ function fileDeleteEndpoint(baseUrl) {
876
916
  return `${baseUrl}/v1/files/delete`;
877
917
  }
878
918
 
919
+ // src/config/models.ts
920
+ var DEFAULT_TEXT_MODEL = "MiniMax-M3.1-Flash";
921
+
879
922
  // src/sdk/text/index.ts
880
923
  class TextSDK extends Client {
881
924
  async* chatStream(body) {
@@ -912,7 +955,7 @@ class TextSDK extends Client {
912
955
  }
913
956
  return {
914
957
  ...params,
915
- model: params.model ?? "MiniMax-M3",
958
+ model: params.model ?? DEFAULT_TEXT_MODEL,
916
959
  max_tokens: params.max_tokens ?? 4096
917
960
  };
918
961
  }
@@ -920,7 +963,7 @@ class TextSDK extends Client {
920
963
 
921
964
  // src/sdk/speech/index.ts
922
965
  import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, statSync, writeFileSync as writeFileSync2 } from "node:fs";
923
- import { basename, resolve, dirname } from "node:path";
966
+ import { basename, resolve as resolve2, dirname as dirname2 } from "node:path";
924
967
 
925
968
  // src/command.ts
926
969
  function defineCommand(spec) {
@@ -1121,6 +1164,16 @@ function toMerged(target, source) {
1121
1164
  }
1122
1165
  });
1123
1166
  }
1167
+ // src/utils/audio-formats.ts
1168
+ var T2A_SAMPLE_RATE = {
1169
+ opus: 24000,
1170
+ pcmu_raw: 8000,
1171
+ pcmu_wav: 8000
1172
+ };
1173
+ function t2aDefaultSampleRate(format, fallback) {
1174
+ return Object.hasOwn(T2A_SAMPLE_RATE, format) ? T2A_SAMPLE_RATE[format] ?? fallback : fallback;
1175
+ }
1176
+
1124
1177
  // src/utils/stt.ts
1125
1178
  var STT_DEFAULT_MODEL = "asr-1.0";
1126
1179
  var STT_RESPONSE_FORMATS = [
@@ -1211,7 +1264,7 @@ function blobFilename(file) {
1211
1264
  }
1212
1265
  function prepareAudioUpload(file) {
1213
1266
  if (typeof file === "string") {
1214
- const fullPath = resolve(file);
1267
+ const fullPath = resolve2(file);
1215
1268
  if (!existsSync2(fullPath)) {
1216
1269
  throw new SDKError(`File not found: ${fullPath}`, ExitCode.USAGE);
1217
1270
  }
@@ -1309,12 +1362,12 @@ class SpeechSDK extends Client {
1309
1362
  }
1310
1363
  }
1311
1364
  save(response, outPath, ext = "mp3") {
1312
- const dest = resolve(outPath || defaultFilename("speech", ext));
1365
+ const dest = resolve2(outPath || defaultFilename("speech", ext));
1313
1366
  const audioHex = response.data.audio;
1314
1367
  if (!audioHex) {
1315
1368
  throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1316
1369
  }
1317
- const dir = dirname(dest);
1370
+ const dir = dirname2(dest);
1318
1371
  if (!existsSync2(dir))
1319
1372
  mkdirSync(dir, { recursive: true });
1320
1373
  try {
@@ -1338,7 +1391,7 @@ class SpeechSDK extends Client {
1338
1391
  },
1339
1392
  audio_setting: {
1340
1393
  format: "mp3",
1341
- sample_rate: 32000,
1394
+ sample_rate: t2aDefaultSampleRate(params.audio_setting?.format ?? "mp3", 32000),
1342
1395
  bitrate: 128000,
1343
1396
  channel: 1
1344
1397
  },
@@ -1354,8 +1407,12 @@ class SpeechSDK extends Client {
1354
1407
  }
1355
1408
 
1356
1409
  // src/sdk/image/index.ts
1357
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
1358
- import { join as join2, resolve as resolve2, dirname as dirname2 } from "node:path";
1410
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "node:fs";
1411
+ import { join as join3, resolve as resolve4, dirname as dirname4 } from "node:path";
1412
+
1413
+ // src/image/h3.ts
1414
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
1415
+ import { dirname as dirname3, extname as extname2, join as join2, resolve as resolve3 } from "path";
1359
1416
 
1360
1417
  // src/files/download.ts
1361
1418
  import { createWriteStream, renameSync as renameSync2, unlinkSync as unlinkSync2 } from "fs";
@@ -1772,9 +1829,255 @@ async function downloadFile(url, destPath, opts) {
1772
1829
  throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, exitCode, exitCode === ExitCode.NETWORK ? "Check your network connection and proxy settings." : undefined);
1773
1830
  }
1774
1831
 
1832
+ // src/utils/image.ts
1833
+ import { readFileSync as readFileSync3, existsSync as existsSync3, statSync as statSync2 } from "fs";
1834
+ import { extname } from "path";
1835
+ var IMAGE_MIME_TYPES = {
1836
+ ".jpg": "image/jpeg",
1837
+ ".jpeg": "image/jpeg",
1838
+ ".png": "image/png",
1839
+ ".webp": "image/webp",
1840
+ ".heic": "image/heic",
1841
+ ".heif": "image/heif"
1842
+ };
1843
+ function localFileToDataUri(filePath, maxBytes) {
1844
+ if (maxBytes !== undefined) {
1845
+ const size = statSync2(filePath).size;
1846
+ if (size > maxBytes) {
1847
+ 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.");
1848
+ }
1849
+ }
1850
+ const ext = extname(filePath).toLowerCase();
1851
+ const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
1852
+ const data = readFileSync3(filePath);
1853
+ return `data:${mime};base64,${data.toString("base64")}`;
1854
+ }
1855
+ var MAX_IMAGE_SIZE_BYTES = 50 * 1024 * 1024;
1856
+ async function toDataUri(image) {
1857
+ if (image.startsWith("data:"))
1858
+ return image;
1859
+ if (image.startsWith("http://") || image.startsWith("https://")) {
1860
+ const res = await fetch(image);
1861
+ if (!res.ok)
1862
+ throw new CLIError(`Failed to download image: HTTP ${res.status}`, ExitCode.GENERAL);
1863
+ const contentType = res.headers.get("content-type") || "image/jpeg";
1864
+ const mime = contentType.split(";")[0].trim();
1865
+ const buf = await res.arrayBuffer();
1866
+ if (buf.byteLength > MAX_IMAGE_SIZE_BYTES) {
1867
+ throw new CLIError(`Image too large (${(buf.byteLength / 1024 / 1024).toFixed(1)} MB). Maximum is 50 MB.`, ExitCode.USAGE);
1868
+ }
1869
+ return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
1870
+ }
1871
+ if (!existsSync3(image))
1872
+ throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
1873
+ const ext = extname(image).toLowerCase();
1874
+ if (!IMAGE_MIME_TYPES[ext])
1875
+ throw new CLIError(`Unsupported image format "${ext}". Supported: jpg, jpeg, png, webp`, ExitCode.USAGE);
1876
+ return localFileToDataUri(image);
1877
+ }
1878
+
1879
+ // src/utils/media.ts
1880
+ var VIDEO_V2_MEDIA_SIZE_LIMITS = {
1881
+ image: 30 * 1024 * 1024,
1882
+ video: 50 * 1024 * 1024,
1883
+ audio: 15 * 1024 * 1024
1884
+ };
1885
+ var VIDEO_V2_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
1886
+ function dataUriDecodedSize(input) {
1887
+ const match = /^data:[^;,]+;base64,([\s\S]*)$/.exec(input);
1888
+ if (!match)
1889
+ return;
1890
+ const base64 = match[1].replace(/\s/g, "");
1891
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
1892
+ return Math.max(0, Math.floor(base64.length * 3 / 4) - padding);
1893
+ }
1894
+
1895
+ // src/image/h3.ts
1896
+ var IMAGE_H3_MODEL = "MiniMax-H3-Image";
1897
+ var IMAGE_H3_MIN_TIMEOUT_SEC = 600;
1898
+ var IMAGE_H3_MAX_PROMPT_CHARS = 32000;
1899
+ var IMAGE_H3_MAX_IMAGES_PER_REQUEST = 10;
1900
+ var IMAGE_H3_MAX_REFERENCE_IMAGES = 16;
1901
+ var IMAGE_H3_MIN_AREA = 655360;
1902
+ var IMAGE_H3_MAX_AREA = 20000000;
1903
+ var IMAGE_H3_MAX_FILE_BYTES = 64 * 1024 * 1024;
1904
+ var IMAGE_H3_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
1905
+ var AREA_LEVEL_PIXELS = {
1906
+ "1K": 1024 * 1024,
1907
+ "2K": 2048 * 2048,
1908
+ "4K": 4096 * 4096
1909
+ };
1910
+ var IMAGE_H3_B64_MAX_TOTAL_AREA_PNG = 20000000;
1911
+ var IMAGE_H3_B64_MAX_TOTAL_AREA = 80000000;
1912
+ var AREAS = new Set(["1K", "2K", "4K"]);
1913
+ var OUTPUT_FORMATS = new Set(["png", "jpeg", "jpg", "webp"]);
1914
+ var RESPONSE_FORMATS = new Set(["url", "b64_json"]);
1915
+
1916
+ class ImageH3InputError extends Error {
1917
+ constructor(message) {
1918
+ super(message);
1919
+ this.name = "ImageH3InputError";
1920
+ }
1921
+ }
1922
+ function isImageH3Model(model) {
1923
+ return model === IMAGE_H3_MODEL;
1924
+ }
1925
+ function isImageH3EditRequest(request) {
1926
+ return Array.isArray(request.images);
1927
+ }
1928
+ function isImageH3Response(response) {
1929
+ return typeof response === "object" && response !== null && Array.isArray(response.data);
1930
+ }
1931
+ function imageH3Extension(format) {
1932
+ if (format === "png" || format === "webp")
1933
+ return format;
1934
+ return "jpg";
1935
+ }
1936
+ function parseRatio(value) {
1937
+ const match = /^(\d+):(\d+)$/.exec(value);
1938
+ if (!match)
1939
+ return;
1940
+ return [Number(match[1]), Number(match[2])];
1941
+ }
1942
+ function withinRatioRange(a, b) {
1943
+ return Math.max(a, b) <= 3 * Math.min(a, b);
1944
+ }
1945
+ function validateImageH3Request(request) {
1946
+ if (!isImageH3Model(request.model)) {
1947
+ throw new ImageH3InputError(`Only ${IMAGE_H3_MODEL} is supported by /v1/images/*.`);
1948
+ }
1949
+ const prompt = typeof request.prompt === "string" ? request.prompt.trim() : "";
1950
+ if (!prompt) {
1951
+ throw new ImageH3InputError("MiniMax-H3-Image requires a non-empty prompt.");
1952
+ }
1953
+ if ([...prompt].length > IMAGE_H3_MAX_PROMPT_CHARS) {
1954
+ throw new ImageH3InputError(`MiniMax-H3-Image prompt must not exceed ${IMAGE_H3_MAX_PROMPT_CHARS} characters.`);
1955
+ }
1956
+ if (request.n !== undefined && (!Number.isInteger(request.n) || request.n < 1 || request.n > IMAGE_H3_MAX_IMAGES_PER_REQUEST)) {
1957
+ throw new ImageH3InputError(`MiniMax-H3-Image n must be an integer from 1 to ${IMAGE_H3_MAX_IMAGES_PER_REQUEST}.`);
1958
+ }
1959
+ const size = request.size;
1960
+ const explicitSize = size !== undefined && size !== "auto";
1961
+ if (explicitSize) {
1962
+ const match = /^(\d+)x(\d+)$/.exec(size);
1963
+ if (!match) {
1964
+ throw new ImageH3InputError('MiniMax-H3-Image size must be "auto" or WIDTHxHEIGHT, e.g. 2720x1536.');
1965
+ }
1966
+ const width = Number(match[1]);
1967
+ const height = Number(match[2]);
1968
+ const area = width * height;
1969
+ if (width < 1 || height < 1 || area < IMAGE_H3_MIN_AREA || area > IMAGE_H3_MAX_AREA) {
1970
+ throw new ImageH3InputError(`MiniMax-H3-Image size area (width x height) must be between 655,360 and 20,000,000 pixels, got ${area.toLocaleString("en-US")}.`);
1971
+ }
1972
+ if (!withinRatioRange(width, height)) {
1973
+ throw new ImageH3InputError("MiniMax-H3-Image size aspect ratio must be between 1:3 and 3:1.");
1974
+ }
1975
+ if (request.aspect_ratio !== undefined || request.area !== undefined) {
1976
+ throw new ImageH3InputError("MiniMax-H3-Image size WIDTHxHEIGHT cannot be combined with aspect ratio or area.");
1977
+ }
1978
+ }
1979
+ const aspectRatio = request.aspect_ratio;
1980
+ if (aspectRatio !== undefined && aspectRatio !== "auto") {
1981
+ const ratio = parseRatio(aspectRatio);
1982
+ if (!ratio || ratio.some((v) => v < 1 || v > 300)) {
1983
+ throw new ImageH3InputError('MiniMax-H3-Image aspect ratio must be "auto" or X:Y with integers from 1 to 300.');
1984
+ }
1985
+ if (!withinRatioRange(ratio[0], ratio[1])) {
1986
+ throw new ImageH3InputError("MiniMax-H3-Image aspect ratio must be between 1:3 and 3:1.");
1987
+ }
1988
+ }
1989
+ if (request.area !== undefined && !AREAS.has(request.area)) {
1990
+ throw new ImageH3InputError("MiniMax-H3-Image area must be one of: 1K, 2K, 4K.");
1991
+ }
1992
+ if (request.output_format !== undefined && !OUTPUT_FORMATS.has(request.output_format)) {
1993
+ throw new ImageH3InputError("MiniMax-H3-Image output format must be one of: jpg, jpeg, png, webp.");
1994
+ }
1995
+ if (request.output_compression !== undefined && (!Number.isInteger(request.output_compression) || request.output_compression < 0 || request.output_compression > 100)) {
1996
+ throw new ImageH3InputError("MiniMax-H3-Image output compression must be an integer from 0 to 100.");
1997
+ }
1998
+ if (request.response_format !== undefined && !RESPONSE_FORMATS.has(request.response_format)) {
1999
+ throw new ImageH3InputError("MiniMax-H3-Image response format must be url or b64_json (alias: base64).");
2000
+ }
2001
+ if (request.response_format === "b64_json") {
2002
+ const perImage = explicitSize ? Number(size.split("x")[0]) * Number(size.split("x")[1]) : AREA_LEVEL_PIXELS[request.area ?? "4K"];
2003
+ const total = (request.n ?? 1) * perImage;
2004
+ const isPng = request.output_format === "png";
2005
+ const limit = isPng ? IMAGE_H3_B64_MAX_TOTAL_AREA_PNG : IMAGE_H3_B64_MAX_TOTAL_AREA;
2006
+ if (total > limit) {
2007
+ throw new ImageH3InputError(`MiniMax-H3-Image b64_json total output area (n x width x height) is ${total.toLocaleString("en-US")} px; ` + `the limit for ${isPng ? "png" : "jpeg/webp"} is ${limit.toLocaleString("en-US")} px. ` + "Lower n or the size/area, or use the url response format.");
2008
+ }
2009
+ }
2010
+ if (isImageH3EditRequest(request)) {
2011
+ if (request.disable_prompt_enhanced !== undefined) {
2012
+ throw new ImageH3InputError("disable_prompt_enhanced is not supported for image edits (enhancement is always on).");
2013
+ }
2014
+ const count = request.images.length;
2015
+ if (count < 1 || count > IMAGE_H3_MAX_REFERENCE_IMAGES) {
2016
+ throw new ImageH3InputError(`MiniMax-H3-Image accepts 1 to ${IMAGE_H3_MAX_REFERENCE_IMAGES} reference images.`);
2017
+ }
2018
+ for (const image of request.images) {
2019
+ if (typeof image?.image_url !== "string" || !image.image_url) {
2020
+ throw new ImageH3InputError("Each reference image needs a non-empty image_url.");
2021
+ }
2022
+ const decoded = dataUriDecodedSize(image.image_url);
2023
+ if (decoded !== undefined && decoded > IMAGE_H3_MAX_FILE_BYTES) {
2024
+ throw new ImageH3InputError(`MiniMax-H3-Image reference image is ${(decoded / 1024 / 1024).toFixed(1)} MB; the maximum is 64 MB.`);
2025
+ }
2026
+ }
2027
+ } else if (request.disable_prompt_enhanced) {
2028
+ const hasConcreteRatio = aspectRatio !== undefined && aspectRatio !== "auto";
2029
+ if (!explicitSize && !hasConcreteRatio) {
2030
+ throw new ImageH3InputError("With prompt enhancement disabled, MiniMax-H3-Image needs an explicit size (WIDTHxHEIGHT) or aspect ratio (X:Y).");
2031
+ }
2032
+ }
2033
+ const bodyBytes = Buffer.byteLength(JSON.stringify(request));
2034
+ if (bodyBytes > IMAGE_H3_MAX_REQUEST_BODY_BYTES) {
2035
+ throw new ImageH3InputError(`MiniMax-H3-Image request body is ${(bodyBytes / 1024 / 1024).toFixed(1)} MB; the maximum is 64 MB. Use public URLs or mm_file:// file IDs instead of local files.`);
2036
+ }
2037
+ }
2038
+ async function saveImageH3Images(response, options = {}) {
2039
+ const ext = imageH3Extension(response.output_format);
2040
+ const failures = [];
2041
+ const succeeded = [];
2042
+ response.data.forEach((item, index) => {
2043
+ if (item.url || item.b64_json) {
2044
+ succeeded.push({ index, url: item.url, b64: item.b64_json });
2045
+ } else {
2046
+ failures.push({ index, code: item.error?.code, message: item.error?.message });
2047
+ }
2048
+ });
2049
+ if (options.out && succeeded.length > 1) {
2050
+ throw new ImageH3InputError("Cannot use `out` with multiple images. Use `outDir` instead.");
2051
+ }
2052
+ const saved = [];
2053
+ const quiet = options.quiet ?? true;
2054
+ const outDir = resolve3(options.outDir || ".");
2055
+ const prefix = options.prefix || "image";
2056
+ for (const image of succeeded) {
2057
+ const destPath = options.out ? resolve3(options.out) : join2(outDir, `${prefix}_${String(image.index + 1).padStart(3, "0")}.${ext}`);
2058
+ const dir = dirname3(destPath);
2059
+ if (!existsSync4(dir))
2060
+ mkdirSync2(dir, { recursive: true });
2061
+ if (options.warnOverwrite && existsSync4(destPath)) {
2062
+ process.stderr.write(`Warning: overwriting existing file: ${destPath}
2063
+ `);
2064
+ }
2065
+ if (image.b64) {
2066
+ writeFileSync3(destPath, image.b64, "base64");
2067
+ } else {
2068
+ await downloadFile(image.url, destPath, { quiet });
2069
+ }
2070
+ saved.push(destPath);
2071
+ }
2072
+ return { saved, failures };
2073
+ }
2074
+
1775
2075
  // src/sdk/image/index.ts
1776
2076
  class ImageSDK extends Client {
1777
2077
  async generate(request) {
2078
+ if (isImageH3Model(request.model)) {
2079
+ return await this.generateH3(request);
2080
+ }
1778
2081
  const body = this.validateParams(request);
1779
2082
  const url = imageEndpoint(this.config.baseUrl);
1780
2083
  return await this.requestJson({
@@ -1783,7 +2086,42 @@ class ImageSDK extends Client {
1783
2086
  body
1784
2087
  });
1785
2088
  }
2089
+ async generateH3(request) {
2090
+ const { images, ...rest } = request;
2091
+ if (rest.stream) {
2092
+ throw new SDKError("stream is not supported by the SDK for MiniMax-H3-Image.", ExitCode.USAGE);
2093
+ }
2094
+ const body = images !== undefined ? { ...rest, images } : rest;
2095
+ try {
2096
+ validateImageH3Request(body);
2097
+ } catch (error) {
2098
+ if (error instanceof ImageH3InputError)
2099
+ throw new SDKError(error.message, ExitCode.USAGE);
2100
+ throw error;
2101
+ }
2102
+ return await this.requestJson({
2103
+ url: isImageH3EditRequest(body) ? imageEditsEndpoint(this.config.baseUrl) : imageGenerationsEndpoint(this.config.baseUrl),
2104
+ method: "POST",
2105
+ body,
2106
+ timeout: Math.max(this.config.timeout, IMAGE_H3_MIN_TIMEOUT_SEC)
2107
+ });
2108
+ }
1786
2109
  async save(response, options = {}) {
2110
+ if (isImageH3Response(response)) {
2111
+ try {
2112
+ const { saved } = await saveImageH3Images(response, {
2113
+ out: options.out,
2114
+ outDir: options.outDir,
2115
+ prefix: options.prefix,
2116
+ quiet: options.quiet ?? true
2117
+ });
2118
+ return saved;
2119
+ } catch (error) {
2120
+ if (error instanceof ImageH3InputError)
2121
+ throw new SDKError(error.message, ExitCode.USAGE);
2122
+ throw error;
2123
+ }
2124
+ }
1787
2125
  const fmt = options.responseFormat || "url";
1788
2126
  const quiet = options.quiet ?? true;
1789
2127
  const saved = [];
@@ -1792,14 +2130,14 @@ class ImageSDK extends Client {
1792
2130
  if (count > 1) {
1793
2131
  throw new SDKError("Cannot use `out` with multiple images. Use `outDir` instead.", ExitCode.USAGE);
1794
2132
  }
1795
- const destPath = resolve2(options.out);
1796
- const dir = dirname2(destPath);
1797
- if (!existsSync3(dir))
1798
- mkdirSync2(dir, { recursive: true });
2133
+ const destPath = resolve4(options.out);
2134
+ const dir = dirname4(destPath);
2135
+ if (!existsSync5(dir))
2136
+ mkdirSync3(dir, { recursive: true });
1799
2137
  if (fmt === "base64") {
1800
2138
  const image = (response.data.image_base64 || [])[0];
1801
2139
  if (image)
1802
- writeFileSync3(destPath, image, "base64");
2140
+ writeFileSync4(destPath, image, "base64");
1803
2141
  } else {
1804
2142
  const imageUrl = (response.data.image_urls || [])[0];
1805
2143
  if (imageUrl)
@@ -1807,21 +2145,21 @@ class ImageSDK extends Client {
1807
2145
  }
1808
2146
  saved.push(destPath);
1809
2147
  } else {
1810
- const outDir = resolve2(options.outDir || ".");
1811
- if (!existsSync3(outDir))
1812
- mkdirSync2(outDir, { recursive: true });
2148
+ const outDir = resolve4(options.outDir || ".");
2149
+ if (!existsSync5(outDir))
2150
+ mkdirSync3(outDir, { recursive: true });
1813
2151
  const prefix = options.prefix || "image";
1814
2152
  if (fmt === "base64") {
1815
2153
  const images = response.data.image_base64 || [];
1816
2154
  for (let i = 0;i < images.length; i++) {
1817
- const destPath = join2(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
1818
- writeFileSync3(destPath, images[i], "base64");
2155
+ const destPath = join3(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
2156
+ writeFileSync4(destPath, images[i], "base64");
1819
2157
  saved.push(destPath);
1820
2158
  }
1821
2159
  } else {
1822
2160
  const imageUrls = response.data.image_urls || [];
1823
2161
  for (let i = 0;i < imageUrls.length; i++) {
1824
- const destPath = join2(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
2162
+ const destPath = join3(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
1825
2163
  await downloadFile(imageUrls[i], destPath, { quiet });
1826
2164
  saved.push(destPath);
1827
2165
  }
@@ -1876,7 +2214,7 @@ async function poll(config, opts) {
1876
2214
  const extra = failureReason ? ` (${failureReason})` : "";
1877
2215
  throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1878
2216
  }
1879
- await new Promise((r) => setTimeout(r, opts.intervalSec * 1000));
2217
+ await new Promise((r) => setTimeout(r, Math.min(opts.intervalSec * 1000, Math.max(0, deadline - Date.now()))));
1880
2218
  }
1881
2219
  } finally {
1882
2220
  spinner.stop();
@@ -1884,24 +2222,9 @@ async function poll(config, opts) {
1884
2222
  throw new CLIError("Polling timed out.", ExitCode.TIMEOUT, "Try increasing --timeout or check task status manually.");
1885
2223
  }
1886
2224
 
1887
- // src/utils/media.ts
1888
- var VIDEO_V2_MEDIA_SIZE_LIMITS = {
1889
- image: 30 * 1024 * 1024,
1890
- video: 50 * 1024 * 1024,
1891
- audio: 15 * 1024 * 1024
1892
- };
1893
- var VIDEO_V2_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
1894
- function dataUriDecodedSize(input) {
1895
- const match = /^data:[^;,]+;base64,([\s\S]*)$/.exec(input);
1896
- if (!match)
1897
- return;
1898
- const base64 = match[1].replace(/\s/g, "");
1899
- const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
1900
- return Math.max(0, Math.floor(base64.length * 3 / 4) - padding);
1901
- }
1902
-
1903
2225
  // src/video/v2.ts
1904
2226
  var VIDEO_V2_MODEL = "MiniMax-H3";
2227
+ var VIDEO_V2_RESOLUTIONS = new Set(["768P", "2K"]);
1905
2228
  var VIDEO_V2_RATIOS = new Set([
1906
2229
  "adaptive",
1907
2230
  "21:9",
@@ -1984,8 +2307,8 @@ function validateVideoV2Request(request) {
1984
2307
  if (textItems.some((item) => item.text.length > 7000)) {
1985
2308
  throw new VideoV2InputError("MiniMax-H3 text content must not exceed 7000 characters.");
1986
2309
  }
1987
- if (request.resolution !== "2K") {
1988
- throw new VideoV2InputError("MiniMax-H3 currently only supports 2K resolution.");
2310
+ if (!VIDEO_V2_RESOLUTIONS.has(request.resolution)) {
2311
+ throw new VideoV2InputError("MiniMax-H3 resolution must be one of: 768P, 2K.");
1989
2312
  }
1990
2313
  if (!Number.isInteger(request.duration) || request.duration < 4 || request.duration > 15) {
1991
2314
  throw new VideoV2InputError("MiniMax-H3 duration must be an integer from 4 to 15 seconds.");
@@ -2213,53 +2536,6 @@ class SearchSDK extends Client {
2213
2536
  }
2214
2537
  }
2215
2538
 
2216
- // src/utils/image.ts
2217
- import { readFileSync as readFileSync3, existsSync as existsSync4, statSync as statSync2 } from "fs";
2218
- import { extname } from "path";
2219
- var IMAGE_MIME_TYPES = {
2220
- ".jpg": "image/jpeg",
2221
- ".jpeg": "image/jpeg",
2222
- ".png": "image/png",
2223
- ".webp": "image/webp",
2224
- ".heic": "image/heic",
2225
- ".heif": "image/heif"
2226
- };
2227
- function localFileToDataUri(filePath, maxBytes) {
2228
- if (maxBytes !== undefined) {
2229
- const size = statSync2(filePath).size;
2230
- if (size > maxBytes) {
2231
- 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.");
2232
- }
2233
- }
2234
- const ext = extname(filePath).toLowerCase();
2235
- const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
2236
- const data = readFileSync3(filePath);
2237
- return `data:${mime};base64,${data.toString("base64")}`;
2238
- }
2239
- var MAX_IMAGE_SIZE_BYTES = 50 * 1024 * 1024;
2240
- async function toDataUri(image) {
2241
- if (image.startsWith("data:"))
2242
- return image;
2243
- if (image.startsWith("http://") || image.startsWith("https://")) {
2244
- const res = await fetch(image);
2245
- if (!res.ok)
2246
- throw new CLIError(`Failed to download image: HTTP ${res.status}`, ExitCode.GENERAL);
2247
- const contentType = res.headers.get("content-type") || "image/jpeg";
2248
- const mime = contentType.split(";")[0].trim();
2249
- const buf = await res.arrayBuffer();
2250
- if (buf.byteLength > MAX_IMAGE_SIZE_BYTES) {
2251
- throw new CLIError(`Image too large (${(buf.byteLength / 1024 / 1024).toFixed(1)} MB). Maximum is 50 MB.`, ExitCode.USAGE);
2252
- }
2253
- return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
2254
- }
2255
- if (!existsSync4(image))
2256
- throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
2257
- const ext = extname(image).toLowerCase();
2258
- if (!IMAGE_MIME_TYPES[ext])
2259
- throw new CLIError(`Unsupported image format "${ext}". Supported: jpg, jpeg, png, webp`, ExitCode.USAGE);
2260
- return localFileToDataUri(image);
2261
- }
2262
-
2263
2539
  // src/sdk/vision/index.ts
2264
2540
  class VisionSDK extends Client {
2265
2541
  async describe(request) {
@@ -2297,12 +2573,12 @@ class QuotaSDK extends Client {
2297
2573
  }
2298
2574
 
2299
2575
  // src/files/upload.ts
2300
- import { existsSync as existsSync5 } from "node:fs";
2576
+ import { existsSync as existsSync6 } from "node:fs";
2301
2577
  import { readFile } from "node:fs/promises";
2302
- import { basename as basename2, resolve as resolve3 } from "node:path";
2578
+ import { basename as basename2, resolve as resolve5 } from "node:path";
2303
2579
  function resolveFileUploadPath(filePath, createFileNotFoundError) {
2304
- const fullPath = resolve3(filePath);
2305
- if (!existsSync5(fullPath)) {
2580
+ const fullPath = resolve5(filePath);
2581
+ if (!existsSync6(fullPath)) {
2306
2582
  throw createFileNotFoundError(fullPath);
2307
2583
  }
2308
2584
  return fullPath;