@vidlab/cli 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VidLab
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,62 @@
1
- # Temporary Holding Version
1
+ # @vidlab/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The VidLab API from your shell: one key for every top image, video and audio model, each at the lowest price. You pay only for generations that succeed. The command is `vidlab`.
4
+
5
+ ## Quickstart
6
+
7
+ ```sh
8
+ npx @vidlab/cli setup # loads the VidLab skill into Claude Code and Codex and checks VIDLAB_API_KEY
9
+ npx @vidlab/cli login # saves your key (opens the keys page; paste it, hidden)
10
+ npx @vidlab/cli run seedance-2.5 --prompt "a red fox in snow" --duration 5 --resolution 720p --wait --out fox.mp4
11
+ ```
12
+
13
+ Install it once with `npm install -g @vidlab/cli` and drop the `npx @vidlab/cli`.
14
+
15
+ ## Commands
16
+
17
+ ```sh
18
+ vidlab models --kind video --search seedance # find
19
+ vidlab model seedance-2.5 # its inputs and every price
20
+ vidlab estimate seedance-2.5 --prompt "a red fox" --duration 5 --resolution 720p
21
+ vidlab run seedance-2.5 --prompt "a red fox" --duration 5 --max-price 2 --wait --out fox.mp4
22
+ vidlab get gen_... --wait # read a job later, download when done
23
+ vidlab upload ./photo.png # prints the link; --image ./photo.png does this by itself
24
+ vidlab formats # our ad formats: a finished video from a brief
25
+ vidlab format run drama-ad --input brief="A tired dad finally sleeps." --max-price 6 --wait --out ad.mp4
26
+ vidlab systems # systems: a whole video made for you (no key needed)
27
+ vidlab system run drama-ad "A Drama Ad for my coffee brand" --brief "warm kitchen" --image ./bag.png --wait
28
+ vidlab system reply srun_... "Make the mother warmer." --wait
29
+ vidlab system approve srun_... --wait # yes past the waiting checkpoint (--checkpoint <id>), or go on after a pause
30
+ vidlab system approve srun_... --all --wait # yes, and run the rest without stopping
31
+ vidlab system wait srun_... --out ad.mp4 # until it needs you or is done; downloads the video
32
+ vidlab system get srun_...
33
+ vidlab system list
34
+ vidlab system cancel srun_...
35
+ vidlab balance
36
+ vidlab skill install # the VidLab skill for Claude Code and Codex
37
+ ```
38
+
39
+ ## Connect your agent
40
+
41
+ `vidlab setup` finds Claude Code and Codex on this computer, loads the VidLab skill into each, and checks `VIDLAB_API_KEY` with one free call. Your agent then calls the VidLab API with the key from its environment: start it from a shell where the variable is set. Name clients with `--client claude-code,codex`, preview with `--dry-run`. For any other agent: `vidlab skill install --dir <folder>`, or `vidlab skill print`.
42
+
43
+ ## For agents and scripts
44
+
45
+ - `--json` on every command prints one JSON document on stdout, errors included: `{"error": {"code", "message", "status", "hint"}}`.
46
+ - Exit codes: `0` done, `1` API or network error, `2` usage error, `3` generation, format run or system run failed, `4` still running when `--wait` ran out (`--timeout`), `5` a format run needs answers, or a system run waits for you (a reply, a yes to a checkpoint, or credit).
47
+ - A system run that waits for you prints what it waits for (its questions, the checkpoint's text and media) and the exact `vidlab system reply|approve ...` to send. It shows no price: a run is billed to the balance as it goes, and waits when there is not enough credit (add credit, then `vidlab system approve <run>`). `--wait` and `system wait` read it every 10 seconds (`--interval`), for up to 30 minutes (`--timeout`).
48
+ - `run` always sends an Idempotency-Key (yours with `--idempotency-key`), so its own retries never pay twice. `--max-price` is the API's `max_cost_usd`: a route dearer than it is skipped, and with none cheaper the call stops with `max_cost_exceeded` before anything is held.
49
+ - `format cancel` exits `0`: the run ended as you asked.
50
+ - A format run that needs answers prints its questions and the exact `vidlab format answer ...` to send; at a terminal it asks you instead. The price is the last question and your approval: `confirm_price=approve`, or pass `--max-price` to approve up to a cap.
51
+
52
+ ## Input
53
+
54
+ `--prompt`, `--image <link or file>` (repeat for several), `--duration`, `--resolution`, `--aspect-ratio`, `--video`, `--audio`, `--end-image`, `--text`, `--voice`, `--seed`, `--n`, and `--param key=value` for any field a model lists (`vidlab model <id>`). A local file in `--image`, `--video`, `--audio` or `--end-image` is uploaded and its link sent.
55
+
56
+ ## The key
57
+
58
+ `VIDLAB_API_KEY` wins when set. `vidlab login` checks the key, then saves it in the macOS Keychain or the Linux Secret Service (through `secret-tool`) when there is one, else in a 0600 file under `~/.config/vidlab`. The key is never printed and never passed on a command line. `VIDLAB_NO_KEYCHAIN=1` skips the keychain. `vidlab logout` forgets it.
59
+
60
+ `--base-url` (or `VIDLAB_BASE_URL`) points the CLI at another address; the default is https://vidlab.ai. Plain http is allowed for localhost only.
61
+
62
+ Node 18.17 or newer. No dependencies. MIT licence.
package/bin/vidlab.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../lib/main.mjs";
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (err) => {
9
+ process.stderr.write(`Error: ${err?.message ?? err}\n`);
10
+ process.exitCode = 1;
11
+ },
12
+ );
package/lib/args.mjs ADDED
@@ -0,0 +1,56 @@
1
+ // A small, strict command-line reader: `--name value`, `--name=value`, switches, repeatable flags. A flag nobody
2
+ // declared is a usage error, never a guess.
3
+
4
+ export class UsageError extends Error {}
5
+
6
+ /** spec: { name: "switch" | "one" | "many" }. Returns { words, flags }. `-h` is --help, `-v` is --version. */
7
+ export function parseArgs(argv, spec) {
8
+ const words = [];
9
+ const flags = {};
10
+ for (let i = 0; i < argv.length; i++) {
11
+ let a = argv[i];
12
+ if (a === "--") {
13
+ words.push(...argv.slice(i + 1));
14
+ break;
15
+ }
16
+ if (a === "-h") a = "--help";
17
+ if (a === "-v") a = "--version";
18
+ if (!a.startsWith("--") || a === "-") {
19
+ words.push(a);
20
+ continue;
21
+ }
22
+ const eq = a.indexOf("=");
23
+ const name = a.slice(2, eq < 0 ? undefined : eq);
24
+ const neg = name.startsWith("no-") && spec[name.slice(3)] === "switch";
25
+ const key = neg ? name.slice(3) : name;
26
+ const kind = spec[key];
27
+ if (!kind) throw new UsageError(`Unknown flag --${name}. See: vidlab help`);
28
+ if (kind === "switch") {
29
+ if (eq >= 0) throw new UsageError(`--${name} takes no value.`);
30
+ flags[key] = !neg;
31
+ continue;
32
+ }
33
+ let value;
34
+ if (eq >= 0) value = a.slice(eq + 1);
35
+ else {
36
+ if (i + 1 >= argv.length) throw new UsageError(`--${name} needs a value.`);
37
+ value = argv[++i];
38
+ }
39
+ if (kind === "many") (flags[key] ??= []).push(value);
40
+ else flags[key] = value;
41
+ }
42
+ return { words, flags };
43
+ }
44
+
45
+ /** "720p" -> "720p", "5" -> 5, "true" -> true, '["a"]' -> ["a"]. */
46
+ export function coerce(v) {
47
+ if (v === "true") return true;
48
+ if (v === "false") return false;
49
+ if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
50
+ if (/^[[{]/.test(v)) {
51
+ try {
52
+ return JSON.parse(v);
53
+ } catch {}
54
+ }
55
+ return v;
56
+ }
package/lib/client.mjs ADDED
@@ -0,0 +1,106 @@
1
+ // A small client for the VidLab API's /v1 routes: the key as a Bearer token, our error envelope read into ApiError
2
+ // (with its code), and retries of 429 / 5xx / network failures that honor Retry-After. POST /v1/generations always
3
+ // carries an Idempotency-Key, the same one on each retry, so a retry never starts or pays twice.
4
+
5
+ import { randomUUID } from "node:crypto";
6
+ import { VERSION } from "./version.mjs";
7
+
8
+ export class ApiError extends Error {
9
+ constructor(message, { status = null, code = "error", body = undefined, retryAfter = null } = {}) {
10
+ super(message);
11
+ this.name = "ApiError";
12
+ this.status = status;
13
+ this.code = code;
14
+ this.body = body;
15
+ this.retryAfter = retryAfter;
16
+ }
17
+ }
18
+
19
+ const RETRY = new Set([408, 429, 500, 502, 503, 504]);
20
+ // A spend limit resets on the hour or at midnight UTC: waiting a minute and retrying never helps.
21
+ const NO_RETRY_CODES = new Set(["api_wallet_exhausted", "api_key_budget_exhausted", "key_spend_limit_reached"]);
22
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
23
+
24
+ export function createClient({ baseUrl, apiKey, fetch: f = globalThis.fetch, maxRetries = 2, timeoutMs = 60_000, sleepFn = sleep }) {
25
+ async function request(method, path, { body, rawBody, contentType, headers: more, query, auth = false, idempotencyKey } = {}) {
26
+ if (auth === true && !apiKey) throw new ApiError("No API key. Run `vidlab login`, or set VIDLAB_API_KEY.", { code: "missing_api_key" });
27
+ const url = new URL(baseUrl + path);
28
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
29
+ const headers = { accept: "application/json", "user-agent": `vidlab-cli/${VERSION}` };
30
+ // `auth: "optional"` (the catalogue, the estimate): the key goes along when there is one, so a key limited to some
31
+ // models lists and prices only those.
32
+ if (auth && apiKey) headers.authorization = `Bearer ${apiKey}`;
33
+ if (body !== undefined) headers["content-type"] = "application/json";
34
+ if (rawBody !== undefined) headers["content-type"] = contentType || "application/octet-stream";
35
+ Object.assign(headers, more ?? {});
36
+ if (idempotencyKey) headers["idempotency-key"] = idempotencyKey;
37
+ for (let attempt = 0; ; attempt++) {
38
+ let res;
39
+ try {
40
+ res = await f(url, { method, headers, body: rawBody !== undefined ? rawBody : body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(rawBody !== undefined ? 10 * 60_000 : timeoutMs) });
41
+ } catch (err) {
42
+ if (attempt < maxRetries) {
43
+ await sleepFn(500 * 2 ** attempt);
44
+ continue;
45
+ }
46
+ throw new ApiError(`Could not reach ${baseUrl} (${err?.name === "TimeoutError" ? "timed out" : (err?.cause?.code ?? err?.message ?? "network error")}).`, { code: "connection_error" });
47
+ }
48
+ const text = await res.text();
49
+ let data;
50
+ try {
51
+ data = text ? JSON.parse(text) : undefined;
52
+ } catch {
53
+ data = undefined;
54
+ }
55
+ if (res.ok) {
56
+ if (data === undefined) throw new ApiError(`Unexpected answer from ${path} (HTTP ${res.status}, not JSON).`, { status: res.status, code: "bad_response" });
57
+ return data;
58
+ }
59
+ const env = data?.error ?? {};
60
+ const raHeader = res.headers.get("retry-after");
61
+ const retryAfter = raHeader !== null && Number.isFinite(Number(raHeader)) ? Number(raHeader) : null;
62
+ const err = new ApiError(typeof env.message === "string" ? env.message : `HTTP ${res.status}`, { status: res.status, code: typeof env.code === "string" ? env.code : `http_${res.status}`, body: data, retryAfter });
63
+ if (attempt < maxRetries && RETRY.has(res.status) && !NO_RETRY_CODES.has(err.code)) {
64
+ await sleepFn(retryAfter !== null ? Math.min(retryAfter * 1000, 60_000) : 500 * 2 ** attempt);
65
+ continue;
66
+ }
67
+ throw err;
68
+ }
69
+ }
70
+
71
+ return {
72
+ baseUrl,
73
+ listModels: async (q = {}) => (await request("GET", "/v1/models", { query: q, auth: "optional" })).data,
74
+ getModel: async (id) => (await request("GET", `/v1/models/${encodeURIComponent(id)}`, { auth: "optional" })).data,
75
+ estimate: async (model, input) => (await request("POST", "/v1/estimate", { body: { model, input }, auth: "optional" })).data,
76
+ createGeneration: async (body, idempotencyKey = `cli-${randomUUID()}`) => (await request("POST", "/v1/generations", { body, auth: true, idempotencyKey })).data,
77
+ getGeneration: async (id) => (await request("GET", `/v1/generations/${encodeURIComponent(id)}`, { auth: true })).data,
78
+ balance: async () => (await request("GET", "/v1/balance", { auth: true })).data,
79
+ /** Uploads one local file (raw body) and returns { url, mime, bytes, kind, expires_at }: the url goes in an input field. */
80
+ upload: async (bytes, { contentType, fileName }) => (await request("POST", "/v1/uploads", { rawBody: bytes, contentType, headers: { "x-file-name": String(fileName ?? "file").replace(/[^A-Za-z0-9._ -]/g, "_").slice(0, 120) }, auth: true })).data,
81
+ listFormats: async () => (await request("GET", "/v1/formats")).data,
82
+ getFormat: async (id) => request("GET", `/v1/formats/${encodeURIComponent(id)}`),
83
+ startFormatRun: async (id, body, idempotencyKey = `cli-${randomUUID()}`) => request("POST", `/v1/formats/${encodeURIComponent(id)}/runs`, { body, auth: true, idempotencyKey }),
84
+ answerFormatRun: async (runId, answers) => request("POST", `/v1/formats/runs/${encodeURIComponent(runId)}/answers`, { body: { answers }, auth: true }),
85
+ getFormatRun: async (runId) => request("GET", `/v1/formats/runs/${encodeURIComponent(runId)}`, { auth: true }),
86
+ cancelFormatRun: async (runId) => request("POST", `/v1/formats/runs/${encodeURIComponent(runId)}/cancel`, { auth: true, body: {} }),
87
+ // Systems: a whole video made for you (/v1/system-runs). The catalog is public; every run call takes the key.
88
+ listSystems: async () => request("GET", "/v1/system-runs/catalog"),
89
+ startSystemRun: async (body, idempotencyKey = `cli-${randomUUID()}`) => request("POST", "/v1/system-runs", { body, auth: true, idempotencyKey }),
90
+ listSystemRuns: async (limit) => (await request("GET", "/v1/system-runs", { query: { limit }, auth: true })).data,
91
+ getSystemRun: async (runId) => request("GET", `/v1/system-runs/${encodeURIComponent(runId)}`, { auth: true }),
92
+ replySystemRun: async (runId, text, inputs) => request("POST", `/v1/system-runs/${encodeURIComponent(runId)}/messages`, { body: inputs && Object.keys(inputs).length ? { text, inputs } : { text }, auth: true }),
93
+ /** `rest` = { maxPriceUsd? }: yes to this stop and to everything after it (the API's run_rest); the limit on media is optional. */
94
+ approveSystemRun: async (runId, checkpointId, rest) =>
95
+ request("POST", `/v1/system-runs/${encodeURIComponent(runId)}/approve`, { body: { ...(checkpointId ? { checkpoint_id: checkpointId } : {}), ...(rest ? { run_rest: true, ...(rest.maxPriceUsd !== undefined ? { max_price_usd: rest.maxPriceUsd } : {}) } : {}) }, auth: true }),
96
+ cancelSystemRun: async (runId) => request("POST", `/v1/system-runs/${encodeURIComponent(runId)}/cancel`, { body: {}, auth: true }),
97
+ /** Downloads one output to a file (a relative link is read against the base URL). */
98
+ async download(url, dest, { writeFile }) {
99
+ const res = await f(new URL(url, baseUrl), { signal: AbortSignal.timeout(10 * 60_000) });
100
+ if (!res.ok) throw new ApiError(`Could not download the output (HTTP ${res.status}). Read the generation again for a fresh link: vidlab get <id>.`, { status: res.status, code: "download_failed" });
101
+ const bytes = Buffer.from(await res.arrayBuffer());
102
+ await writeFile(dest, bytes);
103
+ return bytes.length;
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,324 @@
1
+ // The commands beyond the models API's own: upload, the formats (our ad formats, with their question loop), setup and
2
+ // skill. Each takes one context object from main.mjs: { rest, flags, api, io, json, emit, note, baseUrl, creds }.
3
+
4
+ import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { UsageError } from "./args.mjs";
7
+ import { ApiError } from "./client.mjs";
8
+ import { CLIENT_IDS, connectClient, detectClients, installSkill, mcpUrlOf, skillDirOf } from "./setup.mjs";
9
+
10
+ export const EXIT_NEEDS_INPUT = 5;
11
+ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg" };
12
+ const MAX_UPLOAD = 200 * 1024 * 1024;
13
+ const FILE_FIELDS = ["end_image", "video", "audio"];
14
+
15
+ export const isUrl = (v) => /^https?:\/\//i.test(String(v));
16
+ const money = (usd) => (usd < 0.01 && usd > 0 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(usd < 1 ? 3 : 2).replace(/(\.\d\d)0$/, "$1")}`);
17
+
18
+ /** Uploads one local file; returns the upload ({ url, mime, bytes, kind, expires_at }). */
19
+ export async function uploadFile(file, { api, io, note }) {
20
+ const abs = path.resolve(io.cwd, file);
21
+ let st;
22
+ try {
23
+ st = await (io.stat ?? fsStat)(abs);
24
+ } catch {
25
+ throw new UsageError(`"${file}" is not a link (https://...) and no such file exists.`);
26
+ }
27
+ if (!st.isFile()) throw new UsageError(`"${file}" is not a file.`);
28
+ if (st.size > MAX_UPLOAD) throw new UsageError(`"${file}" is over 200 MB. Send a smaller file, or its public link.`);
29
+ const bytes = await (io.readFile ?? fsReadFile)(abs);
30
+ let up;
31
+ try {
32
+ up = await api.upload(bytes, { contentType: MIME[path.extname(abs).toLowerCase()] ?? "application/octet-stream", fileName: path.basename(abs) });
33
+ } catch (err) {
34
+ if (err?.status === 404 || err?.status === 405) throw new UsageError(`This server does not take uploads yet. Send "${file}" as a public https link instead.`);
35
+ throw err;
36
+ }
37
+ note?.(`Uploaded ${path.basename(abs)} (${bytes.length.toLocaleString("en-US")} bytes).`);
38
+ return up;
39
+ }
40
+
41
+ /** A value that is a link stays; a local file path is uploaded and becomes its link. */
42
+ export async function linkOf(value, ctx) {
43
+ return isUrl(value) ? value : (await uploadFile(value, ctx)).url;
44
+ }
45
+
46
+ /** The input with every local file replaced by an uploaded link (images, end_image, video, audio). */
47
+ export async function resolveFiles(input, ctx) {
48
+ const out = { ...input };
49
+ if (out.images) out.images = await Promise.all(out.images.map((v) => linkOf(v, ctx)));
50
+ for (const k of FILE_FIELDS) if (out[k] !== undefined) out[k] = await linkOf(out[k], ctx);
51
+ return out;
52
+ }
53
+
54
+ export async function cmdUpload({ rest, api, io, emit, note }) {
55
+ if (!rest.length) throw new UsageError("Usage: vidlab upload <file> [file ...]");
56
+ const ups = [];
57
+ for (const f of rest) ups.push({ file: f, ...(await uploadFile(f, { api, io, note })) });
58
+ emit(ups.length === 1 ? ups[0] : ups, () => ups.map((u) => u.url).join("\n"));
59
+ return 0;
60
+ }
61
+
62
+ /* ------------------------------------------------------------------------------------------------ formats */
63
+
64
+ async function askLine(io, prompt) {
65
+ if (io.ask) return io.ask(prompt);
66
+ const { createInterface } = await import("node:readline/promises");
67
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
68
+ try {
69
+ return (await rl.question(prompt)).trim();
70
+ } finally {
71
+ rl.close();
72
+ }
73
+ }
74
+
75
+ const pairs = (list, what) =>
76
+ Object.fromEntries(
77
+ (list ?? []).map((p) => {
78
+ const eq = p.indexOf("=");
79
+ if (eq <= 0) throw new UsageError(`${what} takes name=value (got "${p}").`);
80
+ return [p.slice(0, eq).trim(), p.slice(eq + 1)];
81
+ }),
82
+ );
83
+
84
+ export async function cmdFormats({ api, emit }) {
85
+ const list = await api.listFormats();
86
+ emit(list, () => {
87
+ // No set or "from" price: each run is quoted for its own inputs before anything is spent.
88
+ const rows = list.map((f) => [f.id, f.name, `${f.minutes ?? "?"} min`, "quoted per run"]);
89
+ const w = [0, 1, 2].map((i) => Math.max(...rows.map((r) => String(r[i]).length)));
90
+ return `${rows.map((r) => `${String(r[0]).padEnd(w[0])} ${String(r[1]).padEnd(w[1])} ${String(r[2]).padEnd(w[2])} ${r[3]}`).join("\n")}\n\nDetails: vidlab format <id>. Start one: vidlab format run <id> --input brief="..."`;
91
+ });
92
+ return 0;
93
+ }
94
+
95
+ function showRun(run) {
96
+ const lines = [`${run.run_id}: ${run.status} (${run.format?.name ?? run.format?.id ?? ""})`];
97
+ const p = run.price ?? {};
98
+ if (p.quoted_usd != null) lines.push(`Price: ${money(p.quoted_usd)} quoted${p.charged_usd != null ? `, ${money(p.charged_usd)} charged` : ""}.`);
99
+ if (run.progress?.stage) lines.push(`Stage: ${run.progress.stage} (${run.progress.done}/${run.progress.total})`);
100
+ for (const q of run.questions ?? []) lines.push(`Question ${q.id}: ${q.text}${q.options ? ` [${q.options.join(" | ")}]` : ""}`);
101
+ if (run.error) lines.push(`Error: ${typeof run.error === "string" ? run.error : (run.error.message ?? JSON.stringify(run.error))}`);
102
+ return lines.join("\n");
103
+ }
104
+
105
+ const ENDED = new Set(["succeeded", "failed", "cancelled"]);
106
+
107
+ async function follow(run, { api, io, flags, json }) {
108
+ const timeoutS = flags.timeout === undefined ? 1800 : Number(flags.timeout);
109
+ const end = Date.now() + timeoutS * 1000;
110
+ const intervalMs = Math.max(250, Number(flags.interval ?? 10) * 1000);
111
+ while (!ENDED.has(run.status) && run.status !== "needs_input" && Date.now() < end) {
112
+ if (!json) io.stderr.write(".");
113
+ await io.sleep(intervalMs);
114
+ run = await api.getFormatRun(run.run_id);
115
+ }
116
+ if (!json) io.stderr.write("\n");
117
+ return run;
118
+ }
119
+
120
+ async function finish(run, ctx, { asked } = {}) {
121
+ const { api, io, flags, emit } = ctx;
122
+ const files = [];
123
+ const videos = run.output?.videos ?? [];
124
+ if (run.status === "succeeded" && flags.download !== false && (flags.wait || flags.out)) {
125
+ const stem = flags.out ? path.resolve(io.cwd, flags.out) : path.join(io.cwd, run.run_id);
126
+ for (let i = 0; i < videos.length; i++) {
127
+ const parsed = path.parse(stem);
128
+ const dest = videos.length === 1 && flags.out ? stem : path.join(parsed.dir, `${parsed.name}${videos.length > 1 ? `-${i + 1}` : ""}${flags.out && parsed.ext ? parsed.ext : ".mp4"}`);
129
+ files.push({ path: dest, bytes: await api.download(videos[i].url, dest, { writeFile: io.writeFile }) });
130
+ }
131
+ }
132
+ emit({ ...run, ...(files.length ? { files } : {}) }, () => {
133
+ const lines = [showRun(run)];
134
+ for (const f of files) lines.push(`Saved ${f.path} (${f.bytes.toLocaleString("en-US")} bytes)`);
135
+ if (run.status === "succeeded" && !files.length) for (const v of videos) lines.push(v.url);
136
+ if (run.status === "queued" || run.status === "running") lines.push(`Check again: vidlab format get ${run.run_id} --wait`);
137
+ return lines.join("\n");
138
+ });
139
+ // A run the caller stopped (format cancel) ended as asked: 0. One that failed or was closed on its own: 3.
140
+ if (run.status === "cancelled" && asked === "cancel") return 0;
141
+ if (run.status === "failed" || run.status === "cancelled") return 3;
142
+ if (run.status === "needs_input") return EXIT_NEEDS_INPUT;
143
+ if (!ENDED.has(run.status) && flags.wait) return 4;
144
+ return 0;
145
+ }
146
+
147
+ /** Walks the questions at a terminal: the answers a person types, the price as a yes or no. */
148
+ async function askThrough(run, { api, io, note }) {
149
+ while (run.status === "needs_input" && (run.questions ?? []).length) {
150
+ const answers = {};
151
+ for (const q of run.questions) {
152
+ if (q.id === "confirm_price") {
153
+ const yes = (await askLine(io, `${q.text} [y/N] `)).toLowerCase();
154
+ answers.confirm_price = yes === "y" || yes === "yes" ? "approve" : "cancel";
155
+ } else {
156
+ const hint = q.options ? ` (${q.options.join(" / ")})` : "";
157
+ answers[q.id] = await askLine(io, `${q.text}${hint} `);
158
+ }
159
+ }
160
+ run = await api.answerFormatRun(run.run_id, answers);
161
+ note(`Sent ${Object.keys(answers).length} answer${Object.keys(answers).length === 1 ? "" : "s"}.`);
162
+ }
163
+ return run;
164
+ }
165
+
166
+ export async function cmdFormat(ctx) {
167
+ const { rest, flags, api, io, json, note } = ctx;
168
+ const [sub, ...args] = rest;
169
+ if (!sub) throw new UsageError("Usage: vidlab format <id> | run <id> | answer <run> | get <run> | cancel <run>");
170
+ if (sub === "run") {
171
+ if (!args[0]) throw new UsageError('Usage: vidlab format run <format id> [--input name=value ...] [--max-price usd] [--wait] [--out file]');
172
+ const def = await api.getFormat(args[0]);
173
+ const types = Object.fromEntries((def.inputs ?? []).map((i) => [i.name, i.type]));
174
+ const inputs = pairs(flags.input, "--input");
175
+ for (const [k, v] of Object.entries(inputs)) if (["image", "video", "audio"].includes(types[k])) inputs[k] = await linkOf(v, { api, io, note });
176
+ const body = { inputs };
177
+ if (flags["max-price"] !== undefined) {
178
+ const max = Number(flags["max-price"]);
179
+ if (!Number.isFinite(max) || max < 0) throw new UsageError("--max-price takes US dollars, e.g. --max-price 8");
180
+ body.max_price_usd = max;
181
+ }
182
+ let run = await api.startFormatRun(args[0], body, flags["idempotency-key"]);
183
+ if (!json) note(`Started ${run.run_id} (${run.format?.name ?? args[0]}).`);
184
+ if (run.status === "needs_input" && !json && io.interactive !== false && (io.stdinIsTTY ?? process.stdin.isTTY)) run = await askThrough(run, ctx);
185
+ if (flags.wait && !ENDED.has(run.status) && run.status !== "needs_input") run = await follow(run, ctx);
186
+ if (run.status === "needs_input" && !json) note(`It needs answers. Answer: vidlab format answer ${run.run_id} ${(run.questions ?? []).map((q) => (q.id === "confirm_price" ? "confirm_price=approve" : `${q.id}="..."`)).join(" ")}${flags.wait ? " --wait" : ""}`);
187
+ return finish(run, ctx);
188
+ }
189
+ if (sub === "answer") {
190
+ if (!args[0] || args.length < 2) throw new UsageError('Usage: vidlab format answer <run id> name=value [name=value ...] [--wait] [--out file]');
191
+ let run = await api.answerFormatRun(args[0], pairs(args.slice(1), "an answer"));
192
+ if (flags.wait && !ENDED.has(run.status) && run.status !== "needs_input") run = await follow(run, ctx);
193
+ return finish(run, ctx);
194
+ }
195
+ if (sub === "get" || sub === "cancel") {
196
+ if (!args[0]) throw new UsageError(`Usage: vidlab format ${sub} <run id>${sub === "get" ? " [--wait] [--out file]" : ""}`);
197
+ let run = sub === "get" ? await api.getFormatRun(args[0]) : await api.cancelFormatRun(args[0]);
198
+ if (sub === "get" && flags.wait && !ENDED.has(run.status) && run.status !== "needs_input") run = await follow(run, ctx);
199
+ return finish(run, ctx, { asked: sub });
200
+ }
201
+ // vidlab format <id>: one format, its inputs.
202
+ const f = await api.getFormat(sub);
203
+ ctx.emit(f, () =>
204
+ [
205
+ `${f.name} (${f.id}): ${f.description ?? ""}`,
206
+ f.price?.note ? f.price.note : null,
207
+ "",
208
+ "Inputs:",
209
+ ...(f.inputs ?? []).map((i) => ` ${i.name.padEnd(20)} ${i.type}${i.required ? ", required" : ""}${i.options ? `: ${i.options.join(" | ")}` : ""}${i.description ? ` ${i.description}` : ""}`),
210
+ "",
211
+ `Start: vidlab format run ${f.id} --input name=value`,
212
+ ]
213
+ .filter((l) => l !== null)
214
+ .join("\n"),
215
+ );
216
+ return 0;
217
+ }
218
+
219
+ /* ------------------------------------------------------------------------------------------------ setup, skill */
220
+
221
+ const chosenClients = (flag, detected) => {
222
+ if (!flag || flag === "all") return flag === "all" ? [...CLIENT_IDS] : detected;
223
+ const list = flag.split(",").map((c) => c.trim());
224
+ const bad = list.filter((c) => !CLIENT_IDS.includes(c));
225
+ if (bad.length) throw new UsageError(`Unknown client "${bad[0]}". Clients: ${CLIENT_IDS.join(", ")}, all.`);
226
+ return list;
227
+ };
228
+
229
+ /**
230
+ * `vidlab setup`. VidLab's MCP is not open to members yet (the server's VIDLAB_API_MCP_PUBLIC, owner 2026-11-03): agents
231
+ * call the API with a key and the VidLab skill. So by default setup loads the skill into the agents found here (Claude
232
+ * Code, Codex) and checks VIDLAB_API_KEY with one free call. `--mcp` (not in the help) also adds VidLab's MCP server to
233
+ * Claude Code, Claude desktop, Cursor and Codex, but only when the server says its MCP is open: its MCP docs page
234
+ * (/vidlab-api/docs/mcp.md) is served only while VIDLAB_API_MCP_PUBLIC is on. Otherwise it stops before writing anything.
235
+ */
236
+ export async function cmdSetup({ flags, io, emit, note, baseUrl }) {
237
+ const home = io.home;
238
+ const dry = !!flags["dry-run"];
239
+ const withMcp = flags.mcp === true;
240
+ const envKey = io.env.VIDLAB_API_KEY?.trim() || "";
241
+ const auth = flags.auth ?? (envKey ? "key" : "oauth");
242
+ if (!["key", "oauth"].includes(auth)) throw new UsageError("--auth is key or oauth.");
243
+ if (flags.auth !== undefined && !withMcp) throw new UsageError("--auth is for --mcp: without it, setup only loads the skill and checks VIDLAB_API_KEY.");
244
+ if (withMcp && auth === "key" && !envKey && !dry) note("VIDLAB_API_KEY is not set in this shell. The config will read it when the client starts, so set it in your shell profile first.");
245
+ if (withMcp && !(await mcpOpenAt(baseUrl, io.fetch))) {
246
+ throw new ApiError(`VidLab's MCP is not open on ${baseUrl}. Run \`vidlab setup\` without --mcp: your agent uses the API with your key and the VidLab skill.`, { code: "mcp_not_open" });
247
+ }
248
+ const detected = detectClients({ home, env: io.env });
249
+ const clients = chosenClients(flags.client, detected);
250
+ const results = [];
251
+ if (withMcp) for (const c of clients) results.push(connectClient(c, { baseUrl, keyMode: auth === "key", dry, home, env: io.env, run: io.run }));
252
+ const skills = flags.skill !== false ? await installSkill({ clients, baseUrl, dry, home, env: io.env, fetch: io.fetch }) : [];
253
+ const key = dry ? { status: "skipped" } : await checkKey(envKey, baseUrl, io.fetch);
254
+ const keysPage = `${baseUrl}/vidlab-api/api-keys`;
255
+ const ok = results.every((r) => r.status !== "failed") && skills.every((r) => r.status !== "failed");
256
+ const report = {
257
+ ok,
258
+ base_url: baseUrl,
259
+ mode: withMcp ? "mcp" : "api",
260
+ ...(withMcp ? { mcp_url: mcpUrlOf(baseUrl), auth, clients: results } : {}),
261
+ detected,
262
+ skill: skills,
263
+ key,
264
+ ...(clients.length ? {} : { note: withMcp ? "No supported client found on this computer. Use --client claude-code|claude-desktop|cursor|codex, or see the docs for the URL." : "No Claude Code or Codex found on this computer. Name one with --client, or use: vidlab skill install --dir <folder>" }),
265
+ };
266
+ emit(report, () => {
267
+ const lines = [];
268
+ if (!clients.length) lines.push(withMcp ? `No Claude Code, Claude desktop, Cursor or Codex found here. Name one with --client, or add this URL to your client:\n ${mcpUrlOf(baseUrl)}` : "No Claude Code or Codex found here. Name one with --client, or save the skill where your agent reads skills: vidlab skill install --dir <folder>");
269
+ for (const r of results) lines.push(`${r.status === "failed" ? "x" : "+"} ${r.label}: ${r.status}${r.how ? ` (${r.how})` : ""}${r.next ? `\n ${r.next}` : ""}`);
270
+ for (const s of skills) lines.push(`${s.status === "failed" ? "x" : "+"} Skill${s.client ? ` for ${s.client}` : ""}: ${s.status} (${s.how})`);
271
+ if (clients.length && !skills.length && flags.skill !== false) lines.push("Skill: no client here reads skills (Claude Code and Codex do). Use: vidlab skill install --dir <folder>");
272
+ if (key.status === "ok") lines.push(`+ VIDLAB_API_KEY works: ${money(key.available_usd)} available.`);
273
+ else if (key.status === "missing") lines.push(`! VIDLAB_API_KEY is not set. Create a key at ${keysPage}, then add this to your shell profile (~/.zshrc or ~/.bashrc) and open a new terminal:\n export VIDLAB_API_KEY="vidlab_sk_your_key_here"`);
274
+ else if (key.status === "refused") lines.push(`x VIDLAB_API_KEY was refused (${key.code}). Create a new key at ${keysPage}.`);
275
+ else if (key.status === "unreachable") lines.push(`! Could not reach ${baseUrl} to check VIDLAB_API_KEY.`);
276
+ lines.push("");
277
+ if (withMcp) lines.push(auth === "key" ? "Clients read your key from VIDLAB_API_KEY. It is not written to any config." : "Clients sign in with your browser. No key is stored in any config.");
278
+ else lines.push("Your agent calls the VidLab API with the key in VIDLAB_API_KEY. Start it from a terminal where the variable is set. The key is not written anywhere.");
279
+ lines.push("Check: ask your agent to list three VidLab video models and the price of a 5 second clip.");
280
+ return lines.join("\n");
281
+ });
282
+ return ok && key.status !== "refused" ? 0 : 1;
283
+ }
284
+
285
+ /** Whether the server's MCP is open: its MCP docs page answers only then. A network failure counts as closed. */
286
+ async function mcpOpenAt(baseUrl, f = globalThis.fetch) {
287
+ try {
288
+ const res = await f(`${baseUrl}/vidlab-api/docs/mcp.md`, { headers: { accept: "text/markdown" }, signal: AbortSignal.timeout(10_000) });
289
+ return res.ok;
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
294
+
295
+ /** One free call with VIDLAB_API_KEY (GET /v1/balance): does the key work here? The key is never printed or kept. */
296
+ async function checkKey(key, baseUrl, f = globalThis.fetch) {
297
+ if (!key) return { status: "missing" };
298
+ try {
299
+ const res = await f(`${baseUrl}/v1/balance`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
300
+ const body = await res.json().catch(() => ({}));
301
+ if (res.ok) return { status: "ok", available_usd: Number(body?.data?.available_usd ?? 0) };
302
+ return { status: "refused", code: body?.error?.code ?? `http_${res.status}` };
303
+ } catch {
304
+ return { status: "unreachable" };
305
+ }
306
+ }
307
+
308
+ export async function cmdSkill({ rest, flags, io, emit, baseUrl }) {
309
+ const [sub] = rest;
310
+ if (sub !== "install" && sub !== "print") throw new UsageError("Usage: vidlab skill install [--client claude-code|codex|all] [--dir folder] | vidlab skill print");
311
+ if (sub === "print") {
312
+ const { fetchSkill } = await import("./setup.mjs");
313
+ const s = await fetchSkill(baseUrl, { fetch: io.fetch });
314
+ if (!s) throw new Error("The skill could not be fetched.");
315
+ emit({ from: s.from, text: s.text }, () => s.text);
316
+ return 0;
317
+ }
318
+ const clients = flags.dir ? [] : chosenClients(flags.client === undefined ? "claude-code,codex" : flags.client, []);
319
+ const results = await installSkill({ clients, dir: flags.dir, baseUrl, dry: !!flags["dry-run"], home: io.home, env: io.env, fetch: io.fetch });
320
+ emit({ ok: results.every((r) => r.status !== "failed"), skill: results }, () => results.map((s) => `${s.status === "failed" ? "x" : "+"} ${s.client ? `${s.client}: ` : ""}${s.status} (${s.how})`).join("\n"));
321
+ return results.every((r) => r.status !== "failed") ? 0 : 1;
322
+ }
323
+
324
+ export { skillDirOf };