@makemidas/cli 0.1.1 → 0.2.0

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/commands.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import { join, resolve } from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
4
5
  import { envCredential, login } from "./auth.js";
5
6
  import { deleteProfile, loadProfile, saveProfile } from "./config.js";
6
7
  import { CliError, EXIT } from "./errors.js";
@@ -10,7 +11,36 @@ const EXTENSIONS = {
10
11
  'image/png': 'png',
11
12
  'image/webp': 'webp',
12
13
  'video/mp4': 'mp4',
14
+ 'video/quicktime': 'mov',
15
+ 'video/webm': 'webm',
16
+ 'audio/mpeg': 'mp3',
17
+ 'audio/mp3': 'mp3',
18
+ 'audio/wav': 'wav',
19
+ 'audio/x-wav': 'wav',
20
+ 'audio/wave': 'wav',
21
+ 'audio/mp4': 'm4a',
22
+ 'audio/x-m4a': 'm4a',
23
+ 'audio/aac': 'aac',
24
+ 'audio/flac': 'flac',
25
+ 'audio/ogg': 'ogg',
26
+ 'audio/opus': 'opus',
27
+ 'audio/webm': 'webm',
28
+ 'application/json': 'json',
29
+ 'text/plain': 'txt',
13
30
  };
31
+ /** Where a generation's file goes: `<dir>/makemidas-<id>-<n>.<ext>`. */
32
+ function outputPath(dir, generation, n, ext) {
33
+ return join(dir, `makemidas-${generation.id.slice(0, 8)}-${n}.${ext}`);
34
+ }
35
+ async function writeOutput(file, bytes, force) {
36
+ if (existsSync(file) && !force) {
37
+ warn(`${file} exists; skipped (use --force to overwrite).`);
38
+ return false;
39
+ }
40
+ await writeFile(file, bytes);
41
+ log(`Saved ${file} (${formatBytes(bytes.byteLength)})`);
42
+ return true;
43
+ }
14
44
  // ---------------------------------------------------------------------------
15
45
  // auth
16
46
  // ---------------------------------------------------------------------------
@@ -64,15 +94,10 @@ async function saveOutputs(api, generation, save) {
64
94
  if (output.status !== 'done' || !output.url)
65
95
  continue;
66
96
  const { bytes, type } = await api.download(output.url);
67
- const ext = EXTENSIONS[type.split(';')[0]] ?? 'bin';
68
- const file = join(dir, `makemidas-${generation.id.slice(0, 8)}-${index + 1}.${ext}`);
69
- if (existsSync(file) && !save.force) {
70
- warn(`${file} exists; skipped (use --force to overwrite).`);
71
- continue;
72
- }
73
- await writeFile(file, bytes);
74
- log(`Saved ${file} (${formatBytes(bytes.byteLength)})`);
75
- files.push(file);
97
+ const ext = EXTENSIONS[type.split(';')[0].trim()] ?? 'bin';
98
+ const file = outputPath(dir, generation, index + 1, ext);
99
+ if (await writeOutput(file, bytes, save.force))
100
+ files.push(file);
76
101
  }
77
102
  return files;
78
103
  }
@@ -86,7 +111,7 @@ async function waitFor(api, generation, timeoutMin) {
86
111
  }
87
112
  return current;
88
113
  }
