@makemidas/cli 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +77 -2
- package/dist/api.js +147 -0
- package/dist/args.js +90 -0
- package/dist/auth.js +233 -0
- package/dist/cli.js +121 -0
- package/dist/commands.js +182 -0
- package/dist/config.js +56 -0
- package/dist/errors.js +33 -0
- package/dist/output.js +52 -0
- package/package.json +57 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MakeMidas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MakeMidas CLI: AI image and video generation for AI agents
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An AI image and video generation CLI for Claude Code, Cursor, Codex, Gemini
|
|
4
|
+
CLI, OpenClaw and people at a terminal. One command reaches Nano Banana, GPT
|
|
5
|
+
Image, Seedream, Flux, Seedance, Kling, Veo, Wan and more through
|
|
6
|
+
[MakeMidas](https://makemidas.com), paid with your MakeMidas credits. Coding
|
|
7
|
+
agents run it like any other command; the
|
|
8
|
+
[agent skill](https://github.com/makemidas-ai/skills) teaches them the
|
|
9
|
+
options, and the same account works in ChatGPT and Claude through the
|
|
10
|
+
[MakeMidas MCP server](https://makemidas.com/developers).
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm i -g @makemidas/cli # or: npx @makemidas/cli …
|
|
14
|
+
makemidas auth login # opens the browser once
|
|
15
|
+
makemidas image "a lighthouse at dawn, film photo" --aspect 16:9
|
|
16
|
+
makemidas video "the waves roll in" --ref lighthouse.png --duration 5
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Commands
|
|
20
|
+
|
|
21
|
+
| Command | |
|
|
22
|
+
|---|---|
|
|
23
|
+
| `auth login [--no-browser]` | Sign in with your MakeMidas account (OAuth in the browser) |
|
|
24
|
+
| `auth logout` | Revoke the token and forget it |
|
|
25
|
+
| `auth status` | Show the signed-in account |
|
|
26
|
+
| `image "<prompt>"` | Generate 1–4 images and save them (`./makemidas-<id>-<n>.png`) |
|
|
27
|
+
| `video "<prompt>"` | Generate a clip, wait for it and save it |
|
|
28
|
+
| `get <id> [--wait]` | Fetch a generation and save its files |
|
|
29
|
+
| `list [--limit n] [--before t]` | Recent generations |
|
|
30
|
+
| `credits` | Balance, plan, expiring credits |
|
|
31
|
+
| `models [--kind image\|video]` | Model ids, options and credit prices |
|
|
32
|
+
|
|
33
|
+
Common options: `--model`, `--aspect`, `--resolution`, `--count`, `--ref`
|
|
34
|
+
(file or URL, repeatable), `--style`, `--enhance`, `--duration`, `--audio`,
|
|
35
|
+
`--frame-mode`, `--out <dir>`, `--no-download`, `--json`. Run
|
|
36
|
+
`makemidas --help` for all of them.
|
|
37
|
+
|
|
38
|
+
Results go to stdout (file paths, or links with `--no-download`), progress to
|
|
39
|
+
stderr; `--json` gives the full generation as JSON.
|
|
40
|
+
|
|
41
|
+
Exit codes: 0 ok, 2 bad input, 3 not signed in, 4 not enough credits or a
|
|
42
|
+
plan limit, 5 generation failed (credits refunded), 6 network or server
|
|
43
|
+
error, 7 still rendering.
|
|
44
|
+
|
|
45
|
+
## Credits
|
|
46
|
+
|
|
47
|
+
Every generation spends credits at the same prices as the website. Free
|
|
48
|
+
accounts get 10 credits a day, the free models and watermarked images; videos
|
|
49
|
+
need a plan or a credit pack. `makemidas models` shows the prices;
|
|
50
|
+
`--quoted-credits <n>` refuses to charge anything else.
|
|
51
|
+
|
|
52
|
+
## Sign-in and credentials
|
|
53
|
+
|
|
54
|
+
`auth login` opens MakeMidas in your browser, where you sign in and allow
|
|
55
|
+
"MakeMidas CLI" (OAuth with PKCE; the browser hands the result back to the
|
|
56
|
+
CLI on your own machine). Tokens are stored in
|
|
57
|
+
`~/.config/makemidas/credentials.json` (mode 0600; `%APPDATA%\makemidas` on
|
|
58
|
+
Windows). The access token lasts an hour and is refreshed automatically.
|
|
59
|
+
Disconnect the CLI any time in Settings → Connections.
|
|
60
|
+
|
|
61
|
+
For scripts and CI, create an API key in Settings → API keys and set
|
|
62
|
+
`MAKEMIDAS_API_KEY`.
|
|
63
|
+
|
|
64
|
+
Environment: `MAKEMIDAS_API_KEY`, `MAKEMIDAS_TOKEN` (an OAuth access token),
|
|
65
|
+
`MAKEMIDAS_BASE_URL` (server), `MAKEMIDAS_CONFIG_DIR`.
|
|
66
|
+
|
|
67
|
+
## Development
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
npm install
|
|
71
|
+
npm test # node:test, runs the TypeScript sources directly
|
|
72
|
+
npm run build # dist/cli.js
|
|
73
|
+
MAKEMIDAS_BASE_URL=http://localhost:4000 node dist/cli.js auth login
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Node 20+ runs the built CLI; the tests need Node 23.6+ (type stripping).
|
|
77
|
+
|
|
78
|
+
License: MIT
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, extname } from 'node:path';
|
|
3
|
+
import { accessToken, envCredential } from "./auth.js";
|
|
4
|
+
import { USER_AGENT } from "./config.js";
|
|
5
|
+
import { CliError, EXIT, exitCodeFor } from "./errors.js";
|
|
6
|
+
const CONTENT_TYPES = {
|
|
7
|
+
'.jpg': 'image/jpeg',
|
|
8
|
+
'.jpeg': 'image/jpeg',
|
|
9
|
+
'.png': 'image/png',
|
|
10
|
+
'.webp': 'image/webp',
|
|
11
|
+
};
|
|
12
|
+
export class Api {
|
|
13
|
+
baseUrl;
|
|
14
|
+
/** Overridable in tests. */
|
|
15
|
+
fetchImpl = (...args) => fetch(...args);
|
|
16
|
+
constructor(baseUrl) {
|
|
17
|
+
this.baseUrl = baseUrl;
|
|
18
|
+
}
|
|
19
|
+
async send(path, opts, forceRefresh) {
|
|
20
|
+
const url = new URL(`${this.baseUrl}/api/v1${path}`);
|
|
21
|
+
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
22
|
+
if (v !== undefined)
|
|
23
|
+
url.searchParams.set(k, String(v));
|
|
24
|
+
}
|
|
25
|
+
const token = await accessToken(this.baseUrl, forceRefresh);
|
|
26
|
+
try {
|
|
27
|
+
return await this.fetchImpl(url, {
|
|
28
|
+
method: opts.method ?? 'GET',
|
|
29
|
+
headers: {
|
|
30
|
+
Authorization: `Bearer ${token}`,
|
|
31
|
+
'User-Agent': USER_AGENT,
|
|
32
|
+
...(opts.json !== undefined
|
|
33
|
+
? { 'Content-Type': 'application/json' }
|
|
34
|
+
: {}),
|
|
35
|
+
},
|
|
36
|
+
body: opts.form ??
|
|
37
|
+
(opts.json !== undefined ? JSON.stringify(opts.json) : undefined),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw new CliError(`Can't reach ${this.baseUrl}: ${error.message}`, EXIT.NETWORK, 'NETWORK');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The raw response; API errors are thrown as CliError. */
|
|
45
|
+
async request(path, opts = {}) {
|
|
46
|
+
let res = await this.send(path, opts, false);
|
|
47
|
+
// The token may have been revoked or expired early: refresh once.
|
|
48
|
+
if (res.status === 401 && !envCredential() && !opts.form) {
|
|
49
|
+
res = await this.send(path, opts, true);
|
|
50
|
+
}
|
|
51
|
+
if (res.ok)
|
|
52
|
+
return res;
|
|
53
|
+
let code = 'http_error';
|
|
54
|
+
let message = `${res.status} ${res.statusText}`;
|
|
55
|
+
let credits;
|
|
56
|
+
try {
|
|
57
|
+
const body = (await res.json());
|
|
58
|
+
code = body.error?.code ?? code;
|
|
59
|
+
message = body.error?.message ?? message;
|
|
60
|
+
credits = body.error?.credits;
|
|
61
|
+
}
|
|
62
|
+
catch { }
|
|
63
|
+
if (code === 'price_changed' && credits !== undefined) {
|
|
64
|
+
message = `The price is now ${credits} credits; nothing was charged. Run again with --quoted-credits ${credits}.`;
|
|
65
|
+
}
|
|
66
|
+
throw new CliError(message, exitCodeFor(code, res.status), code);
|
|
67
|
+
}
|
|
68
|
+
async json(path, opts = {}) {
|
|
69
|
+
return (await (await this.request(path, opts)).json());
|
|
70
|
+
}
|
|
71
|
+
me() {
|
|
72
|
+
return this.json('/me');
|
|
73
|
+
}
|
|
74
|
+
credits() {
|
|
75
|
+
return this.json('/credits');
|
|
76
|
+
}
|
|
77
|
+
async models(kind) {
|
|
78
|
+
return (await this.json('/models', { query: { kind } }))
|
|
79
|
+
.models;
|
|
80
|
+
}
|
|
81
|
+
/** Upload a local image (or one downloaded from a URL) as a reference. */
|
|
82
|
+
async upload(source) {
|
|
83
|
+
let bytes;
|
|
84
|
+
let type;
|
|
85
|
+
let name;
|
|
86
|
+
if (/^https?:\/\//i.test(source)) {
|
|
87
|
+
const res = await this.fetchImpl(source).catch(() => null);
|
|
88
|
+
if (!res?.ok) {
|
|
89
|
+
throw new CliError(`Could not download ${source}`, EXIT.USAGE, 'invalid_file');
|
|
90
|
+
}
|
|
91
|
+
bytes = new Uint8Array(await res.arrayBuffer());
|
|
92
|
+
type = res.headers.get('content-type')?.split(';')[0].trim();
|
|
93
|
+
name = basename(new URL(source).pathname) || 'image';
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
try {
|
|
97
|
+
bytes = new Uint8Array(await readFile(source));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new CliError(`Can't read ${source}`, EXIT.USAGE, 'invalid_file');
|
|
101
|
+
}
|
|
102
|
+
type = CONTENT_TYPES[extname(source).toLowerCase()];
|
|
103
|
+
name = basename(source);
|
|
104
|
+
}
|
|
105
|
+
if (!type || !Object.values(CONTENT_TYPES).includes(type)) {
|
|
106
|
+
throw new CliError(`${source}: reference images must be JPG, PNG or WebP.`, EXIT.USAGE, 'invalid_file');
|
|
107
|
+
}
|
|
108
|
+
const form = new FormData();
|
|
109
|
+
form.append('file', new Blob([bytes], { type }), name);
|
|
110
|
+
const { id } = await this.json('/uploads', {
|
|
111
|
+
method: 'POST',
|
|
112
|
+
form,
|
|
113
|
+
});
|
|
114
|
+
return id;
|
|
115
|
+
}
|
|
116
|
+
generate(input) {
|
|
117
|
+
return this.json('/generations', {
|
|
118
|
+
method: 'POST',
|
|
119
|
+
json: input,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
generation(id, waitSeconds = 0) {
|
|
123
|
+
return this.json(`/generations/${encodeURIComponent(id)}`, {
|
|
124
|
+
query: { wait: waitSeconds || undefined },
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
async list(query) {
|
|
128
|
+
return (await this.json('/generations', { query })).generations;
|
|
129
|
+
}
|
|
130
|
+
/** Download a signed output link. */
|
|
131
|
+
async download(url) {
|
|
132
|
+
let res;
|
|
133
|
+
try {
|
|
134
|
+
res = await this.fetchImpl(url, { headers: { 'User-Agent': USER_AGENT } });
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
throw new CliError(`Download failed: ${error.message}`, EXIT.NETWORK, 'NETWORK');
|
|
138
|
+
}
|
|
139
|
+
if (!res.ok) {
|
|
140
|
+
throw new CliError(`Download failed (${res.status}); links last an hour, run \`makemidas get <id>\` for fresh ones.`, EXIT.NETWORK, 'NETWORK');
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
bytes: new Uint8Array(await res.arrayBuffer()),
|
|
144
|
+
type: res.headers.get('content-type') ?? 'application/octet-stream',
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
}
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { CliError, EXIT } from "./errors.js";
|
|
3
|
+
export const usageError = (message) => new CliError(`${message}\nRun \`makemidas --help\` for usage.`, EXIT.USAGE, 'usage');
|
|
4
|
+
export function parse(argv) {
|
|
5
|
+
try {
|
|
6
|
+
return parseArgs({
|
|
7
|
+
args: argv,
|
|
8
|
+
allowPositionals: true,
|
|
9
|
+
strict: true,
|
|
10
|
+
options: {
|
|
11
|
+
json: { type: 'boolean', default: false },
|
|
12
|
+
quiet: { type: 'boolean', default: false },
|
|
13
|
+
'base-url': { type: 'string' },
|
|
14
|
+
version: { type: 'boolean', short: 'v', default: false },
|
|
15
|
+
help: { type: 'boolean', short: 'h', default: false },
|
|
16
|
+
'no-browser': { type: 'boolean', default: false },
|
|
17
|
+
model: { type: 'string', short: 'm' },
|
|
18
|
+
aspect: { type: 'string', short: 'a' },
|
|
19
|
+
resolution: { type: 'string', short: 'r' },
|
|
20
|
+
count: { type: 'string', short: 'n' },
|
|
21
|
+
style: { type: 'string' },
|
|
22
|
+
enhance: { type: 'boolean', default: false },
|
|
23
|
+
ref: { type: 'string', multiple: true, default: [] },
|
|
24
|
+
duration: { type: 'string', short: 'd' },
|
|
25
|
+
'frame-mode': { type: 'string' },
|
|
26
|
+
audio: { type: 'boolean', default: false },
|
|
27
|
+
'quoted-credits': { type: 'string' },
|
|
28
|
+
out: { type: 'string', short: 'o', default: '.' },
|
|
29
|
+
'no-download': { type: 'boolean', default: false },
|
|
30
|
+
force: { type: 'boolean', default: false },
|
|
31
|
+
wait: { type: 'boolean', default: false },
|
|
32
|
+
'no-wait': { type: 'boolean', default: false },
|
|
33
|
+
timeout: { type: 'string', default: '15' },
|
|
34
|
+
limit: { type: 'string', default: '20' },
|
|
35
|
+
before: { type: 'string' },
|
|
36
|
+
kind: { type: 'string' },
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw usageError(error.message);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function intOption(value, name, min, max) {
|
|
45
|
+
if (value === undefined)
|
|
46
|
+
return undefined;
|
|
47
|
+
const n = Number(value);
|
|
48
|
+
if (!Number.isInteger(n) || n < min || n > max) {
|
|
49
|
+
throw usageError(`--${name} must be a whole number from ${min} to ${max}.`);
|
|
50
|
+
}
|
|
51
|
+
return n;
|
|
52
|
+
}
|
|
53
|
+
/** The generation request a `makemidas image|video` command line asks for. */
|
|
54
|
+
export function generationInput(kind, prompt, v) {
|
|
55
|
+
if (!prompt?.trim()) {
|
|
56
|
+
throw usageError(`Give a prompt: \`makemidas ${kind} "a fox in the snow"\`.`);
|
|
57
|
+
}
|
|
58
|
+
if (kind === 'image' && (v.duration || v.audio || v['frame-mode'])) {
|
|
59
|
+
throw usageError('--duration, --audio and --frame-mode are for videos.');
|
|
60
|
+
}
|
|
61
|
+
const input = {
|
|
62
|
+
kind,
|
|
63
|
+
prompt: prompt.trim(),
|
|
64
|
+
...(v.model ? { model: v.model } : {}),
|
|
65
|
+
...(v.aspect ? { aspectRatio: v.aspect } : {}),
|
|
66
|
+
...(v.resolution ? { resolution: v.resolution } : {}),
|
|
67
|
+
...(v.style ? { style: v.style } : {}),
|
|
68
|
+
...(v.enhance ? { enhance: true } : {}),
|
|
69
|
+
};
|
|
70
|
+
const count = intOption(v.count, 'count', 1, 4);
|
|
71
|
+
if (count)
|
|
72
|
+
input.count = count;
|
|
73
|
+
const quoted = intOption(v['quoted-credits'], 'quoted-credits', 0, 1_000_000);
|
|
74
|
+
if (quoted !== undefined)
|
|
75
|
+
input.quotedCredits = quoted;
|
|
76
|
+
if (kind === 'video') {
|
|
77
|
+
const duration = intOption(v.duration, 'duration', 1, 30);
|
|
78
|
+
if (duration)
|
|
79
|
+
input.duration = duration;
|
|
80
|
+
if (v.audio)
|
|
81
|
+
input.audio = true;
|
|
82
|
+
if (v['frame-mode']) {
|
|
83
|
+
if (!['none', 'first', 'first_last', 'reference'].includes(v['frame-mode'])) {
|
|
84
|
+
throw usageError('--frame-mode must be none, first, first_last or reference.');
|
|
85
|
+
}
|
|
86
|
+
input.frameMode = v['frame-mode'];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return input;
|
|
90
|
+
}
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { USER_AGENT, loadProfile, saveProfile } from "./config.js";
|
|
5
|
+
import { CliError, EXIT } from "./errors.js";
|
|
6
|
+
import { log } from "./output.js";
|
|
7
|
+
/**
|
|
8
|
+
* OAuth 2.1 sign-in against MakeMidas's authorization server: dynamic client
|
|
9
|
+
* registration, PKCE (S256) and a loopback redirect. The redirect URI must
|
|
10
|
+
* match exactly, so every login registers a client for its own port. The
|
|
11
|
+
* user approves "MakeMidas CLI" in the browser. Tokens are bound to the MCP
|
|
12
|
+
* resource, which /api/v1 accepts too.
|
|
13
|
+
*/
|
|
14
|
+
/** The server only lets this name through on a loopback redirect. */
|
|
15
|
+
export const CLIENT_NAME = 'MakeMidas CLI';
|
|
16
|
+
const SCOPE = 'openid profile email offline_access';
|
|
17
|
+
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
18
|
+
/** Refresh this long before the access token expires. */
|
|
19
|
+
const REFRESH_MARGIN_MS = 60 * 1000;
|
|
20
|
+
const base64url = (buf) => buf.toString('base64url');
|
|
21
|
+
async function fetchJson(url, init = {}) {
|
|
22
|
+
let res;
|
|
23
|
+
try {
|
|
24
|
+
res = await fetch(url, {
|
|
25
|
+
...init,
|
|
26
|
+
headers: { 'User-Agent': USER_AGENT, ...init.headers },
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw new CliError(`Can't reach ${new URL(url).origin}: ${error.message}`, EXIT.NETWORK, 'NETWORK');
|
|
31
|
+
}
|
|
32
|
+
const text = await res.text();
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
let detail = text.slice(0, 300);
|
|
35
|
+
try {
|
|
36
|
+
const body = JSON.parse(text);
|
|
37
|
+
detail = body.error_description || body.error || detail;
|
|
38
|
+
}
|
|
39
|
+
catch { }
|
|
40
|
+
throw new CliError(`${new URL(url).pathname} failed (${res.status}): ${detail}`, res.status >= 500 ? EXIT.NETWORK : EXIT.AUTH, 'AUTH_FAILED');
|
|
41
|
+
}
|
|
42
|
+
return JSON.parse(text);
|
|
43
|
+
}
|
|
44
|
+
const metadata = (baseUrl) => fetchJson(`${baseUrl}/.well-known/oauth-authorization-server`);
|
|
45
|
+
/** The protected resource tokens are issued for. */
|
|
46
|
+
export const resourceFor = (baseUrl) => `${baseUrl}/api/mcp`;
|
|
47
|
+
function tokenRequest(endpoint, params) {
|
|
48
|
+
return fetchJson(endpoint, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
51
|
+
body: new URLSearchParams(params).toString(),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function openBrowser(url) {
|
|
55
|
+
const [cmd, args] = process.platform === 'darwin'
|
|
56
|
+
? ['open', [url]]
|
|
57
|
+
: process.platform === 'win32'
|
|
58
|
+
? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
|
|
59
|
+
: ['xdg-open', [url]];
|
|
60
|
+
try {
|
|
61
|
+
const child = spawn(cmd, args, {
|
|
62
|
+
stdio: 'ignore',
|
|
63
|
+
detached: true,
|
|
64
|
+
});
|
|
65
|
+
child.on('error', () => { });
|
|
66
|
+
child.unref();
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// the URL is printed too
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const PAGE = (title, body) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1 style="font-size:1.4rem">${title}</h1><p>${body}</p></body>`;
|
|
73
|
+
/** Wait for the browser to come back to http://127.0.0.1:<port>/callback. */
|
|
74
|
+
function startCallbackServer() {
|
|
75
|
+
let resolveCode;
|
|
76
|
+
let rejectCode;
|
|
77
|
+
const result = new Promise((res, rej) => {
|
|
78
|
+
resolveCode = res;
|
|
79
|
+
rejectCode = rej;
|
|
80
|
+
});
|
|
81
|
+
const server = createServer((req, res) => {
|
|
82
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
83
|
+
if (url.pathname !== '/callback') {
|
|
84
|
+
res.writeHead(404).end();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const error = url.searchParams.get('error');
|
|
88
|
+
const code = url.searchParams.get('code');
|
|
89
|
+
const state = url.searchParams.get('state') ?? '';
|
|
90
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
91
|
+
if (error || !code) {
|
|
92
|
+
res.end(PAGE('Sign-in cancelled', 'You can close this tab.'));
|
|
93
|
+
rejectCode(new CliError(error === 'access_denied'
|
|
94
|
+
? 'Sign-in was cancelled in the browser.'
|
|
95
|
+
: `Sign-in failed: ${error ?? 'no code returned'}`, EXIT.AUTH, 'AUTH_FAILED'));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
res.end(PAGE('Signed in to MakeMidas', 'You can close this tab and go back to the terminal.'));
|
|
99
|
+
resolveCode({ code, state });
|
|
100
|
+
});
|
|
101
|
+
const listening = new Promise((res, rej) => {
|
|
102
|
+
server.once('error', rej);
|
|
103
|
+
server.listen(0, '127.0.0.1', () => res(server.address().port));
|
|
104
|
+
});
|
|
105
|
+
return { server, listening, result };
|
|
106
|
+
}
|
|
107
|
+
export async function login(baseUrl, opts) {
|
|
108
|
+
const meta = await metadata(baseUrl);
|
|
109
|
+
const { server, listening, result } = startCallbackServer();
|
|
110
|
+
const port = await listening;
|
|
111
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
112
|
+
try {
|
|
113
|
+
const client = await fetchJson(meta.registration_endpoint, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: { 'Content-Type': 'application/json' },
|
|
116
|
+
body: JSON.stringify({
|
|
117
|
+
client_name: CLIENT_NAME,
|
|
118
|
+
redirect_uris: [redirectUri],
|
|
119
|
+
token_endpoint_auth_method: 'none',
|
|
120
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
121
|
+
response_types: ['code'],
|
|
122
|
+
}),
|
|
123
|
+
});
|
|
124
|
+
const verifier = base64url(randomBytes(32));
|
|
125
|
+
const challenge = base64url(createHash('sha256').update(verifier).digest());
|
|
126
|
+
const state = base64url(randomBytes(16));
|
|
127
|
+
const authorize = new URL(meta.authorization_endpoint);
|
|
128
|
+
authorize.search = new URLSearchParams({
|
|
129
|
+
response_type: 'code',
|
|
130
|
+
client_id: client.client_id,
|
|
131
|
+
redirect_uri: redirectUri,
|
|
132
|
+
code_challenge: challenge,
|
|
133
|
+
code_challenge_method: 'S256',
|
|
134
|
+
scope: SCOPE,
|
|
135
|
+
state,
|
|
136
|
+
resource: resourceFor(baseUrl),
|
|
137
|
+
}).toString();
|
|
138
|
+
log(`Open this link to sign in and approve "${CLIENT_NAME}":\n ${authorize}`);
|
|
139
|
+
if (opts.browser)
|
|
140
|
+
openBrowser(authorize.toString());
|
|
141
|
+
log('Waiting for the browser…');
|
|
142
|
+
let timer;
|
|
143
|
+
const timeout = new Promise((_, rej) => {
|
|
144
|
+
timer = setTimeout(() => rej(new CliError('Timed out waiting for sign-in (5 minutes).', EXIT.AUTH, 'AUTH_TIMEOUT')), LOGIN_TIMEOUT_MS);
|
|
145
|
+
});
|
|
146
|
+
const callback = await Promise.race([result, timeout]).finally(() => clearTimeout(timer));
|
|
147
|
+
if (callback.state !== state) {
|
|
148
|
+
throw new CliError('Sign-in response did not match this login (state mismatch).', EXIT.AUTH, 'AUTH_FAILED');
|
|
149
|
+
}
|
|
150
|
+
const token = await tokenRequest(meta.token_endpoint, {
|
|
151
|
+
grant_type: 'authorization_code',
|
|
152
|
+
code: callback.code,
|
|
153
|
+
redirect_uri: redirectUri,
|
|
154
|
+
client_id: client.client_id,
|
|
155
|
+
code_verifier: verifier,
|
|
156
|
+
resource: resourceFor(baseUrl),
|
|
157
|
+
});
|
|
158
|
+
const profile = {
|
|
159
|
+
clientId: client.client_id,
|
|
160
|
+
accessToken: token.access_token,
|
|
161
|
+
refreshToken: token.refresh_token ?? null,
|
|
162
|
+
expiresAt: Date.now() + (token.expires_in ?? 3600) * 1000,
|
|
163
|
+
email: null,
|
|
164
|
+
};
|
|
165
|
+
await saveProfile(baseUrl, profile);
|
|
166
|
+
return profile;
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
server.close();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** Exchange the refresh token for a new pair; null when it no longer works. */
|
|
173
|
+
export async function refresh(baseUrl, profile) {
|
|
174
|
+
if (!profile.refreshToken)
|
|
175
|
+
return null;
|
|
176
|
+
const meta = await metadata(baseUrl);
|
|
177
|
+
let token;
|
|
178
|
+
try {
|
|
179
|
+
token = await tokenRequest(meta.token_endpoint, {
|
|
180
|
+
grant_type: 'refresh_token',
|
|
181
|
+
refresh_token: profile.refreshToken,
|
|
182
|
+
client_id: profile.clientId,
|
|
183
|
+
resource: resourceFor(baseUrl),
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
if (error instanceof CliError && error.exitCode === EXIT.AUTH)
|
|
188
|
+
return null;
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
const next = {
|
|
192
|
+
...profile,
|
|
193
|
+
accessToken: token.access_token,
|
|
194
|
+
refreshToken: token.refresh_token ?? profile.refreshToken,
|
|
195
|
+
expiresAt: Date.now() + (token.expires_in ?? 3600) * 1000,
|
|
196
|
+
};
|
|
197
|
+
await saveProfile(baseUrl, next);
|
|
198
|
+
return next;
|
|
199
|
+
}
|
|
200
|
+
/** Credentials from the environment, which win over a stored sign-in. */
|
|
201
|
+
export function envCredential() {
|
|
202
|
+
return process.env.MAKEMIDAS_API_KEY || process.env.MAKEMIDAS_TOKEN || null;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* A usable bearer credential: MAKEMIDAS_API_KEY, MAKEMIDAS_TOKEN, or the
|
|
206
|
+
* stored access token (refreshed when it is about to expire).
|
|
207
|
+
*/
|
|
208
|
+
export async function accessToken(baseUrl, forceRefresh = false) {
|
|
209
|
+
const fromEnv = envCredential();
|
|
210
|
+
if (fromEnv)
|
|
211
|
+
return fromEnv;
|
|
212
|
+
const profile = await loadProfile(baseUrl);
|
|
213
|
+
if (!profile) {
|
|
214
|
+
throw new CliError('Not signed in. Run `makemidas auth login`, or set MAKEMIDAS_API_KEY.', EXIT.AUTH, 'UNAUTHORIZED');
|
|
215
|
+
}
|
|
216
|
+
if (!forceRefresh && profile.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
|
|
217
|
+
return profile.accessToken;
|
|
218
|
+
}
|
|
219
|
+
const next = await refresh(baseUrl, profile);
|
|
220
|
+
if (!next) {
|
|
221
|
+
// The server retires a refresh token once it is spent. Another process
|
|
222
|
+
// (a parallel `makemidas` run) may have spent ours and saved the new
|
|
223
|
+
// pair: use that instead of signing out.
|
|
224
|
+
const latest = await loadProfile(baseUrl);
|
|
225
|
+
if (latest &&
|
|
226
|
+
latest.refreshToken !== profile.refreshToken &&
|
|
227
|
+
latest.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
|
|
228
|
+
return latest.accessToken;
|
|
229
|
+
}
|
|
230
|
+
throw new CliError('Your sign-in has expired. Run `makemidas auth login`.', EXIT.AUTH, 'UNAUTHORIZED');
|
|
231
|
+
}
|
|
232
|
+
return next.accessToken;
|
|
233
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Api } from "./api.js";
|
|
3
|
+
import { generationInput, intOption, parse, usageError } from "./args.js";
|
|
4
|
+
import * as commands from "./commands.js";
|
|
5
|
+
import { resolveBaseUrl, VERSION } from "./config.js";
|
|
6
|
+
import { CliError, EXIT } from "./errors.js";
|
|
7
|
+
import { setQuiet } from "./output.js";
|
|
8
|
+
const HELP = `makemidas ${VERSION}: AI images and videos from the terminal, with your MakeMidas credits
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
makemidas auth login [--no-browser] Sign in (opens the browser)
|
|
12
|
+
makemidas auth logout Sign out and revoke the token
|
|
13
|
+
makemidas auth status Show the signed-in account
|
|
14
|
+
makemidas image "<prompt>" Generate images and save them
|
|
15
|
+
makemidas video "<prompt>" Generate a video and save it
|
|
16
|
+
makemidas get <id> Fetch a generation (and save its files)
|
|
17
|
+
makemidas list Recent generations
|
|
18
|
+
makemidas credits Credit balance and plan
|
|
19
|
+
makemidas models [--kind image|video] Models, options and credit prices
|
|
20
|
+
|
|
21
|
+
Generation options (image, video):
|
|
22
|
+
-m, --model <id> Model id from \`makemidas models\` (default: cheapest)
|
|
23
|
+
-a, --aspect <ratio> e.g. 1:1, 16:9, 9:16
|
|
24
|
+
-r, --resolution <r> image: 1K | 2K | 4K; video: 480p | 720p | 1080p
|
|
25
|
+
-n, --count <n> Outputs, 1-4 (default 1)
|
|
26
|
+
--ref <file|url> Reference image; repeat for more. For videos: one is
|
|
27
|
+
the first frame, two are first and last frame
|
|
28
|
+
--style <id> photo, cinematic, film, anime, …
|
|
29
|
+
--enhance Let MakeMidas expand a short prompt
|
|
30
|
+
--quoted-credits <n> Refuse to charge anything else
|
|
31
|
+
-d, --duration <s> video: seconds
|
|
32
|
+
--audio video: with sound (models that support it)
|
|
33
|
+
--frame-mode <mode> video: none | first | first_last | reference
|
|
34
|
+
--no-wait video: print the id and exit; fetch later with get
|
|
35
|
+
|
|
36
|
+
Output options (image, video, get):
|
|
37
|
+
-o, --out <dir> Where to save files (default .)
|
|
38
|
+
--no-download Print signed links (valid 1 hour) instead
|
|
39
|
+
--force Overwrite existing files
|
|
40
|
+
--wait get: wait until a video is done
|
|
41
|
+
--timeout <min> How long to wait for a video (default 15)
|
|
42
|
+
|
|
43
|
+
List options:
|
|
44
|
+
--limit <n> How many (default 20, max 50)
|
|
45
|
+
--before <ISO time> Older than this
|
|
46
|
+
|
|
47
|
+
Global:
|
|
48
|
+
--json Machine-readable output on stdout
|
|
49
|
+
--quiet No progress on stderr
|
|
50
|
+
--base-url <url> Server (default https://makemidas.com, or MAKEMIDAS_BASE_URL)
|
|
51
|
+
-v, --version Print the version
|
|
52
|
+
-h, --help This help
|
|
53
|
+
|
|
54
|
+
Credentials: \`auth login\`, or MAKEMIDAS_API_KEY (Settings → API keys).
|
|
55
|
+
|
|
56
|
+
Exit codes: 0 ok, 2 bad input, 3 not signed in, 4 not enough credits or plan
|
|
57
|
+
limit, 5 generation failed, 6 network or server error, 7 not ready yet.
|
|
58
|
+
`;
|
|
59
|
+
async function main(argv) {
|
|
60
|
+
const { values: v, positionals } = parse(argv);
|
|
61
|
+
setQuiet(v.quiet);
|
|
62
|
+
if (v.version) {
|
|
63
|
+
process.stdout.write(`${VERSION}\n`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const [command, ...rest] = positionals;
|
|
67
|
+
if (v.help || !command || command === 'help') {
|
|
68
|
+
process.stdout.write(HELP);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const api = new Api(resolveBaseUrl(v['base-url']));
|
|
72
|
+
const g = { json: v.json };
|
|
73
|
+
const save = { out: v['no-download'] ? null : v.out, force: v.force };
|
|
74
|
+
const timeoutMin = intOption(v.timeout, 'timeout', 1, 120) ?? 15;
|
|
75
|
+
switch (command) {
|
|
76
|
+
case 'auth': {
|
|
77
|
+
const [sub] = rest;
|
|
78
|
+
if (sub === 'login') {
|
|
79
|
+
return commands.authLogin(api, g, { browser: !v['no-browser'] });
|
|
80
|
+
}
|
|
81
|
+
if (sub === 'logout')
|
|
82
|
+
return commands.authLogout(api, g);
|
|
83
|
+
if (sub === 'status')
|
|
84
|
+
return commands.authStatus(api, g);
|
|
85
|
+
throw usageError('Use `auth login`, `auth logout` or `auth status`.');
|
|
86
|
+
}
|
|
87
|
+
case 'image':
|
|
88
|
+
case 'video':
|
|
89
|
+
return commands.generate(api, g, generationInput(command, rest.join(' '), v), v.ref, save, { wait: !v['no-wait'], timeoutMin });
|
|
90
|
+
case 'get':
|
|
91
|
+
return commands.get(api, g, rest[0], save, { wait: v.wait, timeoutMin });
|
|
92
|
+
case 'list':
|
|
93
|
+
return commands.list(api, g, {
|
|
94
|
+
limit: intOption(v.limit, 'limit', 1, 50) ?? 20,
|
|
95
|
+
before: v.before,
|
|
96
|
+
});
|
|
97
|
+
case 'credits':
|
|
98
|
+
return commands.credits(api, g);
|
|
99
|
+
case 'models': {
|
|
100
|
+
const kind = v.kind;
|
|
101
|
+
if (kind && kind !== 'image' && kind !== 'video') {
|
|
102
|
+
throw usageError('--kind must be image or video.');
|
|
103
|
+
}
|
|
104
|
+
return commands.models(api, g, kind);
|
|
105
|
+
}
|
|
106
|
+
default:
|
|
107
|
+
throw usageError(`Unknown command "${command}".`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
main(process.argv.slice(2)).then(() => process.exit(EXIT.OK), (error) => {
|
|
111
|
+
const cli = error instanceof CliError
|
|
112
|
+
? error
|
|
113
|
+
: new CliError(error?.message ?? String(error), EXIT.NETWORK, 'internal');
|
|
114
|
+
if (process.argv.includes('--json')) {
|
|
115
|
+
process.stderr.write(`${JSON.stringify({ error: { code: cli.code, message: cli.message } })}\n`);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
process.stderr.write(`Error: ${cli.message}\n`);
|
|
119
|
+
}
|
|
120
|
+
process.exit(cli.exitCode);
|
|
121
|
+
});
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { envCredential, login } from "./auth.js";
|
|
5
|
+
import { deleteProfile, loadProfile, saveProfile } from "./config.js";
|
|
6
|
+
import { CliError, EXIT } from "./errors.js";
|
|
7
|
+
import { formatBytes, log, print, printJson, warn } from "./output.js";
|
|
8
|
+
const EXTENSIONS = {
|
|
9
|
+
'image/jpeg': 'jpg',
|
|
10
|
+
'image/png': 'png',
|
|
11
|
+
'image/webp': 'webp',
|
|
12
|
+
'video/mp4': 'mp4',
|
|
13
|
+
};
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// auth
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
export async function authLogin(api, g, opts) {
|
|
18
|
+
const profile = await login(api.baseUrl, opts);
|
|
19
|
+
const me = await api.me();
|
|
20
|
+
await saveProfile(api.baseUrl, { ...profile, email: me.email });
|
|
21
|
+
if (g.json)
|
|
22
|
+
printJson({ signedIn: true, ...me, baseUrl: api.baseUrl });
|
|
23
|
+
else
|
|
24
|
+
print(`Signed in as ${me.email} (plan: ${me.plan ?? 'free'}).`);
|
|
25
|
+
}
|
|
26
|
+
export async function authStatus(api, g) {
|
|
27
|
+
const profile = await loadProfile(api.baseUrl);
|
|
28
|
+
if (!profile && !envCredential()) {
|
|
29
|
+
if (g.json)
|
|
30
|
+
printJson({ signedIn: false, baseUrl: api.baseUrl });
|
|
31
|
+
throw new CliError('Not signed in. Run `makemidas auth login`, or set MAKEMIDAS_API_KEY.', EXIT.AUTH, 'unauthorized');
|
|
32
|
+
}
|
|
33
|
+
const me = await api.me();
|
|
34
|
+
if (g.json)
|
|
35
|
+
printJson({ signedIn: true, ...me, baseUrl: api.baseUrl });
|
|
36
|
+
else {
|
|
37
|
+
print(`Signed in as ${me.email} (plan: ${me.plan ?? 'free'}, via ${me.via}) on ${api.baseUrl}.`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export async function authLogout(api, g) {
|
|
41
|
+
const profile = await loadProfile(api.baseUrl);
|
|
42
|
+
if (profile && !envCredential()) {
|
|
43
|
+
try {
|
|
44
|
+
await api.request('/auth/revoke', { method: 'POST' });
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
log(`Could not revoke the token on the server: ${error.message}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const removed = await deleteProfile(api.baseUrl);
|
|
51
|
+
if (g.json)
|
|
52
|
+
printJson({ signedOut: removed });
|
|
53
|
+
else
|
|
54
|
+
print(removed ? 'Signed out.' : 'Not signed in.');
|
|
55
|
+
}
|
|
56
|
+
/** Save every finished output into `dir`; returns the file paths. */
|
|
57
|
+
async function saveOutputs(api, generation, save) {
|
|
58
|
+
if (!save.out)
|
|
59
|
+
return [];
|
|
60
|
+
const dir = resolve(save.out);
|
|
61
|
+
await mkdir(dir, { recursive: true });
|
|
62
|
+
const files = [];
|
|
63
|
+
for (const [index, output] of generation.outputs.entries()) {
|
|
64
|
+
if (output.status !== 'done' || !output.url)
|
|
65
|
+
continue;
|
|
66
|
+
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);
|
|
76
|
+
}
|
|
77
|
+
return files;
|
|
78
|
+
}
|
|
79
|
+
/** Keep asking for a running generation until it finishes or time runs out. */
|
|
80
|
+
async function waitFor(api, generation, timeoutMin) {
|
|
81
|
+
const deadline = Date.now() + timeoutMin * 60_000;
|
|
82
|
+
let current = generation;
|
|
83
|
+
while (current.status === 'running' && Date.now() < deadline) {
|
|
84
|
+
log(`Rendering ${current.kind}… (${current.id})`);
|
|
85
|
+
current = await api.generation(current.id, 40);
|
|
86
|
+
}
|
|
87
|
+
return current;
|
|
88
|
+
}
|
|
89
|
+
function report(g, generation, files) {
|
|
90
|
+
if (g.json) {
|
|
91
|
+
printJson({ ...generation, files });
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
if (files.length)
|
|
95
|
+
for (const file of files)
|
|
96
|
+
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)' : ''}.`);
|
|
103
|
+
}
|
|
104
|
+
if (generation.status === 'failed') {
|
|
105
|
+
throw new CliError(generation.error ?? 'The model could not make this; credits were refunded.', EXIT.FAILED, 'generation_failed');
|
|
106
|
+
}
|
|
107
|
+
if (generation.status === 'running') {
|
|
108
|
+
throw new CliError(`Still rendering. Run \`makemidas get ${generation.id} --wait\` later.`, EXIT.NOT_READY, 'not_ready');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export async function generate(api, g, input, refs, save, wait) {
|
|
112
|
+
const referenceIds = [];
|
|
113
|
+
for (const ref of refs) {
|
|
114
|
+
log(`Uploading ${ref}…`);
|
|
115
|
+
referenceIds.push(await api.upload(ref));
|
|
116
|
+
}
|
|
117
|
+
log(`Generating ${input.kind}…`);
|
|
118
|
+
let generation = await api.generate({ ...input, referenceIds });
|
|
119
|
+
if (generation.status === 'running' && wait.wait) {
|
|
120
|
+
generation = await waitFor(api, generation, wait.timeoutMin);
|
|
121
|
+
}
|
|
122
|
+
const files = await saveOutputs(api, generation, save);
|
|
123
|
+
report(g, generation, files);
|
|
124
|
+
}
|
|
125
|
+
export async function get(api, g, id, save, wait) {
|
|
126
|
+
if (!id) {
|
|
127
|
+
throw new CliError('Give a generation id: `makemidas get <id>`.', EXIT.USAGE, 'usage');
|
|
128
|
+
}
|
|
129
|
+
let generation = await api.generation(id);
|
|
130
|
+
if (generation.status === 'running' && wait.wait) {
|
|
131
|
+
generation = await waitFor(api, generation, wait.timeoutMin);
|
|
132
|
+
}
|
|
133
|
+
const files = await saveOutputs(api, generation, save);
|
|
134
|
+
report(g, generation, files);
|
|
135
|
+
}
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// list / credits / models
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
export async function list(api, g, query) {
|
|
140
|
+
const generations = await api.list(query);
|
|
141
|
+
if (g.json) {
|
|
142
|
+
printJson({ generations });
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (!generations.length) {
|
|
146
|
+
print('No generations yet.');
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
for (const item of generations) {
|
|
150
|
+
print(`${item.id} ${item.createdAt.slice(0, 16).replace('T', ' ')} ${item.kind.padEnd(5)} ${item.status.padEnd(7)} ${item.model} ${item.prompt.replace(/\s+/g, ' ').slice(0, 60)}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export async function credits(api, g) {
|
|
154
|
+
const result = await api.credits();
|
|
155
|
+
if (g.json) {
|
|
156
|
+
printJson(result);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
print(`${result.balance} credits (plan: ${result.plan ?? 'free'}).`);
|
|
160
|
+
if (result.watermarked) {
|
|
161
|
+
print('Free plan: 10 credits a day, free models only, watermarked images.');
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
print(`Up to ${result.concurrency} at once, ${result.maxOutputs} outputs each.`);
|
|
165
|
+
}
|
|
166
|
+
for (const item of result.expiring.slice(0, 3)) {
|
|
167
|
+
print(` ${item.amount} expire ${item.expiresAt.slice(0, 10)}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export async function models(api, g, kind) {
|
|
171
|
+
const result = await api.models(kind);
|
|
172
|
+
if (g.json) {
|
|
173
|
+
printJson({ models: result });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
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}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export const VERSION = '0.1.1';
|
|
5
|
+
export const USER_AGENT = `makemidas-cli/${VERSION}`;
|
|
6
|
+
export const DEFAULT_BASE_URL = 'https://makemidas.com';
|
|
7
|
+
export function resolveBaseUrl(flag) {
|
|
8
|
+
const raw = flag || process.env.MAKEMIDAS_BASE_URL || DEFAULT_BASE_URL;
|
|
9
|
+
return raw.replace(/\/+$/, '');
|
|
10
|
+
}
|
|
11
|
+
/** Where credentials live: $XDG_CONFIG_HOME/makemidas, %APPDATA% on Windows. */
|
|
12
|
+
export function configDir() {
|
|
13
|
+
if (process.env.MAKEMIDAS_CONFIG_DIR)
|
|
14
|
+
return process.env.MAKEMIDAS_CONFIG_DIR;
|
|
15
|
+
if (process.platform === 'win32' && process.env.APPDATA) {
|
|
16
|
+
return join(process.env.APPDATA, 'makemidas');
|
|
17
|
+
}
|
|
18
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
19
|
+
return join(base, 'makemidas');
|
|
20
|
+
}
|
|
21
|
+
const credentialsPath = () => join(configDir(), 'credentials.json');
|
|
22
|
+
async function readAll() {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = JSON.parse(await readFile(credentialsPath(), 'utf8'));
|
|
25
|
+
if (parsed?.version === 1 && parsed.profiles)
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// missing or unreadable: treat as signed out
|
|
30
|
+
}
|
|
31
|
+
return { version: 1, profiles: {} };
|
|
32
|
+
}
|
|
33
|
+
async function writeAll(data) {
|
|
34
|
+
const dir = configDir();
|
|
35
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
const file = credentialsPath();
|
|
37
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
38
|
+
await writeFile(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
|
39
|
+
await rename(tmp, file);
|
|
40
|
+
}
|
|
41
|
+
export async function loadProfile(baseUrl) {
|
|
42
|
+
return (await readAll()).profiles[baseUrl] ?? null;
|
|
43
|
+
}
|
|
44
|
+
export async function saveProfile(baseUrl, profile) {
|
|
45
|
+
const data = await readAll();
|
|
46
|
+
data.profiles[baseUrl] = profile;
|
|
47
|
+
await writeAll(data);
|
|
48
|
+
}
|
|
49
|
+
export async function deleteProfile(baseUrl) {
|
|
50
|
+
const data = await readAll();
|
|
51
|
+
if (!data.profiles[baseUrl])
|
|
52
|
+
return false;
|
|
53
|
+
delete data.profiles[baseUrl];
|
|
54
|
+
await writeAll(data);
|
|
55
|
+
return true;
|
|
56
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Exit codes, documented in the README and the agent skill. */
|
|
2
|
+
export const EXIT = {
|
|
3
|
+
OK: 0,
|
|
4
|
+
USAGE: 2,
|
|
5
|
+
AUTH: 3,
|
|
6
|
+
CREDITS: 4,
|
|
7
|
+
FAILED: 5,
|
|
8
|
+
NETWORK: 6,
|
|
9
|
+
NOT_READY: 7,
|
|
10
|
+
};
|
|
11
|
+
export class CliError extends Error {
|
|
12
|
+
exitCode;
|
|
13
|
+
code;
|
|
14
|
+
constructor(message, exitCode, code = 'ERROR') {
|
|
15
|
+
super(message);
|
|
16
|
+
this.exitCode = exitCode;
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const EXIT_BY_CODE = {
|
|
21
|
+
unauthorized: EXIT.AUTH,
|
|
22
|
+
email_not_verified: EXIT.AUTH,
|
|
23
|
+
insufficient_credits: EXIT.CREDITS,
|
|
24
|
+
upgrade_required: EXIT.CREDITS,
|
|
25
|
+
busy: EXIT.CREDITS,
|
|
26
|
+
generation_failed: EXIT.FAILED,
|
|
27
|
+
unavailable: EXIT.NETWORK,
|
|
28
|
+
internal: EXIT.NETWORK,
|
|
29
|
+
};
|
|
30
|
+
/** Exit code for an API error code; other 4xx codes are input problems. */
|
|
31
|
+
export function exitCodeFor(code, status) {
|
|
32
|
+
return EXIT_BY_CODE[code] ?? (status >= 500 ? EXIT.NETWORK : EXIT.USAGE);
|
|
33
|
+
}
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** stdout carries results only; everything else goes to stderr. */
|
|
2
|
+
let quiet = false;
|
|
3
|
+
export function setQuiet(value) {
|
|
4
|
+
quiet = value;
|
|
5
|
+
}
|
|
6
|
+
export function log(message) {
|
|
7
|
+
if (!quiet)
|
|
8
|
+
process.stderr.write(`${message}\n`);
|
|
9
|
+
}
|
|
10
|
+
/** Shown even with --quiet: the user must know about it. */
|
|
11
|
+
export function warn(message) {
|
|
12
|
+
process.stderr.write(`Warning: ${message}\n`);
|
|
13
|
+
}
|
|
14
|
+
export function printJson(value) {
|
|
15
|
+
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
16
|
+
}
|
|
17
|
+
export function print(line) {
|
|
18
|
+
process.stdout.write(`${line}\n`);
|
|
19
|
+
}
|
|
20
|
+
export const isTty = () => Boolean(process.stderr.isTTY) && !quiet;
|
|
21
|
+
/** A one-line progress indicator on a TTY; silent otherwise. */
|
|
22
|
+
export function progress(label) {
|
|
23
|
+
let last = 0;
|
|
24
|
+
return {
|
|
25
|
+
update(fraction) {
|
|
26
|
+
if (!isTty())
|
|
27
|
+
return;
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
if (now - last < 100 && fraction < 1)
|
|
30
|
+
return;
|
|
31
|
+
last = now;
|
|
32
|
+
const pct = Math.min(100, Math.round(fraction * 100));
|
|
33
|
+
process.stderr.write(`\r${label} ${String(pct).padStart(3)}%`);
|
|
34
|
+
},
|
|
35
|
+
done() {
|
|
36
|
+
if (isTty())
|
|
37
|
+
process.stderr.write('\n');
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function formatBytes(n) {
|
|
42
|
+
if (n < 1024)
|
|
43
|
+
return `${n} B`;
|
|
44
|
+
const units = ['KB', 'MB', 'GB'];
|
|
45
|
+
let v = n / 1024;
|
|
46
|
+
let i = 0;
|
|
47
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
48
|
+
v /= 1024;
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
|
|
52
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@makemidas/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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
|
+
"keywords": [
|
|
6
|
+
"ai-image-generator",
|
|
7
|
+
"ai-video-generator",
|
|
8
|
+
"text-to-image",
|
|
9
|
+
"text-to-video",
|
|
10
|
+
"image-to-video",
|
|
11
|
+
"cli",
|
|
12
|
+
"ai-agent",
|
|
13
|
+
"agent-skill",
|
|
14
|
+
"claude-code",
|
|
15
|
+
"cursor",
|
|
16
|
+
"codex",
|
|
17
|
+
"mcp",
|
|
18
|
+
"image-generation",
|
|
19
|
+
"video-generation",
|
|
20
|
+
"nano-banana",
|
|
21
|
+
"veo",
|
|
22
|
+
"kling",
|
|
23
|
+
"gemini-cli",
|
|
24
|
+
"openclaw"
|
|
25
|
+
],
|
|
26
|
+
"homepage": "https://makemidas.com/developers",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/makemidas-ai/cli.git"
|
|
30
|
+
},
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/makemidas-ai/cli/issues"
|
|
33
|
+
},
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"type": "module",
|
|
36
|
+
"bin": {
|
|
37
|
+
"makemidas": "dist/cli.js"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist"
|
|
41
|
+
],
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -p tsconfig.json && chmod +x dist/cli.js",
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
48
|
+
"test": "node --test test/*.test.ts",
|
|
49
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^20.19.0",
|
|
53
|
+
"typescript": "^5.9.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"registry": "https://registry.npmjs.org/",
|
|
57
|
+
"access": "public"
|
|
58
|
+
}
|
|
59
|
+
}
|