mmx-cli 1.0.13 → 1.0.15

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
@@ -9,8 +9,35 @@ var REGIONS = {
9
9
  global: "https://api.minimax.io",
10
10
  cn: "https://api.minimaxi.com"
11
11
  };
12
+ var OAUTH_HOSTS = {
13
+ global: "https://account.minimax.io",
14
+ cn: "https://account.minimaxi.com"
15
+ };
12
16
  var VALID_REGIONS = new Set(["global", "cn"]);
13
17
  var VALID_OUTPUTS = new Set(["text", "json"]);
18
+ function parseOAuth(raw) {
19
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
20
+ return;
21
+ const o = raw;
22
+ if (typeof o.access_token !== "string" || !o.access_token)
23
+ return;
24
+ if (typeof o.refresh_token !== "string")
25
+ return;
26
+ if (typeof o.expires_at !== "string")
27
+ return;
28
+ const out = {
29
+ access_token: o.access_token,
30
+ refresh_token: o.refresh_token,
31
+ expires_at: o.expires_at
32
+ };
33
+ if (typeof o.region === "string" && VALID_REGIONS.has(o.region))
34
+ out.region = o.region;
35
+ if (typeof o.resource_url === "string" && o.resource_url.startsWith("http"))
36
+ out.resource_url = o.resource_url;
37
+ if (typeof o.account === "string" && o.account.length > 0)
38
+ out.account = o.account;
39
+ return out;
40
+ }
14
41
  function parseConfigFile(raw) {
15
42
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
16
43
  return {};
@@ -28,6 +55,9 @@ function parseConfigFile(raw) {
28
55
  out.timeout = obj.timeout;
29
56
  if (typeof obj.proxy === "string" && obj.proxy.startsWith("http"))
30
57
  out.proxy = obj.proxy;
58
+ const oauth = parseOAuth(obj.oauth);
59
+ if (oauth)
60
+ out.oauth = oauth;
31
61
  if (typeof obj.default_text_model === "string" && obj.default_text_model.length > 0)
32
62
  out.default_text_model = obj.default_text_model;
33
63
  if (typeof obj.default_speech_model === "string" && obj.default_speech_model.length > 0)
@@ -44,14 +74,13 @@ import { homedir } from "os";
44
74
  import { join } from "path";
45
75
  var CONFIG_DIR_NAME = ".mmx";
46
76
  function getConfigDir() {
77
+ if (process.env.MMX_CONFIG_DIR)
78
+ return process.env.MMX_CONFIG_DIR;
47
79
  return join(homedir(), CONFIG_DIR_NAME);
48
80
  }
49
81
  function getConfigPath() {
50
82
  return join(getConfigDir(), "config.json");
51
83
  }
52
- function getCredentialsPath() {
53
- return join(getConfigDir(), "credentials.json");
54
- }
55
84
  async function ensureConfigDir() {
56
85
  const dir = getConfigDir();
57
86
  const fs = await import("fs/promises");
@@ -141,6 +170,50 @@ function formatOutput(data, format) {
141
170
  }
142
171
  }
143
172
 
173
+ // src/errors/codes.ts
174
+ var ExitCode = {
175
+ SUCCESS: 0,
176
+ GENERAL: 1,
177
+ USAGE: 2,
178
+ AUTH: 3,
179
+ QUOTA: 4,
180
+ TIMEOUT: 5,
181
+ NETWORK: 6,
182
+ CONTENT_FILTER: 10
183
+ };
184
+
185
+ // src/errors/base.ts
186
+ class CLIError extends Error {
187
+ exitCode;
188
+ hint;
189
+ constructor(message, exitCode = ExitCode.GENERAL, hint) {
190
+ super(message);
191
+ this.name = "CLIError";
192
+ this.exitCode = exitCode;
193
+ this.hint = hint;
194
+ }
195
+ toJSON() {
196
+ return {
197
+ error: {
198
+ code: this.exitCode,
199
+ message: this.message,
200
+ ...this.hint ? { hint: this.hint } : {}
201
+ }
202
+ };
203
+ }
204
+ }
205
+
206
+ class SDKError extends CLIError {
207
+ exitCode;
208
+ hint;
209
+ constructor(message, exitCode = ExitCode.GENERAL, hint) {
210
+ super(message);
211
+ this.name = "SDKError";
212
+ this.exitCode = exitCode;
213
+ this.hint = hint;
214
+ }
215
+ }
216
+
144
217
  // src/config/loader.ts
145
218
  function readConfigFile() {
146
219
  const path = getConfigPath();
@@ -157,16 +230,27 @@ function readConfigFile() {
157
230
  return {};
158
231
  }
159
232
  }
233
+ async function writeConfigFile(data) {
234
+ await ensureConfigDir();
235
+ const path = getConfigPath();
236
+ const tmp = path + ".tmp";
237
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + `
238
+ `, { mode: 384 });
239
+ renameSync(tmp, path);
240
+ }
160
241
  function loadConfig(flags) {
161
242
  const file = readConfigFile();
162
243
  const apiKey = flags.apiKey || undefined;
163
244
  const fileApiKey = file.api_key;
164
245
  const explicitRegion = flags.region || process.env.MINIMAX_REGION || undefined;
246
+ if (explicitRegion && !(explicitRegion in REGIONS)) {
247
+ throw new CLIError(`Invalid region "${explicitRegion}". Valid values: ${Object.keys(REGIONS).join(", ")}`, ExitCode.USAGE);
248
+ }
165
249
  const cachedRegion = file.region;
166
250
  const region = explicitRegion || cachedRegion || "global";
167
251
  const activeKey = apiKey || fileApiKey;
168
252
  const needsRegionDetection = !explicitRegion && (!cachedRegion || activeKey !== undefined && activeKey !== file.api_key);
169
- const baseUrl = flags.baseUrl || process.env.MINIMAX_BASE_URL || file.base_url || REGIONS[region] || REGIONS.global;
253
+ const baseUrl = flags.baseUrl || process.env.MINIMAX_BASE_URL || file.base_url || file.oauth?.resource_url || REGIONS[region] || REGIONS.global;
170
254
  const output = detectOutputFormat(flags.output || process.env.MINIMAX_OUTPUT || file.output);
171
255
  const envTimeout = process.env.MINIMAX_TIMEOUT ? Number(process.env.MINIMAX_TIMEOUT) : undefined;
172
256
  const validEnvTimeout = envTimeout !== undefined && Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : undefined;
@@ -195,111 +279,40 @@ function loadConfig(flags) {
195
279
  };
196
280
  }
197
281
 
198
- // src/errors/codes.ts
199
- var ExitCode = {
200
- SUCCESS: 0,
201
- GENERAL: 1,
202
- USAGE: 2,
203
- AUTH: 3,
204
- QUOTA: 4,
205
- TIMEOUT: 5,
206
- NETWORK: 6,
207
- CONTENT_FILTER: 10
208
- };
209
-
210
- // src/errors/base.ts
211
- class CLIError extends Error {
212
- exitCode;
213
- hint;
214
- constructor(message, exitCode = ExitCode.GENERAL, hint) {
215
- super(message);
216
- this.name = "CLIError";
217
- this.exitCode = exitCode;
218
- this.hint = hint;
219
- }
220
- toJSON() {
221
- return {
222
- error: {
223
- code: this.exitCode,
224
- message: this.message,
225
- ...this.hint ? { hint: this.hint } : {}
226
- }
227
- };
228
- }
229
- }
230
-
231
- class SDKError extends CLIError {
232
- exitCode;
233
- hint;
234
- constructor(message, exitCode = ExitCode.GENERAL, hint) {
235
- super(message);
236
- this.name = "SDKError";
237
- this.exitCode = exitCode;
238
- this.hint = hint;
239
- }
240
- }
241
-
242
282
  // src/auth/credentials.ts
243
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, renameSync as renameSync2, unlinkSync, existsSync as existsSync2, statSync } from "fs";
244
283
  async function loadCredentials() {
245
- const path = getCredentialsPath();
246
- if (!existsSync2(path))
247
- return null;
248
- try {
249
- checkPermissions(path);
250
- const raw = readFileSync2(path, "utf-8");
251
- const data = JSON.parse(raw);
252
- if (!data.access_token || !data.refresh_token)
253
- return null;
254
- return data;
255
- } catch (err) {
256
- const e = err;
257
- if (e instanceof SyntaxError || e.message.includes("JSON")) {
258
- process.stderr.write(`Warning: credentials file is corrupted. Run 'mmx auth logout' to reset.
259
- `);
260
- }
261
- return null;
262
- }
284
+ const cfg = readConfigFile();
285
+ return cfg.oauth ?? null;
263
286
  }