89
- function report(g, generation, files) {
114
+ function report(g, generation, files, links = generation.outputs.flatMap((o) => (o.url ? [o.url] : []))) {
90
115
  if (g.json) {
91
116
  printJson({ ...generation, files });
92
117
  }
@@ -94,12 +119,10 @@ function report(g, generation, files) {
94
119
  if (files.length)
95
120
  for (const file of files)
96
121
  print(file);
97
- else {
98
- for (const output of generation.outputs)
99
- if (output.url)
100
- print(output.url);
101
- }
102
- log(`${generation.kind} ${generation.id}: ${generation.status}, ${generation.credits} credits${generation.watermarked ? ' (watermarked: free plan)' : ''}.`);
122
+ else
123
+ for (const link of links)
124
+ print(link);
125
+ log(`${generation.kind} ${generation.id}: ${generation.status}, ${generation.credits} credits${generation.watermarked ? ' (watermarked: no plan or credit pack)' : ''}.`);
103
126
  }
104
127
  if (generation.status === 'failed') {
105
128
  throw new CliError(generation.error ?? 'The model could not make this; credits were refunded.', EXIT.FAILED, 'generation_failed');
@@ -108,20 +131,128 @@ function report(g, generation, files) {
108
131
  throw new CliError(`Still rendering. Run \`makemidas get ${generation.id} --wait\` later.`, EXIT.NOT_READY, 'not_ready');
109
132
  }
110
133
  }
111
- export async function generate(api, g, input, refs, save, wait) {
134
+ /** Upload each `--ref` and return the reference ids. */
135
+ async function uploadRefs(api, refs) {
112
136
  const referenceIds = [];
113
137
  for (const ref of refs) {
114
138
  log(`Uploading ${ref}…`);
115
139
  referenceIds.push(await api.upload(ref));
116
140
  }
141
+ return referenceIds;
142
+ }
143
+ /**
144
+ * Price the request first and refuse when it costs more than `maxCredits`;
145
+ * otherwise send the estimated request back with its price as
146
+ * `quotedCredits`, so the server charges exactly that or nothing.
147
+ */
148
+ async function quotedRequest(api, input, maxCredits) {
149
+ const quote = await api.estimate(input);
150
+ if (quote.credits > maxCredits) {
151
+ throw new CliError(`This costs ${quote.credits} credits, over --max-credits ${maxCredits}. Nothing was charged.`, EXIT.CREDITS, 'over_budget');
152
+ }
153
+ if (!quote.affordable) {
154
+ throw new CliError(`This costs ${quote.credits} credits and your balance is ${quote.balance}. Nothing was charged.`, EXIT.CREDITS, 'insufficient_credits', quote.suggestedModel ? { suggestedModel: quote.suggestedModel } : {});
155
+ }
156
+ log(`Quoted ${quote.credits} credits.`);
157
+ return { ...quote.request, quotedCredits: quote.credits };
158
+ }
159
+ /** Upload a file or link to audio- or video-uploads; returns its fileId. */
160
+ async function uploadMedia(api, kind, source) {
161
+ // An id from an earlier upload (or estimate) is used as it is.
162
+ if (UUID.test(source) && !existsSync(source))
163
+ return source;
164
+ log(`Uploading ${source}…`);
165
+ const upload = await api.mediaUpload(kind, source);
166
+ log(`Uploaded ${upload.fileName ?? source}: ${formatSeconds(upload.durationSeconds)}.`);
167
+ return upload.fileId;
168
+ }
169
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
170
+ function formatSeconds(seconds) {
171
+ if (seconds < 60)
172
+ return `${Math.round(seconds * 10) / 10} s`;
173
+ const m = Math.floor(seconds / 60);
174
+ const s = Math.round(seconds % 60);
175
+ return `${m} min ${String(s).padStart(2, '0')} s`;
176
+ }
177
+ /** Upload what the request needs and fill in referenceIds or fileId. */
178
+ async function prepare(api, input, refs, media) {
179
+ const referenceIds = await uploadRefs(api, refs);
180
+ const fileId = media ? await uploadMedia(api, media.kind, media.source) : undefined;
181
+ return {
182
+ ...input,
183
+ // Images and videos always send the list; other kinds only when given.
184
+ ...(input.kind === 'image' || input.kind === 'video' || referenceIds.length
185
+ ? { referenceIds }
186
+ : {}),
187
+ ...(fileId ? { fileId } : {}),
188
+ };
189
+ }
190
+ /** Upload, price when asked, start the generation and wait for it. */
191
+ async function start(api, input, refs, wait, maxCredits, media) {
192
+ const prepared = await prepare(api, input, refs, media);
193
+ const request = maxCredits === undefined
194
+ ? prepared
195
+ : await quotedRequest(api, prepared, maxCredits);
117
196
  log(`Generating ${input.kind}…`);
118
- let generation = await api.generate({ ...input, referenceIds });
197
+ let generation = await api.generate(request);
119
198
  if (generation.status === 'running' && wait.wait) {
120
199
  generation = await waitFor(api, generation, wait.timeoutMin);
121
200
  }
201
+ return generation;
202
+ }
203
+ export async function generate(api, g, input, refs, save, wait, maxCredits, media) {
204
+ const generation = await start(api, input, refs, wait, maxCredits, media);
122
205
  const files = await saveOutputs(api, generation, save);
123
206
  report(g, generation, files);
124
207
  }
208
+ // ---------------------------------------------------------------------------
209
+ // transcribe
210
+ // ---------------------------------------------------------------------------
211
+ /**
212
+ * Upload the audio (or send its link), transcribe it, and save the
213
+ * transcript in `format`. `save.out` of `-` prints the transcript itself.
214
+ */
215
+ export async function transcribe(api, g, input, source, format, save, wait, maxCredits) {
216
+ if (save.out === '-' && g.json) {
217
+ throw new CliError('`--out -` prints the transcript itself; leave out --json.', EXIT.USAGE, 'usage');
218
+ }
219
+ const generation = await start(api, input, [], wait, maxCredits, {
220
+ kind: 'audio',
221
+ source,
222
+ });
223
+ const files = [];
224
+ const links = [];
225
+ for (const [index, output] of generation.outputs.entries()) {
226
+ if (output.status !== 'done')
227
+ continue;
228
+ const link = output.downloads?.[format];
229
+ if (!link) {
230
+ if (output.url) {
231
+ warn(`No ${format} download for this transcript; printing its JSON link.`);
232
+ links.push(output.url);
233
+ }
234
+ continue;
235
+ }
236
+ links.push(link);
237
+ if (!save.out)
238
+ continue;
239
+ const { bytes } = await api.download(link);
240
+ if (save.out === '-') {
241
+ process.stdout.write(bytes);
242
+ continue;
243
+ }
244
+ const dir = resolve(save.out);
245
+ await mkdir(dir, { recursive: true });
246
+ const file = outputPath(dir, generation, index + 1, format);
247
+ if (await writeOutput(file, bytes, save.force))
248
+ files.push(file);
249
+ }
250
+ if (save.out === '-') {
251
+ report({ json: false }, generation, [], []);
252
+ return;
253
+ }
254
+ report(g, generation, files, links);
255
+ }
125
256
  export async function get(api, g, id, save, wait) {
126
257
  if (!id) {
127
258
  throw new CliError('Give a generation id: `makemidas get <id>`.', EXIT.USAGE, 'usage');
@@ -134,6 +265,58 @@ export async function get(api, g, id, save, wait) {
134
265
  report(g, generation, files);
135
266
  }
136
267
  // ---------------------------------------------------------------------------
268
+ // estimate
269
+ // ---------------------------------------------------------------------------
270
+ /** The settings a request resolved to, e.g. `16:9, 720p, 5s, audio`. */
271
+ function settings(request) {
272
+ const parts = [];
273
+ if (request.task)
274
+ parts.push(request.task);
275
+ if (request.aspectRatio)
276
+ parts.push(request.aspectRatio);
277
+ if (request.resolution)
278
+ parts.push(request.resolution);
279
+ if (request.duration)
280
+ parts.push(`${request.duration}s`);
281
+ if (request.durationSeconds)
282
+ parts.push(`${request.durationSeconds}s`);
283
+ if (request.audio)
284
+ parts.push('audio');
285
+ if (request.frameMode && request.frameMode !== 'none') {
286
+ parts.push(`frame mode ${request.frameMode}`);
287
+ }
288
+ if (request.upscaleFactor)
289
+ parts.push(`${request.upscaleFactor}x`);
290
+ if (request.voice)
291
+ parts.push(`voice ${request.voice}`);
292
+ if (request.instrumental)
293
+ parts.push('instrumental');
294
+ if (request.loop)
295
+ parts.push('loop');
296
+ if (request.kind === 'image' || request.kind === 'video') {
297
+ parts.push(`${request.count} output${request.count === 1 ? '' : 's'}`);
298
+ }
299
+ return parts.join(', ');
300
+ }
301
+ export async function estimate(api, g, input, refs, command = input.kind, media) {
302
+ const result = await api.estimate(await prepare(api, input, refs, media));
303
+ if (g.json) {
304
+ printJson(result);
305
+ return;
306
+ }
307
+ const off = result.discount > 0
308
+ ? ` (list ${result.listCredits}, ${Math.round(result.discount * 100)}% off)`
309
+ : '';
310
+ print(`${result.credits} credits${off}`);
311
+ print(`Model: ${result.model}`);
312
+ print(`Settings: ${settings(result.request)}`);
313
+ print(`Balance: ${result.balance} credits, ${result.affordable ? 'affordable' : 'not enough'}`);
314
+ if (!result.affordable && result.suggestedModel) {
315
+ print(`Suggested model: ${result.suggestedModel} (fits your balance)`);
316
+ }
317
+ log(`Nothing was charged. Generate at this price with \`makemidas ${command}\` and the same options plus --max-credits ${result.credits}.`);
318
+ }
319
+ // ---------------------------------------------------------------------------
137
320
  // list / credits / models
138
321
  // ---------------------------------------------------------------------------
139
322
  export async function list(api, g, query) {
@@ -158,7 +341,7 @@ export async function credits(api, g) {
158
341
  }
159
342
  print(`${result.balance} credits (plan: ${result.plan ?? 'free'}).`);
160
343
  if (result.watermarked) {
161
- print('Free plan: 10 credits a day, free models only, watermarked images.');
344
+ print('No plan or credit pack yet: credits come from a plan or a credit pack (`makemidas credits buy`).');
162
345
  }
163
346
  else {
164
347
  print(`Up to ${result.concurrency} at once, ${result.maxOutputs} outputs each.`);
@@ -174,9 +357,277 @@ export async function models(api, g, kind) {
174
357
  return;
175
358
  }
176
359
  for (const model of result) {
177
- const prices = model.kind === 'image'
178
- ? model.credits.map((c) => `${c.resolution} ${c.credits}`).join(', ')
179
- : `${model.credits.map((c) => `${c.resolution} ${c.creditsPerSecond}/s`).join(', ')}; ${model.durations.join('/')}s`;
180
- print(`${model.id} ${model.kind}${model.tier === 'free' ? ' (free)' : ''} ${model.label}: ${prices}`);
360
+ print(`${headline(model)}: ${prices(model)}`);
361
+ }
362
+ }
363
+ function headline(model) {
364
+ const task = 'task' in model ? ` ${model.task}` : '';
365
+ return `${model.id} ${model.kind}${task}${model.tier === 'free' ? ' (free)' : ''} ${model.label}`;
366
+ }
367
+ function prices(model) {
368
+ switch (model.kind) {
369
+ case 'image':
370
+ return model.credits.map((c) => `${c.resolution} ${c.credits}`).join(', ');
371
+ case 'video':
372
+ return `${model.credits.map((c) => `${c.resolution} ${c.creditsPerSecond}/s`).join(', ')}; ${model.durations.join('/')}s`;
373
+ case 'audio':
374
+ if (model.creditsPer1kChars !== undefined) {
375
+ return `${model.creditsPer1kChars} per 1,000 characters`;
376
+ }
377
+ return `${model.creditsPerTrack ?? '?'} per request`;
378
+ case 'transcription':
379
+ return `${model.creditsPerHour} per hour of audio`;
380
+ case 'edit':
381
+ if (model.creditsPerSecond?.length) {
382
+ return model.creditsPerSecond
383
+ .map((c) => `${c.resolution} ${c.creditsPerSecond}/s`)
384
+ .join(', ');
385
+ }
386
+ return (model.credits ?? [])
387
+ .map((c) => `${c.resolution} ${c.credits}`)
388
+ .join(', ');
389
+ }
390
+ }
391
+ export async function modelDetails(api, g, id) {
392
+ const result = await api.modelDetails(id);
393
+ if (g.json) {
394
+ printJson(result);
395
+ return;
396
+ }
397
+ const { model, example } = result;
398
+ print(headline(model));
399
+ if (model.family)
400
+ print(` Family: ${model.family}`);
401
+ if (model.aspectRatios?.length) {
402
+ print(` Aspect ratios: ${model.aspectRatios.join(', ')}`);
403
+ }
404
+ if (model.resolutions?.length) {
405
+ const fallback = model.defaultResolution
406
+ ? ` (default ${model.defaultResolution})`
407
+ : '';
408
+ print(` Resolutions: ${model.resolutions.join(', ')}${fallback}`);
409
+ }
410
+ switch (model.kind) {
411
+ case 'image': {
412
+ const extra = model.creditsPerReference
413
+ ? ` (+${model.creditsPerReference} credits each)`
414
+ : '';
415
+ print(` References: up to ${model.maxReferences}${extra}`);
416
+ print(` Credits: ${prices(model)}`);
417
+ break;
418
+ }
419
+ case 'video': {
420
+ const fallback = model.defaultDuration
421
+ ? ` (default ${model.defaultDuration}s)`
422
+ : '';
423
+ print(` Durations: ${model.durations.join('/')}s${fallback}`);
424
+ const modes = model.frameModes.map((mode) => {
425
+ const limit = model.frameLimits?.[mode];
426
+ if (!limit || mode === 'none')
427
+ return mode;
428
+ const images = limit.min === limit.max ? `${limit.min}` : `${limit.min}-${limit.max}`;
429
+ return `${mode} (${images} image${limit.max === 1 ? '' : 's'})`;
430
+ });
431
+ print(` Frame modes: ${modes.join(', ')}`);
432
+ print(` Audio: ${model.audio ? 'yes' : 'no'}`);
433
+ const rates = model.credits.map((c) => `${c.resolution} ${c.creditsPerSecond}/s${c.creditsPerSecondWithAudio ? ` (${c.creditsPerSecondWithAudio}/s with audio)` : ''}`);
434
+ const extra = model.creditsPerFrame
435
+ ? `; +${model.creditsPerFrame} per frame or reference image`
436
+ : '';
437
+ print(` Credits: ${rates.join(', ')}${extra}`);
438
+ break;
439
+ }
440
+ case 'audio': {
441
+ if (model.task !== 'speech') {
442
+ const fallback = model.defaultDuration
443
+ ? ` (default ${model.defaultDuration}s)`
444
+ : '';
445
+ print(` Durations: ${model.durations.length ? `${model.durations.join('/')}s${fallback}` : 'set by the model'}`);
446
+ }
447
+ const options = [
448
+ model.lyrics && 'lyrics',
449
+ model.instrumental && 'instrumental',
450
+ model.loop && 'loop and bpm',
451
+ model.maxDeliveryChars && `delivery (up to ${model.maxDeliveryChars} characters)`,
452
+ model.speedRange &&
453
+ `speed ${model.speedRange.min}-${model.speedRange.max} and stability`,
454
+ ].filter(Boolean);
455
+ if (options.length)
456
+ print(` Options: ${options.join(', ')}`);
457
+ if (model.maxChars)
458
+ print(` Text: up to ${model.maxChars} characters`);
459
+ if (model.voices?.length) {
460
+ print(` Voices${model.defaultVoice ? ` (default ${model.defaultVoice})` : ''}:`);
461
+ for (const voice of model.voices) {
462
+ print(` ${voice.id} ${voice.name}: ${voice.description}`);
463
+ }
464
+ }
465
+ if (model.languages?.length) {
466
+ print(` Languages: ${model.languages.join(', ')}`);
467
+ }
468
+ print(` Credits: ${prices(model)}`);
469
+ break;
470
+ }
471
+ case 'transcription':
472
+ print(` Languages: about ${model.languages}${model.speakers ? ', speaker labels' : ''}`);
473
+ print(` Files: ${model.formats}, up to ${Math.round(model.maxDurationSeconds / 60)} min and ${formatBytes(model.maxBytes)}`);
474
+ print(` Downloads: ${model.outputFormats.join(', ')}`);
475
+ print(` Credits: ${prices(model)}, at least 1`);
476
+ break;
477
+ case 'edit':
478
+ print(` Takes: ${model.input}`);
479
+ print(` Limits: ${model.limits}`);
480
+ if (model.upscaleFactors?.length) {
481
+ print(` Scales: ${model.upscaleFactors.map((f) => `${f}x`).join(', ')}`);
482
+ }
483
+ print(` Credits: ${prices(model)}`);
484
+ break;
485
+ }
486
+ if (model.discount) {
487
+ print(` Discount: ${Math.round(model.discount * 100)}% off the list price`);
488
+ }
489
+ print('Example request:');
490
+ print(JSON.stringify(example, null, 2));
491
+ }
492
+ /**
493
+ * Price each model as the comparison will run it (one image at its default
494
+ * size) and refuse when the total is over `maxCredits` or the balance.
495
+ */
496
+ async function quotedComparison(api, request, maxCredits) {
497
+ const quotes = await Promise.all(request.models.map((model) => api.estimate({
498
+ kind: 'image',
499
+ prompt: request.prompt,
500
+ model,
501
+ count: 1,
502
+ ...(request.aspectRatio ? { aspectRatio: request.aspectRatio } : {}),
503
+ referenceIds: request.referenceIds,
504
+ })));
505
+ const total = quotes.reduce((sum, quote) => sum + quote.credits, 0);
506
+ const balance = quotes[0]?.balance ?? 0;
507
+ if (total > maxCredits) {
508
+ throw new CliError(`This comparison costs ${total} credits (${quotes.map((q) => `${q.model} ${q.credits}`).join(', ')}), over --max-credits ${maxCredits}. Nothing was charged.`, EXIT.CREDITS, 'over_budget');
509
+ }
510
+ if (total > balance) {
511
+ throw new CliError(`This comparison costs ${total} credits and your balance is ${balance}. Nothing was charged.`, EXIT.CREDITS, 'insufficient_credits');
512
+ }
513
+ log(`Quoted ${total} credits.`);
514
+ return total;
515
+ }
516
+ /** One prompt on 2-4 image models; saves every model's image. */
517
+ export async function compare(api, g, request, refs, save, maxCredits) {
518
+ const referenceIds = await uploadRefs(api, refs);
519
+ const body = { ...request, referenceIds };
520
+ if (maxCredits !== undefined) {
521
+ body.quotedCredits = await quotedComparison(api, body, maxCredits);
522
+ }
523
+ log(`Comparing ${request.models.join(', ')}…`);
524
+ const result = await api.compare(body);
525
+ const files = [];
526
+ for (const generation of result.generations) {
527
+ files.push(...(await saveOutputs(api, generation, save)));
528
+ }
529
+ if (g.json) {
530
+ printJson({ ...result, files });
531
+ }
532
+ else {
533
+ for (const generation of result.generations) {
534
+ const mine = files.filter((file) => file.includes(`makemidas-${generation.id.slice(0, 8)}-`));
535
+ const links = mine.length
536
+ ? mine
537
+ : generation.outputs.flatMap((o) => (o.url ? [o.url] : []));
538
+ for (const line of links)
539
+ print(`${generation.model} ${line}`);
540
+ log(`${generation.model} ${generation.id}: ${generation.status}, ${generation.credits} credits${generation.error ? ` (${generation.error})` : ''}.`);
541
+ }
542
+ log(`${result.credits} credits in all.`);
543
+ }
544
+ for (const item of result.failed) {
545
+ warn(`${item.model} did not start: ${item.error.message}`);
546
+ }
547
+ if (!result.generations.some((generation) => generation.status === 'done')) {
548
+ const first = result.failed[0]?.error;
549
+ throw new CliError(first?.message ??
550
+ result.generations[0]?.error ??
551
+ 'No model could make this; credits were refunded.', EXIT.FAILED, 'generation_failed', first
552
+ ? {
553
+ ...(first.retryable !== undefined ? { retryable: first.retryable } : {}),
554
+ ...(first.requiresPromptRevision !== undefined
555
+ ? { requiresPromptRevision: first.requiresPromptRevision }
556
+ : {}),
557
+ }
558
+ : {});
559
+ }
560
+ }
561
+ // ---------------------------------------------------------------------------
562
+ // delete / feedback / credits link
563
+ // ---------------------------------------------------------------------------
564
+ /** Ask a yes/no question on the terminal; anything but y/yes is no. */
565
+ export async function askYesNo(question) {
566
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
567
+ try {
568
+ const answer = await rl.question(`${question} [y/N] `);
569
+ return /^y(es)?$/i.test(answer.trim());
570
+ }
571
+ finally {
572
+ rl.close();
573
+ }
574
+ }
575
+ export async function deleteGeneration(api, g, id, opts) {
576
+ if (!id) {
577
+ throw new CliError('Give a generation id: `makemidas delete <id>`.', EXIT.USAGE, 'usage');
578
+ }
579
+ if (!opts.yes) {
580
+ if (!opts.interactive) {
581
+ throw new CliError(`Deleting ${id} removes its files for good. Run again with --yes to confirm.`, EXIT.USAGE, 'confirmation_required');
582
+ }
583
+ const confirm = opts.confirm ?? askYesNo;
584
+ const ok = await confirm(`Delete generation ${id} and its files for good? Credits are not refunded.`);
585
+ if (!ok) {
586
+ throw new CliError('Not deleted.', EXIT.USAGE, 'cancelled');
587
+ }
588
+ }
589
+ const result = await api.deleteGeneration(id);
590
+ if (g.json)
591
+ printJson(result);
592
+ else
593
+ print(`Deleted ${result.id}.`);
594
+ }
595
+ export async function feedback(api, g, input) {
596
+ if (!input.message.trim()) {
597
+ throw new CliError('Give a message: `makemidas feedback "The upscale kept the noise"`.', EXIT.USAGE, 'usage');
598
+ }
599
+ const result = await api.feedback({ ...input, message: input.message.trim() });
600
+ if (g.json)
601
+ printJson(result);
602
+ else
603
+ print('Thanks, your feedback was sent.');
604
+ }
605
+ /** Where to buy credits; prints links only and opens nothing. */
606
+ export async function creditsLink(api, g) {
607
+ const result = await api.purchaseLink();
608
+ if (g.json) {
609
+ printJson(result);
610
+ return;
611
+ }
612
+ print(result.url);
613
+ print(`Balance: ${result.balance} credits (plan: ${result.plan ?? 'none'}).`);
614
+ if (!result.purchasable) {
615
+ print('Checkout is switched off on this site for now.');
616
+ }
617
+ if (result.plans.length) {
618
+ print(`Plans (${result.plansUrl}):`);
619
+ for (const plan of result.plans) {
620
+ const marks = [plan.current && 'current', plan.popular && 'popular']
621
+ .filter(Boolean)
622
+ .join(', ');
623
+ print(` ${plan.name}: $${plan.priceUsd}/${plan.interval}, ${plan.monthlyCredits} credits a month, ${plan.concurrency} at once${marks ? ` (${marks})` : ''}`);
624
+ }
625
+ }
626
+ if (result.packs.length) {
627
+ print(`Credit packs (${result.packsUrl}):`);
628
+ for (const pack of result.packs) {
629
+ print(` $${pack.priceUsd}: ${pack.credits} credits (${pack.subscriberCredits} with a plan)${pack.popular ? ' (popular)' : ''}`);
630
+ }
181
631
  }
632
+ print(`Manage billing: ${result.billingUrl}`);
182
633
  }
package/dist/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- export const VERSION = '0.1.1';
4
+ export const VERSION = '0.2.0';
5
5
  export const USER_AGENT = `makemidas-cli/${VERSION}`;
6
6
  export const DEFAULT_BASE_URL = 'https://makemidas.com';
7
7
  export function resolveBaseUrl(flag) {
package/dist/errors.js CHANGED
@@ -11,12 +11,39 @@ export const EXIT = {
11
11
  export class CliError extends Error {
12
12
  exitCode;
13
13
  code;
14
- constructor(message, exitCode, code = 'ERROR') {
14
+ details;
15
+ constructor(message, exitCode, code = 'ERROR', details = {}) {
15
16
  super(message);
16
17
  this.exitCode = exitCode;
17
18
  this.code = code;
19
+ this.details = details;
18
20
  }
19
21
  }
22
+ /** One short line on what to do next, from the server's error details. */
23
+ export function errorHint(error) {
24
+ const { retryable, requiresPromptRevision, suggestedModel } = error.details;
25
+ const parts = [];
26
+ if (requiresPromptRevision) {
27
+ parts.push('Change the prompt or reference images before trying again.');
28
+ }
29
+ else if (retryable) {
30
+ parts.push('Trying again later may work.');
31
+ }
32
+ if (suggestedModel) {
33
+ parts.push(`\`--model ${suggestedModel}\` fits your balance.`);
34
+ }
35
+ return parts.length ? parts.join(' ') : undefined;
36
+ }
37
+ /** What the CLI writes to stderr for a failed command. */
38
+ export function formatError(error, json) {
39
+ if (json) {
40
+ return JSON.stringify({
41
+ error: { code: error.code, message: error.message, ...error.details },
42
+ });
43
+ }
44
+ const hint = errorHint(error);
45
+ return `Error: ${error.message}${hint ? `\nHint: ${hint}` : ''}`;
46
+ }
20
47
  const EXIT_BY_CODE = {
21
48
  unauthorized: EXIT.AUTH,
22
49
  email_not_verified: EXIT.AUTH,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makemidas/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "AI image and video generation CLI for AI agents (Claude Code, Cursor, Codex) and people: Nano Banana, GPT Image, Seedream, Seedance, Kling, Veo and more through MakeMidas.",
5
5
  "keywords": [
6
6
  "ai-image-generator",