mmx-cli 1.0.12 → 1.0.13
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/index.d.ts +419 -0
- package/dist/mmx.mjs +188 -187
- package/dist/sdk.mjs +1505 -0
- package/package.json +16 -4
package/dist/sdk.mjs
ADDED
|
@@ -0,0 +1,1505 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/config/loader.ts
|
|
5
|
+
import { readFileSync, writeFileSync, renameSync, existsSync } from "fs";
|
|
6
|
+
|
|
7
|
+
// src/config/schema.ts
|
|
8
|
+
var REGIONS = {
|
|
9
|
+
global: "https://api.minimax.io",
|
|
10
|
+
cn: "https://api.minimaxi.com"
|
|
11
|
+
};
|
|
12
|
+
var VALID_REGIONS = new Set(["global", "cn"]);
|
|
13
|
+
var VALID_OUTPUTS = new Set(["text", "json"]);
|
|
14
|
+
function parseConfigFile(raw) {
|
|
15
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
16
|
+
return {};
|
|
17
|
+
const obj = raw;
|
|
18
|
+
const out = {};
|
|
19
|
+
if (typeof obj.api_key === "string")
|
|
20
|
+
out.api_key = obj.api_key;
|
|
21
|
+
if (typeof obj.region === "string" && VALID_REGIONS.has(obj.region))
|
|
22
|
+
out.region = obj.region;
|
|
23
|
+
if (typeof obj.base_url === "string" && obj.base_url.startsWith("http"))
|
|
24
|
+
out.base_url = obj.base_url;
|
|
25
|
+
if (typeof obj.output === "string" && VALID_OUTPUTS.has(obj.output))
|
|
26
|
+
out.output = obj.output;
|
|
27
|
+
if (typeof obj.timeout === "number" && obj.timeout > 0)
|
|
28
|
+
out.timeout = obj.timeout;
|
|
29
|
+
if (typeof obj.proxy === "string" && obj.proxy.startsWith("http"))
|
|
30
|
+
out.proxy = obj.proxy;
|
|
31
|
+
if (typeof obj.default_text_model === "string" && obj.default_text_model.length > 0)
|
|
32
|
+
out.default_text_model = obj.default_text_model;
|
|
33
|
+
if (typeof obj.default_speech_model === "string" && obj.default_speech_model.length > 0)
|
|
34
|
+
out.default_speech_model = obj.default_speech_model;
|
|
35
|
+
if (typeof obj.default_video_model === "string" && obj.default_video_model.length > 0)
|
|
36
|
+
out.default_video_model = obj.default_video_model;
|
|
37
|
+
if (typeof obj.default_music_model === "string" && obj.default_music_model.length > 0)
|
|
38
|
+
out.default_music_model = obj.default_music_model;
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/config/paths.ts
|
|
43
|
+
import { homedir } from "os";
|
|
44
|
+
import { join } from "path";
|
|
45
|
+
var CONFIG_DIR_NAME = ".mmx";
|
|
46
|
+
function getConfigDir() {
|
|
47
|
+
return join(homedir(), CONFIG_DIR_NAME);
|
|
48
|
+
}
|
|
49
|
+
function getConfigPath() {
|
|
50
|
+
return join(getConfigDir(), "config.json");
|
|
51
|
+
}
|
|
52
|
+
function getCredentialsPath() {
|
|
53
|
+
return join(getConfigDir(), "credentials.json");
|
|
54
|
+
}
|
|
55
|
+
async function ensureConfigDir() {
|
|
56
|
+
const dir = getConfigDir();
|
|
57
|
+
const fs = await import("fs/promises");
|
|
58
|
+
await fs.mkdir(dir, { recursive: true, mode: 448 });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/output/text.ts
|
|
62
|
+
function formatText(data) {
|
|
63
|
+
if (data === null || data === undefined)
|
|
64
|
+
return "";
|
|
65
|
+
if (typeof data === "string")
|
|
66
|
+
return data;
|
|
67
|
+
if (typeof data === "number" || typeof data === "boolean")
|
|
68
|
+
return String(data);
|
|
69
|
+
if (Array.isArray(data)) {
|
|
70
|
+
if (data.length === 0)
|
|
71
|
+
return "(empty)";
|
|
72
|
+
if (typeof data[0] === "object" && data[0] !== null) {
|
|
73
|
+
return formatTable(data);
|
|
74
|
+
}
|
|
75
|
+
return data.map(String).join(`
|
|
76
|
+
`);
|
|
77
|
+
}
|
|
78
|
+
if (typeof data === "object") {
|
|
79
|
+
return formatKeyValue(data);
|
|
80
|
+
}
|
|
81
|
+
return String(data);
|
|
82
|
+
}
|
|
83
|
+
function formatKeyValue(obj, indent = 0) {
|
|
84
|
+
const prefix = " ".repeat(indent);
|
|
85
|
+
const lines = [];
|
|
86
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
87
|
+
if (value === null || value === undefined)
|
|
88
|
+
continue;
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
lines.push(`${prefix}${key}:`);
|
|
91
|
+
for (const item of value) {
|
|
92
|
+
if (typeof item === "object" && item !== null) {
|
|
93
|
+
lines.push(`${prefix} - ${formatKeyValue(item, indent + 4).trimStart()}`);
|
|
94
|
+
} else {
|
|
95
|
+
lines.push(`${prefix} - ${String(item)}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
} else if (typeof value === "object") {
|
|
99
|
+
lines.push(`${prefix}${key}:`);
|
|
100
|
+
lines.push(formatKeyValue(value, indent + 2));
|
|
101
|
+
} else {
|
|
102
|
+
lines.push(`${prefix}${key}: ${String(value)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return lines.join(`
|
|
106
|
+
`);
|
|
107
|
+
}
|
|
108
|
+
function formatTable(rows) {
|
|
109
|
+
if (rows.length === 0)
|
|
110
|
+
return "(empty)";
|
|
111
|
+
const keys = Object.keys(rows[0]);
|
|
112
|
+
const widths = keys.map((k) => Math.max(k.length, ...rows.map((r) => String(r[k] ?? "").length)));
|
|
113
|
+
const header = keys.map((k, i) => k.toUpperCase().padEnd(widths[i])).join(" ");
|
|
114
|
+
const separator = widths.map((w) => "-".repeat(w)).join(" ");
|
|
115
|
+
const body = rows.map((r) => keys.map((k, i) => String(r[k] ?? "").padEnd(widths[i])).join(" "));
|
|
116
|
+
return [header, separator, ...body].join(`
|
|
117
|
+
`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/output/json.ts
|
|
121
|
+
function formatJson(data) {
|
|
122
|
+
return JSON.stringify(data, null, 2);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/output/formatter.ts
|
|
126
|
+
function detectOutputFormat(flagValue) {
|
|
127
|
+
if (flagValue === "json" || flagValue === "text") {
|
|
128
|
+
return flagValue;
|
|
129
|
+
}
|
|
130
|
+
if (!process.stdout.isTTY) {
|
|
131
|
+
return "json";
|
|
132
|
+
}
|
|
133
|
+
return "text";
|
|
134
|
+
}
|
|
135
|
+
function formatOutput(data, format) {
|
|
136
|
+
switch (format) {
|
|
137
|
+
case "json":
|
|
138
|
+
return formatJson(data);
|
|
139
|
+
case "text":
|
|
140
|
+
return formatText(data);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/config/loader.ts
|
|
145
|
+
function readConfigFile() {
|
|
146
|
+
const path = getConfigPath();
|
|
147
|
+
if (!existsSync(path))
|
|
148
|
+
return {};
|
|
149
|
+
try {
|
|
150
|
+
return parseConfigFile(JSON.parse(readFileSync(path, "utf-8")));
|
|
151
|
+
} catch (err) {
|
|
152
|
+
const e = err;
|
|
153
|
+
if (e instanceof SyntaxError || e.message.includes("JSON")) {
|
|
154
|
+
process.stderr.write(`Warning: config file is corrupted. Run 'mmx config set' to reset.
|
|
155
|
+
`);
|
|
156
|
+
}
|
|
157
|
+
return {};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function loadConfig(flags) {
|
|
161
|
+
const file = readConfigFile();
|
|
162
|
+
const apiKey = flags.apiKey || undefined;
|
|
163
|
+
const fileApiKey = file.api_key;
|
|
164
|
+
const explicitRegion = flags.region || process.env.MINIMAX_REGION || undefined;
|
|
165
|
+
const cachedRegion = file.region;
|
|
166
|
+
const region = explicitRegion || cachedRegion || "global";
|
|
167
|
+
const activeKey = apiKey || fileApiKey;
|
|
168
|
+
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;
|
|
170
|
+
const output = detectOutputFormat(flags.output || process.env.MINIMAX_OUTPUT || file.output);
|
|
171
|
+
const envTimeout = process.env.MINIMAX_TIMEOUT ? Number(process.env.MINIMAX_TIMEOUT) : undefined;
|
|
172
|
+
const validEnvTimeout = envTimeout !== undefined && Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : undefined;
|
|
173
|
+
const timeout = flags.timeout ?? validEnvTimeout ?? file.timeout ?? 300;
|
|
174
|
+
return {
|
|
175
|
+
apiKey,
|
|
176
|
+
fileApiKey,
|
|
177
|
+
fileRegion: file.region,
|
|
178
|
+
configPath: getConfigPath(),
|
|
179
|
+
region,
|
|
180
|
+
baseUrl,
|
|
181
|
+
output,
|
|
182
|
+
timeout,
|
|
183
|
+
defaultTextModel: file.default_text_model,
|
|
184
|
+
defaultSpeechModel: file.default_speech_model,
|
|
185
|
+
defaultVideoModel: file.default_video_model,
|
|
186
|
+
defaultMusicModel: file.default_music_model,
|
|
187
|
+
verbose: flags.verbose || process.env.MINIMAX_VERBOSE === "1",
|
|
188
|
+
quiet: flags.quiet || false,
|
|
189
|
+
noColor: flags.noColor || process.env.NO_COLOR !== undefined || !process.stdout.isTTY,
|
|
190
|
+
yes: flags.yes || false,
|
|
191
|
+
dryRun: flags.dryRun || false,
|
|
192
|
+
nonInteractive: flags.nonInteractive || false,
|
|
193
|
+
async: flags.async || false,
|
|
194
|
+
needsRegionDetection
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
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
|
+
// src/auth/credentials.ts
|
|
243
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, renameSync as renameSync2, unlinkSync, existsSync as existsSync2, statSync } from "fs";
|
|
244
|
+
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
|
+
}
|
|
263
|
+
}
|
|
264
|
+
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 {}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// src/auth/refresh.ts
|
|
284
|
+
var TOKEN_URL = "https://api.minimax.io/v1/oauth/token";
|
|
285
|
+
var MAX_REFRESH_RETRIES = 2;
|
|
286
|
+
var RETRY_DELAY_MS = 500;
|
|
287
|
+
async function refreshAccessToken(refreshToken) {
|
|
288
|
+
let lastErr = null;
|
|
289
|
+
for (let attempt = 0;attempt <= MAX_REFRESH_RETRIES; attempt++) {
|
|
290
|
+
if (attempt > 0) {
|
|
291
|
+
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
|
|
292
|
+
}
|
|
293
|
+
let res;
|
|
294
|
+
try {
|
|
295
|
+
res = await fetch(TOKEN_URL, {
|
|
296
|
+
method: "POST",
|
|
297
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
298
|
+
body: new URLSearchParams({
|
|
299
|
+
grant_type: "refresh_token",
|
|
300
|
+
refresh_token: refreshToken
|
|
301
|
+
}),
|
|
302
|
+
signal: AbortSignal.timeout(1e4)
|
|
303
|
+
});
|
|
304
|
+
} catch (err) {
|
|
305
|
+
const isTimeout = err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError" || err.message.includes("timed out"));
|
|
306
|
+
lastErr = new Error(isTimeout ? "Token refresh timed out — auth server did not respond within 10 s." : `Token refresh failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (!res.ok) {
|
|
310
|
+
if (res.status >= 400 && res.status < 500) {
|
|
311
|
+
throw new CLIError("OAuth session expired and could not be refreshed.", ExitCode.AUTH, "Re-authenticate: mmx auth login");
|
|
312
|
+
}
|
|
313
|
+
lastErr = new Error(`Token refresh failed: HTTP ${res.status}`);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
const data = await res.json();
|
|
317
|
+
return data;
|
|
318
|
+
}
|
|
319
|
+
throw new CLIError(`Token refresh failed after ${MAX_REFRESH_RETRIES + 1} attempts: ${lastErr?.message}`, ExitCode.AUTH, `Check your network connection.
|
|
320
|
+
Re-authenticate: mmx auth login`);
|
|
321
|
+
}
|
|
322
|
+
async function ensureFreshToken(creds) {
|
|
323
|
+
const expiresAt = new Date(creds.expires_at).getTime();
|
|
324
|
+
const bufferMs = 5 * 60 * 1000;
|
|
325
|
+
if (Date.now() < expiresAt - bufferMs) {
|
|
326
|
+
return creds.access_token;
|
|
327
|
+
}
|
|
328
|
+
const tokens = await refreshAccessToken(creds.refresh_token);
|
|
329
|
+
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",
|
|
334
|
+
account: creds.account
|
|
335
|
+
};
|
|
336
|
+
await saveCredentials(updated);
|
|
337
|
+
return updated.access_token;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// src/auth/resolver.ts
|
|
341
|
+
async function resolveCredential(config) {
|
|
342
|
+
if (config.apiKey) {
|
|
343
|
+
return { token: config.apiKey, method: "api-key", source: "flag" };
|
|
344
|
+
}
|
|
345
|
+
const oauth = await loadCredentials();
|
|
346
|
+
if (oauth) {
|
|
347
|
+
const token = await ensureFreshToken(oauth);
|
|
348
|
+
return { token, method: "oauth", source: "credentials.json" };
|
|
349
|
+
}
|
|
350
|
+
if (config.fileApiKey) {
|
|
351
|
+
return { token: config.fileApiKey, method: "api-key", source: "config.json" };
|
|
352
|
+
}
|
|
353
|
+
throw new CLIError("No credentials found.", ExitCode.AUTH, `Log in: mmx auth login
|
|
354
|
+
Pass directly: --api-key sk-xxxxx`);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// src/errors/api.ts
|
|
358
|
+
function planHintForUrl(url) {
|
|
359
|
+
if (!url)
|
|
360
|
+
return "";
|
|
361
|
+
if (url.includes("/t2a"))
|
|
362
|
+
return `
|
|
363
|
+
|
|
364
|
+
Speech models require the Plus plan or above.`;
|
|
365
|
+
if (url.includes("/image_generation"))
|
|
366
|
+
return `
|
|
367
|
+
|
|
368
|
+
image-01 requires the Plus plan or above.`;
|
|
369
|
+
if (url.includes("/video_generation") || url.includes("/query/video_generation"))
|
|
370
|
+
return `
|
|
371
|
+
|
|
372
|
+
Video models (Hailuo-2.3 / 2.3-Fast) require the Max plan or above.`;
|
|
373
|
+
if (url.includes("/music_generation"))
|
|
374
|
+
return `
|
|
375
|
+
|
|
376
|
+
Music-2.6 requires the Max plan or above.`;
|
|
377
|
+
return "";
|
|
378
|
+
}
|
|
379
|
+
function upgradeUrl(url) {
|
|
380
|
+
const host = url?.includes("minimaxi.com") ? "https://platform.minimaxi.com" : "https://platform.minimax.io";
|
|
381
|
+
return `${host}/subscribe/token-plan`;
|
|
382
|
+
}
|
|
383
|
+
function mapApiError(status, body, url) {
|
|
384
|
+
const apiMsg = body.base_resp?.status_msg || body.error?.message || `HTTP ${status}`;
|
|
385
|
+
const apiCode = body.base_resp?.status_code || body.error?.code;
|
|
386
|
+
if (status === 401 || status === 403) {
|
|
387
|
+
return new CLIError(`API key rejected (HTTP ${status}).`, ExitCode.AUTH, `Check status: mmx auth status
|
|
388
|
+
Re-authenticate: mmx auth login`);
|
|
389
|
+
}
|
|
390
|
+
if (status === 429) {
|
|
391
|
+
return new CLIError(`Rate limit or quota exceeded. ${apiMsg}`, ExitCode.QUOTA, "Check usage: mmx quota show");
|
|
392
|
+
}
|
|
393
|
+
if (status === 408 || status === 504) {
|
|
394
|
+
return new CLIError(`Request timed out (HTTP ${status}).`, ExitCode.TIMEOUT, "Try increasing --timeout or retry later.");
|
|
395
|
+
}
|
|
396
|
+
if (apiCode === 1002 || apiCode === 1039) {
|
|
397
|
+
const filterType = body.base_resp?.status_msg || "content sensitivity";
|
|
398
|
+
return new CLIError(`Input content flagged by sensitivity filter (${filterType}).`, ExitCode.CONTENT_FILTER);
|
|
399
|
+
}
|
|
400
|
+
if (apiCode === 1028 || apiCode === 1030) {
|
|
401
|
+
const hint = planHintForUrl(url);
|
|
402
|
+
return new CLIError(`Quota exhausted. ${apiMsg}`, ExitCode.QUOTA, `Check usage: mmx quota show${hint}
|
|
403
|
+
Upgrade plan: ${upgradeUrl(url)}`);
|
|
404
|
+
}
|
|
405
|
+
if (apiCode === 2061) {
|
|
406
|
+
const hint = planHintForUrl(url);
|
|
407
|
+
return new CLIError(`This model is not available on your current Token Plan. ${apiMsg}`, ExitCode.QUOTA, `Check usage: mmx quota show${hint}
|
|
408
|
+
Upgrade plan: ${upgradeUrl(url)}`);
|
|
409
|
+
}
|
|
410
|
+
return new CLIError(`API error: ${apiMsg} (HTTP ${status})`, ExitCode.GENERAL);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// src/output/status-bar.ts
|
|
414
|
+
import { homedir as homedir2 } from "os";
|
|
415
|
+
|
|
416
|
+
// src/utils/token.ts
|
|
417
|
+
function maskToken(token) {
|
|
418
|
+
return token.length > 8 ? `${token.slice(0, 4)}...${token.slice(-4)}` : "***";
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// src/output/status-bar.ts
|
|
422
|
+
var printed = false;
|
|
423
|
+
var reset = "\x1B[0m";
|
|
424
|
+
var dim = "\x1B[2m";
|
|
425
|
+
var bold = "\x1B[1m";
|
|
426
|
+
var mmBlue = "\x1B[38;2;43;82;255m";
|
|
427
|
+
var mmPurple = "\x1B[38;2;147;51;234m";
|
|
428
|
+
var mmCyan = "\x1B[38;2;6;184;212m";
|
|
429
|
+
var mmPink = "\x1B[38;2;236;72;153m";
|
|
430
|
+
function tildePath(p) {
|
|
431
|
+
return p.startsWith(homedir2()) ? p.replace(homedir2(), "~") : p;
|
|
432
|
+
}
|
|
433
|
+
function maybeShowStatusBar(config, token, model) {
|
|
434
|
+
if (config.quiet || printed || !process.stderr.isTTY)
|
|
435
|
+
return;
|
|
436
|
+
printed = true;
|
|
437
|
+
const filePath = config.configPath ? tildePath(config.configPath) : "~/.mmx/config.json";
|
|
438
|
+
const regionSrc = config.fileRegion ? `${config.fileRegion} (file)` : "global (default)";
|
|
439
|
+
const keySrc = config.apiKey ? "(flag)" : "(file)";
|
|
440
|
+
const maskedKey = maskToken(token);
|
|
441
|
+
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}
|
|
443
|
+
`);
|
|
444
|
+
}
|
|
445
|
+
// package.json
|
|
446
|
+
var package_default = {
|
|
447
|
+
name: "mmx-cli",
|
|
448
|
+
version: "1.0.13",
|
|
449
|
+
description: "CLI for the MiniMax AI Platform",
|
|
450
|
+
type: "module",
|
|
451
|
+
engines: {
|
|
452
|
+
node: ">=18"
|
|
453
|
+
},
|
|
454
|
+
bin: {
|
|
455
|
+
mmx: "dist/mmx.mjs"
|
|
456
|
+
},
|
|
457
|
+
files: [
|
|
458
|
+
"dist/mmx.mjs",
|
|
459
|
+
"dist/sdk.mjs",
|
|
460
|
+
"dist/index.d.ts"
|
|
461
|
+
],
|
|
462
|
+
exports: {
|
|
463
|
+
"./sdk": {
|
|
464
|
+
import: "./dist/sdk.mjs",
|
|
465
|
+
types: "./dist/index.d.ts"
|
|
466
|
+
},
|
|
467
|
+
"./package.json": "./package.json"
|
|
468
|
+
},
|
|
469
|
+
scripts: {
|
|
470
|
+
dev: "bun run src/main.ts",
|
|
471
|
+
build: "bun run build.ts",
|
|
472
|
+
"build:dev": "bun run build.ts --dev",
|
|
473
|
+
prepublishOnly: "bun run build",
|
|
474
|
+
lint: "eslint src/ test/",
|
|
475
|
+
typecheck: "tsc --noEmit",
|
|
476
|
+
test: "bun test",
|
|
477
|
+
"test:watch": "bun test --watch"
|
|
478
|
+
},
|
|
479
|
+
dependencies: {
|
|
480
|
+
"@clack/prompts": "^0.7.0",
|
|
481
|
+
"bun-plugin-dts": "^0.4.0",
|
|
482
|
+
"es-toolkit": "^1.46.1",
|
|
483
|
+
undici: "^6.21.1"
|
|
484
|
+
},
|
|
485
|
+
devDependencies: {
|
|
486
|
+
"@eslint/js": "^9.0.0",
|
|
487
|
+
"@types/bun": "latest",
|
|
488
|
+
eslint: "^9.24.0",
|
|
489
|
+
typescript: "^5.8.3",
|
|
490
|
+
"typescript-eslint": "^8.58.0"
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
// src/version.ts
|
|
495
|
+
var CLI_VERSION = process.env.CLI_VERSION ?? package_default.version;
|
|
496
|
+
|
|
497
|
+
// src/client/http.ts
|
|
498
|
+
async function request(config, opts) {
|
|
499
|
+
const isFormData = typeof FormData !== "undefined" && opts.body instanceof FormData;
|
|
500
|
+
const headers = {
|
|
501
|
+
"User-Agent": `mmx-cli/${CLI_VERSION}`,
|
|
502
|
+
...opts.headers
|
|
503
|
+
};
|
|
504
|
+
if (!isFormData && !headers["Content-Type"]) {
|
|
505
|
+
headers["Content-Type"] = "application/json";
|
|
506
|
+
}
|
|
507
|
+
if (!opts.noAuth) {
|
|
508
|
+
const credential = await resolveCredential(config);
|
|
509
|
+
if (opts.authStyle === "x-api-key") {
|
|
510
|
+
headers["x-api-key"] = credential.token;
|
|
511
|
+
} else {
|
|
512
|
+
headers["Authorization"] = `Bearer ${credential.token}`;
|
|
513
|
+
}
|
|
514
|
+
if (config.verbose) {
|
|
515
|
+
process.stderr.write(`> ${opts.method ?? "GET"} ${opts.url}
|
|
516
|
+
`);
|
|
517
|
+
process.stderr.write(`> Auth: ${credential.token.slice(0, 8)}...
|
|
518
|
+
`);
|
|
519
|
+
}
|
|
520
|
+
const model = opts.body && typeof opts.body === "object" && "model" in opts.body ? String(opts.body.model) : undefined;
|
|
521
|
+
maybeShowStatusBar(config, credential.token, model);
|
|
522
|
+
}
|
|
523
|
+
const timeoutMs = (opts.timeout ?? config.timeout) * 1000;
|
|
524
|
+
const res = await fetch(opts.url, {
|
|
525
|
+
method: opts.method ?? "GET",
|
|
526
|
+
headers,
|
|
527
|
+
body: opts.body ? isFormData ? opts.body : JSON.stringify(opts.body) : undefined,
|
|
528
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
529
|
+
});
|
|
530
|
+
if (config.verbose) {
|
|
531
|
+
process.stderr.write(`< ${res.status} ${res.statusText}
|
|
532
|
+
`);
|
|
533
|
+
}
|
|
534
|
+
if (!res.ok) {
|
|
535
|
+
let body = {};
|
|
536
|
+
try {
|
|
537
|
+
body = await res.json();
|
|
538
|
+
} catch {}
|
|
539
|
+
throw mapApiError(res.status, body, opts.url);
|
|
540
|
+
}
|
|
541
|
+
return res;
|
|
542
|
+
}
|
|
543
|
+
async function requestJson(config, opts) {
|
|
544
|
+
const res = await request(config, opts);
|
|
545
|
+
let data;
|
|
546
|
+
try {
|
|
547
|
+
data = await res.json();
|
|
548
|
+
} catch {
|
|
549
|
+
const contentType = res.headers.get("content-type") || "";
|
|
550
|
+
throw new CLIError(`API returned non-JSON response (${contentType || "unknown type"}). Server may be experiencing issues.`, ExitCode.GENERAL);
|
|
551
|
+
}
|
|
552
|
+
if (data.base_resp?.status_code && data.base_resp.status_code !== 0) {
|
|
553
|
+
throw mapApiError(200, { base_resp: data.base_resp }, opts.url);
|
|
554
|
+
}
|
|
555
|
+
return data;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/client/stream.ts
|
|
559
|
+
async function* parseSSE(response) {
|
|
560
|
+
const reader = response.body?.getReader();
|
|
561
|
+
if (!reader)
|
|
562
|
+
return;
|
|
563
|
+
const decoder = new TextDecoder;
|
|
564
|
+
let buffer = "";
|
|
565
|
+
try {
|
|
566
|
+
while (true) {
|
|
567
|
+
const { done, value } = await reader.read();
|
|
568
|
+
if (done)
|
|
569
|
+
break;
|
|
570
|
+
buffer += decoder.decode(value, { stream: true });
|
|
571
|
+
const lines = buffer.split(`
|
|
572
|
+
`);
|
|
573
|
+
buffer = lines.pop() || "";
|
|
574
|
+
let event = {};
|
|
575
|
+
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;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
if (buffer.trim() && buffer.includes("data:")) {
|
|
605
|
+
const colonIndex = buffer.indexOf(":");
|
|
606
|
+
if (colonIndex !== -1) {
|
|
607
|
+
yield { data: buffer.slice(colonIndex + 1).trimStart() };
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
} finally {
|
|
611
|
+
reader.releaseLock();
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/sdk/client.ts
|
|
616
|
+
class Client {
|
|
617
|
+
config;
|
|
618
|
+
constructor(options) {
|
|
619
|
+
const { apiKey, region, baseUrl } = options;
|
|
620
|
+
this.config = loadConfig({
|
|
621
|
+
apiKey,
|
|
622
|
+
baseUrl,
|
|
623
|
+
region,
|
|
624
|
+
quiet: true,
|
|
625
|
+
verbose: false,
|
|
626
|
+
noColor: true,
|
|
627
|
+
yes: false,
|
|
628
|
+
dryRun: false,
|
|
629
|
+
help: false,
|
|
630
|
+
nonInteractive: false,
|
|
631
|
+
async: false
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
request(opts) {
|
|
635
|
+
return request(this.config, opts);
|
|
636
|
+
}
|
|
637
|
+
requestJson(opts) {
|
|
638
|
+
return requestJson(this.config, opts);
|
|
639
|
+
}
|
|
640
|
+
async* streamSSE(res) {
|
|
641
|
+
for await (const event of parseSSE(res)) {
|
|
642
|
+
if (event.data === "[DONE]")
|
|
643
|
+
break;
|
|
644
|
+
if (!event.data)
|
|
645
|
+
continue;
|
|
646
|
+
try {
|
|
647
|
+
yield JSON.parse(event.data);
|
|
648
|
+
} catch (err) {
|
|
649
|
+
throw new SDKError(`Failed to parse stream chunk: ${err instanceof Error ? err.message : String(err)}`, ExitCode.GENERAL);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// src/client/endpoints.ts
|
|
656
|
+
function chatEndpoint(baseUrl) {
|
|
657
|
+
return `${baseUrl}/anthropic/v1/messages`;
|
|
658
|
+
}
|
|
659
|
+
function speechEndpoint(baseUrl) {
|
|
660
|
+
return `${baseUrl}/v1/t2a_v2`;
|
|
661
|
+
}
|
|
662
|
+
function voicesEndpoint(baseUrl) {
|
|
663
|
+
return `${baseUrl}/v1/get_voice`;
|
|
664
|
+
}
|
|
665
|
+
function imageEndpoint(baseUrl) {
|
|
666
|
+
return `${baseUrl}/v1/image_generation`;
|
|
667
|
+
}
|
|
668
|
+
function videoGenerateEndpoint(baseUrl) {
|
|
669
|
+
return `${baseUrl}/v1/video_generation`;
|
|
670
|
+
}
|
|
671
|
+
function videoTaskEndpoint(baseUrl, taskId) {
|
|
672
|
+
return `${baseUrl}/v1/query/video_generation?task_id=${taskId}`;
|
|
673
|
+
}
|
|
674
|
+
function fileRetrieveEndpoint(baseUrl, fileId) {
|
|
675
|
+
return `${baseUrl}/v1/files/retrieve?file_id=${fileId}`;
|
|
676
|
+
}
|
|
677
|
+
function musicEndpoint(baseUrl) {
|
|
678
|
+
return `${baseUrl}/v1/music_generation`;
|
|
679
|
+
}
|
|
680
|
+
function searchEndpoint(baseUrl) {
|
|
681
|
+
return `${baseUrl}/v1/coding_plan/search`;
|
|
682
|
+
}
|
|
683
|
+
function vlmEndpoint(baseUrl) {
|
|
684
|
+
return `${baseUrl}/v1/coding_plan/vlm`;
|
|
685
|
+
}
|
|
686
|
+
function quotaEndpoint(baseUrl) {
|
|
687
|
+
const host = baseUrl.includes("minimaxi.com") ? "https://api.minimaxi.com" : "https://api.minimax.io";
|
|
688
|
+
return `${host}/v1/token_plan/remains`;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// src/sdk/text/index.ts
|
|
692
|
+
class TextSDK extends Client {
|
|
693
|
+
async* chatStream(body) {
|
|
694
|
+
const url = chatEndpoint(this.config.baseUrl);
|
|
695
|
+
const res = await this.request({
|
|
696
|
+
url,
|
|
697
|
+
method: "POST",
|
|
698
|
+
body,
|
|
699
|
+
stream: true,
|
|
700
|
+
authStyle: "x-api-key"
|
|
701
|
+
});
|
|
702
|
+
const contentType = res.headers.get("content-type") || "";
|
|
703
|
+
if (!contentType.includes("text/event-stream") && !contentType.includes("stream")) {
|
|
704
|
+
throw new SDKError(`Expected SSE stream but got content-type "${contentType}". Server may be experiencing issues.`, ExitCode.GENERAL);
|
|
705
|
+
}
|
|
706
|
+
yield* this.streamSSE(res);
|
|
707
|
+
}
|
|
708
|
+
async chat(request2) {
|
|
709
|
+
const body = this.validateParams(request2);
|
|
710
|
+
const url = chatEndpoint(this.config.baseUrl);
|
|
711
|
+
if (body.stream) {
|
|
712
|
+
return this.chatStream(body);
|
|
713
|
+
}
|
|
714
|
+
return await this.requestJson({
|
|
715
|
+
url,
|
|
716
|
+
method: "POST",
|
|
717
|
+
body,
|
|
718
|
+
authStyle: "x-api-key"
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
validateParams(params) {
|
|
722
|
+
if (params.messages?.length === 0) {
|
|
723
|
+
throw new SDKError("At least one message is required.", ExitCode.USAGE);
|
|
724
|
+
}
|
|
725
|
+
return {
|
|
726
|
+
...params,
|
|
727
|
+
model: params.model ?? "MiniMax-M2.7",
|
|
728
|
+
max_tokens: params.max_tokens ?? 4096
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// src/command.ts
|
|
734
|
+
function defineCommand(spec) {
|
|
735
|
+
return {
|
|
736
|
+
name: spec.name,
|
|
737
|
+
description: spec.description,
|
|
738
|
+
usage: spec.usage,
|
|
739
|
+
options: spec.options,
|
|
740
|
+
examples: spec.examples,
|
|
741
|
+
apiDocs: spec.apiDocs,
|
|
742
|
+
execute: spec.run
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// src/commands/speech/voices.ts
|
|
747
|
+
function extractLanguage(voiceId) {
|
|
748
|
+
const match = voiceId.match(/^(.+?)_[A-Z]/);
|
|
749
|
+
return match ? match[1] : voiceId;
|
|
750
|
+
}
|
|
751
|
+
function filterByLanguage(voices, language) {
|
|
752
|
+
const lang = language.toLowerCase();
|
|
753
|
+
return voices.filter((v) => {
|
|
754
|
+
const voiceLang = extractLanguage(v.voice_id).toLowerCase();
|
|
755
|
+
return voiceLang === lang || voiceLang.startsWith(lang + "_") || voiceLang.startsWith(lang + " (");
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
var voices_default = defineCommand({
|
|
759
|
+
name: "speech voices",
|
|
760
|
+
description: "List available system voices",
|
|
761
|
+
usage: "mmx speech voices [--language <lang>]",
|
|
762
|
+
options: [
|
|
763
|
+
{ flag: "--language <lang>", description: "Filter voices by language (e.g. english, korean, japanese)" }
|
|
764
|
+
],
|
|
765
|
+
examples: [
|
|
766
|
+
"mmx speech voices",
|
|
767
|
+
"mmx speech voices --language english",
|
|
768
|
+
"mmx speech voices --language korean",
|
|
769
|
+
"mmx speech voices --output json"
|
|
770
|
+
],
|
|
771
|
+
async run(config, flags) {
|
|
772
|
+
const format = detectOutputFormat(config.output);
|
|
773
|
+
if (config.dryRun) {
|
|
774
|
+
console.log(formatOutput({ request: { voice_type: "system" } }, format));
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
const response = await requestJson(config, {
|
|
778
|
+
url: voicesEndpoint(config.baseUrl),
|
|
779
|
+
method: "POST",
|
|
780
|
+
body: { voice_type: "system" }
|
|
781
|
+
});
|
|
782
|
+
const voices = response.system_voice ?? [];
|
|
783
|
+
const language = flags.language;
|
|
784
|
+
if (language) {
|
|
785
|
+
const filtered = filterByLanguage(voices, language);
|
|
786
|
+
if (format !== "text") {
|
|
787
|
+
console.log(formatOutput(filtered, format));
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
for (const v of filtered) {
|
|
791
|
+
const desc = v.description?.join("; ") || "";
|
|
792
|
+
const name = v.voice_name ? ` (${v.voice_name})` : "";
|
|
793
|
+
console.log(` ${v.voice_id}${name}`);
|
|
794
|
+
if (desc)
|
|
795
|
+
console.log(` ${desc}`);
|
|
796
|
+
}
|
|
797
|
+
} else {
|
|
798
|
+
if (format !== "text") {
|
|
799
|
+
console.log(formatOutput(voices.map((v) => v.voice_id), format));
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
for (const v of voices) {
|
|
803
|
+
console.log(v.voice_id);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
// node_modules/es-toolkit/dist/predicate/isPrimitive.mjs
|
|
809
|
+
function isPrimitive(value) {
|
|
810
|
+
return value == null || typeof value !== "object" && typeof value !== "function";
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// node_modules/es-toolkit/dist/predicate/isTypedArray.mjs
|
|
814
|
+
function isTypedArray(x) {
|
|
815
|
+
return ArrayBuffer.isView(x) && !(x instanceof DataView);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// node_modules/es-toolkit/dist/object/clone.mjs
|
|
819
|
+
function clone(obj) {
|
|
820
|
+
if (isPrimitive(obj)) {
|
|
821
|
+
return obj;
|
|
822
|
+
}
|
|
823
|
+
if (Array.isArray(obj) || isTypedArray(obj) || obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) {
|
|
824
|
+
return obj.slice(0);
|
|
825
|
+
}
|
|
826
|
+
const prototype = Object.getPrototypeOf(obj);
|
|
827
|
+
if (prototype == null) {
|
|
828
|
+
return Object.assign(Object.create(prototype), obj);
|
|
829
|
+
}
|
|
830
|
+
const Constructor = prototype.constructor;
|
|
831
|
+
if (obj instanceof Date || obj instanceof Map || obj instanceof Set) {
|
|
832
|
+
return new Constructor(obj);
|
|
833
|
+
}
|
|
834
|
+
if (obj instanceof RegExp) {
|
|
835
|
+
const newRegExp = new Constructor(obj);
|
|
836
|
+
newRegExp.lastIndex = obj.lastIndex;
|
|
837
|
+
return newRegExp;
|
|
838
|
+
}
|
|
839
|
+
if (obj instanceof DataView) {
|
|
840
|
+
return new Constructor(obj.buffer.slice(0));
|
|
841
|
+
}
|
|
842
|
+
if (obj instanceof Error) {
|
|
843
|
+
let newError;
|
|
844
|
+
if (obj instanceof AggregateError) {
|
|
845
|
+
newError = new Constructor(obj.errors, obj.message, { cause: obj.cause });
|
|
846
|
+
} else {
|
|
847
|
+
newError = new Constructor(obj.message, { cause: obj.cause });
|
|
848
|
+
}
|
|
849
|
+
newError.stack = obj.stack;
|
|
850
|
+
Object.assign(newError, obj);
|
|
851
|
+
return newError;
|
|
852
|
+
}
|
|
853
|
+
if (typeof File !== "undefined" && obj instanceof File) {
|
|
854
|
+
const newFile = new Constructor([obj], obj.name, { type: obj.type, lastModified: obj.lastModified });
|
|
855
|
+
return newFile;
|
|
856
|
+
}
|
|
857
|
+
if (typeof obj === "object") {
|
|
858
|
+
const newObject = Object.create(prototype);
|
|
859
|
+
return Object.assign(newObject, obj);
|
|
860
|
+
}
|
|
861
|
+
return obj;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// node_modules/es-toolkit/dist/_internal/isUnsafeProperty.mjs
|
|
865
|
+
function isUnsafeProperty(key) {
|
|
866
|
+
return key === "__proto__";
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// node_modules/es-toolkit/dist/predicate/isPlainObject.mjs
|
|
870
|
+
function isPlainObject(value) {
|
|
871
|
+
if (!value || typeof value !== "object") {
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
const proto = Object.getPrototypeOf(value);
|
|
875
|
+
const hasObjectPrototype = proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
|
|
876
|
+
if (!hasObjectPrototype) {
|
|
877
|
+
return false;
|
|
878
|
+
}
|
|
879
|
+
return Object.prototype.toString.call(value) === "[object Object]";
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// node_modules/es-toolkit/dist/object/mergeWith.mjs
|
|
883
|
+
function mergeWith(target, source, merge) {
|
|
884
|
+
const sourceKeys = Object.keys(source);
|
|
885
|
+
for (let i = 0;i < sourceKeys.length; i++) {
|
|
886
|
+
const key = sourceKeys[i];
|
|
887
|
+
if (isUnsafeProperty(key)) {
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
const sourceValue = source[key];
|
|
891
|
+
const targetValue = target[key];
|
|
892
|
+
const merged = merge(targetValue, sourceValue, key, target, source);
|
|
893
|
+
if (merged !== undefined) {
|
|
894
|
+
target[key] = merged;
|
|
895
|
+
} else if (Array.isArray(sourceValue)) {
|
|
896
|
+
if (Array.isArray(targetValue)) {
|
|
897
|
+
target[key] = mergeWith(targetValue, sourceValue, merge);
|
|
898
|
+
} else {
|
|
899
|
+
target[key] = mergeWith([], sourceValue, merge);
|
|
900
|
+
}
|
|
901
|
+
} else if (isPlainObject(sourceValue)) {
|
|
902
|
+
if (isPlainObject(targetValue)) {
|
|
903
|
+
target[key] = mergeWith(targetValue, sourceValue, merge);
|
|
904
|
+
} else {
|
|
905
|
+
target[key] = mergeWith({}, sourceValue, merge);
|
|
906
|
+
}
|
|
907
|
+
} else if (targetValue === undefined || sourceValue !== undefined) {
|
|
908
|
+
target[key] = sourceValue;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
return target;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// node_modules/es-toolkit/dist/object/toMerged.mjs
|
|
915
|
+
function toMerged(target, source) {
|
|
916
|
+
return mergeWith(clone(target), source, function mergeRecursively(targetValue, sourceValue) {
|
|
917
|
+
if (Array.isArray(sourceValue)) {
|
|
918
|
+
if (Array.isArray(targetValue)) {
|
|
919
|
+
return mergeWith(clone(targetValue), sourceValue, mergeRecursively);
|
|
920
|
+
} else {
|
|
921
|
+
return mergeWith([], sourceValue, mergeRecursively);
|
|
922
|
+
}
|
|
923
|
+
} else if (isPlainObject(sourceValue)) {
|
|
924
|
+
if (isPlainObject(targetValue)) {
|
|
925
|
+
return mergeWith(clone(targetValue), sourceValue, mergeRecursively);
|
|
926
|
+
} else {
|
|
927
|
+
return mergeWith({}, sourceValue, mergeRecursively);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
// src/sdk/speech/index.ts
|
|
933
|
+
class SpeechSDK extends Client {
|
|
934
|
+
async synthesize(request2) {
|
|
935
|
+
const body = this.validateParams(request2);
|
|
936
|
+
const url = speechEndpoint(this.config.baseUrl);
|
|
937
|
+
if (body.stream) {
|
|
938
|
+
return this.synthesizeStream(body, url);
|
|
939
|
+
}
|
|
940
|
+
const res = await this.requestJson({
|
|
941
|
+
url,
|
|
942
|
+
method: "POST",
|
|
943
|
+
body
|
|
944
|
+
});
|
|
945
|
+
return res;
|
|
946
|
+
}
|
|
947
|
+
async* synthesizeStream(body, url) {
|
|
948
|
+
const res = await this.request({
|
|
949
|
+
url,
|
|
950
|
+
method: "POST",
|
|
951
|
+
body,
|
|
952
|
+
stream: true
|
|
953
|
+
});
|
|
954
|
+
yield* this.streamSSE(res);
|
|
955
|
+
}
|
|
956
|
+
async voices(language) {
|
|
957
|
+
const url = voicesEndpoint(this.config.baseUrl);
|
|
958
|
+
const res = await this.requestJson({
|
|
959
|
+
url,
|
|
960
|
+
method: "POST",
|
|
961
|
+
body: { voice_type: "system" }
|
|
962
|
+
});
|
|
963
|
+
const voices = res.system_voice ?? [];
|
|
964
|
+
if (language) {
|
|
965
|
+
const filtered = filterByLanguage(voices, language);
|
|
966
|
+
return filtered;
|
|
967
|
+
}
|
|
968
|
+
return voices;
|
|
969
|
+
}
|
|
970
|
+
validateParams(params) {
|
|
971
|
+
if (!params.text) {
|
|
972
|
+
throw new SDKError("text is required", ExitCode.USAGE);
|
|
973
|
+
}
|
|
974
|
+
return toMerged({
|
|
975
|
+
model: "speech-2.8-hd",
|
|
976
|
+
voice_setting: {
|
|
977
|
+
voice_id: "English_expressive_narrator"
|
|
978
|
+
},
|
|
979
|
+
audio_setting: {
|
|
980
|
+
format: "mp3",
|
|
981
|
+
sample_rate: 32000,
|
|
982
|
+
bitrate: 128000,
|
|
983
|
+
channel: 1
|
|
984
|
+
},
|
|
985
|
+
output_format: "hex"
|
|
986
|
+
}, params);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// 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
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// src/output/progress.ts
|
|
1025
|
+
var SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
1026
|
+
function createSpinner(label) {
|
|
1027
|
+
const isTTY = process.stderr.isTTY;
|
|
1028
|
+
let frame = 0;
|
|
1029
|
+
let interval = null;
|
|
1030
|
+
let currentLabel = label;
|
|
1031
|
+
return {
|
|
1032
|
+
start() {
|
|
1033
|
+
if (!isTTY)
|
|
1034
|
+
return;
|
|
1035
|
+
interval = setInterval(() => {
|
|
1036
|
+
process.stderr.write(`\r${SPINNER_FRAMES[frame % SPINNER_FRAMES.length]} ${currentLabel}`);
|
|
1037
|
+
frame++;
|
|
1038
|
+
}, 80);
|
|
1039
|
+
},
|
|
1040
|
+
update(text) {
|
|
1041
|
+
currentLabel = text;
|
|
1042
|
+
},
|
|
1043
|
+
stop(finalText) {
|
|
1044
|
+
if (interval) {
|
|
1045
|
+
clearInterval(interval);
|
|
1046
|
+
interval = null;
|
|
1047
|
+
}
|
|
1048
|
+
if (isTTY) {
|
|
1049
|
+
process.stderr.write("\r\x1B[K");
|
|
1050
|
+
if (finalText) {
|
|
1051
|
+
process.stderr.write(`${finalText}
|
|
1052
|
+
`);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
function createProgressBar(total, label = "") {
|
|
1059
|
+
const isTTY = process.stderr.isTTY;
|
|
1060
|
+
const width = 30;
|
|
1061
|
+
return {
|
|
1062
|
+
update(current) {
|
|
1063
|
+
if (!isTTY)
|
|
1064
|
+
return;
|
|
1065
|
+
const pct = Math.min(1, current / total);
|
|
1066
|
+
const filled = Math.round(width * pct);
|
|
1067
|
+
const empty = width - filled;
|
|
1068
|
+
const bar = "█".repeat(filled) + "░".repeat(empty);
|
|
1069
|
+
const pctStr = `${Math.round(pct * 100)}%`;
|
|
1070
|
+
process.stderr.write(`\r${label} ${bar} ${pctStr}`);
|
|
1071
|
+
},
|
|
1072
|
+
finish() {
|
|
1073
|
+
if (isTTY) {
|
|
1074
|
+
process.stderr.write(`
|
|
1075
|
+
`);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
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
|
+
// src/files/download.ts
|
|
1112
|
+
import { createWriteStream, renameSync as renameSync3, unlinkSync as unlinkSync2 } from "fs";
|
|
1113
|
+
async function downloadFile(url, destPath, opts) {
|
|
1114
|
+
const downloadUrl = url.startsWith("http://") ? url.replace("http://", "https://") : url;
|
|
1115
|
+
const maxRetries = opts?.retries ?? 3;
|
|
1116
|
+
const baseDelay = opts?.retryDelayMs ?? 1000;
|
|
1117
|
+
let lastError;
|
|
1118
|
+
for (let attempt = 0;attempt <= maxRetries; attempt++) {
|
|
1119
|
+
try {
|
|
1120
|
+
if (attempt > 0) {
|
|
1121
|
+
const delay = baseDelay * Math.pow(2, attempt - 1);
|
|
1122
|
+
if (!opts?.quiet) {
|
|
1123
|
+
process.stderr.write(`
|
|
1124
|
+
Retry ${attempt}/${maxRetries} in ${delay}ms...
|
|
1125
|
+
`);
|
|
1126
|
+
}
|
|
1127
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
1128
|
+
}
|
|
1129
|
+
const res = await fetch(downloadUrl);
|
|
1130
|
+
if (!res.ok) {
|
|
1131
|
+
throw new CLIError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL);
|
|
1132
|
+
}
|
|
1133
|
+
const contentLength = Number(res.headers.get("content-length") || 0);
|
|
1134
|
+
const reader = res.body?.getReader();
|
|
1135
|
+
if (!reader)
|
|
1136
|
+
throw new CLIError("No response body", ExitCode.GENERAL);
|
|
1137
|
+
const tmpPath = `${destPath}.tmp-${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;
|
|
1138
|
+
const writer = createWriteStream(tmpPath);
|
|
1139
|
+
const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null;
|
|
1140
|
+
let received = 0;
|
|
1141
|
+
let readComplete = false;
|
|
1142
|
+
let completed = false;
|
|
1143
|
+
try {
|
|
1144
|
+
const writeError = new Promise((_, reject) => {
|
|
1145
|
+
writer.on("error", reject);
|
|
1146
|
+
});
|
|
1147
|
+
while (true) {
|
|
1148
|
+
const { done, value } = await Promise.race([
|
|
1149
|
+
reader.read(),
|
|
1150
|
+
writeError
|
|
1151
|
+
]);
|
|
1152
|
+
if (done)
|
|
1153
|
+
break;
|
|
1154
|
+
const ok = writer.write(value);
|
|
1155
|
+
if (!ok)
|
|
1156
|
+
await new Promise((r) => writer.once("drain", r));
|
|
1157
|
+
received += value.byteLength;
|
|
1158
|
+
progress?.update(received);
|
|
1159
|
+
}
|
|
1160
|
+
readComplete = true;
|
|
1161
|
+
} finally {
|
|
1162
|
+
reader.releaseLock();
|
|
1163
|
+
progress?.finish();
|
|
1164
|
+
try {
|
|
1165
|
+
if (!writer.destroyed) {
|
|
1166
|
+
await new Promise((resolve, reject) => {
|
|
1167
|
+
writer.on("finish", resolve);
|
|
1168
|
+
writer.on("error", reject);
|
|
1169
|
+
writer.end();
|
|
1170
|
+
});
|
|
1171
|
+
completed = readComplete;
|
|
1172
|
+
}
|
|
1173
|
+
} finally {
|
|
1174
|
+
if (!completed) {
|
|
1175
|
+
try {
|
|
1176
|
+
unlinkSync2(tmpPath);
|
|
1177
|
+
} catch {}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
renameSync3(tmpPath, destPath);
|
|
1182
|
+
return { size: received };
|
|
1183
|
+
} catch (err) {
|
|
1184
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
1185
|
+
if (!opts?.quiet) {
|
|
1186
|
+
process.stderr.write(`
|
|
1187
|
+
Download attempt ${attempt + 1} failed: ${lastError.message}
|
|
1188
|
+
`);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
throw new CLIError(`Download failed after ${maxRetries + 1} attempts: ${lastError?.message}`, ExitCode.NETWORK, "Check your network connection and proxy settings.");
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// src/sdk/video/index.ts
|
|
1196
|
+
class VideoSDK extends Client {
|
|
1197
|
+
async generate(request2) {
|
|
1198
|
+
const body = this.validateParams(request2);
|
|
1199
|
+
const url = videoGenerateEndpoint(this.config.baseUrl);
|
|
1200
|
+
const res = await this.requestJson({
|
|
1201
|
+
url,
|
|
1202
|
+
method: "POST",
|
|
1203
|
+
body
|
|
1204
|
+
});
|
|
1205
|
+
const taskId = res.task_id;
|
|
1206
|
+
if (request2.async) {
|
|
1207
|
+
return { taskId };
|
|
1208
|
+
}
|
|
1209
|
+
const taskUrl = videoTaskEndpoint(this.config.baseUrl, taskId);
|
|
1210
|
+
const result = await poll(this.config, {
|
|
1211
|
+
url: taskUrl,
|
|
1212
|
+
intervalSec: request2.pollInterval ?? 5,
|
|
1213
|
+
timeoutSec: request2.timeout ?? this.config.timeout,
|
|
1214
|
+
isComplete: (d) => d.status === "Success",
|
|
1215
|
+
isFailed: (d) => d.status === "Failed",
|
|
1216
|
+
getStatus: (d) => d.status
|
|
1217
|
+
});
|
|
1218
|
+
return result;
|
|
1219
|
+
}
|
|
1220
|
+
async getTask({ taskId }) {
|
|
1221
|
+
const url = videoTaskEndpoint(this.config.baseUrl, taskId);
|
|
1222
|
+
return await this.requestJson({ url });
|
|
1223
|
+
}
|
|
1224
|
+
async download(request2) {
|
|
1225
|
+
const url = fileRetrieveEndpoint(this.config.baseUrl, request2.fileId);
|
|
1226
|
+
const fileInfo = await this.requestJson({ url });
|
|
1227
|
+
const downloadUrl = fileInfo.file?.download_url;
|
|
1228
|
+
if (!downloadUrl) {
|
|
1229
|
+
throw new SDKError("No download URL available for this file.", ExitCode.GENERAL);
|
|
1230
|
+
}
|
|
1231
|
+
const { size } = await downloadFile(downloadUrl, request2.outPath, { quiet: true });
|
|
1232
|
+
return {
|
|
1233
|
+
size,
|
|
1234
|
+
save: request2.outPath,
|
|
1235
|
+
downloadUrl
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
validateParams(request2) {
|
|
1239
|
+
const { prompt, model, first_frame_image, last_frame_image, subject_reference } = request2;
|
|
1240
|
+
if (!prompt) {
|
|
1241
|
+
throw new SDKError("prompt is required", ExitCode.USAGE);
|
|
1242
|
+
}
|
|
1243
|
+
let resolvedModel;
|
|
1244
|
+
if (model) {
|
|
1245
|
+
resolvedModel = model;
|
|
1246
|
+
} else if (last_frame_image) {
|
|
1247
|
+
resolvedModel = "MiniMax-Hailuo-02";
|
|
1248
|
+
} else if (subject_reference) {
|
|
1249
|
+
resolvedModel = "S2V-01";
|
|
1250
|
+
} else {
|
|
1251
|
+
resolvedModel = "MiniMax-Hailuo-2.3";
|
|
1252
|
+
}
|
|
1253
|
+
if (resolvedModel === "MiniMax-Hailuo-2.3-Fast" && !first_frame_image) {
|
|
1254
|
+
throw new SDKError("MiniMax-Hailuo-2.3-Fast only supports I2V (image-to-video). Provide first_frame_image.", ExitCode.USAGE);
|
|
1255
|
+
}
|
|
1256
|
+
if (last_frame_image && !first_frame_image) {
|
|
1257
|
+
throw new SDKError("last_frame_image requires first_frame_image (SEF mode).", ExitCode.USAGE);
|
|
1258
|
+
}
|
|
1259
|
+
if (last_frame_image && subject_reference) {
|
|
1260
|
+
throw new SDKError("last_frame_image and subject_reference cannot be used together (SEF and S2V are different modes).", ExitCode.USAGE);
|
|
1261
|
+
}
|
|
1262
|
+
return toMerged({
|
|
1263
|
+
model: resolvedModel
|
|
1264
|
+
}, request2);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/commands/music/models.ts
|
|
1269
|
+
function isCodingPlan(config) {
|
|
1270
|
+
const key = config.apiKey ?? config.fileApiKey ?? "";
|
|
1271
|
+
return key.startsWith("sk-cp-");
|
|
1272
|
+
}
|
|
1273
|
+
function musicGenerateModel(config) {
|
|
1274
|
+
if (config.defaultMusicModel)
|
|
1275
|
+
return config.defaultMusicModel;
|
|
1276
|
+
return isCodingPlan(config) ? "music-2.6" : "music-2.6-free";
|
|
1277
|
+
}
|
|
1278
|
+
var VALID_COVER_MODELS = new Set(["music-cover", "music-cover-free"]);
|
|
1279
|
+
|
|
1280
|
+
// src/sdk/music/index.ts
|
|
1281
|
+
class MusicSDK extends Client {
|
|
1282
|
+
async* generateStream(body, url) {
|
|
1283
|
+
const res = await this.request({
|
|
1284
|
+
url,
|
|
1285
|
+
method: "POST",
|
|
1286
|
+
body,
|
|
1287
|
+
stream: true
|
|
1288
|
+
});
|
|
1289
|
+
const reader = res.body?.getReader();
|
|
1290
|
+
if (!reader) {
|
|
1291
|
+
throw new SDKError("No response body", ExitCode.GENERAL);
|
|
1292
|
+
}
|
|
1293
|
+
try {
|
|
1294
|
+
while (true) {
|
|
1295
|
+
const { done, value } = await reader.read();
|
|
1296
|
+
if (done)
|
|
1297
|
+
break;
|
|
1298
|
+
yield value;
|
|
1299
|
+
}
|
|
1300
|
+
} finally {
|
|
1301
|
+
reader.releaseLock();
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async generate(request2) {
|
|
1305
|
+
const body = this.validateParams(request2);
|
|
1306
|
+
const url = musicEndpoint(this.config.baseUrl);
|
|
1307
|
+
if (request2.stream) {
|
|
1308
|
+
return this.generateStream(body, url);
|
|
1309
|
+
}
|
|
1310
|
+
return await this.requestJson({
|
|
1311
|
+
url,
|
|
1312
|
+
method: "POST",
|
|
1313
|
+
body
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
buildPrompt(request2) {
|
|
1317
|
+
const structuredParts = [];
|
|
1318
|
+
if (request2.vocals)
|
|
1319
|
+
structuredParts.push(`Vocals: ${request2.vocals}`);
|
|
1320
|
+
if (request2.genre)
|
|
1321
|
+
structuredParts.push(`Genre: ${request2.genre}`);
|
|
1322
|
+
if (request2.mood)
|
|
1323
|
+
structuredParts.push(`Mood: ${request2.mood}`);
|
|
1324
|
+
if (request2.instruments)
|
|
1325
|
+
structuredParts.push(`Instruments: ${request2.instruments}`);
|
|
1326
|
+
if (request2.tempo)
|
|
1327
|
+
structuredParts.push(`Tempo: ${request2.tempo}`);
|
|
1328
|
+
if (request2.bpm)
|
|
1329
|
+
structuredParts.push(`BPM: ${request2.bpm}`);
|
|
1330
|
+
if (request2.key)
|
|
1331
|
+
structuredParts.push(`Key: ${request2.key}`);
|
|
1332
|
+
if (request2.avoid)
|
|
1333
|
+
structuredParts.push(`Avoid: ${request2.avoid}`);
|
|
1334
|
+
if (request2.useCase)
|
|
1335
|
+
structuredParts.push(`Use case: ${request2.useCase}`);
|
|
1336
|
+
if (request2.structure)
|
|
1337
|
+
structuredParts.push(`Structure: ${request2.structure}`);
|
|
1338
|
+
if (request2.references)
|
|
1339
|
+
structuredParts.push(`References: ${request2.references}`);
|
|
1340
|
+
if (request2.extra)
|
|
1341
|
+
structuredParts.push(`Extra: ${request2.extra}`);
|
|
1342
|
+
let lyrics = request2.lyrics;
|
|
1343
|
+
let prompt = request2.prompt;
|
|
1344
|
+
if (request2.instrumental || !lyrics || lyrics === "无歌词" || lyrics === "no lyrics") {
|
|
1345
|
+
lyrics = "[intro] [outro]";
|
|
1346
|
+
structuredParts.push("Style: instrumental, no vocals, pure music");
|
|
1347
|
+
}
|
|
1348
|
+
if (structuredParts.length > 0) {
|
|
1349
|
+
const structured = structuredParts.join(". ");
|
|
1350
|
+
prompt = prompt ? `${prompt}. ${structured}` : structured;
|
|
1351
|
+
}
|
|
1352
|
+
return prompt;
|
|
1353
|
+
}
|
|
1354
|
+
validateParams(params) {
|
|
1355
|
+
const {
|
|
1356
|
+
model,
|
|
1357
|
+
output_format,
|
|
1358
|
+
stream,
|
|
1359
|
+
prompt,
|
|
1360
|
+
lyrics,
|
|
1361
|
+
is_instrumental,
|
|
1362
|
+
lyrics_optimizer
|
|
1363
|
+
} = params;
|
|
1364
|
+
if (is_instrumental && lyrics) {
|
|
1365
|
+
throw new SDKError("Cannot use is_instrumental with lyrics", ExitCode.USAGE);
|
|
1366
|
+
}
|
|
1367
|
+
if (lyrics_optimizer && (lyrics || is_instrumental)) {
|
|
1368
|
+
throw new SDKError("Cannot use lyrics_optimizer with lyrics or is_instrumental", ExitCode.USAGE);
|
|
1369
|
+
}
|
|
1370
|
+
if (!prompt && !lyrics && !is_instrumental && !lyrics_optimizer) {
|
|
1371
|
+
throw new SDKError("At least one of prompt or lyrics or is_instrumental or lyrics_optimizer is required", ExitCode.USAGE);
|
|
1372
|
+
}
|
|
1373
|
+
if (!is_instrumental && !lyrics_optimizer && !lyrics?.trim()) {
|
|
1374
|
+
throw new SDKError("lyrics is required", ExitCode.USAGE);
|
|
1375
|
+
}
|
|
1376
|
+
const VALID_MODELS = ["music-2.6", "music-2.6-free", "music-2.5+", "music-2.5"];
|
|
1377
|
+
if (model && !VALID_MODELS.includes(model)) {
|
|
1378
|
+
throw new SDKError(`Invalid model: ${model}. Valid models are ${VALID_MODELS.join(", ")}.`, ExitCode.USAGE);
|
|
1379
|
+
}
|
|
1380
|
+
const VALID_OUTPUT_FORMATS = ["hex", "url"];
|
|
1381
|
+
if (output_format && !VALID_OUTPUT_FORMATS.includes(output_format)) {
|
|
1382
|
+
throw new SDKError(`Invalid output format: ${output_format}. Valid formats are ${VALID_OUTPUT_FORMATS.join(", ")}.`, ExitCode.USAGE);
|
|
1383
|
+
}
|
|
1384
|
+
if (stream && output_format === "url") {
|
|
1385
|
+
throw new SDKError(`stream and output_format url cannot be used together. Streaming requires hex format.`, ExitCode.USAGE);
|
|
1386
|
+
}
|
|
1387
|
+
const targetPrompt = this.buildPrompt(params);
|
|
1388
|
+
return toMerged({
|
|
1389
|
+
model: musicGenerateModel(this.config),
|
|
1390
|
+
audio_setting: {
|
|
1391
|
+
format: "mp3",
|
|
1392
|
+
sample_rate: 44100,
|
|
1393
|
+
bitrate: 256000
|
|
1394
|
+
},
|
|
1395
|
+
output_format: "hex"
|
|
1396
|
+
}, {
|
|
1397
|
+
...params,
|
|
1398
|
+
prompt: targetPrompt
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
// src/sdk/search/index.ts
|
|
1404
|
+
class SearchSDK extends Client {
|
|
1405
|
+
async query(query) {
|
|
1406
|
+
const url = searchEndpoint(this.config.baseUrl);
|
|
1407
|
+
const res = await this.requestJson({
|
|
1408
|
+
url,
|
|
1409
|
+
method: "POST",
|
|
1410
|
+
body: { q: query }
|
|
1411
|
+
});
|
|
1412
|
+
return res;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// src/utils/image.ts
|
|
1417
|
+
import { readFileSync as readFileSync3, existsSync as existsSync3 } from "fs";
|
|
1418
|
+
import { extname } from "path";
|
|
1419
|
+
var IMAGE_MIME_TYPES = {
|
|
1420
|
+
".jpg": "image/jpeg",
|
|
1421
|
+
".jpeg": "image/jpeg",
|
|
1422
|
+
".png": "image/png",
|
|
1423
|
+
".webp": "image/webp"
|
|
1424
|
+
};
|
|
1425
|
+
function localFileToDataUri(filePath) {
|
|
1426
|
+
const ext = extname(filePath).toLowerCase();
|
|
1427
|
+
const mime = IMAGE_MIME_TYPES[ext] || "image/jpeg";
|
|
1428
|
+
const data = readFileSync3(filePath);
|
|
1429
|
+
return `data:${mime};base64,${data.toString("base64")}`;
|
|
1430
|
+
}
|
|
1431
|
+
var MAX_IMAGE_SIZE_BYTES = 50 * 1024 * 1024;
|
|
1432
|
+
async function toDataUri(image) {
|
|
1433
|
+
if (image.startsWith("data:"))
|
|
1434
|
+
return image;
|
|
1435
|
+
if (image.startsWith("http://") || image.startsWith("https://")) {
|
|
1436
|
+
const res = await fetch(image);
|
|
1437
|
+
if (!res.ok)
|
|
1438
|
+
throw new CLIError(`Failed to download image: HTTP ${res.status}`, ExitCode.GENERAL);
|
|
1439
|
+
const contentType = res.headers.get("content-type") || "image/jpeg";
|
|
1440
|
+
const mime = contentType.split(";")[0].trim();
|
|
1441
|
+
const buf = await res.arrayBuffer();
|
|
1442
|
+
if (buf.byteLength > MAX_IMAGE_SIZE_BYTES) {
|
|
1443
|
+
throw new CLIError(`Image too large (${(buf.byteLength / 1024 / 1024).toFixed(1)} MB). Maximum is 50 MB.`, ExitCode.USAGE);
|
|
1444
|
+
}
|
|
1445
|
+
return `data:${mime};base64,${Buffer.from(buf).toString("base64")}`;
|
|
1446
|
+
}
|
|
1447
|
+
if (!existsSync3(image))
|
|
1448
|
+
throw new CLIError(`File not found: ${image}`, ExitCode.USAGE);
|
|
1449
|
+
const ext = extname(image).toLowerCase();
|
|
1450
|
+
if (!IMAGE_MIME_TYPES[ext])
|
|
1451
|
+
throw new CLIError(`Unsupported image format "${ext}". Supported: jpg, jpeg, png, webp`, ExitCode.USAGE);
|
|
1452
|
+
return localFileToDataUri(image);
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// src/sdk/vision/index.ts
|
|
1456
|
+
class VisionSDK extends Client {
|
|
1457
|
+
async describe(request2) {
|
|
1458
|
+
const body = {
|
|
1459
|
+
prompt: request2.prompt || "Describe the image.",
|
|
1460
|
+
image_url: await toDataUri(request2.image)
|
|
1461
|
+
};
|
|
1462
|
+
const url = vlmEndpoint(this.config.baseUrl);
|
|
1463
|
+
const res = await this.requestJson({
|
|
1464
|
+
url,
|
|
1465
|
+
method: "POST",
|
|
1466
|
+
body
|
|
1467
|
+
});
|
|
1468
|
+
return res;
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// src/sdk/quota/index.ts
|
|
1473
|
+
class QuotaSDK extends Client {
|
|
1474
|
+
async info() {
|
|
1475
|
+
const url = quotaEndpoint(this.config.baseUrl);
|
|
1476
|
+
const res = await this.requestJson({ url });
|
|
1477
|
+
return res;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
// src/sdk/index.ts
|
|
1482
|
+
class MiniMaxSDK extends Client {
|
|
1483
|
+
text;
|
|
1484
|
+
speech;
|
|
1485
|
+
image;
|
|
1486
|
+
video;
|
|
1487
|
+
music;
|
|
1488
|
+
search;
|
|
1489
|
+
vision;
|
|
1490
|
+
quota;
|
|
1491
|
+
constructor(options) {
|
|
1492
|
+
super(options);
|
|
1493
|
+
this.text = new TextSDK(options);
|
|
1494
|
+
this.speech = new SpeechSDK(options);
|
|
1495
|
+
this.image = new ImageSDK(options);
|
|
1496
|
+
this.video = new VideoSDK(options);
|
|
1497
|
+
this.music = new MusicSDK(options);
|
|
1498
|
+
this.search = new SearchSDK(options);
|
|
1499
|
+
this.vision = new VisionSDK(options);
|
|
1500
|
+
this.quota = new QuotaSDK(options);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
export {
|
|
1504
|
+
MiniMaxSDK
|
|
1505
|
+
};
|