@vidlab/cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +51 -2
- package/bin/vidlab.mjs +12 -0
- package/lib/args.mjs +56 -0
- package/lib/client.mjs +96 -0
- package/lib/commands.mjs +324 -0
- package/lib/credentials.mjs +136 -0
- package/lib/main.mjs +408 -0
- package/lib/setup.mjs +175 -0
- package/lib/version.mjs +1 -0
- package/package.json +34 -4
- package/skill/SKILL.md +235 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Where `vidlab login` keeps the API key, and how every command finds it again.
|
|
2
|
+
//
|
|
3
|
+
// Order when a command needs the key: VIDLAB_API_KEY, then the OS keychain (macOS Keychain through `security`, Linux
|
|
4
|
+
// Secret Service through `secret-tool`), then a 0600 file in a 0700 folder under ~/.config/vidlab (or
|
|
5
|
+
// $XDG_CONFIG_HOME/vidlab). The key never goes on a command line: `security -i` and `secret-tool store` read it from
|
|
6
|
+
// stdin. VIDLAB_NO_KEYCHAIN=1 skips the keychain (CI, tests).
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from "node:child_process";
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir, platform } from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
export const SERVICE = "vidlab-cli";
|
|
14
|
+
export const DEFAULT_BASE_URL = "https://vidlab.ai";
|
|
15
|
+
export const KEY_PATTERN = /^vidlab_sk_[A-Za-z0-9_-]{10,200}$/;
|
|
16
|
+
|
|
17
|
+
export function configDir(env = process.env) {
|
|
18
|
+
const base = env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(homedir(), ".config");
|
|
19
|
+
return path.join(base, "vidlab");
|
|
20
|
+
}
|
|
21
|
+
const configFile = (env) => path.join(configDir(env), "config.json");
|
|
22
|
+
const keyFile = (env) => path.join(configDir(env), "credentials.json");
|
|
23
|
+
|
|
24
|
+
function readJson(file) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Writes a private file atomically: 0600 inside a 0700 folder. */
|
|
33
|
+
function writePrivate(env, file, value) {
|
|
34
|
+
const dir = configDir(env);
|
|
35
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
try {
|
|
37
|
+
chmodSync(dir, 0o700);
|
|
38
|
+
} catch {}
|
|
39
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
40
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
41
|
+
renameSync(tmp, file);
|
|
42
|
+
try {
|
|
43
|
+
chmodSync(file, 0o600);
|
|
44
|
+
} catch {}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The saved settings (base URL, where the key lives); never the key itself. */
|
|
48
|
+
export const readConfig = (env = process.env) => readJson(configFile(env)) ?? {};
|
|
49
|
+
|
|
50
|
+
const origin = (baseUrl) => new URL(baseUrl).origin;
|
|
51
|
+
|
|
52
|
+
/** Which keychain this machine offers, or null. */
|
|
53
|
+
export function keychainKind(env = process.env, run = spawnSync) {
|
|
54
|
+
if (env.VIDLAB_NO_KEYCHAIN === "1") return null;
|
|
55
|
+
if (platform() === "darwin") return run("security", ["help"], { stdio: "ignore" }).error ? null : "macos";
|
|
56
|
+
if (platform() === "linux") return run("secret-tool", ["--version"], { stdio: "ignore" }).status === 0 ? "secret-service" : null;
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function keychainSet(kind, account, key, run) {
|
|
61
|
+
if (kind === "macos") {
|
|
62
|
+
// Interactive mode reads the command from stdin, so the key is not in any process's arguments.
|
|
63
|
+
const r = run("security", ["-i"], { input: `add-generic-password -U -s ${SERVICE} -a ${account} -l "VidLab API key" -w ${key}\n`, stdio: ["pipe", "ignore", "pipe"] });
|
|
64
|
+
return r.status === 0 && !String(r.stderr ?? "").trim();
|
|
65
|
+
}
|
|
66
|
+
const r = run("secret-tool", ["store", "--label=VidLab API key", "service", SERVICE, "account", account], { input: key, stdio: ["pipe", "ignore", "ignore"] });
|
|
67
|
+
return r.status === 0;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function keychainGet(kind, account, run) {
|
|
71
|
+
const r = kind === "macos" ? run("security", ["find-generic-password", "-s", SERVICE, "-a", account, "-w"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) : run("secret-tool", ["lookup", "service", SERVICE, "account", account], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
72
|
+
const v = r.status === 0 ? String(r.stdout ?? "").trim() : "";
|
|
73
|
+
return v || null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function keychainDelete(kind, account, run) {
|
|
77
|
+
if (kind === "macos") run("security", ["delete-generic-password", "-s", SERVICE, "-a", account], { stdio: "ignore" });
|
|
78
|
+
else run("secret-tool", ["clear", "service", SERVICE, "account", account], { stdio: "ignore" });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Saves the key for this base URL: the keychain when there is one, else the private file. Returns where it went. */
|
|
82
|
+
export function saveKey(key, baseUrl, { env = process.env, run = spawnSync } = {}) {
|
|
83
|
+
const account = origin(baseUrl);
|
|
84
|
+
const kind = keychainKind(env, run);
|
|
85
|
+
let store = "file";
|
|
86
|
+
if (kind && keychainSet(kind, account, key, run)) store = kind;
|
|
87
|
+
else {
|
|
88
|
+
const all = readJson(keyFile(env)) ?? { version: 1, keys: {} };
|
|
89
|
+
all.keys = { ...(all.keys ?? {}), [account]: key };
|
|
90
|
+
writePrivate(env, keyFile(env), all);
|
|
91
|
+
}
|
|
92
|
+
writePrivate(env, configFile(env), { version: 1, base_url: baseUrl, key_store: store });
|
|
93
|
+
return store;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The key for this base URL, and where it came from; null when there is none. */
|
|
97
|
+
export function loadKey(baseUrl, { env = process.env, run = spawnSync } = {}) {
|
|
98
|
+
if (env.VIDLAB_API_KEY?.trim()) return { key: env.VIDLAB_API_KEY.trim(), source: "VIDLAB_API_KEY" };
|
|
99
|
+
const account = origin(baseUrl);
|
|
100
|
+
const cfg = readConfig(env);
|
|
101
|
+
if (cfg.key_store === "macos" || cfg.key_store === "secret-service") {
|
|
102
|
+
const kind = keychainKind(env, run);
|
|
103
|
+
const key = kind ? keychainGet(kind, account, run) : null;
|
|
104
|
+
if (key) return { key, source: kind === "macos" ? "macOS Keychain" : "Secret Service" };
|
|
105
|
+
}
|
|
106
|
+
const file = keyFile(env);
|
|
107
|
+
if (existsSync(file)) {
|
|
108
|
+
const key = readJson(file)?.keys?.[account];
|
|
109
|
+
if (typeof key === "string" && key) return { key, source: file };
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Forgets the key for this base URL everywhere it may be. */
|
|
115
|
+
export function deleteKey(baseUrl, { env = process.env, run = spawnSync } = {}) {
|
|
116
|
+
const account = origin(baseUrl);
|
|
117
|
+
const kind = keychainKind(env, run);
|
|
118
|
+
if (kind) keychainDelete(kind, account, run);
|
|
119
|
+
const file = keyFile(env);
|
|
120
|
+
const all = readJson(file);
|
|
121
|
+
if (all?.keys?.[account]) {
|
|
122
|
+
delete all.keys[account];
|
|
123
|
+
if (Object.keys(all.keys).length) writePrivate(env, file, all);
|
|
124
|
+
else rmSync(file, { force: true });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The base URL: --base-url, then VIDLAB_BASE_URL, then the one saved at login, then https://vidlab.ai. */
|
|
129
|
+
export function baseUrlOf(flag, env = process.env) {
|
|
130
|
+
const raw = flag || env.VIDLAB_BASE_URL || readConfig(env).base_url || DEFAULT_BASE_URL;
|
|
131
|
+
const u = new URL(raw);
|
|
132
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("--base-url must be an http(s) URL.");
|
|
133
|
+
// The key travels in the clear over http: only to this machine.
|
|
134
|
+
if (u.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)) throw new Error("--base-url must be https (http is allowed for localhost only).");
|
|
135
|
+
return u.origin + u.pathname.replace(/\/+$/, "");
|
|
136
|
+
}
|
package/lib/main.mjs
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// `vidlab`: the VidLab API from a shell. Every command takes --json (one JSON document on stdout, errors included) for
|
|
2
|
+
// agents and scripts, and --base-url (default https://vidlab.ai). Exit codes: 0 done, 1 API or network error,
|
|
3
|
+
// 2 usage error, 3 the generation failed (nothing charged), 4 still running when --wait ran out of time, 5 a format run
|
|
4
|
+
// is waiting for answers.
|
|
5
|
+
|
|
6
|
+
import { spawnSync } from "node:child_process";
|
|
7
|
+
import { writeFile as fsWriteFile } from "node:fs/promises";
|
|
8
|
+
import { homedir, platform } from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { coerce, parseArgs, UsageError } from "./args.mjs";
|
|
11
|
+
import { ApiError, createClient } from "./client.mjs";
|
|
12
|
+
import { cmdFormat, cmdFormats, cmdSetup, cmdSkill, cmdUpload, resolveFiles } from "./commands.mjs";
|
|
13
|
+
import { baseUrlOf, deleteKey, KEY_PATTERN, loadKey, saveKey } from "./credentials.mjs";
|
|
14
|
+
import { VERSION } from "./version.mjs";
|
|
15
|
+
|
|
16
|
+
const EXIT = { ok: 0, error: 1, usage: 2, failed: 3, timeout: 4 };
|
|
17
|
+
|
|
18
|
+
const HELP = `vidlab ${VERSION}: one key for every top image, video and audio model. Pay only for successful runs.
|
|
19
|
+
|
|
20
|
+
Usage: vidlab <command> [options]
|
|
21
|
+
|
|
22
|
+
Commands
|
|
23
|
+
setup [--client c] [--dry-run] Load the VidLab skill into Claude Code and Codex and check your key
|
|
24
|
+
login Save your API key (VIDLAB_API_KEY if set, else the keys page opens and you paste it, hidden)
|
|
25
|
+
logout Forget the saved key
|
|
26
|
+
models [--kind k] [--maker m] [--search words]
|
|
27
|
+
List models (kind: video, image, audio, lipsync, upscale)
|
|
28
|
+
model <id> One model: its params and every price
|
|
29
|
+
estimate <model> [input] The exact price before you start (free)
|
|
30
|
+
run <model> [input] [--wait] [--out file] [--max-price usd] [--idempotency-key k]
|
|
31
|
+
Start a generation (also: generate); --wait polls and downloads the result
|
|
32
|
+
get <id> [--wait] [--out file]
|
|
33
|
+
Read a generation (and download its outputs when done)
|
|
34
|
+
upload <file> [file ...] Upload a local file and print its link (--image ./a.png does this by itself)
|
|
35
|
+
formats Our ad formats (a finished video from a brief)
|
|
36
|
+
format <id> One format: its inputs
|
|
37
|
+
format run <id> [--input name=value ...] [--max-price usd] [--wait] [--out file]
|
|
38
|
+
Start a format run; it asks questions (the price last) at a terminal
|
|
39
|
+
format answer <run> name=value ... Answer a run's questions (confirm_price=approve starts it)
|
|
40
|
+
format get <run> [--wait] [--out file] | format cancel <run>
|
|
41
|
+
skill install [--client claude-code|codex|all] [--dir folder] | skill print
|
|
42
|
+
Load the VidLab skill so your agent knows how to use it
|
|
43
|
+
balance Your API wallet's spendable balance
|
|
44
|
+
|
|
45
|
+
Input options (estimate, run)
|
|
46
|
+
--prompt text What to make
|
|
47
|
+
--image url-or-file An image link or a local file (repeat for several; the first is the first frame or reference)
|
|
48
|
+
--param key=value Any input field, e.g. --param resolution=720p --param duration=5
|
|
49
|
+
--duration s --resolution r --aspect-ratio a --video url-or-file --audio url-or-file --text t --voice v --seed n --n n
|
|
50
|
+
|
|
51
|
+
Options
|
|
52
|
+
--json Print JSON (errors too) for agents and scripts
|
|
53
|
+
--base-url url API address (default https://vidlab.ai, or VIDLAB_BASE_URL)
|
|
54
|
+
--timeout s With --wait: give up after this many seconds (default 900)
|
|
55
|
+
--interval s With --wait: seconds between polls (default 3)
|
|
56
|
+
--no-download With --wait: do not download outputs
|
|
57
|
+
-h, --help -v, --version
|
|
58
|
+
|
|
59
|
+
Exit codes: 0 done, 1 error, 2 usage, 3 generation failed (nothing charged), 4 still running after --timeout,
|
|
60
|
+
5 a format run needs answers.
|
|
61
|
+
Docs: https://vidlab.ai/vidlab-api/docs`;
|
|
62
|
+
|
|
63
|
+
const FLAGS = {
|
|
64
|
+
help: "switch",
|
|
65
|
+
version: "switch",
|
|
66
|
+
json: "switch",
|
|
67
|
+
"base-url": "one",
|
|
68
|
+
kind: "one",
|
|
69
|
+
maker: "one",
|
|
70
|
+
search: "one",
|
|
71
|
+
prompt: "one",
|
|
72
|
+
"negative-prompt": "one",
|
|
73
|
+
image: "many",
|
|
74
|
+
param: "many",
|
|
75
|
+
duration: "one",
|
|
76
|
+
resolution: "one",
|
|
77
|
+
"aspect-ratio": "one",
|
|
78
|
+
video: "one",
|
|
79
|
+
audio: "one",
|
|
80
|
+
"end-image": "one",
|
|
81
|
+
text: "one",
|
|
82
|
+
voice: "one",
|
|
83
|
+
seed: "one",
|
|
84
|
+
n: "one",
|
|
85
|
+
wait: "switch",
|
|
86
|
+
out: "one",
|
|
87
|
+
"max-price": "one",
|
|
88
|
+
"idempotency-key": "one",
|
|
89
|
+
timeout: "one",
|
|
90
|
+
download: "switch",
|
|
91
|
+
interval: "one",
|
|
92
|
+
input: "many",
|
|
93
|
+
client: "one",
|
|
94
|
+
dir: "one",
|
|
95
|
+
auth: "one",
|
|
96
|
+
"dry-run": "switch",
|
|
97
|
+
skill: "switch",
|
|
98
|
+
mcp: "switch",
|
|
99
|
+
browser: "switch",
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const STRING_FIELDS = new Set(["prompt", "negative_prompt", "end_image", "video", "audio", "resolution", "aspect_ratio", "quality", "text", "voice"]);
|
|
103
|
+
const NUMBER_FIELDS = new Set(["duration", "seed", "n"]);
|
|
104
|
+
const SHORTCUTS = { "negative-prompt": "negative_prompt", duration: "duration", resolution: "resolution", "aspect-ratio": "aspect_ratio", video: "video", audio: "audio", "end-image": "end_image", text: "text", voice: "voice", seed: "seed", n: "n" };
|
|
105
|
+
|
|
106
|
+
const HINTS = {
|
|
107
|
+
unauthorized: "Run `vidlab login`, or set VIDLAB_API_KEY to a vidlab_sk_ key.",
|
|
108
|
+
developer_access_forbidden: "This account does not have API access yet.",
|
|
109
|
+
api_wallet_exhausted: "Add credit to your API wallet on the billing page, then try again.",
|
|
110
|
+
api_key_budget_exhausted: "This key reached its monthly budget: raise it under API keys, or use another key.",
|
|
111
|
+
max_price_exceeded: "Raise --max-price, or lower the resolution or duration.",
|
|
112
|
+
model_not_found: "List the models with `vidlab models`.",
|
|
113
|
+
variant_unavailable: "Check the priced options with `vidlab model <id>`.",
|
|
114
|
+
invalid_request: "Check the input fields with `vidlab model <id>`.",
|
|
115
|
+
invalid_input: "Check the input fields with `vidlab model <id>`.",
|
|
116
|
+
generation_not_found: "Use an id that `vidlab run` printed, with the same key.",
|
|
117
|
+
api_key_required: "Generations need a vidlab_sk_ API key: set VIDLAB_API_KEY or run `vidlab login`.",
|
|
118
|
+
// A failed generation's public codes (the older names stay: a server that still sends them reads the same).
|
|
119
|
+
input_unreachable: "A file link did not open. Send a public https link, or a local file (it is uploaded for you).",
|
|
120
|
+
content_policy: "A content policy blocked the prompt or a file. Change them and run again; nothing was charged.",
|
|
121
|
+
content_blocked: "A content policy blocked the prompt or a file. Change them and run again; nothing was charged.",
|
|
122
|
+
model_declined: "The model is not offered with these options right now. Try another resolution or length (`vidlab model <id>`).",
|
|
123
|
+
reference_changed: "The reference clip is longer than the call was priced for. Run again with --param video_seconds=<its length in whole seconds>.",
|
|
124
|
+
max_cost_exceeded: "The price is over your cap. Raise --max-price, or lower the resolution or duration.",
|
|
125
|
+
max_wait_exceeded: "No route could finish inside your wait. Raise it, or run without it.",
|
|
126
|
+
model_busy: "No route can take this model right now. Try again in a few minutes, or use another model.",
|
|
127
|
+
no_capacity: "No route can take this model right now. Try again in a few minutes, or use another model.",
|
|
128
|
+
model_unavailable: "The model is switched off for the moment. Try again later, or use another model.",
|
|
129
|
+
all_routes_failed: "Every route turned the call away. Try again in a few minutes.",
|
|
130
|
+
timeout: "A route did not answer in time. Try again.",
|
|
131
|
+
upstream_timeout: "A route did not answer in time. Try again.",
|
|
132
|
+
processing_failed: "The route could not make it. Try again, or change the prompt.",
|
|
133
|
+
generation_failed: "The route could not make it. Try again, or change the prompt.",
|
|
134
|
+
key_expired: "This key has expired: create a new one under API keys, then run `vidlab login`.",
|
|
135
|
+
ip_not_allowed: "This key may not be used from this address: add it to the key's IP list, or use another key.",
|
|
136
|
+
model_not_allowed: "This key may not run this model: allow it on the key, or use another key.",
|
|
137
|
+
key_quota_exceeded: "This key reached its spend quota: raise it under API keys, or use another key.",
|
|
138
|
+
connection_error: "Check your network, or --base-url.",
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** Input from the flags: --prompt, --image (repeatable), the shortcuts, and --param key=value (unknown keys go to extra). */
|
|
142
|
+
export function inputFromFlags(flags) {
|
|
143
|
+
const input = {};
|
|
144
|
+
const put = (key, raw) => {
|
|
145
|
+
if (STRING_FIELDS.has(key)) input[key] = String(raw);
|
|
146
|
+
else if (NUMBER_FIELDS.has(key)) {
|
|
147
|
+
const n = Number(raw);
|
|
148
|
+
if (!Number.isFinite(n)) throw new UsageError(`${key} must be a number (got "${raw}").`);
|
|
149
|
+
input[key] = n;
|
|
150
|
+
} else if (key === "generate_audio") input[key] = raw === true || raw === "true";
|
|
151
|
+
else if (key === "images") input.images = [...(input.images ?? []), ...(Array.isArray(raw) ? raw : [raw])];
|
|
152
|
+
else (input.extra ??= {})[key.replace(/^extra\./, "")] = typeof raw === "string" ? coerce(raw) : raw;
|
|
153
|
+
};
|
|
154
|
+
if (flags.prompt !== undefined) put("prompt", flags.prompt);
|
|
155
|
+
for (const [flag, key] of Object.entries(SHORTCUTS)) if (flags[flag] !== undefined) put(key, flags[flag]);
|
|
156
|
+
for (const url of flags.image ?? []) put("images", url);
|
|
157
|
+
for (const p of flags.param ?? []) {
|
|
158
|
+
const eq = p.indexOf("=");
|
|
159
|
+
if (eq <= 0) throw new UsageError(`--param takes key=value (got "${p}").`);
|
|
160
|
+
put(p.slice(0, eq).trim().replace(/-/g, "_"), p.slice(eq + 1));
|
|
161
|
+
}
|
|
162
|
+
return input;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const money = (usd) => (usd < 0.01 && usd > 0 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(usd < 1 ? 3 : 2).replace(/(\.\d\d)0$/, "$1")}`);
|
|
166
|
+
const UNIT = { per_second: "per second", per_image: "per image", per_job: "per run", per_1k_chars: "per 1k chars", per_minute: "per minute" };
|
|
167
|
+
const UNITS = { per_second: ["second", "seconds"], per_image: ["image", "images"], per_job: ["run", "runs"], per_1k_chars: ["x 1k chars", "x 1k chars"], per_minute: ["minute", "minutes"] };
|
|
168
|
+
const unitWord = (unit, n) => (UNITS[unit] ? UNITS[unit][n === 1 ? 0 : 1] : unit);
|
|
169
|
+
|
|
170
|
+
function table(rows, headers) {
|
|
171
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => String(r[i]).length)));
|
|
172
|
+
const line = (r) => r.map((c, i) => String(c).padEnd(widths[i])).join(" ").trimEnd();
|
|
173
|
+
return [line(headers), ...rows.map(line)].join("\n");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const EXT = { "video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif", "audio/mpeg": "mp3", "audio/wav": "wav", "audio/x-wav": "wav", "audio/ogg": "ogg" };
|
|
177
|
+
function extOf(output) {
|
|
178
|
+
if (output.mime && EXT[output.mime]) return EXT[output.mime];
|
|
179
|
+
const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(output.url);
|
|
180
|
+
return m ? m[1].toLowerCase() : "bin";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Where each output goes: --out as given (numbered when there are several), else <id>[-n].<ext> in the current folder. */
|
|
184
|
+
export function outputPaths(gen, out, cwd) {
|
|
185
|
+
return gen.outputs.map((o, i) => {
|
|
186
|
+
const ext = extOf(o);
|
|
187
|
+
if (!out) return path.join(cwd, `${gen.id}${gen.outputs.length > 1 ? `-${i + 1}` : ""}.${ext}`);
|
|
188
|
+
const abs = path.resolve(cwd, out);
|
|
189
|
+
if (gen.outputs.length === 1) return abs;
|
|
190
|
+
const parsed = path.parse(abs);
|
|
191
|
+
return path.join(parsed.dir, `${parsed.name}-${i + 1}${parsed.ext || `.${ext}`}`);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function readHidden(io, prompt) {
|
|
196
|
+
if (io.readSecret) return io.readSecret(prompt);
|
|
197
|
+
const stdin = process.stdin;
|
|
198
|
+
if (!stdin.isTTY) {
|
|
199
|
+
let data = "";
|
|
200
|
+
for await (const chunk of stdin) data += chunk;
|
|
201
|
+
return data.trim();
|
|
202
|
+
}
|
|
203
|
+
io.stderr.write(prompt);
|
|
204
|
+
stdin.setRawMode(true);
|
|
205
|
+
stdin.resume();
|
|
206
|
+
stdin.setEncoding("utf8");
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
let value = "";
|
|
209
|
+
const onData = (s) => {
|
|
210
|
+
for (const ch of s) {
|
|
211
|
+
if (ch === "\r" || ch === "\n") {
|
|
212
|
+
done();
|
|
213
|
+
return resolve(value.trim());
|
|
214
|
+
}
|
|
215
|
+
if (ch === "\u0003") {
|
|
216
|
+
done();
|
|
217
|
+
return reject(new UsageError("Cancelled."));
|
|
218
|
+
}
|
|
219
|
+
if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
|
|
220
|
+
else value += ch;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const done = () => {
|
|
224
|
+
stdin.off("data", onData);
|
|
225
|
+
stdin.setRawMode(false);
|
|
226
|
+
stdin.pause();
|
|
227
|
+
io.stderr.write("\n");
|
|
228
|
+
};
|
|
229
|
+
stdin.on("data", onData);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Opens a page in the default browser (a list of arguments, no shell). Never fails the command. */
|
|
234
|
+
function openBrowser(url, io) {
|
|
235
|
+
if (io.open) return io.open(url);
|
|
236
|
+
const [cmd, args] = platform() === "darwin" ? ["open", [url]] : platform() === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
237
|
+
try {
|
|
238
|
+
io.run(cmd, args, { stdio: "ignore" });
|
|
239
|
+
} catch {}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Runs one command line. Returns the exit code; never calls process.exit (the bin does). */
|
|
243
|
+
export async function main(argv, io = {}) {
|
|
244
|
+
io = { stdout: process.stdout, stderr: process.stderr, env: process.env, fetch: globalThis.fetch, cwd: process.cwd(), writeFile: fsWriteFile, run: spawnSync, sleep: (ms) => new Promise((r) => setTimeout(r, ms)), home: homedir(), ...io };
|
|
245
|
+
const out = (s) => io.stdout.write(`${s}\n`);
|
|
246
|
+
const note = (s) => io.stderr.write(`${s}\n`);
|
|
247
|
+
let json = argv.includes("--json");
|
|
248
|
+
// The keys page of the address this command talks to (a local or staging copy names its own), for the missing-key hint.
|
|
249
|
+
let keysPage = "https://vidlab.ai/vidlab-api/api-keys";
|
|
250
|
+
try {
|
|
251
|
+
const { words, flags } = parseArgs(argv, FLAGS);
|
|
252
|
+
json = !!flags.json;
|
|
253
|
+
const emit = (value, human) => out(json ? JSON.stringify(value, null, 2) : human());
|
|
254
|
+
const [cmd, ...rest] = words;
|
|
255
|
+
if (flags.version) return out(json ? JSON.stringify({ version: VERSION }) : VERSION), EXIT.ok;
|
|
256
|
+
if (!cmd || cmd === "help" || flags.help) return out(HELP), EXIT.ok;
|
|
257
|
+
|
|
258
|
+
const baseUrl = baseUrlOf(flags["base-url"], io.env);
|
|
259
|
+
keysPage = `${baseUrl}/vidlab-api/api-keys`;
|
|
260
|
+
const noKey = ["login", "logout", "setup", "skill", "formats"].includes(cmd) || (cmd === "format" && !["run", "answer", "get", "cancel"].includes(rest[0]));
|
|
261
|
+
const creds = noKey ? null : loadKey(baseUrl, { env: io.env, run: io.run });
|
|
262
|
+
const api = createClient({ baseUrl, apiKey: creds?.key, fetch: io.fetch, sleepFn: io.sleep });
|
|
263
|
+
const need = (n, what) => {
|
|
264
|
+
if (rest.length < n) throw new UsageError(`Usage: vidlab ${cmd} ${what}`);
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const ctx = { rest, flags, api, io, json, emit, note, baseUrl, creds };
|
|
268
|
+
|
|
269
|
+
switch (cmd) {
|
|
270
|
+
case "setup":
|
|
271
|
+
return await cmdSetup(ctx);
|
|
272
|
+
case "skill":
|
|
273
|
+
return await cmdSkill(ctx);
|
|
274
|
+
case "upload":
|
|
275
|
+
return await cmdUpload(ctx);
|
|
276
|
+
case "formats":
|
|
277
|
+
return await cmdFormats(ctx);
|
|
278
|
+
case "format":
|
|
279
|
+
return await cmdFormat(ctx);
|
|
280
|
+
case "login": {
|
|
281
|
+
const fromEnv = io.env.VIDLAB_API_KEY?.trim();
|
|
282
|
+
if (!fromEnv && flags.browser !== false && (io.stdinIsTTY ?? process.stdin.isTTY)) {
|
|
283
|
+
// The key is made in the browser and pasted here, hidden: it is never in a URL or a command.
|
|
284
|
+
note(`Opening ${baseUrl}/vidlab-api/api-keys to make a key. Paste it here when you have it.`);
|
|
285
|
+
openBrowser(`${baseUrl}/vidlab-api/api-keys`, io);
|
|
286
|
+
}
|
|
287
|
+
const key = fromEnv || (await readHidden(io, "Paste your VidLab API key (vidlab_sk_..., input hidden): "));
|
|
288
|
+
if (!KEY_PATTERN.test(key ?? "")) throw new UsageError("That is not a VidLab API key (they start with vidlab_sk_). Create one at https://vidlab.ai under API keys.");
|
|
289
|
+
const checked = createClient({ baseUrl, apiKey: key, fetch: io.fetch, sleepFn: io.sleep });
|
|
290
|
+
const bal = await checked.balance();
|
|
291
|
+
const store = saveKey(key, baseUrl, { env: io.env, run: io.run });
|
|
292
|
+
const where = store === "macos" ? "the macOS Keychain" : store === "secret-service" ? "the Secret Service keyring" : "a private file (0600) under ~/.config/vidlab";
|
|
293
|
+
emit({ ok: true, base_url: baseUrl, stored_in: store, from_env: !!fromEnv, available_usd: bal.available_usd }, () => `Logged in to ${baseUrl}. Key saved in ${where}${fromEnv ? " (read from VIDLAB_API_KEY)" : ""}. Balance: ${money(bal.available_usd)}.`);
|
|
294
|
+
return EXIT.ok;
|
|
295
|
+
}
|
|
296
|
+
case "logout": {
|
|
297
|
+
deleteKey(baseUrl, { env: io.env, run: io.run });
|
|
298
|
+
emit({ ok: true, base_url: baseUrl }, () => `Forgot the saved key for ${baseUrl}.${io.env.VIDLAB_API_KEY ? " VIDLAB_API_KEY is still set in this shell." : ""}`);
|
|
299
|
+
return EXIT.ok;
|
|
300
|
+
}
|
|
301
|
+
case "models": {
|
|
302
|
+
const models = await api.listModels({ kind: flags.kind, maker: flags.maker, search: flags.search });
|
|
303
|
+
emit(models, () =>
|
|
304
|
+
models.length
|
|
305
|
+
? table(
|
|
306
|
+
models.map((m) => [m.id, m.kind, m.maker, `${money(Math.min(...Object.values(m.prices)))} ${UNIT[m.unit] ?? m.unit}`, m.status]),
|
|
307
|
+
["ID", "KIND", "MAKER", "FROM", "STATUS"],
|
|
308
|
+
) + `\n\n${models.length} model${models.length === 1 ? "" : "s"}. Details: vidlab model <id>`
|
|
309
|
+
: "No models match.",
|
|
310
|
+
);
|
|
311
|
+
return EXIT.ok;
|
|
312
|
+
}
|
|
313
|
+
case "model": {
|
|
314
|
+
need(1, "<id>");
|
|
315
|
+
const m = await api.getModel(rest[0]);
|
|
316
|
+
emit(m, () => {
|
|
317
|
+
const params = Object.entries(m.params).map(([k, p]) => {
|
|
318
|
+
const bits = [p?.required ? "required" : "optional"];
|
|
319
|
+
if (p?.values?.length) bits.push(p.values.join(" | "));
|
|
320
|
+
else if (p?.min !== undefined && p?.max !== undefined) bits.push(`${p.min} to ${p.max}`);
|
|
321
|
+
else if (p?.max !== undefined) bits.push(`up to ${p.max}`);
|
|
322
|
+
else if (p?.min !== undefined) bits.push(`from ${p.min}`);
|
|
323
|
+
return ` ${k.padEnd(16)} ${bits.join(", ")}`;
|
|
324
|
+
});
|
|
325
|
+
const prices = Object.entries(m.prices).map(([v, usd]) => ` ${v.padEnd(22)} ${money(usd)} ${UNIT[m.unit] ?? m.unit}`);
|
|
326
|
+
return [`${m.name} (${m.id}) by ${m.maker}: ${m.kind}, ${m.status}`, m.description ? m.description : null, "", "Prices (charged only on success):", ...prices, "", "Input:", ...params].filter((l) => l !== null).join("\n");
|
|
327
|
+
});
|
|
328
|
+
return EXIT.ok;
|
|
329
|
+
}
|
|
330
|
+
case "estimate": {
|
|
331
|
+
need(1, "<model> --prompt ... [--param k=v]");
|
|
332
|
+
const e = await api.estimate(rest[0], await resolveFiles(inputFromFlags(flags), { api, io, note }));
|
|
333
|
+
emit(e, () => `${e.model} (${e.variant}): ${e.units} ${unitWord(e.unit, e.units)} = ${money(e.price_usd)}. Charged only if it succeeds.${e.note ? `\n${e.note}` : ""}`);
|
|
334
|
+
return EXIT.ok;
|
|
335
|
+
}
|
|
336
|
+
case "run":
|
|
337
|
+
case "generate":
|
|
338
|
+
case "get": {
|
|
339
|
+
need(1, cmd !== "get" ? "<model> --prompt ... [--param k=v] [--wait] [--out file]" : "<generation id> [--wait] [--out file]");
|
|
340
|
+
let gen;
|
|
341
|
+
if (cmd !== "get") {
|
|
342
|
+
const body = { model: rest[0], input: await resolveFiles(inputFromFlags(flags), { api, io, note }) };
|
|
343
|
+
if (flags["max-price"] !== undefined) {
|
|
344
|
+
const max = Number(flags["max-price"]);
|
|
345
|
+
if (!Number.isFinite(max) || max < 0) throw new UsageError("--max-price takes US dollars, e.g. --max-price 2.50");
|
|
346
|
+
// The API's cap, max_cost_usd: a route dearer than this is skipped; none cheaper answers 422 max_cost_exceeded.
|
|
347
|
+
body.max_cost_usd = max;
|
|
348
|
+
}
|
|
349
|
+
gen = await api.createGeneration(body, flags["idempotency-key"]);
|
|
350
|
+
if (!json) note(`Started ${gen.id} on ${gen.model} (${gen.variant}): ${money(gen.price_usd)} if it succeeds.`);
|
|
351
|
+
} else gen = await api.getGeneration(rest[0]);
|
|
352
|
+
|
|
353
|
+
if (flags.wait && gen.status !== "succeeded" && gen.status !== "failed") {
|
|
354
|
+
const timeoutS = flags.timeout === undefined ? 900 : Number(flags.timeout);
|
|
355
|
+
const intervalMs = Math.max(250, Number(flags.interval ?? 3) * 1000);
|
|
356
|
+
const end = Date.now() + timeoutS * 1000;
|
|
357
|
+
while (gen.status !== "succeeded" && gen.status !== "failed" && Date.now() < end) {
|
|
358
|
+
if (!json) io.stderr.write(".");
|
|
359
|
+
await io.sleep(intervalMs);
|
|
360
|
+
gen = await api.getGeneration(gen.id);
|
|
361
|
+
}
|
|
362
|
+
if (!json) io.stderr.write("\n");
|
|
363
|
+
}
|
|
364
|
+
const files = [];
|
|
365
|
+
if (gen.status === "succeeded" && (flags.wait || flags.out) && flags.download !== false) {
|
|
366
|
+
const dests = outputPaths(gen, flags.out, io.cwd);
|
|
367
|
+
for (let i = 0; i < gen.outputs.length; i++) {
|
|
368
|
+
const bytes = await api.download(gen.outputs[i].url, dests[i], { writeFile: io.writeFile });
|
|
369
|
+
files.push({ path: dests[i], bytes });
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
emit({ ...gen, ...(files.length ? { files } : {}) }, () => {
|
|
373
|
+
const lines = [`${gen.id}: ${gen.status} (${gen.model}, ${gen.variant}, ${money(gen.price_usd)}${gen.status === "succeeded" ? " charged" : gen.status === "failed" ? ", not charged" : " if it succeeds"})`];
|
|
374
|
+
if (gen.error) lines.push(`Error [${gen.error.code}]: ${gen.error.message}${gen.error.retryable ? " You can run it again; nothing was charged." : ""}`);
|
|
375
|
+
for (const f of files) lines.push(`Saved ${f.path} (${f.bytes.toLocaleString("en-US")} bytes)`);
|
|
376
|
+
if (gen.status === "succeeded" && !files.length) for (const o of gen.outputs) lines.push(o.url);
|
|
377
|
+
if (gen.status === "queued" || gen.status === "running") lines.push(`Check again: vidlab get ${gen.id} --wait`);
|
|
378
|
+
return lines.join("\n");
|
|
379
|
+
});
|
|
380
|
+
if (gen.status === "failed") return EXIT.failed;
|
|
381
|
+
if (gen.status !== "succeeded" && flags.wait) return EXIT.timeout;
|
|
382
|
+
return EXIT.ok;
|
|
383
|
+
}
|
|
384
|
+
case "balance": {
|
|
385
|
+
const b = await api.balance();
|
|
386
|
+
emit(b, () => `Available: ${money(b.available_usd)} (balance ${money(b.balance_cents / 100)}, monthly credit left ${money(b.monthly_credit_remaining_cents / 100)}, held for running jobs ${money(b.held_cents / 100)}). Monthly credit resets ${b.resets_at.slice(0, 10)}.${creds ? ` Key from ${creds.source === "VIDLAB_API_KEY" ? "VIDLAB_API_KEY" : creds.source}.` : ""}`);
|
|
387
|
+
return EXIT.ok;
|
|
388
|
+
}
|
|
389
|
+
default:
|
|
390
|
+
throw new UsageError(`Unknown command "${cmd}". See: vidlab help`);
|
|
391
|
+
}
|
|
392
|
+
} catch (err) {
|
|
393
|
+
if (err instanceof UsageError || err?.message?.startsWith("--base-url")) {
|
|
394
|
+
if (json) out(JSON.stringify({ error: { code: "usage", message: err.message } }, null, 2));
|
|
395
|
+
else note(`Error: ${err.message}`);
|
|
396
|
+
return EXIT.usage;
|
|
397
|
+
}
|
|
398
|
+
if (err instanceof ApiError) {
|
|
399
|
+
const hint = err.code === "missing_api_key" ? `Create a key at ${keysPage}, then run \`vidlab login\`.` : HINTS[err.code];
|
|
400
|
+
if (json) out(JSON.stringify({ error: { code: err.code, message: err.message, status: err.status, ...(hint ? { hint } : {}) } }, null, 2));
|
|
401
|
+
else note(`Error [${err.code}]: ${err.message}${hint ? `\n${hint}` : ""}`);
|
|
402
|
+
return EXIT.error;
|
|
403
|
+
}
|
|
404
|
+
if (json) out(JSON.stringify({ error: { code: "internal", message: String(err?.message ?? err) } }, null, 2));
|
|
405
|
+
else note(`Error: ${err?.message ?? err}`);
|
|
406
|
+
return EXIT.error;
|
|
407
|
+
}
|
|
408
|
+
}
|