mmx-cli 1.0.28 → 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
  }
@@ -877,7 +917,7 @@ function fileDeleteEndpoint(baseUrl) {
877
917
  }
878
918
 
879
919
  // src/config/models.ts
880
- var DEFAULT_TEXT_MODEL = "MiniMax-M3.1-Flash-Preview";
920
+ var DEFAULT_TEXT_MODEL = "MiniMax-M3.1-Flash";
881
921
 
882
922
  // src/sdk/text/index.ts
883
923
  class TextSDK extends Client {
@@ -923,7 +963,7 @@ class TextSDK extends Client {
923
963
 
924
964
  // src/sdk/speech/index.ts
925
965
  import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, statSync, writeFileSync as writeFileSync2 } from "node:fs";
926
- import { basename, resolve, dirname } from "node:path";
966
+ import { basename, resolve as resolve2, dirname as dirname2 } from "node:path";
927
967
 
928
968
  // src/command.ts
929
969
  function defineCommand(spec) {
@@ -1124,6 +1164,16 @@ function toMerged(target, source) {
1124
1164
  }
1125
1165
  });
1126
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
+
1127
1177
  // src/utils/stt.ts
1128
1178
  var STT_DEFAULT_MODEL = "asr-1.0";
1129
1179
  var STT_RESPONSE_FORMATS = [
@@ -1214,7 +1264,7 @@ function blobFilename(file) {
1214
1264
  }
1215
1265
  function prepareAudioUpload(file) {
1216
1266
  if (typeof file === "string") {
1217
- const fullPath = resolve(file);
1267
+ const fullPath = resolve2(file);
1218
1268
  if (!existsSync2(fullPath)) {
1219
1269
  throw new SDKError(`File not found: ${fullPath}`, ExitCode.USAGE);
1220
1270
  }
@@ -1312,12 +1362,12 @@ class SpeechSDK extends Client {
1312
1362
  }
1313
1363
  }
1314
1364
  save(response, outPath, ext = "mp3") {
1315
- const dest = resolve(outPath || defaultFilename("speech", ext));
1365
+ const dest = resolve2(outPath || defaultFilename("speech", ext));
1316
1366
  const audioHex = response.data.audio;
1317
1367
  if (!audioHex) {
1318
1368
  throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1319
1369
  }
1320
- const dir = dirname(dest);
1370
+ const dir = dirname2(dest);
1321
1371
  if (!existsSync2(dir))
1322
1372
  mkdirSync(dir, { recursive: true });
1323
1373
  try {
@@ -1341,7 +1391,7 @@ class SpeechSDK extends Client {
1341
1391
  },
1342
1392
  audio_setting: {
1343
1393
  format: "mp3",
1344
- sample_rate: 32000,
1394
+ sample_rate: t2aDefaultSampleRate(params.audio_setting?.format ?? "mp3", 32000),
1345
1395
  bitrate: 128000,
1346
1396
  channel: 1
1347
1397
  },
@@ -1357,8 +1407,12 @@ class SpeechSDK extends Client {
1357
1407
  }
1358
1408
 
1359
1409
  // src/sdk/image/index.ts
1360
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
1361
- 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";
1362
1416
 
1363
1417
  // src/files/download.ts
1364
1418
  import { createWriteStream, renameSync as renameSync2, unlinkSync as unlinkSync2 } from "fs";
@@ -1775,9 +1829,255 @@ async function downloadFile(url, destPath, opts) {
1775
1829
  throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, exitCode, exitCode === ExitCode.NETWORK ? "Check your network connection and proxy settings." : undefined);
1776
1830
  }
1777
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
+
1778
2075
  // src/sdk/image/index.ts
1779
2076
  class ImageSDK extends Client {
1780
2077
  async generate(request) {
2078
+ if (isImageH3Model(request.model)) {
2079
+ return await this.generateH3(request);
2080
+ }
1781
2081
  const body = this.validateParams(request);
1782
2082
  const url = imageEndpoint(this.config.baseUrl);
1783
2083
  return await this.requestJson({
@@ -1786,7 +2086,42 @@ class ImageSDK extends Client {
1786
2086
  body
1787
2087
  });
1788
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
+ }
1789
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
+ }
1790
2125
  const fmt = options.responseFormat || "url";
1791
2126
  const quiet = options.quiet ?? true;
1792
2127
  const saved = [];
@@ -1795,14 +2130,14 @@ class ImageSDK extends Client {
1795
2130
  if (count > 1) {
1796
2131
  throw new SDKError("Cannot use `out` with multiple images. Use `outDir` instead.", ExitCode.USAGE);
1797
2132
  }
1798
- const destPath = resolve2(options.out);
1799
- const dir = dirname2(destPath);
1800
- if (!existsSync3(dir))
1801
- mkdirSync2(dir, { recursive: true });
2133
+ const destPath = resolve4(options.out);
2134
+ const dir = dirname4(destPath);
2135
+ if (!existsSync5(dir))
2136
+ mkdirSync3(dir, { recursive: true });
1802
2137
  if (fmt === "base64") {
1803
2138
  const image = (response.data.image_base64 || [])[0];
1804
2139
  if (image)
1805
- writeFileSync3(destPath, image, "base64");
2140
+ writeFileSync4(destPath, image, "base64");
1806
2141
  } else {
1807
2142
  const imageUrl = (response.data.image_urls || [])[0];
1808
2143
  if (imageUrl)
@@ -1810,21 +2145,21 @@ class ImageSDK extends Client {
1810
2145
  }
1811
2146
  saved.push(destPath);
1812
2147
  } else {
1813
- const outDir = resolve2(options.outDir || ".");
1814
- if (!existsSync3(outDir))
1815
- mkdirSync2(outDir, { recursive: true });
2148
+ const outDir = resolve4(options.outDir || ".");
2149
+ if (!existsSync5(outDir))
2150
+ mkdirSync3(outDir, { recursive: true });
1816
2151
  const prefix = options.prefix || "image";
1817
2152
  if (fmt === "base64") {
1818
2153
  const images = response.data.image_base64 || [];
1819
2154
  for (let i = 0;i < images.length; i++) {
1820
- const destPath = join2(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
1821
- writeFileSync3(destPath, images[i], "base64");
2155
+ const destPath = join3(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
2156
+ writeFileSync4(destPath, images[i], "base64");
1822
2157
  saved.push(destPath);
1823
2158
  }
1824
2159
  } else {
1825
2160
  const imageUrls = response.data.image_urls || [];
1826
2161
  for (let i = 0;i < imageUrls.length; i++) {
1827
- 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`);
1828
2163
  await downloadFile(imageUrls[i], destPath, { quiet });
1829
2164
  saved.push(destPath);
1830
2165
  }
@@ -1879,7 +2214,7 @@ async function poll(config, opts) {
1879
2214
  const extra = failureReason ? ` (${failureReason})` : "";
1880
2215
  throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1881
2216
  }
1882
- 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()))));
1883
2218
  }
1884
2219
  } finally {
1885
2220
  spinner.stop();
@@ -1887,24 +2222,9 @@ async function poll(config, opts) {
1887
2222
  throw new CLIError("Polling timed out.", ExitCode.TIMEOUT, "Try increasing --timeout or check task status manually.");
1888
2223
  }
1889
2224
 
1890
- // src/utils/media.ts
1891
- var VIDEO_V2_MEDIA_SIZE_LIMITS = {
1892
- image: 30 * 1024 * 1024,
1893
- video: 50 * 1024 * 1024,
1894
- audio: 15 * 1024 * 1024
1895
- };
1896
- var VIDEO_V2_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
1897
- function dataUriDecodedSize(input) {
1898
- const match = /^data:[^;,]+;base64,([\s\S]*)$/.exec(input);
1899
- if (!match)
1900
- return;
1901
- const base64 = match[1].replace(/\s/g, "");
1902
- const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
1903
- return Math.max(0, Math.floor(base64.length * 3 / 4) - padding);
1904
- }
1905
-
1906
2225
  // src/video/v2.ts
1907
2226
  var VIDEO_V2_MODEL = "MiniMax-H3";
2227
+ var VIDEO_V2_RESOLUTIONS = new Set(["768P", "2K"]);
1908
2228
  var VIDEO_V2_RATIOS = new Set([
1909
2229
  "adaptive",
1910
2230
  "21:9",
@@ -1987,8 +2307,8 @@ function validateVideoV2Request(request) {
1987
2307
  if (textItems.some((item) => item.text.length > 7000)) {
1988
2308
  throw new VideoV2InputError("MiniMax-H3 text content must not exceed 7000 characters.");
1989
2309
  }
1990
- if (request.resolution !== "2K") {
1991
- 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.");
1992
2312
  }
1993
2313
  if (!Number.isInteger(request.duration) || request.duration < 4 || request.duration > 15) {
1994
2314
  throw new VideoV2InputError("MiniMax-H3 duration must be an integer from 4 to 15 seconds.");
@@ -2216,53 +2536,6 @@ class SearchSDK extends Client {
2216
2536
  }
2217
2537
  }
2218
2538
 
2219
- // src/utils/image.ts
2220
- import { readFileSync as readFileSync3, existsSync as existsSync4, statSync as statSync2 } from "fs";
2221
- import { extname } from "path";
2222
- var IMAGE_MIME_TYPES = {
2223
- ".jpg": "image/jpeg",
2224
- ".jpeg": "image/jpeg",
2225
- ".png": "image/png",
2226
- ".webp": "image/webp",
2227
- ".heic": "image/heic",
2228
- ".heif": "image/heif"
2229
- };
2230
- function localFileToDataUri(filePath, maxBytes) {
2231
- if (maxBytes !== undefined) {
2232
- const size = statSync2(filePath).size;
2233
- if (size > maxBytes) {
2234
- 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.");
2235
- }
2236
- }
2237
- const ext = extname(filePath).toLowerCase();
2238
- const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
2239
- const data = readFileSync3(filePath);
2240
- return `data:${mime};base64,${data.toString("base64")}`;
2241
- }
2242
- var MAX_IMAGE_SIZE_BYTES = 50 * 1024 * 1024;
2243
- async function toDataUri(image) {
2244
- if (image.startsWith("data:"))
2245
- return image;
2246
- if (image.startsWith("http://") || image.startsWith("https://")) {
2247
- const res = await fetch(image);
2248
- if (!res.ok)
2249
- throw new CLIError(`Failed to download image: HTTP ${res.status}`, ExitCode.GENERAL);
2250
- const contentType = res.headers.get("content-type") || "image/jpeg";
2251
- const mime = contentType.split(";")[0].trim();
2252
- const buf = await res.arrayBuffer();
2253
- if (buf.byteLength > MAX_IMAGE_SIZE_BYTES) {
2254
- throw new CLIError(`Image too large (${(buf.byteLength / 1024 / 1024).toFixed(1)} MB). Maximum is 50 MB.`, ExitCode.USAGE);
2255
- }
2256
- return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
2257
- }
2258
- if (!existsSync4(image))
2259
- throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
2260
- const ext = extname(image).toLowerCase();
2261
- if (!IMAGE_MIME_TYPES[ext])
2262
- throw new CLIError(`Unsupported image format "${ext}". Supported: jpg, jpeg, png, webp`, ExitCode.USAGE);
2263
- return localFileToDataUri(image);
2264
- }
2265
-
2266
2539
  // src/sdk/vision/index.ts
2267
2540
  class VisionSDK extends Client {
2268
2541
  async describe(request) {
@@ -2300,12 +2573,12 @@ class QuotaSDK extends Client {
2300
2573
  }
2301
2574
 
2302
2575
  // src/files/upload.ts
2303
- import { existsSync as existsSync5 } from "node:fs";
2576
+ import { existsSync as existsSync6 } from "node:fs";
2304
2577
  import { readFile } from "node:fs/promises";
2305
- import { basename as basename2, resolve as resolve3 } from "node:path";
2578
+ import { basename as basename2, resolve as resolve5 } from "node:path";
2306
2579
  function resolveFileUploadPath(filePath, createFileNotFoundError) {
2307
- const fullPath = resolve3(filePath);
2308
- if (!existsSync5(fullPath)) {
2580
+ const fullPath = resolve5(filePath);
2581
+ if (!existsSync6(fullPath)) {
2309
2582
  throw createFileNotFoundError(fullPath);
2310
2583
  }
2311
2584
  return fullPath;