Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

CLI: fuobe, the command line for a Fuobe server (models, estimate, generate, wait, download, skills, MCP)

Claude97914111ae02
diff --git a/bin/fuobe.mjs b/bin/fuobe.mjs
new file mode 100755
index 00000000..4ca6f851
--- /dev/null
+++ b/bin/fuobe.mjs
@@ -0,0 +1,65 @@
+#!/usr/bin/env node
+// fuobe: the Fuobe command line (Node 20+, no dependencies). It talks to a Fuobe server's REST API
+// and MCP endpoint; see docs/cli.md. The logic is in ./lib so tests can drive it without a terminal.
+import os from "node:os";
+import readline from "node:readline";
+import { main } from "./lib/cli.mjs";
+
+/** Ask on the terminal; `hidden` keeps a pasted token off the screen. */
+function ask(question, { hidden = false } = {}) {
+ const { stdin, stderr } = process;
+ if (!hidden || !stdin.isTTY) {
+ const rl = readline.createInterface({ input: stdin, output: stderr });
+ return new Promise((resolve) => rl.question(question, (answer) => (rl.close(), resolve(answer))));
+ }
+ return new Promise((resolve, reject) => {
+ stderr.write(question);
+ let value = "";
+ const done = (fn) => {
+ stdin.off("data", onData);
+ stdin.setRawMode(false);
+ stdin.pause();
+ stderr.write("\n");
+ fn();
+ };
+ const onData = (chunk) => {
+ for (const ch of chunk) {
+ if (ch === "\r" || ch === "\n") return done(() => resolve(value));
+ if (ch === "\u0003") return done(() => reject(new Error("Canceled")));
+ if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
+ else value += ch;
+ }
+ };
+ stdin.setEncoding("utf8");
+ stdin.setRawMode(true);
+ stdin.resume();
+ stdin.on("data", onData);
+ });
+}
+
+async function readStdin() {
+ let text = "";
+ for await (const chunk of process.stdin) text += chunk;
+ return text;
+}
+
+process.exitCode = await main(process.argv.slice(2), {
+ stdout: process.stdout,
+ stderr: process.stderr,
+ env: process.env,
+ cwd: process.cwd(),
+ home: os.homedir(),
+ fetch: globalThis.fetch,
+ columns: process.stdout.columns || 100,
+ stdinIsTTY: !!process.stdin.isTTY,
+ stderrIsTTY: !!process.stderr.isTTY,
+ now: () => Date.now(),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ /** Ctrl+C while waiting stops the wait (the job keeps running on the server). */
+ onInterrupt: (fn) => {
+ process.on("SIGINT", fn);
+ return () => process.off("SIGINT", fn);
+ },
+ ask,
+ readStdin,
+});
diff --git a/bin/lib/args.mjs b/bin/lib/args.mjs
new file mode 100644
index 00000000..9e274c72
--- /dev/null
+++ b/bin/lib/args.mjs
@@ -0,0 +1,145 @@
+// Command-line parsing for the fuobe CLI: long and short options, repeatable options,
+// `--name=value`, `--no-<flag>`, `--` and errors that say what to type instead. Pure (no I/O).
+
+/** A mistake in how the command was typed: printed with the command's usage, exit code 2. */
+export class UsageError extends Error {
+ /** @param {string} message @param {string} [command] */
+ constructor(message, command) {
+ super(message);
+ this.command = command;
+ }
+}
+
+/**
+ * @typedef {object} OptionSpec
+ * @property {"string" | "number" | "boolean"} type
+ * @property {string} [short] one-letter alias
+ * @property {boolean} [multiple] can be given more than once (the values come back as a list)
+ * @property {string[]} [choices]
+ * @property {string} [value] the placeholder shown in help ("file", "id")
+ * @property {string} [describe]
+ */
+
+/** Options every command takes. */
+export const GLOBAL_OPTIONS = /** @type {Record<string, OptionSpec>} */ ({
+ json: { type: "boolean", describe: "Print machine-readable JSON on stdout" },
+ url: { type: "string", value: "url", describe: "The Fuobe server (default: FUOBE_URL, then fuobe login, then http://localhost:3000)" },
+ token: { type: "string", value: "token", describe: "An API token (default: FUOBE_TOKEN, then fuobe login)" },
+ help: { type: "boolean", short: "h", describe: "Show help for the command" },
+});
+
+/** Edit distance where swapping two neighbouring letters counts once ("modle" → "model"), for "did you mean". */
+function distance(a, b) {
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
+ for (let i = 1; i <= a.length; i++) {
+ for (let j = 1; j <= b.length; j++) {
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
+ }
+ }
+ return d[a.length][b.length];
+}
+
+/** The closest of `names` to `word`, if it's close enough to be a typo. */
+export function suggest(word, names) {
+ let best = null;
+ let bestD = Infinity;
+ for (const n of names) {
+ const d = distance(word, n);
+ if (d < bestD) [best, bestD] = [n, d];
+ }
+ return best !== null && bestD <= Math.max(1, Math.floor(word.length / 3)) ? best : null;
+}
+
+function convert(name, spec, raw, command) {
+ if (spec.type === "number") {
+ const n = Number(raw);
+ if (raw.trim() === "" || !Number.isFinite(n)) throw new UsageError(`--${name} takes a number, not “${raw}”`, command);
+ return n;
+ }
+ if (spec.choices && !spec.choices.includes(raw)) {
+ const near = suggest(raw, spec.choices);
+ throw new UsageError(`--${name} is one of ${spec.choices.join(", ")}${near ? ` (did you mean ${near}?)` : ""}, not “${raw}”`, command);
+ }
+ return raw;
+}
+
+/**
+ * Parse `argv` against a command's options (plus the global ones).
+ * @param {string[]} argv
+ * @param {Record<string, OptionSpec>} options
+ * @param {string} [command] named in errors
+ * @returns {{ values: Record<string, any>, positionals: string[] }}
+ */
+export function parseArgs(argv, options, command) {
+ const specs = { ...GLOBAL_OPTIONS, ...options };
+ const byShort = new Map(Object.entries(specs).flatMap(([name, s]) => (s.short ? [[s.short, name]] : [])));
+ /** @type {Record<string, any>} */
+ const values = {};
+ const positionals = [];
+ const set = (name, spec, value) => {
+ if (spec.multiple) (values[name] ??= []).push(value);
+ else values[name] = value;
+ };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === "--") {
+ positionals.push(...argv.slice(i + 1));
+ break;
+ }
+ let name;
+ let inline;
+ if (arg.startsWith("--")) {
+ const eq = arg.indexOf("=");
+ name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
+ inline = eq === -1 ? undefined : arg.slice(eq + 1);
+ if (!specs[name] && name.startsWith("no-") && specs[name.slice(3)]?.type === "boolean") {
+ if (inline !== undefined) throw new UsageError(`--${name} doesn't take a value`, command);
+ values[name.slice(3)] = false;
+ continue;
+ }
+ } else if (/^-[A-Za-z]$/.test(arg)) {
+ name = byShort.get(arg.slice(1));
+ if (!name) throw new UsageError(`Unknown option ${arg}`, command);
+ } else {
+ // "-" alone (stdin) and negative numbers are values.
+ positionals.push(arg);
+ continue;
+ }
+ const spec = specs[name];
+ if (!spec) {
+ const near = suggest(name, Object.keys(specs));
+ throw new UsageError(`Unknown option --${name}${near ? ` — did you mean --${near}?` : ""}`, command);
+ }
+ if (spec.type === "boolean") {
+ if (inline !== undefined && !/^(true|false)$/.test(inline)) throw new UsageError(`--${name} doesn't take a value`, command);
+ set(name, spec, inline !== "false");
+ continue;
+ }
+ let raw = inline;
+ if (raw === undefined) {
+ if (i + 1 >= argv.length || (argv[i + 1].startsWith("--") && argv[i + 1].length > 2)) throw new UsageError(`--${name} needs a ${spec.value ?? "value"}`, command);
+ raw = argv[++i];
+ }
+ set(name, spec, convert(name, spec, raw, command));
+ }
+ return { values, positionals };
+}
+
+/** `key=value` pairs (from --param / --arg): numbers, booleans and JSON are read as such, the rest stays text. */
+export function keyValue(pair, flag = "--param") {
+ const eq = pair.indexOf("=");
+ if (eq <= 0) throw new UsageError(`${flag} takes key=value, not “${pair}”`);
+ const key = pair.slice(0, eq).trim();
+ const raw = pair.slice(eq + 1);
+ let value = raw;
+ if (/^(-?\d+(\.\d+)?|true|false|null)$/.test(raw.trim()) || /^[[{"]/.test(raw.trim())) {
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ value = raw;
+ }
+ }
+ return [key, value];
+}
diff --git a/bin/lib/build.mjs b/bin/lib/build.mjs
new file mode 100644
index 00000000..576c3b80
--- /dev/null
+++ b/bin/lib/build.mjs
@@ -0,0 +1,177 @@
+// Turning `fuobe generate` options into a POST /api/generations body, and the small pure helpers
+// around it (which inputs are local files, which model to use when none is named). No I/O.
+import { keyValue, suggest, UsageError } from "./args.mjs";
+
+/** Params the server reads at the top level of `params` (anything else from --param goes in `params.extra`). */
+const PARAMS = new Set([
+ "aspectRatio",
+ "resolution",
+ "duration",
+ "numOutputs",
+ "seed",
+ "generateAudio",
+ "enhancePrompt",
+ "draft",
+ "draftId",
+ "voice",
+ "targetLanguage",
+ "startTime",
+ "endTime",
+ "fps",
+ "styleId",
+ "sourceLanguage",
+ "numLayers",
+ "palette",
+ "multiShot",
+ "shots",
+ "dialogue",
+]);
+
+/** Already a reference the server reads itself: one of its own files, a public link or a data URI. */
+export const isRemoteRef = (ref) => /^(https?:\/\/|data:)/i.test(ref) || ref.startsWith("/api/files/");
+
+/**
+ * Every file option, in order, as [slot, ref]: `images` (and `endImage`, `mask`), one `video` or
+ * several (reference clips, `videos`), `audio`, `audio2` (a background track), `audios`
+ * (reference clips), `voiceAudio` (a voice to clone or change into) and `voiceAudio2` (a dialogue's
+ * second speaker).
+ * @param {Record<string, any>} v parsed options
+ * @returns {[string, string][]}
+ */
+export function fileInputs(v) {
+ const list = [];
+ for (const ref of v.image ?? []) list.push(["images", ref]);
+ if (v["end-image"]) list.push(["endImage", v["end-image"]]);
+ if (v.mask) list.push(["mask", v.mask]);
+ const videos = v.video ?? [];
+ if (videos.length === 1 && !v["ref-video"]?.length) list.push(["video", videos[0]]);
+ else for (const ref of [...videos, ...(v["ref-video"] ?? [])]) list.push(["videos", ref]);
+ const audios = v.audio ?? [];
+ if (audios.length > 1) throw new UsageError("Pass one --audio. A second track goes in --background-audio; reference clips in --ref-audio.", "generate");
+ if (audios[0]) list.push(["audio", audios[0]]);
+ if (v["background-audio"]) list.push(["audio2", v["background-audio"]]);
+ for (const ref of v["ref-audio"] ?? []) list.push(["audios", ref]);
+ const voices = v["voice-audio"] ?? [];
+ if (voices.length > 2) throw new UsageError("Pass at most two --voice-audio samples (one per speaker of a dialogue).", "generate");
+ if (voices[0]) list.push(["voiceAudio", voices[0]]);
+ if (voices[1]) list.push(["voiceAudio2", voices[1]]);
+ return list;
+}
+
+/** Local files among the inputs (each uploaded once, however often it's named). */
+export const localFiles = (inputs) => [...new Set(inputs.map(([, ref]) => ref).filter((ref) => !isRemoteRef(ref)))];
+
+/**
+ * The request body for POST /api/generations (and its `?preview=1`).
+ * @param {{ prompt?: string, modelId: string, values: Record<string, any>, uploaded?: Map<string, string> }} a
+ * `uploaded` maps each local path to the URL /api/uploads gave it.
+ */
+export function generationRequest({ prompt, modelId, values: v, uploaded = new Map() }) {
+ /** @type {Record<string, any>} */
+ const inputs = {};
+ for (const [slot, ref] of fileInputs(v)) {
+ const url = isRemoteRef(ref) ? ref : uploaded.get(ref);
+ if (!url) throw new Error(`${ref} wasn't uploaded`);
+ if (slot === "images" || slot === "videos" || slot === "audios") (inputs[slot] ??= []).push(url);
+ else inputs[slot] = url;
+ }
+ if ((inputs.images?.length ?? 0) > 14) throw new UsageError("Pass at most 14 images", "generate");
+ /** @type {Record<string, any>} */
+ const params = {};
+ if (v.aspect) params.aspectRatio = v.aspect;
+ if (v.resolution) params.resolution = v.resolution;
+ if (v.duration !== undefined) {
+ if (!(v.duration > 0)) throw new UsageError("--duration is a number of seconds above 0", "generate");
+ params.duration = v.duration;
+ }
+ if (v.count !== undefined) {
+ if (!Number.isInteger(v.count) || v.count < 1 || v.count > 8) throw new UsageError("--count is a whole number from 1 to 8", "generate");
+ params.numOutputs = v.count;
+ }
+ if (v.seed !== undefined) {
+ if (!Number.isInteger(v.seed)) throw new UsageError("--seed is a whole number", "generate");
+ params.seed = v.seed;
+ }
+ if (v.sound !== undefined) params.generateAudio = v.sound;
+ if (v.enhance !== undefined) params.enhancePrompt = v.enhance;
+ if (v.voice) params.voice = v.voice;
+ if (v.language) params.targetLanguage = v.language;
+ if (v["source-language"]) params.sourceLanguage = v["source-language"];
+ if (v.start !== undefined) params.startTime = v.start;
+ if (v.end !== undefined) params.endTime = v.end;
+ for (const pair of v.param ?? []) {
+ const [key, value] = keyValue(pair);
+ if (PARAMS.has(key)) params[key] = value;
+ else (params.extra ??= {})[key] = value;
+ }
+ const text = prompt?.trim();
+ return {
+ feature: "cli",
+ modelId,
+ ...(v.op && { op: v.op }),
+ ...(text && { prompt: text }),
+ ...(v.negative && { negativePrompt: v.negative }),
+ ...(Object.keys(inputs).length && { inputs }),
+ ...(Object.keys(params).length && { params }),
+ };
+}
+
+/**
+ * The studio's own model when none is named: the Image studio's (Edit's when there are images),
+ * Video's or Audio's, on the engine asked for (else cloud, unless the install is open source only).
+ * @param {{ engineMode?: string, defaults?: Record<string, { cloud?: string, open?: string }> }} list GET /api/models
+ * @param {{ kind?: string, engine?: string, hasImages?: boolean, hasMedia?: boolean }} want `hasMedia`: a video or audio input
+ */
+export function defaultModel(list, want) {
+ // A clip or a recording can go to many kinds of model (edit, extend, lipsync, transcribe…): that's the user's pick.
+ if (want.hasMedia) throw new UsageError("Name the model for a video or audio input with --model (fuobe models --search lipsync, for example).", "generate");
+ const kind = want.kind ?? "image";
+ const key = kind === "image" && want.hasImages ? "edit" : kind;
+ const engine = want.engine ?? (list.engineMode === "open" ? "open" : "cloud");
+ const id = list.defaults?.[key]?.[engine];
+ if (!id) {
+ const off = list.engineMode && list.engineMode !== "both" && list.engineMode !== engine;
+ throw new UsageError(
+ off
+ ? `This Fuobe runs ${list.engineMode === "open" ? "open-source" : "cloud"} models only (Settings → Engine mode). Leave out --engine, or pick a model with --model.`
+ : `There's no default ${engine === "open" ? "open-source" : "cloud"} ${kind} model. Pick one with --model (fuobe models --kind ${kind}).`,
+ "generate",
+ );
+ }
+ return id;
+}
+
+/** What the planner asks for ("Add a portrait and a voice track") → the options that give it. */
+const HINTS = [
+ [/voice sample for each/i, "--voice-audio <file> once per speaker"],
+ [/record the voice/i, "--voice-audio <file>"],
+ [/\bstart\b|image|photo|portrait|picture|\bface\b/i, "--image <file|url>"],
+ [/end frame/i, "--end-image <file|url>"],
+ [/paint the area/i, "--mask <file|url>"],
+ [/clips\b/i, "--video <file|url> for each clip"],
+ [/video|\bclip\b/i, "--video <file|url>"],
+ [/audio|voice track|soundtrack|recording/i, "--audio <file|url>"],
+ [/language/i, "--language <lang>"],
+];
+
+/**
+ * The server's reason a request can't run, with the command-line options that fix it:
+ * "Add a portrait and a voice track (use --image <file|url> and --audio <file|url>)". The message
+ * as it was when no option helps.
+ * @param {string} message
+ * @param {string[]} [modelIds] for "Unknown model …": the ids to suggest from
+ */
+export function withInputHint(message, modelIds = []) {
+ const unknown = /^Unknown model (\S+)/.exec(message);
+ if (unknown) {
+ const near = suggest(unknown[1], modelIds);
+ return `${message}.${near ? ` Did you mean ${near}?` : ""} fuobe models --search ${unknown[1].split(/[^a-z]+/i)[0] || unknown[1]} lists the ids.`;
+ }
+ if (/^Write a prompt/.test(message)) return `${message}: it goes in quotes after the command, as in fuobe generate "a red fox in the snow"`;
+ if (/^Write at least one line/.test(message)) return `${message} of the dialogue: --param 'dialogue=[{"text": "Hi!", "voice": "A"}, {"text": "Hello.", "voice": "B"}]'`;
+ if (!/^(Add|Pick)\b/.test(message)) return message;
+ const flags = HINTS.flatMap(([re, flag]) => (re.test(message) ? [flag] : [])).filter((f, i, all) => !(f === "--video <file|url>" && all.includes("--video <file|url> for each clip")));
+ if (!flags.length) return message;
+ const joined = flags.length === 1 ? flags[0] : `${flags.slice(0, -1).join(", ")} ${/audio or video/i.test(message) ? "or" : "and"} ${flags.at(-1)}`;
+ return `${message} (use ${joined})`;
+}
diff --git a/bin/lib/cli.mjs b/bin/lib/cli.mjs
new file mode 100644
index 00000000..7fec4f1a
--- /dev/null
+++ b/bin/lib/cli.mjs
@@ -0,0 +1,132 @@
+// The fuobe command line: picks the command, parses its options, connects to the server and
+// turns every failure into one readable line (or `{"error": …}` with --json).
+import fs from "node:fs";
+import { GLOBAL_OPTIONS, parseArgs, suggest, UsageError } from "./args.mjs";
+import { ApiError, createClient } from "./client.mjs";
+import { ALIASES, COMMANDS, EXIT } from "./commands.mjs";
+import { configPath, readConfig, resolveTarget } from "./config.mjs";
+
+export const VERSION = (() => {
+ try {
+ return JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version ?? "0.0.0";
+ } catch {
+ return "0.0.0";
+ }
+})();
+
+function optionLines(options) {
+ const rows = Object.entries(options).map(([name, s]) => {
+ const value = s.choices ? s.choices.join("|") : (s.value ?? (s.type === "number" ? "n" : "value"));
+ const flag = `${s.short ? `-${s.short}, ` : " "}--${name}${s.type === "boolean" ? "" : ` <${value}>`}`;
+ return [flag, s.describe ?? ""];
+ });
+ const width = Math.max(...rows.map(([f]) => f.length));
+ return rows.map(([f, d]) => ` ${f.padEnd(width)} ${d}`.trimEnd());
+}
+
+export function generalHelp() {
+ const names = Object.keys(COMMANDS);
+ const width = Math.max(...names.map((n) => n.length));
+ return [
+ `fuobe ${VERSION} — make images, video, audio and 3D with a Fuobe studio, from a terminal or an agent`,
+ "",
+ "Usage: fuobe <command> [options]",
+ "",
+ "Commands:",
+ ...names.map((n) => ` ${n.padEnd(width)} ${COMMANDS[n].summary}`),
+ "",
+ "Options for every command:",
+ ...optionLines(GLOBAL_OPTIONS),
+ "",
+ "The server is FUOBE_URL, else the one `fuobe login` saved, else http://localhost:3000. With a password",
+ "set on the server, the CLI needs an API token (Settings → Security → API tokens).",
+ "",
+ 'Start with: fuobe models --kind image, then fuobe generate "a red fox in the snow" --wait',
+ "More: fuobe <command> --help, and docs/cli.md",
+ ].join("\n");
+}
+
+export function commandHelp(name) {
+ const c = COMMANDS[name];
+ return [
+ `${c.summary}.`,
+ "",
+ `Usage: ${c.usage}`,
+ ...(c.options && Object.keys(c.options).length ? ["", "Options:", ...optionLines(c.options)] : []),
+ "",
+ "Options for every command:",
+ ...optionLines(GLOBAL_OPTIONS),
+ ...(c.examples?.length ? ["", "Examples:", ...c.examples.map((e) => ` ${e}`)] : []),
+ ].join("\n");
+}
+
+/**
+ * Run one command line. Returns the exit code.
+ * @param {string[]} argv the arguments after `fuobe`
+ * @param {object} io stdout / stderr streams, env, cwd, home, fetch, and the terminal helpers (see bin/fuobe.mjs)
+ */
+export async function main(argv, io) {
+ const print = (text) => {
+ io.stdout.write(`${text}\n`);
+ };
+ const wantsJson = argv.includes("--json");
+ const fail = (message, code, status) => {
+ if (wantsJson) io.stderr.write(`${JSON.stringify({ error: message, ...(status && { status }) })}\n`);
+ else io.stderr.write(`${message}\n`);
+ return code;
+ };
+
+ let [name, ...rest] = argv;
+ if (!name || name === "help" || name === "--help" || name === "-h") {
+ const about = rest[0] && (ALIASES[rest[0]] ?? rest[0]);
+ print(about && COMMANDS[about] ? commandHelp(about) : generalHelp());
+ return EXIT.ok;
+ }
+ if (name === "--version" || name === "-v" || name === "version") {
+ print(VERSION);
+ return EXIT.ok;
+ }
+ // `fuobe auth login` (Higgsfield's spelling) is `fuobe login`.
+ if (name === "auth") name = rest.shift() ?? "status";
+ name = ALIASES[name] ?? name;
+ const cmd = COMMANDS[name];
+ if (!cmd) {
+ const near = suggest(name, Object.keys(COMMANDS));
+ return fail(`Unknown command “${name}”.${near ? ` Did you mean fuobe ${near}?` : ""} Run fuobe --help for the list.`, EXIT.usage);
+ }
+
+ try {
+ const { values, positionals } = parseArgs(rest, cmd.options ?? {}, name);
+ if (values.help) {
+ print(commandHelp(name));
+ return EXIT.ok;
+ }
+ const target = { ...resolveTarget(values, io.env, readConfig(configPath(io.env, io.home))), fetch: io.fetch };
+ const connect = (t) => createClient({ fetch: io.fetch, ...t });
+ const ctx = {
+ command: name,
+ values,
+ positionals,
+ io,
+ target,
+ connect,
+ client: connect(target),
+ print,
+ note: (text) => io.stderr.write(`${text}\n`),
+ /** Print the --json result; returns the success exit code so `return ctx.json(…)` ends a command. */
+ json: (data) => {
+ print(JSON.stringify(data, null, 2));
+ return EXIT.ok;
+ },
+ };
+ return (await cmd.run(ctx)) ?? EXIT.ok;
+ } catch (e) {
+ if (e instanceof UsageError) {
+ const usage = e.command && COMMANDS[e.command] ? `\nUsage: ${COMMANDS[e.command].usage} (fuobe ${e.command} --help for more)` : "";
+ return fail(`${e.message}${wantsJson ? "" : usage}`, EXIT.usage);
+ }
+ if (e instanceof ApiError) return fail(e.message, EXIT.failed, e.status);
+ if (io.env.FUOBE_DEBUG) io.stderr.write(`${e?.stack ?? e}\n`);
+ return fail(e?.message ?? String(e), EXIT.failed);
+ }
+}
diff --git a/bin/lib/client.mjs b/bin/lib/client.mjs
new file mode 100644
index 00000000..3b1f2905
--- /dev/null
+++ b/bin/lib/client.mjs
@@ -0,0 +1,111 @@
+// The REST client: the API token goes to the Fuobe server only, and every failure becomes a
+// sentence that says what to do (start the server, create a token, fix the address).
+import fs from "node:fs";
+import path from "node:path";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+
+/** A request the server refused or couldn't be reached: `message` is for people, `status` for scripts. */
+export class ApiError extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/** Why a fetch never got an answer, in words. */
+export function networkMessage(err, url) {
+ const code = err?.cause?.code ?? err?.code;
+ const host = new URL(url).host;
+ if (code === "ECONNREFUSED") return `Can't reach Fuobe at ${url} (connection refused). Is the server running? Start it with "pnpm dev" or "pnpm start" in the Fuobe folder, or point FUOBE_URL at it.`;
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return `Can't find ${host}. Check the address (FUOBE_URL, --url or "fuobe login").`;
+ if (code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") return `Fuobe at ${url} didn't answer in time. Is the address right, and is the server running?`;
+ if (code === "ECONNRESET" || code === "UND_ERR_SOCKET") return `Fuobe at ${url} closed the connection. Try again; if it keeps happening, check the server's log.`;
+ if (/certificate|CERT|SSL/i.test(String(code ?? err?.cause?.message ?? ""))) return `Couldn't check ${host}'s HTTPS certificate (${err?.cause?.message ?? code}).`;
+ return `Couldn't reach Fuobe at ${url}: ${err?.cause?.message ?? err?.message ?? err}`;
+}
+
+/** What an error answer means, with the fix where there is one. */
+export function statusMessage(status, body, ctx) {
+ // The server's own sentence ({error}), or a short plain-text answer; never an HTML error page.
+ const said = body && typeof body === "object" && typeof body.error === "string" ? body.error : typeof body === "string" && body.trim() && body.length < 300 && !/^\s*</.test(body) ? body.trim() : "";
+ if (status === 401) {
+ return ctx.token
+ ? `Fuobe at ${ctx.url} refused the API token${ctx.tokenFrom ? ` (from ${ctx.tokenFrom})` : ""}. It may have been revoked: create a new one in Settings → Security → API tokens (${ctx.url}/settings#security), then run "fuobe login".`
+ : `Fuobe at ${ctx.url} has a password, so the CLI needs an API token. Create one in Settings → Security → API tokens (${ctx.url}/settings#security), then run "fuobe login" or set FUOBE_TOKEN.`;
+ }
+ if (status === 404 && !said) return `Not found on ${ctx.url}. Is it a Fuobe server, and up to date?`;
+ return said || `Fuobe answered HTTP ${status}${status >= 500 ? " — check the server's log" : ""}`;
+}
+
+/**
+ * @param {{ url: string, token?: string, tokenFrom?: string, fetch?: typeof fetch }} target
+ */
+export function createClient(target) {
+ const { url, token } = target;
+ const doFetch = target.fetch ?? globalThis.fetch;
+ const origin = new URL(url).origin;
+
+ /** Absolute URL for an API path or a server-relative file URL (kept under a path prefix); the token only rides to this server. */
+ const resolve = (p) => (/^https?:\/\//i.test(p) ? new URL(p) : new URL(`${url}${p.startsWith("/") ? "" : "/"}${p}`));
+ const headersFor = (u, extra = {}) => ({ ...extra, ...(token && u.origin === origin && { Authorization: `Bearer ${token}` }) });
+
+ async function send(method, p, opts = {}) {
+ const u = resolve(p);
+ for (const [k, v] of Object.entries(opts.query ?? {})) if (v !== undefined && v !== null && v !== "") u.searchParams.set(k, String(v));
+ const init = { method, headers: headersFor(u, opts.json !== undefined ? { "Content-Type": "application/json" } : {}) };
+ if (opts.json !== undefined) init.body = JSON.stringify(opts.json);
+ if (opts.form) init.body = opts.form;
+ let res;
+ try {
+ res = await doFetch(u, init);
+ } catch (e) {
+ throw new ApiError(networkMessage(e, url));
+ }
+ return res;
+ }
+
+ async function bodyOf(res) {
+ const text = await res.text();
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+ }
+
+ return {
+ url,
+ resolve: (p) => resolve(p).href,
+ /** JSON in, JSON out; throws ApiError with a readable message on any failure. */
+ async request(method, p, opts = {}) {
+ const res = await send(method, p, opts);
+ const body = await bodyOf(res);
+ if (!res.ok) throw new ApiError(statusMessage(res.status, body, target), res.status);
+ return body;
+ },
+ /** The raw response (for text such as a SKILL.md). */
+ async raw(method, p, opts = {}) {
+ const res = await send(method, p, opts);
+ if (!res.ok) throw new ApiError(statusMessage(res.status, await bodyOf(res), target), res.status);
+ return res;
+ },
+ /** Stream a file URL (an output) to `dest`; returns the bytes written. */
+ async download(fileUrl, dest) {
+ const res = await send("GET", fileUrl);
+ if (!res.ok || !res.body) throw new ApiError(`Couldn't download ${fileUrl}: ${statusMessage(res.status, await bodyOf(res), target)}`, res.status);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ const tmp = `${dest}.part`;
+ try {
+ await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(tmp));
+ } catch (e) {
+ fs.rmSync(tmp, { force: true });
+ throw new ApiError(`The download of ${fileUrl} broke off (${e.message}). Run the command again.`);
+ }
+ fs.renameSync(tmp, dest);
+ return fs.statSync(dest).size;
+ },
+ };
+}
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjs
new file mode 100644
index 00000000..366b0714
--- /dev/null
+++ b/bin/lib/commands.mjs
@@ -0,0 +1,823 @@
+// The fuobe commands. Each gets a context (`ctx`) with the parsed options, a REST client for the
+// server and the process's streams, so tests can run them without a terminal.
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { keyValue, UsageError } from "./args.mjs";
+import { defaultModel, fileInputs, generationRequest, localFiles, withInputHint } from "./build.mjs";
+import { ApiError } from "./client.mjs";
+import { configPath, normalizeUrl, readConfig, removeConfig, writeConfig } from "./config.mjs";
+import { clip, countOutputs, formatCost, formatDuration, previewText, statusText, table, TERMINAL, timeAgo } from "./format.mjs";
+import { findSkillDirs, packSkill, parseSource, skillHead } from "./skills.mjs";
+
+/** Exit codes: 0 done, 1 failed (a generation failed, the server said no), 2 usage, 3 still running at --timeout, 130 stopped with Ctrl+C. */
+export const EXIT = { ok: 0, failed: 1, usage: 2, timeout: 3, interrupted: 130 };
+
+const MAX_UPLOAD = 200 * 1024 * 1024;
+const UPLOAD_TYPES = {
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ webp: "image/webp",
+ gif: "image/gif",
+ mp4: "video/mp4",
+ m4v: "video/mp4",
+ mov: "video/quicktime",
+ webm: "video/webm",
+ mp3: "audio/mpeg",
+ wav: "audio/wav",
+ ogg: "audio/ogg",
+ oga: "audio/ogg",
+ flac: "audio/flac",
+ m4a: "audio/mp4",
+};
+
+// ---------------------------------------------------------------------------
+// Options shared by generate and estimate
+
+/** @typedef {import("./args.mjs").OptionSpec} OptionSpec */
+
+/** @type {OptionSpec} */
+const KIND = { type: "string", choices: ["image", "video", "audio"], value: "kind", describe: "With no --model: the studio whose default model to use (default image)" };
+/** @type {OptionSpec} */
+const ENGINE = { type: "string", choices: ["open", "cloud"], value: "engine", describe: "Open source (ComfyUI) or cloud; with no --model, picks that engine's default" };
+
+/** @type {Record<string, OptionSpec>} */
+export const GEN_OPTIONS = {
+ model: { type: "string", short: "m", value: "id", describe: "Model id (fuobe models); default: the studio's own pick" },
+ kind: KIND,
+ engine: ENGINE,
+ op: { type: "string", value: "op", describe: "Operation (t2i, edit, i2v, t2v, tts…), when the inputs leave it open" },
+ image: { type: "string", short: "i", multiple: true, value: "file|url", describe: "An image: the one to edit, the start frame, or references (repeat for more)" },
+ "end-image": { type: "string", value: "file|url", describe: "End frame (start + end frame video)" },
+ mask: { type: "string", value: "file|url", describe: "Inpaint mask" },
+ video: { type: "string", multiple: true, value: "file|url", describe: "The video to edit, extend, trim, lip-sync… (two or more: clips to join or reference)" },
+ "ref-video": { type: "string", multiple: true, value: "file|url", describe: "Reference clips (reference to video)" },
+ audio: { type: "string", multiple: true, value: "file|url", describe: "Audio: a voice to lip-sync, a track to mux, a recording to transcribe" },
+ "background-audio": { type: "string", value: "file|url", describe: "A second track mixed under --audio (mux)" },
+ "ref-audio": { type: "string", multiple: true, value: "file|url", describe: "Reference audio clips" },
+ "voice-audio": { type: "string", multiple: true, value: "file|url", describe: "A voice to clone (text to speech) or change into; a second one for a dialogue's other speaker" },
+ aspect: { type: "string", short: "a", value: "ratio", describe: "Aspect ratio, e.g. 16:9, 9:16, 1:1" },
+ duration: { type: "number", short: "d", value: "seconds", describe: "Length of a video or audio clip" },
+ resolution: { type: "string", short: "r", value: "res", describe: "e.g. 720p, 1080p, 2K" },
+ count: { type: "number", short: "n", value: "n", describe: "How many takes (1–8)" },
+ seed: { type: "number", value: "n" },
+ negative: { type: "string", value: "text", describe: "Negative prompt" },
+ sound: { type: "boolean", describe: "Native sound on (--no-sound for off), on video models that offer it" },
+ enhance: { type: "boolean", describe: "Let Fuobe rewrite the prompt first" },
+ voice: { type: "string", value: "id", describe: "Voice id for text to speech" },
+ language: { type: "string", value: "lang", describe: "Language to translate or dub into" },
+ "source-language": { type: "string", value: "lang", describe: "Spoken language of the source" },
+ start: { type: "number", value: "seconds", describe: "Trim: where the kept part starts" },
+ end: { type: "number", value: "seconds", describe: "Trim: where the kept part ends" },
+ param: { type: "string", short: "p", multiple: true, value: "key=value", describe: "Any other model setting (repeat for more)" },
+};
+
+/** @type {Record<string, OptionSpec>} */
+const WAIT_OPTIONS = {
+ timeout: { type: "number", value: "seconds", describe: "Stop waiting after this long (default 1800; 0 = no limit)" },
+ interval: { type: "number", value: "seconds", describe: "How often to check (default 2)" },
+};
+
+// ---------------------------------------------------------------------------
+// Helpers
+
+const enc = encodeURIComponent;
+
+/** The prompt from the positionals ("-" reads it from stdin). */
+async function promptFrom(ctx) {
+ const text = ctx.positionals.join(" ");
+ if (text !== "-") return text;
+ return (await ctx.io.readStdin()).trim();
+}
+
+/** Upload a local file through /api/uploads; returns its /api/files/… URL. */
+export async function uploadFile(ctx, file) {
+ const abs = path.resolve(ctx.io.cwd, file);
+ let st;
+ try {
+ st = fs.statSync(abs);
+ } catch {
+ throw new UsageError(`Can't find ${file}. Give a file path, an https:// link or a /api/files/… URL.`);
+ }
+ if (!st.isFile()) throw new UsageError(`${file} isn't a file`);
+ if (st.size > MAX_UPLOAD) throw new UsageError(`${file} is ${Math.round(st.size / 1024 / 1024)} MB; Fuobe takes files up to 200 MB`);
+ const ext = path.extname(abs).slice(1).toLowerCase();
+ const type = UPLOAD_TYPES[ext] ?? "application/octet-stream";
+ const blob = typeof fs.openAsBlob === "function" ? await fs.openAsBlob(abs, { type }) : new Blob([fs.readFileSync(abs)], { type });
+ const form = new FormData();
+ form.append("file", blob, path.basename(abs));
+ ctx.note(`Uploading ${file}…`);
+ const asset = await ctx.client.request("POST", "/api/uploads", { form });
+ return asset.url;
+}
+
+async function uploadAll(ctx, values) {
+ const uploaded = new Map();
+ for (const file of localFiles(fileInputs(values))) uploaded.set(file, await uploadFile(ctx, file));
+ return uploaded;
+}
+
+/** The model to use: --model, else the studio default for --kind / --engine (said on stderr). */
+async function modelFor(ctx) {
+ const v = ctx.values;
+ if (v.model) return v.model;
+ const inputs = fileInputs(v);
+ const list = await ctx.client.request("GET", "/api/models", { query: { kind: v.kind ?? "image" } });
+ const id = defaultModel(list, {
+ kind: v.kind,
+ engine: v.engine,
+ hasImages: inputs.some(([slot]) => slot === "images"),
+ // A voice sample with --kind audio is the voice the default speech model clones.
+ hasMedia: inputs.some(([slot]) => !["images", "endImage", "mask", ...(v.kind === "audio" ? ["voiceAudio", "voiceAudio2"] : [])].includes(slot)),
+ });
+ const name = list.items?.find((m) => m.id === id)?.name;
+ ctx.note(`Using ${name ? `${name} (${id})` : id}. Pick another with --model; fuobe models lists them.`);
+ return id;
+}
+
+function checkEngine(ctx, preview) {
+ const want = ctx.values.engine;
+ if (want && ctx.values.model && preview.engine !== want) {
+ throw new UsageError(
+ `${preview.modelName} is ${preview.engine === "open" ? "an open-source" : "a cloud"} model, but you asked for --engine ${want}. Pick a ${want === "open" ? "open-source" : "cloud"} model (fuobe models --engine ${want}) or leave out --engine.`,
+ ctx.command,
+ );
+ }
+}
+
+/** POST /api/generations, or its `?preview=1`; a request the planner refuses says which options fix it. */
+async function postGeneration(ctx, body, { preview = false } = {}) {
+ try {
+ return await ctx.client.request("POST", "/api/generations", { json: body, ...(preview && { query: { preview: 1 } }) });
+ } catch (e) {
+ if (!(e instanceof ApiError && e.status === 422)) throw e;
+ const ids = /^Unknown model /.test(e.message) ? await ctx.client.request("GET", "/api/models", { query: { hidden: 1 } }).then((r) => r.items.map((m) => m.id), () => []) : [];
+ throw new ApiError(withInputHint(e.message, ids), e.status);
+ }
+}
+
+const absolute = (ctx, url) => ctx.client.resolve(url);
+
+/** File name for output `i` of a generation: <id>.<ext>, or <id>-<n>.<ext> when it has several. */
+export function outputName(g, i) {
+ const ext = path.extname(new URL(g.outputs[i].url, "http://x").pathname) || ".bin";
+ return `${g.id}${g.outputs.length > 1 ? `-${i + 1}` : ""}${ext}`;
+}
+
+const megabytes = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
+
+/** Print finished generations: outputs as full URLs, text results inline. */
+function report(ctx, gens) {
+ for (const g of gens) {
+ const took = g.completedAt ? ` in ${formatDuration(g.completedAt - g.createdAt)}` : "";
+ const demo = g.provider === "mock" ? " (demo)" : "";
+ if (g.status === "succeeded") {
+ ctx.print(`Done ${g.id} · ${g.modelName ?? g.modelId} · ${countOutputs(g.outputs)}${took}${demo}`);
+ for (const o of g.outputs) {
+ ctx.print(` ${absolute(ctx, o.url)}`);
+ if (typeof o.text === "string") ctx.print(o.text.length > 4000 ? `${o.text.slice(0, 4000)}\n … ${o.text.length} characters in all; the whole text is at the URL above` : o.text);
+ }
+ } else if (g.status === "failed") ctx.print(`Failed ${g.id} · ${g.modelName ?? g.modelId}: ${g.error ?? "no reason given"}`);
+ else if (g.status === "canceled") ctx.print(`Canceled ${g.id} · ${g.modelName ?? g.modelId}`);
+ else ctx.print(`${g.id} · ${statusText(g)} · ${g.modelName ?? g.modelId}${g.message && !g.message.toLowerCase().startsWith(g.status) ? ` · ${g.message}` : ""}`);
+ }
+}
+
+/**
+ * Poll generations until every one is finished (or the timeout, or Ctrl+C). Shows progress on a
+ * terminal; prints a line per change otherwise (not with --json).
+ * @returns {Promise<{ gens: any[], stopped?: "timeout" | "interrupted" }>}
+ */
+export async function waitFor(ctx, ids) {
+ const v = ctx.values;
+ const timeout = (v.timeout ?? 1800) * 1000;
+ const interval = Math.max(0.2, v.interval ?? 2) * 1000;
+ const started = ctx.io.now();
+ const gens = new Map();
+ const seen = new Map();
+ let stop;
+ const stopped = new Promise((resolve) => (stop = resolve));
+ const off = ctx.io.onInterrupt(() => stop("interrupted"));
+ const live = ctx.io.stderrIsTTY && !v.json;
+ try {
+ for (;;) {
+ for (const id of ids) if (!TERMINAL.has(gens.get(id)?.status)) gens.set(id, await getGeneration(ctx, id));
+ const all = ids.map((id) => gens.get(id));
+ const done = all.filter((g) => TERMINAL.has(g.status)).length;
+ if (live) {
+ const one = all.length === 1 ? statusText(all[0]) : `${done} of ${all.length} done`;
+ ctx.io.stderr.write(`\r\x1b[2K${one} · ${formatDuration(ctx.io.now() - started)}`);
+ } else if (!v.json) {
+ for (const g of all) {
+ if (seen.get(g.id) !== g.status) ctx.note(`${g.id} ${g.status}${g.status === "failed" && g.error ? `: ${g.error}` : ""}`);
+ seen.set(g.id, g.status);
+ }
+ }
+ if (done === all.length) return { gens: all };
+ if (timeout > 0 && ctx.io.now() - started >= timeout) return { gens: all, stopped: "timeout" };
+ const why = await Promise.race([ctx.io.sleep(interval).then(() => null), stopped]);
+ if (why) return { gens: all, stopped: why };
+ }
+ } finally {
+ off();
+ if (live) ctx.io.stderr.write("\r\x1b[2K");
+ }
+}
+
+/** Save every output of the finished generations into `dir`. */
+async function saveOutputs(ctx, gens, dir) {
+ const files = [];
+ for (const g of gens) {
+ if (g.status !== "succeeded") continue;
+ for (let i = 0; i < g.outputs.length; i++) {
+ const dest = path.join(path.resolve(ctx.io.cwd, dir), outputName(g, i));
+ const bytes = await ctx.client.download(g.outputs[i].url, dest);
+ files.push({ id: g.id, url: absolute(ctx, g.outputs[i].url), path: dest, bytes });
+ if (!ctx.values.json) ctx.print(`Saved ${path.relative(ctx.io.cwd, dest) || dest} (${megabytes(bytes)})`);
+ }
+ }
+ return files;
+}
+
+/** Wait, report, download: shared by generate --wait, wait and download. Returns the exit code. */
+async function finish(ctx, ids, { download }) {
+ const { gens, stopped } = await waitFor(ctx, ids);
+ const files = download && !stopped ? await saveOutputs(ctx, gens, ctx.values.out ?? ".") : [];
+ if (ctx.values.json) ctx.json({ items: gens, ...(download && { files }), ...(stopped && { stopped }) });
+ else if (!download || stopped) report(ctx, gens);
+ else for (const g of gens.filter((x) => x.status !== "succeeded")) report(ctx, [g]);
+ if (stopped === "interrupted") {
+ ctx.note(`Stopped waiting. ${ids.length === 1 ? "It keeps" : "They keep"} running on the server: fuobe wait ${ids.join(" ")}`);
+ return EXIT.interrupted;
+ }
+ if (stopped === "timeout") {
+ ctx.note(`Still running after ${formatDuration((ctx.values.timeout ?? 1800) * 1000)}. Check again with: fuobe wait ${ids.join(" ")}`);
+ return EXIT.timeout;
+ }
+ return gens.every((g) => g.status === "succeeded") ? EXIT.ok : EXIT.failed;
+}
+
+/** One generation by id; an unknown id says so in words. */
+async function getGeneration(ctx, id) {
+ try {
+ const g = await ctx.client.request("GET", `/api/generations/${enc(id)}`);
+ if (g?.id) return g;
+ } catch (e) {
+ if (!(e instanceof ApiError && e.status === 404)) throw e;
+ }
+ throw new ApiError(`There's no generation ${id} on ${ctx.target.url} (it may be in the Trash). fuobe list shows recent ones.`, 404);
+}
+
+function needIds(ctx, what = "a generation id") {
+ if (!ctx.positionals.length) throw new UsageError(`Give ${what} (fuobe list shows recent ones)`, ctx.command);
+ return ctx.positionals;
+}
+
+// ---------------------------------------------------------------------------
+// login / logout / status
+
+async function login(ctx) {
+ const { io, values: v } = ctx;
+ const file = configPath(io.env, io.home);
+ const saved = readConfig(file);
+ let url = v.url ?? io.env.FUOBE_URL ?? (io.stdinIsTTY ? await io.ask(`Fuobe server [${saved.url ?? "http://localhost:3000"}]: `) : "") ?? "";
+ url = normalizeUrl(url.trim() || saved.url || "http://localhost:3000");
+ // Reachable, and does it ask for a token? (A 401 answers both.)
+ let needsToken = false;
+ try {
+ const probe = await ctx.connect({ url }).request("GET", "/api/generations", { query: { limit: 1 } });
+ if (!Array.isArray(probe?.items)) throw new ApiError(`${url} answered, but it doesn't look like a Fuobe server. Check the address.`);
+ } catch (e) {
+ if (!(e instanceof ApiError && e.status === 401)) throw e;
+ needsToken = true;
+ }
+ let token = v.token ?? io.env.FUOBE_TOKEN;
+ if (!token && needsToken) {
+ if (!io.stdinIsTTY) throw new ApiError(`Fuobe at ${url} has a password. Pass --token fuobe_… (create one in Settings → Security → API tokens, ${url}/settings#security).`, 401);
+ ctx.note(`This Fuobe has a password. Create an API token in Settings → Security → API tokens (${url}/settings#security) and paste it here.`);
+ token = (await io.ask("API token: ", { hidden: true })).trim();
+ }
+ if (token && !/^fuobe_[\w-]+$/.test(token)) ctx.note("That doesn't look like a Fuobe token (they start with fuobe_), but trying it anyway.");
+ if (token) await ctx.connect({ url, token }).request("GET", "/api/generations", { query: { limit: 1 } });
+ writeConfig(file, { url, ...(token && { token }) });
+ if (v.json) return ctx.json({ url, token: !!token, needsToken, config: file });
+ ctx.print(`Signed in to ${url}${token ? " with an API token" : needsToken ? "" : " (it has no password, so no token is needed)"}.`);
+ ctx.print(`Saved to ${file} (readable by you only). Try: fuobe models --kind image`);
+ return EXIT.ok;
+}
+
+async function logout(ctx) {
+ const file = configPath(ctx.io.env, ctx.io.home);
+ const removed = removeConfig(file);
+ if (ctx.values.json) return ctx.json({ removed, config: file });
+ ctx.print(removed ? `Removed ${file}.` : "You weren't signed in (no saved config).");
+ if (ctx.io.env.FUOBE_TOKEN) ctx.note("FUOBE_TOKEN is still set in your environment.");
+ return EXIT.ok;
+}
+
+async function status(ctx) {
+ if (ctx.positionals.length) {
+ const gens = [];
+ for (const id of ctx.positionals) gens.push(await getGeneration(ctx, id));
+ if (ctx.values.json) ctx.json(gens.length === 1 ? gens[0] : { items: gens });
+ else report(ctx, gens);
+ return gens.some((g) => g.status === "failed" || g.status === "canceled") ? EXIT.failed : EXIT.ok;
+ }
+ const s = await ctx.client.request("GET", "/api/status");
+ // Reads need the token too once a password is set: this says whether ours works.
+ await ctx.client.request("GET", "/api/generations", { query: { limit: 1 } });
+ const t = ctx.target;
+ if (ctx.values.json) return ctx.json({ url: t.url, urlFrom: t.urlFrom, token: !!t.token, tokenFrom: t.tokenFrom ?? null, ...s });
+ const providers = Object.values(s.providers ?? {})
+ .filter((p) => p.label)
+ .map((p) => `${p.label} ${p.configured ? "✓" : "–"}`);
+ ctx.print(`Fuobe at ${t.url}${t.urlFrom === "default" ? "" : ` (from ${t.urlFrom})`}`);
+ ctx.print(`Engine mode: ${s.engineMode} · Demo mode: ${s.demoMode} · Preferred cloud: ${s.cloudProvider}`);
+ ctx.print(`Providers: ${providers.join(", ")}`);
+ ctx.print(t.token ? `API token: accepted (from ${t.tokenFrom})` : "API token: none (this Fuobe has no password)");
+ return EXIT.ok;
+}
+
+// ---------------------------------------------------------------------------
+// models / estimate / generate / wait / download / list / cancel / upload
+
+async function models(ctx) {
+ const v = ctx.values;
+ const res = await ctx.client.request("GET", "/api/models", { query: { kind: v.kind, engine: v.engine, op: v.op, q: v.search ?? (ctx.positionals.join(" ") || undefined), hidden: v.hidden ? 1 : undefined } });
+ const items = v.limit ? res.items.slice(0, v.limit) : res.items;
+ if (v.json) return ctx.json({ ...res, items });
+ if (!items.length) {
+ ctx.print(`No models match.${res.engineMode !== "both" ? ` This Fuobe runs ${res.engineMode === "open" ? "open-source" : "cloud"} models only (Settings → Engine mode).` : ""}`);
+ return EXIT.ok;
+ }
+ const rows = items.map((m) => [m.id, m.name, m.engine === "open" ? "open" : "cloud", m.connected ? m.price : `${m.price} (demo)`, m.ops.join(", ")]);
+ ctx.print(table(["ID", "NAME", "ENGINE", "PRICE", "DOES"], rows, ctx.io.columns));
+ const demo = items.filter((m) => !m.connected).length;
+ ctx.note(`${items.length} model${items.length === 1 ? "" : "s"}${items.length < res.items.length ? ` of ${res.items.length}` : ""}.${demo ? " Those marked (demo) have no provider set up here yet: they return demo media, for free." : ""}`);
+ return EXIT.ok;
+}
+
+/** Local files aren't uploaded to price a run (or to check the options): a placeholder URL stands in for each. */
+const standIns = (values) => new Map(localFiles(fileInputs(values)).map((f) => [f, `/api/files/uploads/estimate/${path.basename(f)}`]));
+
+async function estimate(ctx) {
+ const prompt = await promptFrom(ctx);
+ const modelId = await modelFor(ctx);
+ const body = generationRequest({ prompt, modelId, values: ctx.values, uploaded: standIns(ctx.values) });
+ const p = await postGeneration(ctx, body, { preview: true });
+ checkEngine(ctx, p);
+ if (ctx.values.json) return ctx.json(p);
+ ctx.print(previewText(p));
+ return EXIT.ok;
+}
+
+async function generate(ctx) {
+ const v = ctx.values;
+ const prompt = await promptFrom(ctx);
+ const modelId = await modelFor(ctx);
+ // Built with stand-ins first, so a bad option or a missing input fails before anything is uploaded.
+ const draft = generationRequest({ prompt, modelId, values: v, uploaded: standIns(v) });
+ if ((v.engine && v.model) || localFiles(fileInputs(v)).length) checkEngine(ctx, await postGeneration(ctx, draft, { preview: true }));
+ const uploaded = await uploadAll(ctx, v);
+ const { items } = await postGeneration(ctx, generationRequest({ prompt, modelId, values: v, uploaded }));
+ const ids = items.map((g) => g.id);
+ if (v.wait || v.out) {
+ if (!v.json) ctx.note(`Started ${ids.length === 1 ? ids[0] : `${ids.length} jobs`} on ${items[0]?.modelName ?? modelId}${items[0]?.provider === "mock" ? " (demo: no provider connected)" : ""}.`);
+ return finish(ctx, ids, { download: !!v.out });
+ }
+ if (v.json) return ctx.json({ items });
+ const g = items[0];
+ ctx.print(`Started ${ids.join(" ")} on ${g?.modelName ?? modelId}${g?.provider === "mock" ? " (demo: no provider connected)" : ""}${g?.costUsd ? `, about ${formatCost(g.costUsd * items.length)}` : ""}.`);
+ ctx.print(`Wait for it: fuobe wait ${ids.join(" ")} Save it: fuobe download ${ids.join(" ")} --out .`);
+ return EXIT.ok;
+}
+
+async function wait(ctx) {
+ return finish(ctx, needIds(ctx), { download: !!ctx.values.out });
+}
+
+async function download(ctx) {
+ const ids = needIds(ctx);
+ if (ctx.values.wait === false) {
+ const gens = [];
+ for (const id of ids) gens.push(await getGeneration(ctx, id));
+ const pending = gens.filter((g) => !TERMINAL.has(g.status));
+ if (pending.length) throw new ApiError(`${pending.map((g) => g.id).join(", ")} ${pending.length === 1 ? "isn't" : "aren't"} finished yet (${pending.map(statusText).join(", ")}). Leave out --no-wait to wait for ${pending.length === 1 ? "it" : "them"}.`);
+ const files = await saveOutputs(ctx, gens, ctx.values.out ?? ".");
+ if (ctx.values.json) ctx.json({ items: gens, files });
+ else report(ctx, gens.filter((g) => g.status !== "succeeded"));
+ return gens.every((g) => g.status === "succeeded") ? EXIT.ok : EXIT.failed;
+ }
+ return finish(ctx, ids, { download: true });
+}
+
+async function list(ctx) {
+ const v = ctx.values;
+ const { items } = await ctx.client.request("GET", "/api/generations", { query: { kind: v.kind, limit: v.limit ?? 20, statuses: v.status, q: v.search, models: v.model } });
+ if (v.json) return ctx.json({ items });
+ if (!items.length) {
+ ctx.print("Nothing yet. Try: fuobe generate \"a red fox in the snow\" --wait");
+ return EXIT.ok;
+ }
+ const now = ctx.io.now();
+ ctx.print(table(["ID", "STATUS", "KIND", "MODEL", "CREATED", "PROMPT"], items.map((g) => [g.id, statusText(g), g.kind, g.modelName ?? g.modelId, timeAgo(g.createdAt, now), g.prompt ?? g.request?.title ?? ""]), ctx.io.columns));
+ return EXIT.ok;
+}
+
+async function cancel(ctx) {
+ const gens = [];
+ for (const id of needIds(ctx)) {
+ await getGeneration(ctx, id);
+ gens.push(await ctx.client.request("POST", `/api/generations/${enc(id)}/cancel`));
+ }
+ if (ctx.values.json) return ctx.json({ items: gens });
+ for (const g of gens) ctx.print(`${g.id} · ${statusText(g)}`);
+ return EXIT.ok;
+}
+
+async function upload(ctx) {
+ const files = needIds(ctx, "a file to upload");
+ const urls = [];
+ for (const f of files) urls.push({ file: f, url: await uploadFile(ctx, f) });
+ if (ctx.values.json) return ctx.json({ items: urls });
+ for (const u of urls) ctx.print(u.url);
+ ctx.note("Use these URLs as inputs: --image, --video, --audio, or a tool's arguments.");
+ return EXIT.ok;
+}
+
+// ---------------------------------------------------------------------------
+// skills
+
+async function skillsList(ctx) {
+ const { items } = await ctx.client.request("GET", "/api/assist/skills");
+ if (ctx.values.json) return ctx.json({ items });
+ ctx.print(table(["NAME", "ON", "SOURCE", "TITLE"], items.map((s) => [s.name, s.enabled ? "on" : "off", s.source === "builtin" ? "built-in" : "yours", s.title]), ctx.io.columns));
+ return EXIT.ok;
+}
+
+async function skillsShow(ctx, name) {
+ const res = await ctx.client.raw("GET", `/api/assist/skills/${enc(name)}/download`);
+ const md = await res.text();
+ if (ctx.values.json) return ctx.json({ name, markdown: md });
+ ctx.io.stdout.write(md.endsWith("\n") ? md : `${md}\n`);
+ return EXIT.ok;
+}
+
+async function skillsToggle(ctx, name, enabled) {
+ const s = await ctx.client.request("PATCH", `/api/assist/skills/${enc(name)}`, { json: { enabled } });
+ if (ctx.values.json) return ctx.json(s);
+ ctx.print(`/${s.name} is ${s.enabled ? "on: Assist and MCP clients can use it" : "off"}.`);
+ return EXIT.ok;
+}
+
+/** Upload one packed or single-file skill; returns a result line (ok or the server's reason). */
+async function sendSkill(ctx, fileName, data) {
+ const form = new FormData();
+ form.append("file", new Blob([data], { type: fileName.endsWith(".md") ? "text/markdown" : "application/zip" }), fileName);
+ try {
+ const r = await ctx.client.request("POST", "/api/assist/skills/upload", { form, query: { replace: ctx.values.replace ? 1 : undefined } });
+ return { ok: true, name: r.skill.name, title: r.skill.title, replaced: r.replaced, skipped: r.skipped ?? [] };
+ } catch (e) {
+ if (!(e instanceof ApiError) || e.status === 401 || e.status === undefined) throw e;
+ const hint = e.status === 409 && /already have/.test(e.message) ? " (add --replace to overwrite it)" : "";
+ return { ok: false, file: fileName, error: `${e.message}${hint}` };
+ }
+}
+
+/** Clone a repository (shallow) into a temporary folder; the caller removes it. */
+function clone(ctx, src) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skills-"));
+ ctx.note(`Cloning ${src.url}${src.ref ? ` (${src.ref})` : ""}…`);
+ const args = ["clone", "--depth", "1", "--quiet", ...(src.ref ? ["--branch", src.ref] : []), "--", src.url, dir];
+ const r = spawnSync("git", args, { stdio: ["ignore", "ignore", "pipe"], env: { ...ctx.io.env, GIT_TERMINAL_PROMPT: "0" }, encoding: "utf8" });
+ if (r.error?.code === "ENOENT") {
+ fs.rmSync(dir, { recursive: true, force: true });
+ throw new ApiError("git isn't installed. Download the skill as a .zip and run: fuobe skills add <file.zip>");
+ }
+ if (r.status !== 0) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ const why = (r.stderr || "").trim().split("\n").pop() || `git exited with ${r.status}`;
+ // GitHub asks for a login when a repository doesn't exist (or is private).
+ if (/could not read Username|Authentication failed|Repository not found|terminal prompts disabled/i.test(why)) {
+ throw new ApiError(`Couldn't clone ${src.url}: it doesn't exist, or it's private. Check the name, or download the skill as a .zip and run: fuobe skills add <file.zip>`);
+ }
+ if (src.ref && /Remote branch .* not found/i.test(why)) throw new ApiError(`${src.url} has no branch or tag ${src.ref}`);
+ throw new ApiError(`Couldn't clone ${src.url}: ${why}`);
+ }
+ return dir;
+}
+
+async function skillsAdd(ctx, source) {
+ const stat = (p) => {
+ try {
+ return fs.statSync(path.resolve(ctx.io.cwd, p));
+ } catch {
+ return null;
+ }
+ };
+ const src = parseSource(source, stat);
+ const wanted = new Set(ctx.values.skill ?? []);
+ const results = [];
+ let temp = null;
+ try {
+ if (src.type === "markdown" || src.type === "archive") {
+ const file = path.resolve(ctx.io.cwd, src.path);
+ results.push(await sendSkill(ctx, src.type === "markdown" ? "SKILL.md" : path.basename(file), fs.readFileSync(file)));
+ } else if (src.type === "link") {
+ ctx.note(`Downloading ${src.url}…`);
+ const res = await ctx.io.fetch(src.url);
+ if (!res.ok) throw new ApiError(`Couldn't download ${src.url} (HTTP ${res.status})`);
+ const name = /\.md(\?|$)/i.test(src.url) ? "SKILL.md" : path.basename(new URL(src.url).pathname);
+ results.push(await sendSkill(ctx, name, Buffer.from(await res.arrayBuffer())));
+ } else {
+ let root = src.type === "dir" ? path.resolve(ctx.io.cwd, src.path) : (temp = clone(ctx, src));
+ if (src.type === "git" && src.subpath) root = path.join(root, src.subpath);
+ const dirs = findSkillDirs(root).filter((d) => {
+ const head = skillHead(fs.readFileSync(path.join(d, "SKILL.md"), "utf8"));
+ const name = head.name ?? path.basename(d);
+ return wanted.size ? wanted.has(name) || wanted.has(path.basename(d)) : !head.internal;
+ });
+ if (!dirs.length) throw new ApiError(wanted.size ? `None of ${[...wanted].join(", ")} is in ${source}.` : `No SKILL.md found in ${source}.`);
+ for (const d of dirs) {
+ const packed = packSkill(d);
+ const r = await sendSkill(ctx, `${path.basename(d)}.zip`, packed.zip);
+ results.push({ ...r, ...(r.ok ? {} : { file: path.relative(root, d) || path.basename(d) }), skipped: [...new Set([...(r.skipped ?? []), ...packed.skipped])] });
+ }
+ }
+ } finally {
+ if (temp) fs.rmSync(temp, { recursive: true, force: true });
+ }
+ if (ctx.values.json) ctx.json({ items: results });
+ else {
+ for (const r of results) {
+ if (r.ok) ctx.print(`${r.replaced ? "Replaced" : "Added"} /${r.name} · ${r.title}${r.skipped.length ? ` (left out: ${r.skipped.join(", ")})` : ""}`);
+ else ctx.print(`Skipped ${r.file}: ${r.error}`);
+ }
+ if (results.some((r) => r.ok)) ctx.note("Type /name in Assist to use one; MCP clients get them as prompts.");
+ }
+ return results.some((r) => r.ok) ? EXIT.ok : EXIT.failed;
+}
+
+async function skills(ctx) {
+ const [sub, ...rest] = ctx.positionals;
+ const arg = (what) => {
+ if (!rest[0]) throw new UsageError(`fuobe skills ${sub} needs ${what}`, "skills");
+ return rest[0];
+ };
+ switch (sub ?? "list") {
+ case "list":
+ case "ls":
+ return skillsList(ctx);
+ case "show":
+ return skillsShow(ctx, arg("a skill name"));
+ case "add":
+ return skillsAdd(ctx, arg("a SKILL.md, a .zip / .skill file, a folder, owner/repo or a git URL"));
+ case "enable":
+ return skillsToggle(ctx, arg("a skill name"), true);
+ case "disable":
+ return skillsToggle(ctx, arg("a skill name"), false);
+ default:
+ throw new UsageError(`Unknown skills command “${sub}”: use list, show, add, enable or disable`, "skills");
+ }
+}
+
+// ---------------------------------------------------------------------------
+// MCP: tools, tool, mcp
+
+async function rpc(ctx, method, params) {
+ const res = await ctx.client.request("POST", "/api/mcp", { json: { jsonrpc: "2.0", id: 1, method, params } });
+ if (res?.error) throw new ApiError(res.error.message ?? "The MCP call failed");
+ return res.result;
+}
+
+async function tools(ctx) {
+ const { tools: list } = await rpc(ctx, "tools/list", {});
+ if (ctx.values.json) return ctx.json({ items: list });
+ ctx.print(table(["TOOL", "WHAT IT DOES"], list.map((t) => [t.name, t.description.split(/(?<=\.)\s/)[0]]), ctx.io.columns));
+ ctx.note('Run one with: fuobe tool <name> \'{"key": "value"}\' (or --arg key=value). fuobe tool <name> --schema shows its arguments.');
+ return EXIT.ok;
+}
+
+async function tool(ctx) {
+ const [name, json] = ctx.positionals;
+ if (!name) throw new UsageError("Name the tool (fuobe tools lists them)", "tool");
+ if (ctx.values.schema) {
+ const t = (await rpc(ctx, "tools/list", {})).tools.find((x) => x.name === name);
+ if (!t) throw new UsageError(`No tool called ${name} (fuobe tools lists them)`, "tool");
+ if (ctx.values.json) return ctx.json(t);
+ ctx.print(t.description);
+ ctx.print(JSON.stringify(t.inputSchema, null, 2));
+ return EXIT.ok;
+ }
+ let args = {};
+ if (json) {
+ const text = json === "-" ? await ctx.io.readStdin() : json;
+ try {
+ args = JSON.parse(text);
+ } catch {
+ throw new UsageError(`The arguments aren't valid JSON: ${clip(text, 60)}`, "tool");
+ }
+ }
+ for (const pair of ctx.values.arg ?? []) {
+ const [k, val] = keyValue(pair, "--arg");
+ args[k] = val;
+ }
+ const r = await rpc(ctx, "tools/call", { name, arguments: args });
+ const texts = (r.content ?? []).filter((c) => c.type === "text").map((c) => c.text);
+ if (r.isError) throw new ApiError(toolFailure(name, texts.join("\n")));
+ if (ctx.values.json) ctx.json(r.structuredContent ?? (texts.length === 1 ? parsed(texts[0]) : r));
+ else
+ for (const t of texts) {
+ const p = parsed(t);
+ ctx.print(typeof p === "string" ? p : JSON.stringify(p, null, 2));
+ }
+ return EXIT.ok;
+}
+
+/**
+ * Why a tool call failed, in words. A failed argument check comes back as a list of {path, message}
+ * ("jobs.0.model_id: Required."), a priced plan as {jobs: [{error}]}, anything else as its text.
+ */
+export function toolFailure(name, text) {
+ const p = parsed(text);
+ if (Array.isArray(p) && p.length && p.every((i) => i && typeof i.message === "string")) {
+ const issues = p.map((i) => `${Array.isArray(i.path) && i.path.length ? `${i.path.join(".")}: ` : ""}${i.message}.`).join(" ");
+ return `${name} needs other arguments: ${issues} (fuobe tool ${name} --schema lists them)`;
+ }
+ const errors = p && typeof p === "object" ? [p.error, ...(Array.isArray(p.jobs) ? p.jobs.map((j, i) => j?.error && `job ${i + 1}: ${j.error}`) : [])].filter((e) => typeof e === "string" && e) : [];
+ return `${name} failed: ${errors.length ? errors.join("; ") : text.trim() || "no reason given"}`;
+}
+
+const parsed = (text) => {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+};
+
+/** The command that connects Claude Code (and the JSON other MCP clients take). */
+export function mcpSetup(target) {
+ const endpoint = `${target.url}/api/mcp`;
+ const header = target.token ? ` --header "Authorization: Bearer ${target.token}"` : "";
+ return {
+ endpoint,
+ command: `claude mcp add --transport http fuobe ${endpoint}${header}`,
+ config: { mcpServers: { fuobe: { type: "http", url: endpoint, ...(target.token && { headers: { Authorization: `Bearer ${target.token}` } }) } } },
+ };
+}
+
+async function mcp(ctx) {
+ const setup = mcpSetup(ctx.target);
+ if (ctx.values.json) return ctx.json(setup);
+ ctx.print(setup.command);
+ ctx.note(`\nOther MCP clients (Claude Desktop, Cursor, Codex…) take this server entry:\n${JSON.stringify(setup.config, null, 2)}`);
+ if (ctx.target.token) ctx.note("These lines include your API token: keep them out of shared places.");
+ return EXIT.ok;
+}
+
+// ---------------------------------------------------------------------------
+
+/**
+ * @typedef {object} Command
+ * @property {string} summary
+ * @property {string} usage
+ * @property {Record<string, OptionSpec>} [options]
+ * @property {string[]} [examples]
+ * @property {(ctx: any) => Promise<number | void>} run
+ */
+
+/** @type {Record<string, Command>} */
+export const COMMANDS = {
+ login: {
+ summary: "Save the server address and API token",
+ usage: "fuobe login [--url <url>] [--token <token>]",
+ examples: ["fuobe login", "fuobe login --url https://studio.example.com --token fuobe_…"],
+ run: login,
+ },
+ logout: { summary: "Forget the saved address and token", usage: "fuobe logout", run: logout },
+ status: {
+ summary: "The server (engine, providers, sign-in), or the state of generations",
+ usage: "fuobe status [<id>…]",
+ examples: ["fuobe status", "fuobe status V1StGXR8_Z5j"],
+ run: status,
+ },
+ models: {
+ summary: "List the models you can run",
+ usage: "fuobe models [--kind <kind>] [--engine open|cloud] [--search <words>]",
+ options: {
+ kind: { type: "string", short: "k", choices: ["image", "video", "audio", "text", "model3d"], describe: "What it makes" },
+ engine: { type: "string", short: "e", choices: ["open", "cloud"], describe: "Open source (ComfyUI on your GPU) or cloud (paid APIs)" },
+ search: { type: "string", short: "s", value: "words", describe: "Words that must all match (name, vendor, what it does, id)" },
+ op: { type: "string", value: "op", describe: "Only models that run this operation (t2i, i2v, tts…)" },
+ hidden: { type: "boolean", describe: "Include the helper models studios use behind the scenes" },
+ limit: { type: "number", value: "n", describe: "Show at most n" },
+ },
+ examples: ["fuobe models --kind video --engine open", "fuobe models --search kling", "fuobe models --op tts --json"],
+ run: models,
+ },
+ estimate: {
+ summary: "Price a generation without running it",
+ usage: 'fuobe estimate "<prompt>" [--model <id>] [generate options]',
+ options: GEN_OPTIONS,
+ examples: ['fuobe estimate "a fox in the snow" --model nano-banana-pro --count 4', 'fuobe estimate "slow push-in" --model kling-3 --image still.png --duration 10'],
+ run: estimate,
+ },
+ generate: {
+ summary: "Make images, video, audio, 3D or text",
+ usage: 'fuobe generate "<prompt>" [--model <id>] [--image <file|url>]… [--wait] [--out <dir>]',
+ options: {
+ ...GEN_OPTIONS,
+ wait: { type: "boolean", short: "w", describe: "Wait until it's done and print the results" },
+ out: { type: "string", short: "o", value: "dir", describe: "Wait, then save the outputs here" },
+ ...WAIT_OPTIONS,
+ },
+ examples: [
+ 'fuobe generate "a red fox in fresh snow, golden hour" --wait',
+ 'fuobe generate "she turns and smiles" --model kling-3 --image portrait.jpg --aspect 9:16 --duration 5 --out .',
+ 'fuobe generate "a cosy cabin" --engine open --count 4 --wait',
+ 'fuobe generate "Welcome to the studio." --kind audio --out audio/',
+ ],
+ run: generate,
+ },
+ wait: {
+ summary: "Wait for generations to finish",
+ usage: "fuobe wait <id>… [--out <dir>] [--timeout <seconds>]",
+ options: { out: { type: "string", short: "o", value: "dir", describe: "Also save the outputs here" }, ...WAIT_OPTIONS },
+ examples: ["fuobe wait V1StGXR8_Z5j", "fuobe wait V1StGXR8_Z5j 3Kp9x2LmQa7c --out renders/"],
+ run: wait,
+ },
+ download: {
+ summary: "Save a generation's outputs (waits for it first)",
+ usage: "fuobe download <id>… [--out <dir>]",
+ options: {
+ out: { type: "string", short: "o", value: "dir", describe: "Folder to save into (default: here)" },
+ wait: { type: "boolean", describe: "Wait for unfinished ones (default; --no-wait fails instead)" },
+ ...WAIT_OPTIONS,
+ },
+ examples: ["fuobe download V1StGXR8_Z5j --out renders/"],
+ run: download,
+ },
+ list: {
+ summary: "Your recent generations",
+ usage: "fuobe list [--kind <kind>] [--limit <n>]",
+ options: {
+ kind: { type: "string", short: "k", choices: ["image", "video", "audio", "text", "model3d"], describe: "Only this kind of result" },
+ limit: { type: "number", short: "l", value: "n", describe: "How many (default 20, up to 200)" },
+ status: { type: "string", value: "status", describe: "queued, running, succeeded, failed or canceled (comma-separated)" },
+ search: { type: "string", short: "s", value: "words", describe: "Words in the prompt" },
+ model: { type: "string", short: "m", value: "id", describe: "Only this model's" },
+ },
+ examples: ["fuobe list --kind video --limit 5", "fuobe list --status failed --json"],
+ run: list,
+ },
+ cancel: { summary: "Stop queued or running generations", usage: "fuobe cancel <id>…", run: cancel },
+ upload: {
+ summary: "Upload files and print their URLs (to use as inputs)",
+ usage: "fuobe upload <file>…",
+ examples: ["fuobe upload product.png"],
+ run: upload,
+ },
+ skills: {
+ summary: "List, read, add, switch on or off Assist skills",
+ usage: "fuobe skills [list | show <name> | add <source> | enable <name> | disable <name>]",
+ options: {
+ skill: { type: "string", multiple: true, value: "name", describe: "add: only these skills from a folder or repository" },
+ replace: { type: "boolean", describe: "add: overwrite your own skill of the same name" },
+ },
+ examples: [
+ "fuobe skills list",
+ "fuobe skills add ./my-skill",
+ "fuobe skills add owner/repo --skill launch-video",
+ "fuobe skills add https://github.com/owner/repo/tree/main/skills/launch-video",
+ "fuobe skills disable katana",
+ ],
+ run: skills,
+ },
+ tools: { summary: "List the MCP tools (the studio jobs agents can run)", usage: "fuobe tools", run: tools },
+ tool: {
+ summary: "Run one MCP tool with JSON arguments",
+ usage: "fuobe tool <name> ['<json>' | -] [--arg key=value]… [--schema]",
+ options: {
+ arg: { type: "string", multiple: true, value: "key=value", describe: "One argument (values that read as JSON are JSON)" },
+ schema: { type: "boolean", describe: "Show the tool's description and arguments instead" },
+ },
+ examples: [
+ "fuobe tool search_models --arg kind=video --arg query=kling",
+ 'fuobe tool estimate_job \'{"tool": "katana", "arguments": {"reference": "/api/files/…", "photos": ["/api/files/…"]}}\'',
+ "fuobe tool katana --schema",
+ ],
+ run: tool,
+ },
+ mcp: {
+ summary: "Print the command that connects an agent over MCP",
+ usage: "fuobe mcp",
+ examples: ["fuobe mcp", "fuobe mcp --json"],
+ run: mcp,
+ },
+};
+
+/** Other names people type. */
+export const ALIASES = { ls: "list", gen: "generate", model: "models", skill: "skills" };
diff --git a/bin/lib/config.mjs b/bin/lib/config.mjs
new file mode 100644
index 00000000..554a42a0
--- /dev/null
+++ b/bin/lib/config.mjs
@@ -0,0 +1,78 @@
+// Where the CLI finds its server and token: --url / --token, then FUOBE_URL / FUOBE_TOKEN, then
+// the file `fuobe login` writes (~/.config/fuobe/config.json, readable by you only).
+import fs from "node:fs";
+import path from "node:path";
+import { UsageError } from "./args.mjs";
+
+export const DEFAULT_URL = "http://localhost:3000";
+
+/** The config file: FUOBE_CONFIG, else $XDG_CONFIG_HOME/fuobe/config.json, else ~/.config/fuobe/config.json. */
+export function configPath(env, home) {
+ if (env.FUOBE_CONFIG) return env.FUOBE_CONFIG;
+ return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "fuobe", "config.json");
+}
+
+/** @returns {{ url?: string, token?: string }} */
+export function readConfig(file) {
+ let text;
+ try {
+ text = fs.readFileSync(file, "utf8");
+ } catch {
+ return {};
+ }
+ try {
+ const data = JSON.parse(text);
+ return data && typeof data === "object" ? { ...(typeof data.url === "string" && { url: data.url }), ...(typeof data.token === "string" && { token: data.token }) } : {};
+ } catch {
+ throw new Error(`${file} isn't valid JSON. Run "fuobe login" again, or delete the file.`);
+ }
+}
+
+/** Save the config readable by you only (the folder 0700, the file 0600, also when it existed). */
+export function writeConfig(file, data) {
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
+ fs.chmodSync(file, 0o600);
+}
+
+export function removeConfig(file) {
+ try {
+ fs.unlinkSync(file);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** "localhost:3000" → "http://localhost:3000"; no trailing slash, no path beyond the server's own. */
+export function normalizeUrl(raw) {
+ const text = String(raw).trim();
+ const withScheme = /^[a-z][a-z\d+.-]*:\/\//i.test(text) ? text : `http://${text}`;
+ let u;
+ try {
+ u = new URL(withScheme);
+ } catch {
+ throw new UsageError(`“${raw}” isn't a server address — use something like http://localhost:3000`);
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") throw new UsageError(`The server address must start with http:// or https://, not ${u.protocol}//`);
+ return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
+}
+
+/**
+ * The server and token to use, and where each came from (shown by `fuobe status`).
+ * @param {{ url?: string, token?: string }} flags
+ * @param {Record<string, string | undefined>} env
+ * @param {{ url?: string, token?: string }} config
+ */
+export function resolveTarget(flags, env, config) {
+ const pick = (flag, envName) =>
+ flags[flag] ? { value: flags[flag], from: `--${flag}` } : env[envName] ? { value: env[envName], from: envName } : config[flag] ? { value: config[flag], from: "config" } : null;
+ const url = pick("url", "FUOBE_URL");
+ const token = pick("token", "FUOBE_TOKEN");
+ return {
+ url: normalizeUrl(url?.value ?? DEFAULT_URL),
+ urlFrom: url?.from ?? "default",
+ token: token?.value?.trim() || undefined,
+ tokenFrom: token?.from,
+ };
+}
diff --git a/bin/lib/format.mjs b/bin/lib/format.mjs
new file mode 100644
index 00000000..be17c4b2
--- /dev/null
+++ b/bin/lib/format.mjs
@@ -0,0 +1,81 @@
+// How the CLI writes things for people: prices, durations, status lines and aligned tables. Pure.
+
+export const TERMINAL = new Set(["succeeded", "failed", "canceled"]);
+
+/** $0.30, <$0.01, free, or "price unknown". */
+export function formatCost(usd) {
+ if (usd === null || usd === undefined) return "price unknown";
+ if (usd === 0) return "free";
+ if (usd < 0.01) return "<$0.01";
+ return `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(0)}`;
+}
+
+/** 0:04, 1:12, 1:02:03. */
+export function formatDuration(ms) {
+ const s = Math.max(0, Math.round(ms / 1000));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
+}
+
+/** "just now", "5 min ago", "3 h ago", "2 days ago". */
+export function timeAgo(ts, now = Date.now()) {
+ const s = Math.max(0, (now - ts) / 1000);
+ if (s < 60) return "just now";
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
+ if (s < 86_400) return `${Math.floor(s / 3600)} h ago`;
+ const d = Math.floor(s / 86_400);
+ return `${d} day${d === 1 ? "" : "s"} ago`;
+}
+
+const plural = (n, word) => `${n} ${word}${n === 1 ? "" : word.endsWith("s") ? "" : "s"}`;
+
+/** "1 image", "3 videos", "2 files". */
+export function countOutputs(outputs) {
+ if (!outputs.length) return "no output";
+ const kinds = [...new Set(outputs.map((o) => o.kind))];
+ const word = kinds.length === 1 ? { image: "image", video: "video", audio: "audio file", text: "text", model3d: "3D model" }[kinds[0]] ?? "file" : "file";
+ return word === "text" ? (outputs.length === 1 ? "text" : `${outputs.length} texts`) : plural(outputs.length, word);
+}
+
+/** A generation's state in words: "queued", "running 42%", "succeeded"… */
+export function statusText(g) {
+ // Progress is a fraction (0–1).
+ if (g.status === "running" && typeof g.progress === "number") return `running ${Math.round(g.progress * 100)}%`;
+ return g.status;
+}
+
+/** What a preview (POST /api/generations?preview=1) would run: model, operation, outputs, price. */
+export function previewText(p) {
+ const runs = p.jobs > 1 ? ` in ${p.jobs} jobs` : "";
+ const outputs = p.outputs ? `${plural(p.outputs, p.kind === "audio" ? "audio file" : p.kind === "model3d" ? "3D model" : p.kind === "text" ? "text" : p.kind)}${runs}` : "";
+ const price = p.demo ? "a demo (no provider connected), costs nothing" : p.engine === "open" ? "free (open source, your GPU)" : formatCost(p.costUsd) === "price unknown" ? "price unknown" : `about ${formatCost(p.costUsd)}`;
+ return `${p.modelName} (${p.engine === "open" ? "open source" : "cloud"}) · ${p.opLabel ?? p.op}${outputs ? ` · ${outputs}` : ""} · ${price}`;
+}
+
+/** Cut to `width` characters with an ellipsis. */
+export function clip(text, width) {
+ const s = String(text ?? "").replace(/\s+/g, " ").trim();
+ return width > 1 && s.length > width ? `${s.slice(0, width - 1)}…` : s;
+}
+
+/**
+ * Rows as aligned columns under a header; the last column takes what's left of `width`.
+ * @param {string[]} header
+ * @param {string[][]} rows
+ */
+export function table(header, rows, width = 100) {
+ const all = [header, ...rows].map((r) => r.map((c) => String(c ?? "")));
+ const widths = header.map((_, i) => (i === header.length - 1 ? 0 : Math.max(...all.map((r) => r[i].length))));
+ const fixed = widths.reduce((a, b) => a + b + 2, 0);
+ const last = Math.max(12, width - fixed);
+ return all
+ .map((r) =>
+ r
+ .map((c, i) => (i === r.length - 1 ? clip(c, last) : c.padEnd(widths[i])))
+ .join(" ")
+ .trimEnd(),
+ )
+ .join("\n");
+}
diff --git a/bin/lib/skills.mjs b/bin/lib/skills.mjs
new file mode 100644
index 00000000..73f59dd5
--- /dev/null
+++ b/bin/lib/skills.mjs
@@ -0,0 +1,112 @@
+// `fuobe skills add`: where a skill comes from (a SKILL.md, a .zip / .skill, a folder, a git repo
+// or a link), finding the skills in a folder the way the open `skills` CLI does, and packing one
+// skill folder for /api/assist/skills/upload.
+import fs from "node:fs";
+import path from "node:path";
+import { UsageError } from "./args.mjs";
+import { zipFiles } from "./zip.mjs";
+
+/** Text files a skill may carry next to SKILL.md (the server keeps these, and drops the rest). */
+export const TEXT_FILE = /\.(md|markdown|txt|json|ya?ml|csv|tsv|srt|vtt|html?|css|xml|js|mjs|ts|py|sh)$/i;
+/** The server's limits for the files beside SKILL.md. */
+export const MAX_FILES = 30;
+export const MAX_FILES_BYTES = 400_000;
+
+/** Folders the `skills` CLI looks in (the common ones; see its docs/creating-skills.md). */
+const CONTAINERS = ["skills", "skills/.curated", "skills/.experimental", "skills/.system", ".agents/skills", ".claude/skills", "data/skills"];
+const SKIP = new Set(["node_modules", ".git", "dist", "build", "__pycache__", ".next"]);
+
+/**
+ * What `fuobe skills add <source>` was given.
+ * @param {string} source
+ * @param {(p: string) => fs.Stats | null} stat a stat that returns null for a missing path
+ * @returns {{ type: "markdown" | "archive" | "dir", path: string } | { type: "git", url: string, ref?: string, subpath?: string } | { type: "link", url: string }}
+ */
+export function parseSource(source, stat) {
+ const s = source.trim();
+ const st = stat(s);
+ if (st?.isDirectory()) return { type: "dir", path: s };
+ if (st?.isFile()) {
+ if (/\.(zip|skill)$/i.test(s)) return { type: "archive", path: s };
+ if (/\.(md|markdown)$/i.test(s)) return { type: "markdown", path: s };
+ throw new UsageError(`${s} isn't a skill: give a SKILL.md, a .zip or .skill archive, a folder or a git repository`, "skills");
+ }
+ // https://github.com/owner/repo/tree/<ref>/<path>: one folder of a repository.
+ const tree = /^https:\/\/(github\.com|gitlab\.com)\/([^/]+)\/([^/]+?)(?:\.git)?\/(?:-\/)?tree\/([^/]+)(?:\/(.+?))?\/?$/.exec(s);
+ if (tree) return { type: "git", url: `https://${tree[1]}/${tree[2]}/${tree[3]}.git`, ref: tree[4], ...(tree[5] && { subpath: tree[5] }) };
+ if (/^https?:\/\/.+\.(zip|skill|md)(\?.*)?$/i.test(s)) return { type: "link", url: s };
+ if (/^(https?:\/\/|ssh:\/\/|git@|git:\/\/|file:\/\/)/.test(s) || /\.git$/.test(s)) return { type: "git", url: s };
+ // owner/repo: GitHub, as `npx skills add owner/repo` reads it.
+ if (/^[\w.-]+\/[\w.-]+$/.test(s) && !s.startsWith(".")) return { type: "git", url: `https://github.com/${s.replace(/\.git$/, "")}.git` };
+ throw new UsageError(`Can't find ${s}. Give a SKILL.md, a .zip or .skill archive, a folder, owner/repo or a git URL.`, "skills");
+}
+
+/** The frontmatter fields `skills add` needs: the name, and whether it's marked internal. */
+export function skillHead(markdown) {
+ const fm = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)?.[1] ?? "";
+ const name = /^name:\s*["']?([^"'\r\n#]+?)["']?\s*(?:#.*)?$/m.exec(fm)?.[1]?.trim() ?? null;
+ // metadata.internal: true (the skills CLI hides these unless asked for by name).
+ const internal = /^metadata:\s*\r?\n(?:[ \t]+.*\r?\n)*?[ \t]+internal:\s*true\s*$/m.test(fm);
+ return { name, internal };
+}
+
+/**
+ * Skill folders under `root`: the root itself when it has a SKILL.md, else the usual container
+ * folders (and folders right under the root) up to three levels deep, else any SKILL.md up to five
+ * levels down. A SKILL.md shadows anything nested below it.
+ * @returns {string[]} folder paths
+ */
+export function findSkillDirs(root) {
+ const has = (dir) => fs.existsSync(path.join(dir, "SKILL.md"));
+ if (has(root)) return [root];
+ const found = [];
+ const walk = (dir, depth) => {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ if (!e.isDirectory() || SKIP.has(e.name)) continue;
+ const sub = path.join(dir, e.name);
+ if (has(sub)) found.push(sub);
+ else if (depth > 1) walk(sub, depth - 1);
+ }
+ };
+ walk(root, 1);
+ for (const c of CONTAINERS) if (fs.existsSync(path.join(root, c))) walk(path.join(root, c), 3);
+ if (!found.length) walk(root, 5);
+ return [...new Set(found.map((d) => path.resolve(d)))].sort();
+}
+
+/**
+ * One skill folder as a zip for the upload: SKILL.md and the text files beside it (skipping
+ * dot-files, binaries and anything past the server's limits, which are listed in `skipped`).
+ */
+export function packSkill(dir) {
+ const folder = path.basename(path.resolve(dir));
+ const files = [{ name: `${folder}/SKILL.md`, data: fs.readFileSync(path.join(dir, "SKILL.md")) }];
+ const skipped = [];
+ let bytes = 0;
+ const walk = (sub) => {
+ for (const e of fs.readdirSync(path.join(dir, sub), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
+ const rel = sub ? `${sub}/${e.name}` : e.name;
+ if (e.name.startsWith(".") || SKIP.has(e.name)) continue;
+ if (e.isDirectory()) {
+ walk(rel);
+ continue;
+ }
+ if (!e.isFile() || rel === "SKILL.md") continue;
+ const data = fs.readFileSync(path.join(dir, rel));
+ if (!TEXT_FILE.test(rel) || data.includes(0) || files.length > MAX_FILES || bytes + data.length > MAX_FILES_BYTES) {
+ skipped.push(rel);
+ continue;
+ }
+ bytes += data.length;
+ files.push({ name: `${folder}/${rel}`, data });
+ }
+ };
+ walk("");
+ return { zip: zipFiles(files), files: files.map((f) => f.name.slice(folder.length + 1)), skipped };
+}
diff --git a/bin/lib/zip.mjs b/bin/lib/zip.mjs
new file mode 100644
index 00000000..2978cf0a
--- /dev/null
+++ b/bin/lib/zip.mjs
@@ -0,0 +1,81 @@
+// A minimal zip writer (deflate, or stored when that's smaller) for packing a skill folder before
+// it's uploaded to /api/assist/skills/upload. Node's zlib only; no zip64 (skills are small).
+import zlib from "node:zlib";
+
+const CRC_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+export function crc32(buf) {
+ let c = 0xffffffff;
+ for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+/** DOS date and time fields of a Date. */
+function dosTime(d) {
+ const time = (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2);
+ const date = (Math.max(0, d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate();
+ return { time, date };
+}
+
+/**
+ * Build a zip archive in memory.
+ * @param {{ name: string, data: Buffer }[]} files names use "/" between folders
+ * @param {Date} [when]
+ */
+export function zipFiles(files, when = new Date()) {
+ const { time, date } = dosTime(when);
+ const locals = [];
+ const central = [];
+ let offset = 0;
+ for (const f of files) {
+ const name = Buffer.from(f.name, "utf8");
+ const deflated = zlib.deflateRawSync(f.data);
+ const method = deflated.length < f.data.length ? 8 : 0;
+ const body = method === 8 ? deflated : f.data;
+ const crc = crc32(f.data);
+ const local = Buffer.alloc(30);
+ local.writeUInt32LE(0x04034b50, 0);
+ local.writeUInt16LE(20, 4); // version needed
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
+ local.writeUInt16LE(method, 8);
+ local.writeUInt16LE(time, 10);
+ local.writeUInt16LE(date, 12);
+ local.writeUInt32LE(crc, 14);
+ local.writeUInt32LE(body.length, 18);
+ local.writeUInt32LE(f.data.length, 22);
+ local.writeUInt16LE(name.length, 26);
+ local.writeUInt16LE(0, 28);
+ locals.push(local, name, body);
+ const entry = Buffer.alloc(46);
+ entry.writeUInt32LE(0x02014b50, 0);
+ entry.writeUInt16LE(20, 4); // version made by
+ entry.writeUInt16LE(20, 6);
+ entry.writeUInt16LE(0x0800, 8);
+ entry.writeUInt16LE(method, 10);
+ entry.writeUInt16LE(time, 12);
+ entry.writeUInt16LE(date, 14);
+ entry.writeUInt32LE(crc, 16);
+ entry.writeUInt32LE(body.length, 20);
+ entry.writeUInt32LE(f.data.length, 24);
+ entry.writeUInt16LE(name.length, 28);
+ entry.writeUInt32LE(offset, 42);
+ central.push(entry, name);
+ offset += 30 + name.length + body.length;
+ }
+ const centralSize = central.reduce((a, b) => a + b.length, 0);
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(files.length, 8);
+ end.writeUInt16LE(files.length, 10);
+ end.writeUInt32LE(centralSize, 12);
+ end.writeUInt32LE(offset, 16);
+ return Buffer.concat([...locals, ...central, end]);
+}
diff --git a/package.json b/package.json
index d07ea81f..33a0f6b1 100644
--- a/package.json
+++ b/package.json
@@ -2,6 +2,9 @@
"name": "fuobe",
"version": "0.1.0",
"private": true,
+ "bin": {
+ "fuobe": "bin/fuobe.mjs"
+ },
"scripts": {
"dev": "next dev",
"dev:clean": "rm -rf .next && next dev",
diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.ts
new file mode 100644
index 00000000..1e913c22
--- /dev/null
+++ b/tests/cli-run.test.ts
@@ -0,0 +1,267 @@
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { unzip } from "@/server/assist/unzip";
+
+/**
+ * The fuobe CLI as a child process against a stub of Fuobe's REST API: upload → generate → wait →
+ * download, the MCP bridge, skills add, login, and the messages for a missing token or server.
+ */
+
+const TOKEN = "fuobe_test-token";
+const CLI = path.join(process.cwd(), "bin/fuobe.mjs");
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-run-"));
+const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");
+
+interface Seen {
+ method: string;
+ path: string;
+ auth: string | null;
+ json?: unknown;
+ file?: { name: string; type: string; data: Buffer };
+}
+
+let server: http.Server;
+let base = "";
+let requireAuth = true;
+let seen: Seen[] = [];
+let polls = 0;
+
+const generation = (status: string, extra: Record<string, unknown> = {}) => ({
+ id: "gen1",
+ status,
+ progress: status === "running" ? 0.5 : status === "succeeded" ? 1 : null,
+ modelId: "nano-banana-pro",
+ modelName: "Nano Banana Pro",
+ provider: "fal",
+ kind: "image",
+ op: "edit",
+ prompt: "a red fox",
+ outputs: [],
+ error: null,
+ createdAt: 1_000,
+ completedAt: null,
+ ...extra,
+});
+
+async function body(req: http.IncomingMessage): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ return Buffer.concat(chunks);
+}
+
+beforeAll(async () => {
+ server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://stub");
+ const raw = await body(req);
+ const s: Seen = { method: req.method ?? "GET", path: url.pathname + url.search, auth: req.headers.authorization ?? null };
+ if (/json/.test(req.headers["content-type"] ?? "")) s.json = JSON.parse(raw.toString());
+ if (/multipart/.test(req.headers["content-type"] ?? "")) {
+ const form = await new Request("http://stub", { method: "POST", headers: { "content-type": req.headers["content-type"]! }, body: new Uint8Array(raw) }).formData();
+ const f = form.get("file") as File;
+ s.file = { name: f.name, type: f.type, data: Buffer.from(await f.arrayBuffer()) };
+ }
+ seen.push(s);
+ const send = (status: number, data: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(data));
+ };
+ if (requireAuth && s.auth !== `Bearer ${TOKEN}`) return send(401, { error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" });
+ const route = `${s.method} ${url.pathname}`;
+ if (route === "POST /api/uploads") return send(201, { id: "up1", url: "/api/files/uploads/2026-10-22/up1.png" });
+ if (route === "GET /api/models")
+ return send(200, { engineMode: "both", defaults: { image: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" }, edit: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } }, items: [{ id: "nano-banana-pro", name: "Nano Banana Pro" }] });
+ if (route === "POST /api/generations" && (s.json as { modelId?: string }).modelId === "kling-3") return send(422, { error: "Add a start frame" });
+ if (route === "POST /api/generations" && url.searchParams.get("preview") === "1")
+ return send(200, { modelId: "nano-banana-pro", modelName: "Nano Banana Pro", engine: "cloud", kind: "image", op: "edit", opLabel: "Edit", jobs: 1, outputs: 1, demo: false, providerId: "fal", costUsd: 0.15 });
+ if (route === "POST /api/generations") return send(201, { items: [generation("queued")] });
+ if (route === "GET /api/generations/gen1") {
+ polls++;
+ return send(200, polls < 2 ? generation("running") : generation("succeeded", { outputs: [{ url: "/api/files/outputs/2026-10-22/out1.png", kind: "image" }], completedAt: 5_000 }));
+ }
+ if (route === "GET /api/generations") return send(200, { items: [generation("succeeded")] });
+ if (route === "GET /api/files/outputs/2026-10-22/out1.png") {
+ res.writeHead(200, { "content-type": "image/png" });
+ return res.end(PNG);
+ }
+ if (route === "POST /api/mcp") {
+ const rpc = s.json as { id: number; params: { name: string; arguments: Record<string, unknown> } };
+ return send(200, { jsonrpc: "2.0", id: rpc.id, result: { content: [{ type: "text", text: JSON.stringify({ echo: rpc.params }) }], isError: false } });
+ }
+ if (route === "POST /api/assist/skills/upload") {
+ const entries = unzip(s.file!.data);
+ const md = entries.find((e) => e.name.endsWith("/SKILL.md"))!.data.toString();
+ const name = /name:\s*(\S+)/.exec(md)![1];
+ return send(201, { skill: { name, title: name }, skipped: [], replaced: false });
+ }
+ send(404, { error: "Not found" });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise((r) => server.close(r));
+ fs.rmSync(tmp, { recursive: true, force: true });
+});
+
+beforeEach(() => {
+ seen = [];
+ polls = 0;
+ requireAuth = true;
+});
+
+function run(args: string[], env: Record<string, string | undefined> = {}): Promise<{ code: number | null; stdout: string; stderr: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [CLI, ...args], {
+ cwd: tmp,
+ // Undefined values are left out of the child's environment.
+ env: { PATH: process.env.PATH, HOME: tmp, FUOBE_CONFIG: path.join(tmp, "config.json"), FUOBE_URL: base, FUOBE_TOKEN: TOKEN, ...env } as unknown as NodeJS.ProcessEnv,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
+ });
+}
+
+describe("fuobe CLI against a Fuobe server", () => {
+ it("uploads a local image, generates, waits and downloads the result", async () => {
+ fs.writeFileSync(path.join(tmp, "me.png"), PNG);
+ const r = await run(["generate", "a red fox", "--image", "me.png", "--aspect", "1:1", "--out", "renders", "--interval", "0.2"]);
+ expect(r.stderr).toContain("Using Nano Banana Pro (nano-banana-pro)");
+ expect(r.code).toBe(0);
+ expect(r.stdout).toMatch(/^Saved renders\/gen1\.png \(1 KB\)$/m);
+ expect(fs.readFileSync(path.join(tmp, "renders/gen1.png")).equals(PNG)).toBe(true);
+ // Every request carried the token.
+ expect(seen.every((s) => s.auth === `Bearer ${TOKEN}`)).toBe(true);
+ const upload = seen.find((s) => s.path === "/api/uploads")!;
+ expect(upload.file).toMatchObject({ name: "me.png", type: "image/png" });
+ expect(upload.file!.data.equals(PNG)).toBe(true);
+ // The default came from the edit studio (an image is attached); the request uses the uploaded URL.
+ expect(seen.find((s) => s.path.startsWith("/api/models"))!.path).toBe("/api/models?kind=image");
+ expect(seen.find((s) => s.path === "/api/generations" && s.method === "POST")!.json).toEqual({
+ feature: "cli",
+ modelId: "nano-banana-pro",
+ prompt: "a red fox",
+ inputs: { images: ["/api/files/uploads/2026-10-22/up1.png"] },
+ params: { aspectRatio: "1:1" },
+ });
+ expect(seen.filter((s) => s.path === "/api/generations/gen1").length).toBe(2);
+ });
+
+ it("prints JSON for scripts: generate without waiting, then wait", async () => {
+ const started = await run(["generate", "a red fox", "--model", "nano-banana-pro", "--json"]);
+ expect(started.code).toBe(0);
+ expect(JSON.parse(started.stdout).items[0]).toMatchObject({ id: "gen1", status: "queued" });
+ const waited = await run(["wait", "gen1", "--json", "--interval", "0.2"]);
+ expect(waited.code).toBe(0);
+ const out = JSON.parse(waited.stdout);
+ expect(out.items[0]).toMatchObject({ id: "gen1", status: "succeeded" });
+ expect(waited.stderr).toBe("");
+ });
+
+ it("prices a run without uploading anything, and refuses a model of the other engine", async () => {
+ fs.writeFileSync(path.join(tmp, "big.png"), PNG);
+ const r = await run(["estimate", "a red fox", "-m", "nano-banana-pro", "-i", "big.png"]);
+ expect(r.code).toBe(0);
+ expect(r.stdout.trim()).toBe("Nano Banana Pro (cloud) · Edit · 1 image · about $0.15");
+ expect(seen.some((s) => s.path === "/api/uploads")).toBe(false);
+ expect((seen.find((s) => s.path === "/api/generations?preview=1")!.json as { inputs: { images: string[] } }).inputs.images[0]).toMatch(/^\/api\/files\/uploads\/estimate\/big\.png$/);
+ const wrong = await run(["generate", "a red fox", "-m", "nano-banana-pro", "--engine", "open"]);
+ expect(wrong.code).toBe(2);
+ expect(wrong.stderr).toMatch(/Nano Banana Pro is a cloud model, but you asked for --engine open/);
+ expect(seen.some((s) => s.path === "/api/generations")).toBe(false);
+ });
+
+ it("runs MCP tools with JSON or key=value arguments", async () => {
+ const r = await run(["tool", "search_models", "--arg", "kind=video", "--arg", "query=kling"]);
+ expect(r.code).toBe(0);
+ expect(JSON.parse(r.stdout)).toEqual({ echo: { name: "search_models", arguments: { kind: "video", query: "kling" } } });
+ const j = await run(["tool", "estimate_job", '{"tool":"katana","arguments":{"reference":"/api/files/a.mp4"}}', "--json"]);
+ expect(JSON.parse(j.stdout).echo.arguments).toEqual({ tool: "katana", arguments: { reference: "/api/files/a.mp4" } });
+ });
+
+ it("adds skills from a folder as zips the server unpacks", async () => {
+ const dir = path.join(tmp, "my-skills");
+ for (const n of ["launch-video", "promo-card"]) {
+ fs.mkdirSync(path.join(dir, "skills", n), { recursive: true });
+ fs.writeFileSync(path.join(dir, "skills", n, "SKILL.md"), `---\nname: ${n}\ndescription: Does ${n}.\n---\n\n# ${n}\n`);
+ }
+ const r = await run(["skills", "add", "my-skills"]);
+ expect(r.code).toBe(0);
+ expect(r.stdout).toContain("Added /launch-video");
+ expect(r.stdout).toContain("Added /promo-card");
+ const uploads = seen.filter((s) => s.path.startsWith("/api/assist/skills/upload"));
+ expect(uploads.map((u) => u.file!.name)).toEqual(["launch-video.zip", "promo-card.zip"]);
+ const only = await run(["skills", "add", "my-skills", "--skill", "promo-card", "--replace", "--json"]);
+ expect(JSON.parse(only.stdout).items).toEqual([{ ok: true, name: "promo-card", title: "promo-card", replaced: false, skipped: [] }]);
+ expect(seen.at(-1)!.path).toBe("/api/assist/skills/upload?replace=1");
+ });
+
+ it("logs in: checks the token and saves it readable by you only", async () => {
+ const r = await run(["login", "--url", base, "--token", TOKEN], { FUOBE_TOKEN: undefined, FUOBE_URL: undefined });
+ expect(r.code).toBe(0);
+ expect(r.stdout).toContain(`Signed in to ${base} with an API token.`);
+ const file = path.join(tmp, "config.json");
+ expect(JSON.parse(fs.readFileSync(file, "utf8"))).toEqual({ url: base, token: TOKEN });
+ if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ // Later commands use the saved address and token.
+ const list = await run(["list", "--json"], { FUOBE_TOKEN: undefined, FUOBE_URL: undefined });
+ expect(list.code).toBe(0);
+ expect(seen.at(-1)).toMatchObject({ path: "/api/generations?limit=20", auth: `Bearer ${TOKEN}` });
+ const bad = await run(["login", "--url", base, "--token", "fuobe_wrong"], { FUOBE_TOKEN: undefined, FUOBE_URL: undefined });
+ expect(bad.code).toBe(1);
+ expect(bad.stderr).toMatch(/refused the API token/);
+ fs.rmSync(file);
+ });
+
+ it("explains a missing token and a server that isn't running", async () => {
+ const noToken = await run(["list"], { FUOBE_TOKEN: undefined });
+ expect(noToken.code).toBe(1);
+ expect(noToken.stderr).toMatch(/has a password, so the CLI needs an API token\. Create one in Settings → Security → API tokens/);
+ const json = await run(["models", "--json"], { FUOBE_TOKEN: undefined });
+ expect(JSON.parse(json.stderr)).toMatchObject({ status: 401 });
+ // A port nothing listens on.
+ const probe = http.createServer();
+ await new Promise<void>((r) => probe.listen(0, "127.0.0.1", r));
+ const port = (probe.address() as AddressInfo).port;
+ await new Promise((r) => probe.close(r));
+ const down = await run(["status"], { FUOBE_URL: `http://127.0.0.1:${port}` });
+ expect(down.code).toBe(1);
+ expect(down.stderr).toMatch(/Can't reach Fuobe at http:\/\/127\.0\.0\.1:\d+ \(connection refused\)\. Is the server running\?/);
+ });
+
+ it("names the options a refused request needs, and an unknown id in words", async () => {
+ fs.writeFileSync(path.join(tmp, "clip.mp4"), "not really a clip");
+ const refused = await run(["generate", "she smiles", "-m", "kling-3", "--video", "clip.mp4"]);
+ expect(refused.code).toBe(1);
+ expect(refused.stderr.trim()).toBe("Add a start frame (use --image <file|url>)");
+ // The request was checked before the clip was uploaded.
+ expect(seen.some((s) => s.path === "/api/uploads")).toBe(false);
+ const unknown = await run(["status", "nope"]);
+ expect(unknown.code).toBe(1);
+ expect(unknown.stderr).toMatch(/There's no generation nope on http:\/\/127\.0\.0\.1:\d+ \(it may be in the Trash\)\. fuobe list shows recent ones\./);
+ const cancel = await run(["cancel", "nope", "--json"]);
+ expect(JSON.parse(cancel.stderr)).toMatchObject({ status: 404 });
+ expect(seen.some((s) => s.path.endsWith("/cancel"))).toBe(false);
+ });
+
+ it("answers usage mistakes with exit code 2 and help with 0", async () => {
+ const typo = await run(["generat", "x"]);
+ expect(typo.code).toBe(2);
+ expect(typo.stderr).toMatch(/Did you mean fuobe generate\?/);
+ const help = await run(["generate", "--help"]);
+ expect(help.code).toBe(0);
+ expect(help.stdout).toMatch(/^Usage: fuobe generate/m);
+ const mcp = await run(["mcp"], { FUOBE_TOKEN: undefined });
+ expect(mcp.stdout.trim()).toBe(`claude mcp add --transport http fuobe ${base}/api/mcp`);
+ expect(seen).toHaveLength(0);
+ });
+});
diff --git a/tests/cli.test.ts b/tests/cli.test.ts
new file mode 100644
index 00000000..de1b9eb1
--- /dev/null
+++ b/tests/cli.test.ts
@@ -0,0 +1,380 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { keyValue, parseArgs, suggest, UsageError } from "../bin/lib/args.mjs";
+import { defaultModel, fileInputs, generationRequest, isRemoteRef, localFiles, withInputHint } from "../bin/lib/build.mjs";
+import { createClient, networkMessage, statusMessage } from "../bin/lib/client.mjs";
+import { GEN_OPTIONS, mcpSetup, outputName, toolFailure } from "../bin/lib/commands.mjs";
+import { configPath, normalizeUrl, readConfig, resolveTarget, writeConfig } from "../bin/lib/config.mjs";
+import { clip, countOutputs, formatCost, formatDuration, previewText, table } from "../bin/lib/format.mjs";
+import { findSkillDirs, packSkill, parseSource, skillHead } from "../bin/lib/skills.mjs";
+import { crc32, zipFiles } from "../bin/lib/zip.mjs";
+import { unzip } from "@/server/assist/unzip";
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-"));
+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
+
+const GEN = { ...GEN_OPTIONS, wait: { type: "boolean" as const, short: "w" }, out: { type: "string" as const, short: "o" } };
+const usage = (fn: () => unknown) => {
+ try {
+ fn();
+ } catch (e) {
+ expect(e).toBeInstanceOf(UsageError);
+ return (e as Error).message;
+ }
+ throw new Error("expected a UsageError");
+};
+
+describe("argument parsing", () => {
+ it("reads long, short, inline, repeated and negated options, and keeps the rest as positionals", () => {
+ const { values, positionals } = parseArgs(
+ ["a red fox", "-m", "kling-3", "--image=one.png", "-i", "https://x.test/two.png", "--duration", "5", "--no-sound", "-w", "--json", "--", "--not-an-option"],
+ GEN,
+ "generate",
+ );
+ expect(positionals).toEqual(["a red fox", "--not-an-option"]);
+ expect(values).toMatchObject({ model: "kling-3", image: ["one.png", "https://x.test/two.png"], duration: 5, sound: false, wait: true, json: true });
+ });
+
+ it("says what's wrong: unknown options with a suggestion, numbers, choices and missing values", () => {
+ expect(usage(() => parseArgs(["--modle", "x"], GEN))).toBe("Unknown option --modle — did you mean --model?");
+ expect(usage(() => parseArgs(["--duration", "five"], GEN))).toBe("--duration takes a number, not “five”");
+ expect(usage(() => parseArgs(["--engine", "opn"], GEN))).toMatch(/--engine is one of open, cloud \(did you mean open\?\), not “opn”/);
+ expect(usage(() => parseArgs(["--model"], GEN))).toBe("--model needs a id");
+ expect(usage(() => parseArgs(["--model", "--wait"], GEN))).toMatch(/needs/);
+ expect(usage(() => parseArgs(["-z"], GEN))).toBe("Unknown option -z");
+ expect(usage(() => parseArgs(["--wait=maybe"], GEN))).toMatch(/doesn't take a value/);
+ // A negative number is a value, not an option.
+ expect(parseArgs(["--seed", "-3"], GEN).values.seed).toBe(-3);
+ });
+
+ it("suggests close commands only", () => {
+ expect(suggest("genrate", ["generate", "models"])).toBe("generate");
+ expect(suggest("xyz", ["generate", "models"])).toBeNull();
+ });
+
+ it("reads key=value pairs as JSON when they look like it", () => {
+ expect(keyValue("stability=0.4")).toEqual(["stability", 0.4]);
+ expect(keyValue("draft=true")).toEqual(["draft", true]);
+ expect(keyValue('palette=["#ff0000"]')).toEqual(["palette", ["#ff0000"]]);
+ expect(keyValue("genre=film noir")).toEqual(["genre", "film noir"]);
+ expect(keyValue("x={broken")).toEqual(["x", "{broken"]);
+ expect(usage(() => keyValue("novalue"))).toMatch(/key=value/);
+ });
+});
+
+describe("the generation request", () => {
+ const parse = (argv: string[]) => parseArgs(argv, GEN, "generate").values;
+
+ it("maps the options to POST /api/generations, with local files replaced by their upload URLs", () => {
+ const v = parse([
+ "-m",
+ "kling-3",
+ "-i",
+ "me.png",
+ "-i",
+ "/api/files/uploads/a.png",
+ "--end-image",
+ "https://cdn.test/end.jpg",
+ "-a",
+ "9:16",
+ "-d",
+ "5",
+ "-n",
+ "2",
+ "--seed",
+ "7",
+ "--sound",
+ "--negative",
+ "blur",
+ "--language",
+ "Spanish",
+ "-p",
+ "stability=0.5",
+ "-p",
+ "resolution=1080p",
+ ]);
+ const inputs = fileInputs(v);
+ expect(localFiles(inputs)).toEqual(["me.png"]);
+ const body = generationRequest({ prompt: " she smiles ", modelId: "kling-3", values: v, uploaded: new Map([["me.png", "/api/files/uploads/up1.png"]]) });
+ expect(body).toEqual({
+ feature: "cli",
+ modelId: "kling-3",
+ prompt: "she smiles",
+ negativePrompt: "blur",
+ inputs: { images: ["/api/files/uploads/up1.png", "/api/files/uploads/a.png"], endImage: "https://cdn.test/end.jpg" },
+ params: { aspectRatio: "9:16", duration: 5, numOutputs: 2, seed: 7, generateAudio: true, targetLanguage: "Spanish", resolution: "1080p", extra: { stability: 0.5 } },
+ });
+ });
+
+ it("sends one video as the input video, several as clips, and audio to the right slots", () => {
+ expect(fileInputs(parse(["--video", "a.mp4"]))).toEqual([["video", "a.mp4"]]);
+ expect(fileInputs(parse(["--video", "a.mp4", "--video", "b.mp4"]))).toEqual([
+ ["videos", "a.mp4"],
+ ["videos", "b.mp4"],
+ ]);
+ expect(fileInputs(parse(["--audio", "v.wav", "--background-audio", "bed.mp3", "--ref-audio", "r.wav", "--voice-audio", "me.m4a"]))).toEqual([
+ ["audio", "v.wav"],
+ ["audio2", "bed.mp3"],
+ ["audios", "r.wav"],
+ ["voiceAudio", "me.m4a"],
+ ]);
+ expect(usage(() => fileInputs(parse(["--audio", "a.wav", "--audio", "b.wav"])))).toMatch(/--background-audio/);
+ // A dialogue's two speakers.
+ expect(fileInputs(parse(["--voice-audio", "a.wav", "--voice-audio", "b.wav"]))).toEqual([
+ ["voiceAudio", "a.wav"],
+ ["voiceAudio2", "b.wav"],
+ ]);
+ expect(usage(() => fileInputs(parse(["--voice-audio", "a", "--voice-audio", "b", "--voice-audio", "c"])))).toMatch(/at most two/);
+ });
+
+ it("answers the planner's “Add …” with the options that give it", () => {
+ expect(withInputHint("Add a start frame")).toBe("Add a start frame (use --image <file|url>)");
+ expect(withInputHint("Add a portrait and a voice track")).toBe("Add a portrait and a voice track (use --image <file|url> and --audio <file|url>)");
+ expect(withInputHint("Add a start and an end frame")).toBe("Add a start and an end frame (use --image <file|url> and --end-image <file|url>)");
+ expect(withInputHint("Add at least two clips to join")).toBe("Add at least two clips to join (use --video <file|url> for each clip)");
+ expect(withInputHint("Add the audio or video to split")).toBe("Add the audio or video to split (use --video <file|url> or --audio <file|url>)");
+ expect(withInputHint("Pick or record the voice to speak with")).toBe("Pick or record the voice to speak with (use --voice-audio <file>)");
+ expect(withInputHint("Pick a language to translate into")).toBe("Pick a language to translate into (use --language <lang>)");
+ expect(withInputHint("Write a prompt first")).toMatch(/in quotes after the command, as in fuobe generate "/);
+ expect(withInputHint("Unknown model kling3", ["kling-3", "seedance-2-5"])).toBe("Unknown model kling3. Did you mean kling-3? fuobe models --search kling lists the ids.");
+ // Anything else is left as the server said it.
+ expect(withInputHint("Connect fal.ai in Settings to run this model")).toBe("Connect fal.ai in Settings to run this model");
+ expect(withInputHint("Pick a camera motion or effect to mix in")).toBe("Pick a camera motion or effect to mix in");
+ });
+
+ it("refuses counts and durations the server would reject, before anything is uploaded", () => {
+ expect(usage(() => generationRequest({ modelId: "m", values: parse(["-n", "9"]) }))).toMatch(/1 to 8/);
+ expect(usage(() => generationRequest({ modelId: "m", values: parse(["-d", "0"]) }))).toMatch(/above 0/);
+ expect(usage(() => generationRequest({ modelId: "m", values: parse(["--seed", "1.5"]) }))).toMatch(/whole number/);
+ const many = Array.from({ length: 15 }, (_, i) => ["-i", `https://x.test/${i}.png`]).flat();
+ expect(usage(() => generationRequest({ modelId: "m", values: parse(many) }))).toMatch(/14 images/);
+ });
+
+ it("knows which references the server reads itself", () => {
+ expect(["https://a.test/x.png", "/api/files/uploads/x.png", "data:image/png;base64,AA"].every(isRemoteRef)).toBe(true);
+ expect(isRemoteRef("./x.png")).toBe(false);
+ });
+
+ it("picks the studio's model when none is named", () => {
+ const list = { engineMode: "both", defaults: { image: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" }, edit: { cloud: "nano-banana-pro", open: "oss-qwen-edit" }, video: { cloud: "seedance-2-5", open: "oss-wan22-14b-fast" } } };
+ expect(defaultModel(list, {})).toBe("nano-banana-pro");
+ expect(defaultModel(list, { engine: "open", hasImages: true })).toBe("oss-qwen-edit");
+ expect(defaultModel(list, { kind: "video", engine: "open" })).toBe("oss-wan22-14b-fast");
+ // An open-source-only install answers with its open picks only.
+ expect(defaultModel({ engineMode: "open", defaults: { image: { open: "oss-z-image-turbo" } } }, {})).toBe("oss-z-image-turbo");
+ expect(usage(() => defaultModel({ engineMode: "open", defaults: { image: { open: "oss-z-image-turbo" } } }, { engine: "cloud" }))).toMatch(/open-source models only/);
+ expect(usage(() => defaultModel(list, { hasMedia: true }))).toMatch(/--model/);
+ });
+});
+
+describe("output", () => {
+ it("formats prices, durations and counts", () => {
+ expect([formatCost(null), formatCost(0), formatCost(0.004), formatCost(0.3), formatCost(12.4)]).toEqual(["price unknown", "free", "<$0.01", "$0.30", "$12"]);
+ expect([formatDuration(4_000), formatDuration(72_000), formatDuration(3_723_000)]).toEqual(["0:04", "1:12", "1:02:03"]);
+ expect(countOutputs([{ kind: "image" }, { kind: "image" }])).toBe("2 images");
+ expect(countOutputs([{ kind: "audio" }])).toBe("1 audio file");
+ expect(countOutputs([{ kind: "image" }, { kind: "video" }])).toBe("2 files");
+ });
+
+ it("describes a preview", () => {
+ expect(previewText({ modelName: "Nano Banana Pro", engine: "cloud", opLabel: "Text to image", outputs: 2, jobs: 1, kind: "image", costUsd: 0.3, demo: false })).toBe(
+ "Nano Banana Pro (cloud) · Text to image · 2 images · about $0.30",
+ );
+ expect(previewText({ modelName: "Wan 2.2", engine: "open", op: "t2v", outputs: 1, jobs: 1, kind: "video", costUsd: 0, demo: false })).toMatch(/free \(open source/);
+ expect(previewText({ modelName: "Kling", engine: "cloud", opLabel: "Image to video", outputs: 2, jobs: 2, kind: "video", costUsd: 1, demo: true })).toBe(
+ "Kling (cloud) · Image to video · 2 videos in 2 jobs · a demo (no provider connected), costs nothing",
+ );
+ });
+
+ it("aligns tables and cuts the last column to the width", () => {
+ const t = table(["ID", "NAME", "DOES"], [["a", "Alpha", "x".repeat(80)], ["bbbb", "B", "short"]], 40).split("\n");
+ expect(t[0]).toBe("ID NAME DOES");
+ expect(t[1].length).toBeLessThanOrEqual(40);
+ expect(t[1].endsWith("…")).toBe(true);
+ expect(t[2]).toBe("bbbb B short");
+ expect(clip("a\n b", 10)).toBe("a b");
+ });
+
+ it("names downloaded files after the generation", () => {
+ const g = { id: "abc", outputs: [{ url: "/api/files/outputs/2026-10-22/x1.png" }, { url: "/api/files/outputs/2026-10-22/x2.mp4?v=1" }] };
+ expect([outputName(g, 0), outputName(g, 1)]).toEqual(["abc-1.png", "abc-2.mp4"]);
+ expect(outputName({ id: "z", outputs: [{ url: "/api/files/x/y.srt" }] }, 0)).toBe("z.srt");
+ });
+});
+
+describe("config and the server address", () => {
+ it("finds the config file", () => {
+ expect(configPath({}, "/home/me")).toBe("/home/me/.config/fuobe/config.json");
+ expect(configPath({ XDG_CONFIG_HOME: "/cfg" }, "/home/me")).toBe("/cfg/fuobe/config.json");
+ expect(configPath({ FUOBE_CONFIG: "/x.json" }, "/home/me")).toBe("/x.json");
+ });
+
+ it("takes flags over the environment over the saved config", () => {
+ const saved = { url: "http://saved:3000", token: "fuobe_saved" };
+ expect(resolveTarget({}, {}, {})).toMatchObject({ url: "http://localhost:3000", urlFrom: "default", token: undefined });
+ expect(resolveTarget({}, {}, saved)).toMatchObject({ url: "http://saved:3000", token: "fuobe_saved", tokenFrom: "config" });
+ expect(resolveTarget({}, { FUOBE_URL: "studio.lan:3000/", FUOBE_TOKEN: "fuobe_env" }, saved)).toMatchObject({ url: "http://studio.lan:3000", token: "fuobe_env", tokenFrom: "FUOBE_TOKEN" });
+ expect(resolveTarget({ url: "https://f.example.com", token: "fuobe_flag" }, { FUOBE_TOKEN: "fuobe_env" }, saved)).toMatchObject({ url: "https://f.example.com", tokenFrom: "--token" });
+ });
+
+ it("normalizes addresses and refuses what isn't one", () => {
+ expect(normalizeUrl("localhost:3000")).toBe("http://localhost:3000");
+ expect(normalizeUrl("https://host/fuobe/")).toBe("https://host/fuobe");
+ expect(usage(() => normalizeUrl("ftp://host"))).toMatch(/http:\/\/ or https:\/\//);
+ });
+
+ it("writes the config readable by its owner only", () => {
+ const file = path.join(tmp, "cfg", "fuobe", "config.json");
+ writeConfig(file, { url: "http://localhost:3000", token: "fuobe_x" });
+ expect(readConfig(file)).toEqual({ url: "http://localhost:3000", token: "fuobe_x" });
+ if (process.platform !== "win32") {
+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ expect(fs.statSync(path.dirname(file)).mode & 0o777).toBe(0o700);
+ }
+ fs.writeFileSync(file, "{nope");
+ expect(() => readConfig(file)).toThrow(/isn't valid JSON/);
+ expect(readConfig(path.join(tmp, "missing.json"))).toEqual({});
+ });
+});
+
+describe("the REST client", () => {
+ it("sends the token to the Fuobe server only, never to another host", async () => {
+ const seen: { url: string; auth: string | null }[] = [];
+ const fakeFetch = (async (u: URL, init: RequestInit) => {
+ seen.push({ url: String(u), auth: new Headers(init.headers).get("authorization") });
+ return new Response(JSON.stringify({ ok: true }), { status: 200 });
+ }) as unknown as typeof fetch;
+ const c = createClient({ url: "http://studio.lan:3000", token: "fuobe_secret", fetch: fakeFetch });
+ await c.request("GET", "/api/generations", { query: { limit: 1, kind: undefined } });
+ await c.request("GET", "https://elsewhere.test/file.png");
+ expect(seen).toEqual([
+ { url: "http://studio.lan:3000/api/generations?limit=1", auth: "Bearer fuobe_secret" },
+ { url: "https://elsewhere.test/file.png", auth: null },
+ ]);
+ // A server under a path prefix keeps it.
+ expect(createClient({ url: "https://host/fuobe" }).resolve("/api/files/x.png")).toBe("https://host/fuobe/api/files/x.png");
+ });
+
+ it("explains failures: no server, no token, a refused token, the server's own words", () => {
+ const refused = Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } });
+ expect(networkMessage(refused, "http://localhost:3000")).toMatch(/Is the server running\? Start it with "pnpm dev"/);
+ expect(networkMessage(Object.assign(new TypeError("fetch failed"), { cause: { code: "ENOTFOUND" } }), "http://nope.test")).toMatch(/Can't find nope\.test/);
+ const ctx = { url: "http://localhost:3000" };
+ expect(statusMessage(401, { error: "Sign in" }, ctx)).toMatch(/has a password, so the CLI needs an API token\. Create one in Settings → Security → API tokens \(http:\/\/localhost:3000\/settings#security\)/);
+ expect(statusMessage(401, null, { ...ctx, token: "fuobe_x", tokenFrom: "FUOBE_TOKEN" })).toMatch(/refused the API token \(from FUOBE_TOKEN\)/);
+ expect(statusMessage(422, { error: "Add an image" }, ctx)).toBe("Add an image");
+ expect(statusMessage(500, "<html>", ctx)).toMatch(/HTTP 500 — check the server's log/);
+ });
+
+ it("says why a tool call failed: argument checks, a priced plan's errors, or its text", () => {
+ const issues = JSON.stringify([{ path: ["jobs", 0, "model_id"], message: "Invalid input: expected string" }, { path: [], message: "Too many jobs" }]);
+ expect(toolFailure("estimate_cost", issues)).toBe(
+ "estimate_cost needs other arguments: jobs.0.model_id: Invalid input: expected string. Too many jobs. (fuobe tool estimate_cost --schema lists them)",
+ );
+ expect(toolFailure("estimate_cost", JSON.stringify({ jobs: [{ error: "Unknown model nope" }, {}], total: 0 }))).toBe("estimate_cost failed: job 1: Unknown model nope");
+ expect(toolFailure("katana", "Add 1–5 photos of the subject")).toBe("katana failed: Add 1–5 photos of the subject");
+ expect(toolFailure("katana", "")).toBe("katana failed: no reason given");
+ });
+
+ it("prints the MCP setup with the token only when there is one", () => {
+ expect(mcpSetup({ url: "http://localhost:3000" }).command).toBe("claude mcp add --transport http fuobe http://localhost:3000/api/mcp");
+ const s = mcpSetup({ url: "https://f.test", token: "fuobe_t" });
+ expect(s.command).toBe('claude mcp add --transport http fuobe https://f.test/api/mcp --header "Authorization: Bearer fuobe_t"');
+ expect(s.config.mcpServers.fuobe).toEqual({ type: "http", url: "https://f.test/api/mcp", headers: { Authorization: "Bearer fuobe_t" } });
+ });
+});
+
+describe("skills add", () => {
+ const stat = (p: string) => {
+ try {
+ return fs.statSync(p);
+ } catch {
+ return null;
+ }
+ };
+ const write = (rel: string, text: string) => {
+ const file = path.join(tmp, rel);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, text);
+ return file;
+ };
+ const skill = (name: string, extra = "") => `---\nname: ${name}\ndescription: Does ${name}.\n${extra}---\n\n# ${name}\n\nSteps.\n`;
+
+ it("reads where a skill comes from", () => {
+ const md = write("src/one/SKILL.md", skill("one"));
+ const zip = write("src/one.zip", "PK");
+ expect(parseSource(path.dirname(md), stat)).toEqual({ type: "dir", path: path.dirname(md) });
+ expect(parseSource(md, stat)).toEqual({ type: "markdown", path: md });
+ expect(parseSource(zip, stat)).toEqual({ type: "archive", path: zip });
+ expect(parseSource("workingprototype/Fuobe", stat)).toEqual({ type: "git", url: "https://github.com/workingprototype/Fuobe.git" });
+ expect(parseSource("https://github.com/o/r/tree/main/skills/launch", stat)).toEqual({ type: "git", url: "https://github.com/o/r.git", ref: "main", subpath: "skills/launch" });
+ expect(parseSource("[email protected]:o/r.git", stat)).toEqual({ type: "git", url: "[email protected]:o/r.git" });
+ expect(parseSource("https://example.test/skill.zip", stat)).toEqual({ type: "link", url: "https://example.test/skill.zip" });
+ expect(usage(() => parseSource("./nothing-here", stat))).toMatch(/Can't find/);
+ });
+
+ it("reads a skill's name and the internal flag", () => {
+ expect(skillHead(skill("launch-video"))).toEqual({ name: "launch-video", internal: false });
+ expect(skillHead(skill("wip", "metadata:\n title: WIP\n internal: true\n"))).toEqual({ name: "wip", internal: true });
+ expect(skillHead("no frontmatter")).toEqual({ name: null, internal: false });
+ });
+
+ it("finds skills the way the skills CLI does: the root, container folders, categories, shadowing", () => {
+ const repo = path.join(tmp, "repo");
+ write("repo/skills/a/SKILL.md", skill("a"));
+ write("repo/skills/marketing/b/SKILL.md", skill("b"));
+ write("repo/skills/a/examples/inner/SKILL.md", skill("inner"));
+ write("repo/.agents/skills/c/SKILL.md", skill("c"));
+ write("repo/top/SKILL.md", skill("top"));
+ write("repo/node_modules/x/SKILL.md", skill("x"));
+ write("repo/docs/deep/er/SKILL.md", skill("deep"));
+ const names = findSkillDirs(repo).map((d) => path.relative(repo, d));
+ expect(names).toEqual([".agents/skills/c", "skills/a", "skills/marketing/b", "top"]);
+ // A folder that is a skill is just that skill.
+ expect(findSkillDirs(path.join(repo, "skills/a"))).toEqual([path.join(repo, "skills/a")]);
+ // Nothing in the usual places: any SKILL.md a few levels down.
+ expect(findSkillDirs(path.join(repo, "docs")).map((d) => path.basename(d))).toEqual(["er"]);
+ });
+
+ it("packs a skill folder into a zip the server reads, leaving out binaries and dot-files", () => {
+ write("pack/launch/SKILL.md", skill("launch"));
+ write("pack/launch/references/style.md", "Bold colours.");
+ write("pack/launch/.secret", "x");
+ fs.writeFileSync(path.join(tmp, "pack/launch/logo.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2]));
+ const packed = packSkill(path.join(tmp, "pack/launch"));
+ expect(packed.files).toEqual(["SKILL.md", "references/style.md"]);
+ expect(packed.skipped).toEqual(["logo.png"]);
+ const entries = unzip(packed.zip);
+ expect(entries.map((e) => e.name)).toEqual(["launch/SKILL.md", "launch/references/style.md"]);
+ expect(entries[1].data.toString()).toBe("Bold colours.");
+ });
+
+ it("writes zips with correct CRCs, stored or deflated", () => {
+ expect(crc32(Buffer.from("123456789"))).toBe(0xcbf43926);
+ const big = Buffer.from("fuobe ".repeat(500));
+ const entries = unzip(zipFiles([{ name: "a.txt", data: Buffer.from("x") }, { name: "dir/b.txt", data: big }]));
+ expect(entries.map((e) => [e.name, e.data.length])).toEqual([
+ ["a.txt", 1],
+ ["dir/b.txt", big.length],
+ ]);
+ });
+});
+
+describe("the CLI package", () => {
+ it("imports nothing but Node's own modules and its own files (it runs from a plain npm install)", () => {
+ const root = path.join(process.cwd(), "bin");
+ const files = fs.readdirSync(root, { recursive: true }).map(String).filter((f) => f.endsWith(".mjs"));
+ expect(files.length).toBeGreaterThan(5);
+ for (const f of files) {
+ const text = fs.readFileSync(path.join(root, f), "utf8");
+ const specs = [...text.matchAll(/(?:^|\n)\s*import\s[^;]*?from\s+["']([^"']+)["']|import\(\s*["']([^"']+)["']\s*\)/g)].map((m) => m[1] ?? m[2]);
+ for (const s of specs) expect(s.startsWith("node:") || s.startsWith("./") || s.startsWith("../"), `${f} imports ${s}`).toBe(true);
+ for (const s of specs.filter((x) => x.startsWith("."))) expect(path.resolve(root, path.dirname(f), s).startsWith(root), `${f} imports ${s} from outside bin/`).toBe(true);
+ }
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8"));
+ expect(pkg.bin).toEqual({ fuobe: "bin/fuobe.mjs" });
+ expect(fs.readFileSync(path.join(root, "fuobe.mjs"), "utf8").startsWith("#!/usr/bin/env node\n")).toBe(true);
+ });
+});