264
287
  async function saveCredentials(creds) {
265
- await ensureConfigDir();
266
- const path = getCredentialsPath();
267
- const tmp = path + ".tmp";
268
- writeFileSync2(tmp, JSON.stringify(creds, null, 2) + `
269
- `, { mode: 384 });
270
- renameSync2(tmp, path);
271
- }
272
- function checkPermissions(path) {
273
- try {
274
- const stat = statSync(path);
275
- const mode = stat.mode & 511;
276
- if (mode !== 384) {
277
- process.stderr.write(`Warning: ${path} has permissions ${mode.toString(8)}, expected 600.
278
- `);
279
- }
280
- } catch {}
288
+ const existing = readConfigFile();
289
+ existing.oauth = creds;
290
+ await writeConfigFile(existing);
281
291
  }
282
292
 
283
293
  // src/auth/refresh.ts
284
- var TOKEN_URL = "https://api.minimax.io/v1/oauth/token";
285
- var MAX_REFRESH_RETRIES = 2;
294
+ var CLIENT_ID = "659cf4c1-615c-45f6-a5f6-4bf15eb476e5";
295
+ var MAX_RETRIES = 2;
286
296
  var RETRY_DELAY_MS = 500;
287
- async function refreshAccessToken(refreshToken) {
297
+ var REQUEST_TIMEOUT_MS = 1e4;
298
+ var REFRESH_BUFFER_MS = 5 * 60 * 1000;
299
+ async function refreshAccessToken(refreshToken, region = "global") {
300
+ const tokenUrl = `${OAUTH_HOSTS[region]}/oauth2/token`;
288
301
  let lastErr = null;
289
- for (let attempt = 0;attempt <= MAX_REFRESH_RETRIES; attempt++) {
290
- if (attempt > 0) {
302
+ for (let attempt = 0;attempt <= MAX_RETRIES; attempt++) {
303
+ if (attempt > 0)
291
304
  await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
292
- }
293
305
  let res;
294
306
  try {
295
- res = await fetch(TOKEN_URL, {
307
+ res = await fetch(tokenUrl, {
296
308
  method: "POST",
297
309
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
298
310
  body: new URLSearchParams({
299
311
  grant_type: "refresh_token",
300
- refresh_token: refreshToken
312
+ refresh_token: refreshToken,
313
+ client_id: CLIENT_ID
301
314
  }),
302
- signal: AbortSignal.timeout(1e4)
315
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
303
316
  });
304
317
  } catch (err) {
305
318
  const isTimeout = err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError" || err.message.includes("timed out"));
@@ -313,24 +326,31 @@ async function refreshAccessToken(refreshToken) {
313
326
  lastErr = new Error(`Token refresh failed: HTTP ${res.status}`);
314
327
  continue;
315
328
  }
316
- const data = await res.json();
317
- return data;
329
+ const body = await res.json();
330
+ if (body.status !== "success" || !body.access_token) {
331
+ throw new CLIError(`OAuth refresh failed: ${body.status}.`, ExitCode.AUTH, "Re-authenticate: mmx auth login");
332
+ }
333
+ return {
334
+ access_token: body.access_token,
335
+ refresh_token: body.refresh_token ?? refreshToken,
336
+ expires_at: new Date(body.expired_in ?? Date.now()).toISOString(),
337
+ resource_url: body.resource_url
338
+ };
318
339
  }
319
- throw new CLIError(`Token refresh failed after ${MAX_REFRESH_RETRIES + 1} attempts: ${lastErr?.message}`, ExitCode.AUTH, `Check your network connection.
340
+ throw new CLIError(`Token refresh failed after ${MAX_RETRIES + 1} attempts: ${lastErr?.message}`, ExitCode.AUTH, `Check your network connection.
320
341
  Re-authenticate: mmx auth login`);
321
342
  }
322
343
  async function ensureFreshToken(creds) {
323
344
  const expiresAt = new Date(creds.expires_at).getTime();
324
- const bufferMs = 5 * 60 * 1000;
325
- if (Date.now() < expiresAt - bufferMs) {
345
+ if (Date.now() < expiresAt - REFRESH_BUFFER_MS)
326
346
  return creds.access_token;
327
- }
328
- const tokens = await refreshAccessToken(creds.refresh_token);
347
+ const fresh = await refreshAccessToken(creds.refresh_token, creds.region ?? "global");
329
348
  const updated = {
330
- access_token: tokens.access_token,
331
- refresh_token: tokens.refresh_token,
332
- expires_at: new Date(Date.now() + tokens.expires_in * 1000).toISOString(),
333
- token_type: "Bearer",
349
+ access_token: fresh.access_token,
350
+ refresh_token: fresh.refresh_token,
351
+ expires_at: fresh.expires_at,
352
+ region: creds.region,
353
+ resource_url: fresh.resource_url ?? creds.resource_url,
334
354
  account: creds.account
335
355
  };
336
356
  await saveCredentials(updated);
@@ -345,7 +365,7 @@ async function resolveCredential(config) {
345
365
  const oauth = await loadCredentials();
346
366
  if (oauth) {
347
367
  const token = await ensureFreshToken(oauth);
348
- return { token, method: "oauth", source: "credentials.json" };
368
+ return { token, method: "oauth", source: "config.json" };
349
369
  }
350
370
  if (config.fileApiKey) {
351
371
  return { token: config.fileApiKey, method: "api-key", source: "config.json" };
@@ -430,22 +450,25 @@ var mmPink = "\x1B[38;2;236;72;153m";
430
450
  function tildePath(p) {
431
451
  return p.startsWith(homedir2()) ? p.replace(homedir2(), "~") : p;
432
452
  }
453
+ function stripScheme(url) {
454
+ return url.replace(/^https?:\/\//, "");
455
+ }
433
456
  function maybeShowStatusBar(config, token, model) {
434
457
  if (config.quiet || printed || !process.stderr.isTTY)
435
458
  return;
436
459
  printed = true;
437
460
  const filePath = config.configPath ? tildePath(config.configPath) : "~/.mmx/config.json";
438
- const regionSrc = config.fileRegion ? `${config.fileRegion} (file)` : "global (default)";
461
+ const baseUrlStr = stripScheme(config.baseUrl);
439
462
  const keySrc = config.apiKey ? "(flag)" : "(file)";
440
463
  const maskedKey = maskToken(token);
441
464
  const modelStr = model ? ` ${dim}|${reset} ${dim}Model:${reset} ${mmPurple}${model}${reset}` : "";
442
- process.stderr.write(`${bold}${mmBlue}MINIMAX${reset} ` + `${dim}${filePath}${reset} ` + `${dim}|${reset} ` + `${dim}Region:${reset} ${mmCyan}${regionSrc}${reset} ` + `${dim}|${reset} ` + `${dim}Key:${reset} ${mmPink}${maskedKey}${reset} ${dim}${keySrc}${reset}` + `${modelStr}
465
+ process.stderr.write(`${bold}${mmBlue}MINIMAX${reset} ` + `${dim}${filePath}${reset} ` + `${dim}|${reset} ` + `${dim}URL:${reset} ${mmCyan}${baseUrlStr}${reset} ` + `${dim}|${reset} ` + `${dim}Key:${reset} ${mmPink}${maskedKey}${reset} ${dim}${keySrc}${reset}` + `${modelStr}
443
466
  `);
444
467
  }
445
468
  // package.json
446
469
  var package_default = {
447
470
  name: "mmx-cli",
448
- version: "1.0.13",
471
+ version: "1.0.15",
449
472
  description: "CLI for the MiniMax AI Platform",
450
473
  type: "module",
451
474
  engines: {
@@ -525,7 +548,7 @@ async function request(config, opts) {
525
548
  method: opts.method ?? "GET",
526
549
  headers,
527
550
  body: opts.body ? isFormData ? opts.body : JSON.stringify(opts.body) : undefined,
528
- signal: AbortSignal.timeout(timeoutMs)
551
+ signal: opts.stream ? undefined : AbortSignal.timeout(timeoutMs)
529
552
  });
530
553
  if (config.verbose) {
531
554
  process.stderr.write(`< ${res.status} ${res.statusText}
@@ -562,6 +585,35 @@ async function* parseSSE(response) {
562
585
  return;
563
586
  const decoder = new TextDecoder;
564
587
  let buffer = "";
588
+ let event = {};
589
+ const processLine = (rawLine) => {
590
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
591
+ if (line === "") {
592
+ const completed = event.data !== undefined ? { data: event.data, event: event.event, id: event.id } : undefined;
593
+ event = {};
594
+ return completed;
595
+ }
596
+ if (line.startsWith(":"))
597
+ return;
598
+ const colonIndex = line.indexOf(":");
599
+ if (colonIndex === -1)
600
+ return;
601
+ const field = line.slice(0, colonIndex);
602
+ const value = line.slice(colonIndex + 1).trimStart();
603
+ switch (field) {
604
+ case "data":
605
+ event.data = event.data !== undefined ? `${event.data}
606
+ ${value}` : value;
607
+ break;
608
+ case "event":
609
+ event.event = value;
610
+ break;
611
+ case "id":
612
+ event.id = value;
613
+ break;
614
+ }
615
+ return;
616
+ };
565
617
  try {
566
618
  while (true) {
567
619
  const { done, value } = await reader.read();
@@ -571,42 +623,23 @@ async function* parseSSE(response) {
571
623
  const lines = buffer.split(`
572
624
  `);
573
625
  buffer = lines.pop() || "";
574
- let event = {};
575
626
  for (const line of lines) {
576
- if (line === "") {
577
- if (event.data !== undefined) {
578
- yield { data: event.data, event: event.event, id: event.id };
579
- }
580
- event = {};
581
- continue;
582
- }
583
- if (line.startsWith(":"))
584
- continue;
585
- const colonIndex = line.indexOf(":");
586
- if (colonIndex === -1)
587
- continue;
588
- const field = line.slice(0, colonIndex);
589
- const value2 = line.slice(colonIndex + 1).trimStart();
590
- switch (field) {
591
- case "data":
592
- event.data = event.data !== undefined ? `${event.data}
593
- ${value2}` : value2;
594
- break;
595
- case "event":
596
- event.event = value2;
597
- break;
598
- case "id":
599
- event.id = value2;
600
- break;
627
+ const completed = processLine(line);
628
+ if (completed) {
629
+ yield completed;
601
630
  }
602
631
  }
603
632
  }
604
- if (buffer.trim() && buffer.includes("data:")) {
605
- const colonIndex = buffer.indexOf(":");
606
- if (colonIndex !== -1) {
607
- yield { data: buffer.slice(colonIndex + 1).trimStart() };
633
+ buffer += decoder.decode();
634
+ if (buffer.length > 0) {
635
+ const completed = processLine(buffer);
636
+ if (completed) {
637
+ yield completed;
608
638
  }
609
639
  }
640
+ if (event.data !== undefined) {
641
+ yield { data: event.data, event: event.event, id: event.id };
642
+ }
610
643
  } finally {
611
644
  reader.releaseLock();
612
645
  }
@@ -687,6 +720,15 @@ function quotaEndpoint(baseUrl) {
687
720
  const host = baseUrl.includes("minimaxi.com") ? "https://api.minimaxi.com" : "https://api.minimax.io";
688
721
  return `${host}/v1/token_plan/remains`;
689
722
  }
723
+ function fileUploadEndpoint(baseUrl) {
724
+ return `${baseUrl}/v1/files`;
725
+ }
726
+ function fileListEndpoint(baseUrl) {
727
+ return `${baseUrl}/v1/files/list`;
728
+ }
729
+ function fileDeleteEndpoint(baseUrl) {
730
+ return `${baseUrl}/v1/files/delete`;
731
+ }
690
732
 
691
733
  // src/sdk/text/index.ts
692
734
  class TextSDK extends Client {
@@ -730,6 +772,10 @@ class TextSDK extends Client {
730
772
  }
731
773
  }
732
774
 
775
+ // src/sdk/speech/index.ts
776
+ import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
777
+ import { resolve, dirname } from "node:path";
778
+
733
779
  // src/command.ts
734
780
  function defineCommand(spec) {
735
781
  return {
@@ -930,6 +976,20 @@ function toMerged(target, source) {
930
976
  });
931
977
  }
932
978
  // src/sdk/speech/index.ts
979
+ function hexToBuffer(hex) {
980
+ if (!/^[0-9a-fA-F]*$/.test(hex)) {
981
+ throw new SDKError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
982
+ }
983
+ if (hex.length % 2 !== 0) {
984
+ throw new SDKError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
985
+ }
986
+ return Buffer.from(hex, "hex");
987
+ }
988
+ function defaultFilename(prefix, ext) {
989
+ const ts = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-");
990
+ return `${prefix}_${ts}.${ext}`;
991
+ }
992
+
933
993
  class SpeechSDK extends Client {
934
994
  async synthesize(request2) {
935
995
  const body = this.validateParams(request2);
@@ -967,6 +1027,25 @@ class SpeechSDK extends Client {
967
1027
  }
968
1028
  return voices;
969
1029
  }
1030
+ save(response, outPath, ext = "mp3") {
1031
+ const dest = resolve(outPath || defaultFilename("speech", ext));
1032
+ const audioHex = response.data.audio;
1033
+ if (!audioHex) {
1034
+ throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1035
+ }
1036
+ const dir = dirname(dest);
1037
+ if (!existsSync2(dir))
1038
+ mkdirSync(dir, { recursive: true });
1039
+ try {
1040
+ writeFileSync2(dest, hexToBuffer(audioHex));
1041
+ } catch (err) {
1042
+ if (err.code === "ENOSPC") {
1043
+ throw new SDKError("Disk full — cannot write audio file.", ExitCode.GENERAL);
1044
+ }
1045
+ throw err;
1046
+ }
1047
+ return dest;
1048
+ }
970
1049
  validateParams(params) {
971
1050
  if (!params.text) {
972
1051
  throw new SDKError("text is required", ExitCode.USAGE);
@@ -988,38 +1067,11 @@ class SpeechSDK extends Client {
988
1067
  }
989
1068
 
990
1069
  // src/sdk/image/index.ts
991
- class ImageSDK extends Client {
992
- async generate(request2) {
993
- const body = this.validateParams(request2);
994
- const url = imageEndpoint(this.config.baseUrl);
995
- return await this.requestJson({
996
- url,
997
- method: "POST",
998
- body
999
- });
1000
- }
1001
- validateParams(params) {
1002
- const { width, height, aspect_ratio } = params;
1003
- if (width !== undefined || height !== undefined) {
1004
- if (width === undefined || height === undefined) {
1005
- throw new SDKError("Both width and height must be provided", ExitCode.USAGE);
1006
- }
1007
- for (const [name, val] of Object.entries({ width, height })) {
1008
- if (val < 512 || val > 2048) {
1009
- throw new SDKError(`${name} must be between 512 and 2048, got ${val}.`, ExitCode.USAGE);
1010
- }
1011
- if (val % 8 !== 0) {
1012
- throw new SDKError(`${name} must be a multiple of 8, got ${val}.`, ExitCode.USAGE);
1013
- }
1014
- }
1015
- }
1016
- return toMerged({
1017
- model: "image-01",
1018
- aspect_ratio: width !== undefined && height !== undefined ? undefined : aspect_ratio,
1019
- n: 1
1020
- }, params);
1021
- }
1022
- }
1070
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
1071
+ import { join as join2, resolve as resolve2, dirname as dirname2 } from "node:path";
1072
+
1073
+ // src/files/download.ts
1074
+ import { createWriteStream, renameSync as renameSync2, unlinkSync } from "fs";
1023
1075
 
1024
1076
  // src/output/progress.ts
1025
1077
  var SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -1078,38 +1130,7 @@ function createProgressBar(total, label = "") {
1078
1130
  };
1079
1131
  }
1080
1132
 
1081
- // src/polling/poll.ts
1082
- async function poll(config, opts) {
1083
- const deadline = Date.now() + opts.timeoutSec * 1000;
1084
- const spinner = createSpinner("Polling...");
1085
- if (!config.quiet)
1086
- spinner.start();
1087
- try {
1088
- while (Date.now() < deadline) {
1089
- const data = await requestJson(config, { url: opts.url });
1090
- if (opts.getStatus && !config.quiet) {
1091
- spinner.update(`Status: ${opts.getStatus(data)}`);
1092
- }
1093
- if (opts.isComplete(data)) {
1094
- spinner.stop("Done.");
1095
- return data;
1096
- }
1097
- if (opts.isFailed(data)) {
1098
- spinner.stop("Failed.");
1099
- const status = opts.getStatus ? opts.getStatus(data) : "failed";
1100
- const extra = data?.base_resp ? ` (${data.base_resp.status_msg})` : "";
1101
- throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1102
- }
1103
- await new Promise((r) => setTimeout(r, opts.intervalSec * 1000));
1104
- }
1105
- } finally {
1106
- spinner.stop();
1107
- }
1108
- throw new CLIError("Polling timed out.", ExitCode.TIMEOUT, "Try increasing --timeout or check task status manually.");
1109
- }
1110
-
1111
1133
  // src/files/download.ts
1112
- import { createWriteStream, renameSync as renameSync3, unlinkSync as unlinkSync2 } from "fs";
1113
1134
  async function downloadFile(url, destPath, opts) {
1114
1135
  const downloadUrl = url.startsWith("http://") ? url.replace("http://", "https://") : url;
1115
1136
  const maxRetries = opts?.retries ?? 3;
@@ -1163,8 +1184,8 @@ async function downloadFile(url, destPath, opts) {
1163
1184
  progress?.finish();
1164
1185
  try {
1165
1186
  if (!writer.destroyed) {
1166
- await new Promise((resolve, reject) => {
1167
- writer.on("finish", resolve);
1187
+ await new Promise((resolve2, reject) => {
1188
+ writer.on("finish", resolve2);
1168
1189
  writer.on("error", reject);
1169
1190
  writer.end();
1170
1191
  });
@@ -1173,12 +1194,12 @@ async function downloadFile(url, destPath, opts) {
1173
1194
  } finally {
1174
1195
  if (!completed) {
1175
1196
  try {
1176
- unlinkSync2(tmpPath);
1197
+ unlinkSync(tmpPath);
1177
1198
  } catch {}
1178
1199
  }
1179
1200
  }
1180
1201
  }
1181
- renameSync3(tmpPath, destPath);
1202
+ renameSync2(tmpPath, destPath);
1182
1203
  return { size: received };
1183
1204
  } catch (err) {
1184
1205
  lastError = err instanceof Error ? err : new Error(String(err));
@@ -1192,6 +1213,116 @@ async function downloadFile(url, destPath, opts) {
1192
1213
  throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, ExitCode.NETWORK, "Check your network connection and proxy settings.");
1193
1214
  }
1194
1215
 
1216
+ // src/sdk/image/index.ts
1217
+ class ImageSDK extends Client {
1218
+ async generate(request2) {
1219
+ const body = this.validateParams(request2);
1220
+ const url = imageEndpoint(this.config.baseUrl);
1221
+ return await this.requestJson({
1222
+ url,
1223
+ method: "POST",
1224
+ body
1225
+ });
1226
+ }
1227
+ async save(response, options = {}) {
1228
+ const fmt = options.responseFormat || "url";
1229
+ const quiet = options.quiet ?? true;
1230
+ const saved = [];
1231
+ if (options.out) {
1232
+ const count = fmt === "base64" ? (response.data.image_base64 || []).length : (response.data.image_urls || []).length;
1233
+ if (count > 1) {
1234
+ throw new SDKError("Cannot use `out` with multiple images. Use `outDir` instead.", ExitCode.USAGE);
1235
+ }
1236
+ const destPath = resolve2(options.out);
1237
+ const dir = dirname2(destPath);
1238
+ if (!existsSync3(dir))
1239
+ mkdirSync2(dir, { recursive: true });
1240
+ if (fmt === "base64") {
1241
+ const image = (response.data.image_base64 || [])[0];
1242
+ if (image)
1243
+ writeFileSync3(destPath, image, "base64");
1244
+ } else {
1245
+ const imageUrl = (response.data.image_urls || [])[0];
1246
+ if (imageUrl)
1247
+ await downloadFile(imageUrl, destPath, { quiet });
1248
+ }
1249
+ saved.push(destPath);
1250
+ } else {
1251
+ const outDir = resolve2(options.outDir || ".");
1252
+ if (!existsSync3(outDir))
1253
+ mkdirSync2(outDir, { recursive: true });
1254
+ const prefix = options.prefix || "image";
1255
+ if (fmt === "base64") {
1256
+ const images = response.data.image_base64 || [];
1257
+ for (let i = 0;i < images.length; i++) {
1258
+ const destPath = join2(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
1259
+ writeFileSync3(destPath, images[i], "base64");
1260
+ saved.push(destPath);
1261
+ }
1262
+ } else {
1263
+ const imageUrls = response.data.image_urls || [];
1264
+ for (let i = 0;i < imageUrls.length; i++) {
1265
+ const destPath = join2(outDir, `${prefix}_${String(i + 1).padStart(3, "0")}.jpg`);
1266
+ await downloadFile(imageUrls[i], destPath, { quiet });
1267
+ saved.push(destPath);
1268
+ }
1269
+ }
1270
+ }
1271
+ return saved;
1272
+ }
1273
+ validateParams(params) {
1274
+ const { width, height, aspect_ratio } = params;
1275
+ if (width !== undefined || height !== undefined) {
1276
+ if (width === undefined || height === undefined) {
1277
+ throw new SDKError("Both width and height must be provided", ExitCode.USAGE);
1278
+ }
1279
+ for (const [name, val] of Object.entries({ width, height })) {
1280
+ if (val < 512 || val > 2048) {
1281
+ throw new SDKError(`${name} must be between 512 and 2048, got ${val}.`, ExitCode.USAGE);
1282
+ }
1283
+ if (val % 8 !== 0) {
1284
+ throw new SDKError(`${name} must be a multiple of 8, got ${val}.`, ExitCode.USAGE);
1285
+ }
1286
+ }
1287
+ }
1288
+ return toMerged({
1289
+ model: "image-01",
1290
+ aspect_ratio: width !== undefined && height !== undefined ? undefined : aspect_ratio,
1291
+ n: 1
1292
+ }, params);
1293
+ }
1294
+ }
1295
+
1296
+ // src/polling/poll.ts
1297
+ async function poll(config, opts) {
1298
+ const deadline = Date.now() + opts.timeoutSec * 1000;
1299
+ const spinner = createSpinner("Polling...");
1300
+ if (!config.quiet)
1301
+ spinner.start();
1302
+ try {
1303
+ while (Date.now() < deadline) {
1304
+ const data = await requestJson(config, { url: opts.url });
1305
+ if (opts.getStatus && !config.quiet) {
1306
+ spinner.update(`Status: ${opts.getStatus(data)}`);
1307
+ }
1308
+ if (opts.isComplete(data)) {
1309
+ spinner.stop("Done.");
1310
+ return data;
1311
+ }
1312
+ if (opts.isFailed(data)) {
1313
+ spinner.stop("Failed.");
1314
+ const status = opts.getStatus ? opts.getStatus(data) : "failed";
1315
+ const extra = data?.base_resp ? ` (${data.base_resp.status_msg})` : "";
1316
+ throw new CLIError(`Task ${status}.${extra}`, ExitCode.GENERAL, "Check the MiniMax dashboard or --verbose output for details.");
1317
+ }
1318
+ await new Promise((r) => setTimeout(r, opts.intervalSec * 1000));
1319
+ }
1320
+ } finally {
1321
+ spinner.stop();
1322
+ }
1323
+ throw new CLIError("Polling timed out.", ExitCode.TIMEOUT, "Try increasing --timeout or check task status manually.");
1324
+ }
1325
+
1195
1326
  // src/sdk/video/index.ts
1196
1327
  class VideoSDK extends Client {
1197
1328
  async generate(request2) {
@@ -1265,19 +1396,31 @@ class VideoSDK extends Client {
1265
1396
  }
1266
1397
  }
1267
1398
 
1399
+ // src/sdk/music/index.ts
1400
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "node:fs";
1401
+ import { resolve as resolve3, dirname as dirname3 } from "node:path";
1402
+
1268
1403
  // src/commands/music/models.ts
1269
- function isCodingPlan(config) {
1270
- const key = config.apiKey ?? config.fileApiKey ?? "";
1271
- return key.startsWith("sk-cp-");
1272
- }
1273
1404
  function musicGenerateModel(config) {
1274
- if (config.defaultMusicModel)
1275
- return config.defaultMusicModel;
1276
- return isCodingPlan(config) ? "music-2.6" : "music-2.6-free";
1405
+ return config.defaultMusicModel ?? "music-2.6";
1277
1406
  }
1278
- var VALID_COVER_MODELS = new Set(["music-cover", "music-cover-free"]);
1407
+ var VALID_COVER_MODELS = new Set(["music-cover"]);
1279
1408
 
1280
1409
  // src/sdk/music/index.ts
1410
+ function hexToBuffer2(hex) {
1411
+ if (!/^[0-9a-fA-F]*$/.test(hex)) {
1412
+ throw new SDKError("API returned invalid audio data (not valid hex).", ExitCode.GENERAL);
1413
+ }
1414
+ if (hex.length % 2 !== 0) {
1415
+ throw new SDKError("API returned truncated audio data (odd-length hex string).", ExitCode.GENERAL);
1416
+ }
1417
+ return Buffer.from(hex, "hex");
1418
+ }
1419
+ function defaultFilename2(prefix, ext) {
1420
+ const ts = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-");
1421
+ return `${prefix}_${ts}.${ext}`;
1422
+ }
1423
+
1281
1424
  class MusicSDK extends Client {
1282
1425
  async* generateStream(body, url) {
1283
1426
  const res = await this.request({
@@ -1313,6 +1456,25 @@ class MusicSDK extends Client {
1313
1456
  body
1314
1457
  });
1315
1458
  }
1459
+ save(response, outPath, ext = "mp3") {
1460
+ const dest = resolve3(outPath || defaultFilename2("music", ext));
1461
+ const audioHex = response.data.audio;
1462
+ if (!audioHex) {
1463
+ throw new SDKError("API response missing audio data.", ExitCode.GENERAL);
1464
+ }
1465
+ const dir = dirname3(dest);
1466
+ if (!existsSync4(dir))
1467
+ mkdirSync3(dir, { recursive: true });
1468
+ try {
1469
+ writeFileSync4(dest, hexToBuffer2(audioHex));
1470
+ } catch (err) {
1471
+ if (err.code === "ENOSPC") {
1472
+ throw new SDKError("Disk full — cannot write audio file.", ExitCode.GENERAL);
1473
+ }
1474
+ throw err;
1475
+ }
1476
+ return dest;
1477
+ }
1316
1478
  buildPrompt(request2) {
1317
1479
  const structuredParts = [];
1318
1480
  if (request2.vocals)
@@ -1373,7 +1535,7 @@ class MusicSDK extends Client {
1373
1535
  if (!is_instrumental && !lyrics_optimizer && !lyrics?.trim()) {
1374
1536
  throw new SDKError("lyrics is required", ExitCode.USAGE);
1375
1537
  }
1376
- const VALID_MODELS = ["music-2.6", "music-2.6-free", "music-2.5+", "music-2.5"];
1538
+ const VALID_MODELS = ["music-2.6", "music-2.5+", "music-2.5"];
1377
1539
  if (model && !VALID_MODELS.includes(model)) {
1378
1540
  throw new SDKError(`Invalid model: ${model}. Valid models are ${VALID_MODELS.join(", ")}.`, ExitCode.USAGE);
1379
1541
  }
@@ -1414,7 +1576,7 @@ class SearchSDK extends Client {
1414
1576
  }
1415
1577
 
1416
1578
  // src/utils/image.ts
1417
- import { readFileSync as readFileSync3, existsSync as existsSync3 } from "fs";
1579
+ import { readFileSync as readFileSync2, existsSync as existsSync5 } from "fs";
1418
1580
  import { extname } from "path";
1419
1581
  var IMAGE_MIME_TYPES = {
1420
1582
  ".jpg": "image/jpeg",
@@ -1425,7 +1587,7 @@ var IMAGE_MIME_TYPES = {
1425
1587
  function localFileToDataUri(filePath) {
1426
1588
  const ext = extname(filePath).toLowerCase();
1427
1589
  const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
1428
- const data = readFileSync3(filePath);
1590
+ const data = readFileSync2(filePath);
1429
1591
  return `data:${mime};base64,${data.toString("base64")}`;
1430
1592
  }
1431
1593
  var MAX_IMAGE_SIZE_BYTES = 50 * 1024 * 1024;
@@ -1444,7 +1606,7 @@ async function toDataUri(image) {
1444
1606
  }
1445
1607
  return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
1446
1608
  }
1447
- if (!existsSync3(image))
1609
+ if (!existsSync5(image))
1448
1610
  throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
1449
1611
  const ext = extname(image).toLowerCase();
1450
1612
  if (!IMAGE_MIME_TYPES[ext])
@@ -1478,6 +1640,46 @@ class QuotaSDK extends Client {
1478
1640
  }
1479
1641
  }
1480
1642
 
1643
+ // src/sdk/file/index.ts
1644
+ import { existsSync as existsSync6 } from "node:fs";
1645
+ import { readFile } from "node:fs/promises";
1646
+ import { resolve as resolve4, basename } from "node:path";
1647
+ class FileSDK extends Client {
1648
+ async upload(filePath, purpose = "retrieval") {
1649
+ const fullPath = resolve4(filePath);
1650
+ if (!existsSync6(fullPath)) {
1651
+ throw new SDKError(`File not found: ${fullPath}`, ExitCode.USAGE);
1652
+ }
1653
+ const fileData = await readFile(fullPath);
1654
+ const fileName = basename(fullPath);
1655
+ const formData = new FormData;
1656
+ formData.append("file", new Blob([fileData]), fileName);
1657
+ formData.append("purpose", purpose);
1658
+ const url = fileUploadEndpoint(this.config.baseUrl);
1659
+ return this.requestJson({
1660
+ url,
1661
+ method: "POST",
1662
+ body: formData
1663
+ });
1664
+ }
1665
+ async list() {
1666
+ const url = fileListEndpoint(this.config.baseUrl);
1667
+ return this.requestJson({ url, method: "GET" });
1668
+ }
1669
+ async delete(fileId) {
1670
+ const url = fileDeleteEndpoint(this.config.baseUrl);
1671
+ return this.requestJson({
1672
+ url,
1673
+ method: "POST",
1674
+ body: { file_id: Number(fileId) }
1675
+ });
1676
+ }
1677
+ async retrieve(fileId) {
1678
+ const url = fileRetrieveEndpoint(this.config.baseUrl, fileId);
1679
+ return this.requestJson({ url, method: "GET" });
1680
+ }
1681
+ }
1682
+
1481
1683
  // src/sdk/index.ts
1482
1684
  class MiniMaxSDK extends Client {
1483
1685
  text;
@@ -1488,6 +1690,7 @@ class MiniMaxSDK extends Client {
1488
1690
  search;
1489
1691
  vision;
1490
1692
  quota;
1693
+ file;
1491
1694
  constructor(options) {
1492
1695
  super(options);
1493
1696
  this.text = new TextSDK(options);
@@ -1498,6 +1701,7 @@ class MiniMaxSDK extends Client {
1498
1701
  this.search = new SearchSDK(options);
1499
1702
  this.vision = new VisionSDK(options);
1500
1703
  this.quota = new QuotaSDK(options);
1704
+ this.file = new FileSDK(options);
1501
1705
  }
1502
1706
  }
1503
1707
  export {