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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
CLI: fuobe skills params, estimate, run and export run a saved skill from a terminal, one set of values or a CSV of rows
Claudebb5f336b8bd0
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjsindex a611c877..f13fdd50 100644--- a/bin/lib/commands.mjs+++ b/bin/lib/commands.mjs@@ -5,11 +5,27 @@ 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, voiceSampleProblem, withInputHint } from "./build.mjs";+import { defaultModel, fileInputs, generationRequest, isRemoteRef, localFiles, voiceSampleProblem, 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";+import {+ csvCells,+ engineWords,+ estimateLines,+ estimateProblems,+ exactCost,+ findSkillDirs,+ headerInputs,+ isFileInput,+ packSkill,+ paramsTable,+ parseSource,+ priceWords,+ skillHead,+ skillValues,+ toCsv,+} 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 };@@ -622,6 +638,187 @@ async function skillsAdd(ctx, source) {return results.some((r) => r.ok) ? EXIT.ok : EXIT.failed;}+// ---------------------------------------------------------------------------+// skills that run by themselves (a recipe): params, estimate, run, export++/** A skill's recipe as the server reads it: its inputs, the engines its steps run on, and where its check passed. */+const recipeOf = (ctx, name) => ctx.client.request("GET", `/api/assist/skills/${enc(name)}/recipe`);++/** --engine, else where the skill was checked, else the first engine its steps run on. */+function skillEngine(ctx, view) {+ const want = ctx.values.engine;+ if (want && !view.engines.includes(want)) {+ throw new UsageError(view.engines.length ? `/${view.name} runs on ${view.engines.map(engineWords).join(" or ")} only: leave out --engine` : `/${view.name} can't run on this server as it is`, "skills");+ }+ return want ?? view.ready[0] ?? view.engines[0];+}++/** A stand-in URL for a local file while pricing (nothing is uploaded until it runs), as estimate's are. */+const fileStandIn = (abs) => `/api/files/uploads/estimate/${path.basename(abs).replace(/[^\w.-]+/g, "_")}`;++/**+ * What a skills estimate or run sends, before its local files are uploaded: the -p values, or the --rows table with+ * the -p values filling what its rows leave empty. `files` are the local files it names (a -p path is read from here,+ * a cell's from the table's folder); `body(url)` swaps each for `url(path)`: a stand-in to price, its upload to run.+ */+async function skillRequest(ctx, view) {+ const v = ctx.values;+ const params = view.recipe.params;+ const byId = new Map(params.map((p) => [p.id, p]));+ const given = skillValues(v.param ?? []);+ const unknown = Object.keys(given).filter((k) => !byId.has(k));+ if (unknown.length) {+ throw new UsageError(`/${view.name} has no input ${unknown.map((k) => `“${k}”`).join(", ")}. It takes ${params.map((p) => p.id).join(", ") || "none"} (fuobe skills params ${view.name}).`, "skills");+ }+ const files = new Set();+ /** A file input's value: a link stays as it is; a local path is checked now and kept as an absolute path. */+ const fileRef = (ref, dir) => {+ if (!ref || isRemoteRef(ref)) return ref;+ const abs = checkFile(ctx, path.resolve(dir, ref));+ files.add(abs);+ return abs;+ };+ const isFile = (id) => !!id && isFileInput(byId.get(id));+ const swap = (cell, url) => (files.has(cell) ? url(cell) : cell);+ for (const [id, ref] of Object.entries(given)) if (isFile(id)) given[id] = fileRef(ref, ctx.io.cwd);+ if (!v.rows) {+ return {+ rows: false,+ files: [...files],+ lineOf: (l) => l,+ body: (url) => ({ values: Object.fromEntries(Object.entries(given).map(([id, val]) => [id, isFile(id) ? swap(val, url) : val])) }),+ };+ }+ const text = v.rows === "-" ? await ctx.io.readStdin() : fs.readFileSync(checkFile(ctx, v.rows), "utf8");+ const dir = v.rows === "-" ? ctx.io.cwd : path.dirname(path.resolve(ctx.io.cwd, v.rows));+ const all = csvCells(text);+ if (all.length < 2) throw new UsageError(`${v.rows === "-" ? "The table" : v.rows} needs a header row naming the inputs (${params.map((p) => p.id).join(", ")}), then one row per run`, "skills");+ const [head, ...rest] = all;+ const header = [...head.cells];+ const columns = headerInputs(header, params);+ header.forEach((h, i) => {+ if (!columns[i] && h) ctx.note(`“${h}” isn't an input of /${view.name}, so that column is left out.`);+ });+ const rows = rest.map((r) => header.map((_, i) => r.cells[i] ?? ""));+ // -p fills what the rows leave empty: a column of its own when the table has none.+ for (const [id, val] of Object.entries(given)) {+ let col = columns.indexOf(id);+ if (col === -1) {+ header.push(id);+ columns.push(id);+ col = header.length - 1;+ for (const r of rows) r.push("");+ }+ for (const r of rows) if (!r[col]) r[col] = val;+ }+ for (const r of rows) columns.forEach((id, i) => isFile(id) && (r[i] = fileRef(r[i], dir)));+ let sent = [];+ return {+ rows: true,+ files: [...files],+ // A row's line in the table sent, back to its line in the person's file.+ lineOf: (l) => {+ const k = sent.indexOf(l);+ return k > 0 ? rest[k - 1].line : l;+ },+ body: (url) => {+ const csv = toCsv([header, ...rows.map((r) => r.map((c, i) => (isFile(columns[i]) ? swap(c, url) : c)))]);+ sent = csv.lines;+ return { csv: csv.text };+ },+ };+}++/** A skill not checked on this engine gets its free plan check first (it prices every step; nothing runs). */+async function checkSkill(ctx, view, engine) {+ if (!ctx.values.json) ctx.note(`Checking /${view.name} on ${engineWords(engine)} first (free: it prices each step, nothing runs)…`);+ const r = await ctx.client.request("POST", `/api/assist/skills/${enc(view.name)}/verify`, { json: { level: "plan", engine } });+ if (r.ok) return;+ const why = r.engines.flatMap((e) => e.plan.errors)[0];+ throw new ApiError(`/${view.name} doesn't run on ${engineWords(engine)} as it is${why ? `: ${why}` : ""}. Check it in Assist → Skills.`);+}++const priceSkill = (ctx, view, engine, body) => ctx.client.request("POST", `/api/assist/skills/${enc(view.name)}/estimate`, { json: { ...body, engine } });++async function skillsParams(ctx, name) {+ const view = await recipeOf(ctx, name);+ const params = view.recipe.params;+ if (ctx.values.json) return ctx.json({ name: view.name, title: view.title, engines: view.engines, ready: view.ready, params });+ ctx.print(`${view.title} (/${view.name}) · runs on ${view.engines.map(engineWords).join(" or ") || "nothing on this server as it is"}`);+ if (params.length) ctx.print(table(["INPUT", "TYPE", "", "WHAT IT TAKES"], paramsTable(view), ctx.io.columns));+ else ctx.print("It takes no inputs: it runs the same steps each time.");+ const sample = { image: "photo.png", video: "clip.mp4", audio: "voice.wav" };+ const needed = params.filter((p) => p.required && p.default === undefined).map((p) => `-p ${p.id}=${sample[p.type] ?? (p.type === "choice" ? p.options?.[0] : p.type === "number" ? (p.min ?? 1) : p.type === "element" ? "@handle" : '"…"')}`);+ ctx.note(`Run it: fuobe skills run ${view.name}${needed.length ? ` ${needed.join(" ")}` : ""}. Many at once: --rows rows.csv, a header row naming the inputs and one run per row.`);+ return EXIT.ok;+}++async function skillsEstimate(ctx, name) {+ const view = await recipeOf(ctx, name);+ const engine = skillEngine(ctx, view);+ const req = await skillRequest(ctx, view);+ const est = await priceSkill(ctx, view, engine, req.body(fileStandIn));+ if (ctx.values.json) {+ ctx.json(est);+ return est.runnable ? EXIT.ok : EXIT.failed;+ }+ for (const line of estimateLines(est, view.title, { rows: req.rows, lineOf: req.lineOf })) ctx.print(line);+ if (est.runnable && !view.ready.includes(engine)) ctx.note(`Not checked on ${engineWords(engine)} yet: fuobe skills run checks it first, for free.`);+ return est.runnable ? EXIT.ok : EXIT.failed;+}++async function skillsRun(ctx, name) {+ const v = ctx.values;+ const view = await recipeOf(ctx, name);+ const engine = skillEngine(ctx, view);+ const req = await skillRequest(ctx, view);+ // Priced with stand-ins first, so a bad value fails before anything is checked, uploaded or spent.+ const est = await priceSkill(ctx, view, engine, req.body(fileStandIn));+ if (!est.runnable) throw new ApiError(estimateProblems(est, req).join("\n") || `/${view.name} can't run with these values`);+ const runs = est.runs.length;+ const costs = !est.demo && est.total !== 0;+ if (costs && !v.yes && !v.json) {+ const price = est.total === null ? "(some prices vary)" : `for ${exactCost(est.total)}`;+ if (!ctx.io.stdinIsTTY) throw new UsageError(`Running ${runs === 1 ? "it" : `these ${runs}`} costs ${est.total === null ? "an amount that varies" : exactCost(est.total)}: add --yes to run without asking`);+ const answer = await ctx.io.ask(`Run ${runs} ${price}? [y/N] `);+ if (!/^y(es)?$/i.test(answer.trim())) {+ ctx.note("Nothing was started.");+ return EXIT.failed;+ }+ } else if (!v.json) ctx.note(`${view.title} on ${engineWords(engine)}: ${priceWords(est, runs)}.`);+ if (!view.ready.includes(engine)) await checkSkill(ctx, view, engine);+ const uploaded = new Map();+ for (const f of req.files) uploaded.set(f, await uploadFile(ctx, f));+ const out = await ctx.client.request("POST", `/api/assist/skills/${enc(view.name)}/run`, { json: { ...req.body((f) => uploaded.get(f)), engine } });+ const ids = out.runs.flatMap((r) => r.ids);+ const started = out.runs.filter((r) => !r.error).length;+ const demo = out.demo ? " (a demo: nothing connected, free)" : "";+ for (const [i, r] of out.runs.entries()) if (r.error && !v.json) ctx.note(`Run ${i + 1} didn't start: ${r.error}`);+ const studio = out.runs.find((r) => r.href && !r.href.startsWith("/library"))?.href;+ if (v.wait || v.out) {+ if (!v.json) ctx.note(`Started ${started === 1 ? view.title : `${started} runs of ${view.title}`}${demo}.${studio ? ` It opens in ${absolute(ctx, studio)}` : ""}`);+ return finish(ctx, ids, { download: !!v.out });+ }+ if (v.json) return ctx.json(out);+ ctx.print(`Started ${started === 1 ? view.title : `${started} runs of ${view.title}`} on ${engineWords(out.engine)}${demo}: ${ids.join(" ")}`);+ if (studio) ctx.print(`It opens in ${absolute(ctx, studio)}`);+ if (ids.length) ctx.print(`Wait for ${ids.length === 1 ? "it" : "them"}: fuobe wait ${ids.join(" ")} Save ${ids.length === 1 ? "it" : "them"}: fuobe download ${ids.join(" ")} --out .`);+ return started === out.runs.length ? EXIT.ok : EXIT.failed;+}++async function skillsExport(ctx, name) {+ const v = ctx.values;+ const file = `${name.replace(/[^\w.-]+/g, "_")}.zip`;+ let dest = path.resolve(ctx.io.cwd, v.out ?? file);+ if (fs.statSync(dest, { throwIfNoEntry: false })?.isDirectory()) dest = path.join(dest, file);+ const bytes = await ctx.client.download(`/api/assist/skills/${enc(name)}/download?format=zip${v.examples ? "&examples=1" : ""}`, dest);+ if (v.json) return ctx.json({ name, path: dest, bytes, examples: !!v.examples });+ const shown = path.relative(ctx.io.cwd, dest) || dest;+ ctx.print(`Saved ${shown} (${megabytes(bytes)}): SKILL.md and its files${v.examples ? ", with the values it was made with" : ""}.`);+ ctx.note(`Add it to another Fuobe with: fuobe skills add ${shown}`);+ return EXIT.ok;+}+async function skills(ctx) {const [sub, ...rest] = ctx.positionals;const arg = (what) => {@@ -640,8 +837,16 @@ async function skills(ctx) {return skillsToggle(ctx, arg("a skill name"), true);case "disable":return skillsToggle(ctx, arg("a skill name"), false);+ case "params":+ return skillsParams(ctx, arg("a skill name"));+ case "estimate":+ return skillsEstimate(ctx, arg("a skill name"));+ case "run":+ return skillsRun(ctx, arg("a skill name"));+ case "export":+ return skillsExport(ctx, arg("a skill name"));default:- throw new UsageError(`Unknown skills command “${sub}”: use list, show, add, enable or disable`, "skills");+ throw new UsageError(`Unknown skills command “${sub}”: use list, show, add, enable, disable, params, estimate, run or export`, "skills");}}@@ -862,11 +1067,20 @@ export const COMMANDS = {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>]",+ summary: "List, read, add, switch on or off, and run Assist skills",+ usage:+ "fuobe skills [list | show <name> | add <source> | enable <name> | disable <name> | params <name> | estimate <name> -p input=value… | run <name> -p input=value… [--rows rows.csv] | export <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" },+ param: { type: "string", short: "p", multiple: true, value: "input=value", describe: "estimate, run: a value for one of the skill's inputs (a local file is uploaded when it runs)" },+ rows: { type: "string", value: "file.csv", describe: "estimate, run: one run per row (a header row names the inputs; - reads stdin; -p fills empty cells)" },+ engine: { type: "string", choices: ["open", "cloud"], describe: "estimate, run: where it runs (default: where it was checked)" },+ yes: { type: "boolean", short: "y", describe: "run: start without asking, whatever it costs" },+ wait: { type: "boolean", short: "w", describe: "run: wait until it's done and print the results" },+ out: { type: "string", short: "o", value: "dir|file", describe: "run: wait, then save the outputs here; export: the .zip to write" },+ examples: { type: "boolean", describe: "export: keep the values the skill was made with" },+ ...WAIT_OPTIONS,},examples: ["fuobe skills list",@@ -874,6 +1088,10 @@ export const COMMANDS = {"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",+ "fuobe skills params weekly-promo",+ 'fuobe skills run weekly-promo -p product=lamp.png -p name="Lumen desk lamp" --wait',+ "fuobe skills run weekly-promo --rows products.csv --engine cloud --out renders/",+ "fuobe skills export weekly-promo --out weekly-promo.zip",],run: skills,},diff --git a/bin/lib/skills.mjs b/bin/lib/skills.mjsindex 73f59dd5..a12068e4 100644--- a/bin/lib/skills.mjs+++ b/bin/lib/skills.mjs@@ -110,3 +110,177 @@ export function packSkill(dir) {walk("");return { zip: zipFiles(files), files: files.map((f) => f.name.slice(folder.length + 1)), skipped };}++// ---------------------------------------------------------------------------+// Running a skill that runs by itself (its recipe): `fuobe skills params | estimate | run | export`++/** A skill input that takes a file. */+export const isFileInput = (p) => p.type === "image" || p.type === "video" || p.type === "audio";++/**+ * `-p key=value` for a skill's inputs. Every value stays text, as the Run form sends it (the server reads a number from+ * its digits); `key=` leaves the input to its default. A key given twice is a mistake, not the last one winning.+ * @param {string[]} pairs+ * @returns {Record<string, string>}+ */+export function skillValues(pairs) {+ /** @type {Record<string, string>} */+ const out = {};+ for (const pair of pairs) {+ const eq = pair.indexOf("=");+ if (eq <= 0) throw new UsageError(`-p takes input=value, not “${pair}” (fuobe skills params <name> lists the inputs)`, "skills");+ const key = pair.slice(0, eq).trim();+ if (key in out) throw new UsageError(`-p ${key} is given twice`, "skills");+ out[key] = pair.slice(eq + 1);+ }+ return out;+}++/**+ * Rows of a CSV or TSV text (a spreadsheet's paste is tab-separated): quotes, doubled quotes, line breaks inside quotes,+ * a byte-order mark. Read the way Fuobe reads a pasted table (csvCells in src/lib/recipe.ts), with each row's first line.+ * @param {string} text+ * @returns {{ cells: string[], line: number }[]}+ */+export function csvCells(text) {+ const src = text.replace(/^/, "");+ const first = src.split(/\r?\n/, 1)[0] ?? "";+ const sep = first.includes("\t") && !first.includes(",") ? "\t" : first.includes(";") && !first.includes(",") && !first.includes("\t") ? ";" : ",";+ const rows = [];+ let row = [];+ let cell = "";+ let quoted = false;+ let line = 1;+ let start = 1;+ for (let i = 0; i < src.length; i++) {+ const c = src[i];+ if (quoted) {+ if (c === '"' && src[i + 1] === '"') {+ cell += '"';+ i++;+ } else if (c === '"') quoted = false;+ else {+ if (c === "\n") line++;+ cell += c;+ }+ continue;+ }+ if (c === '"' && !cell.trim()) {+ quoted = true;+ cell = "";+ } else if (c === sep) {+ row.push(cell);+ cell = "";+ } else if (c === "\n" || c === "\r") {+ if (c === "\r" && src[i + 1] === "\n") i++;+ row.push(cell);+ rows.push({ cells: row, line: start });+ row = [];+ cell = "";+ line++;+ start = line;+ } else cell += c;+ }+ if (cell || row.length) {+ row.push(cell);+ rows.push({ cells: row, line: start });+ }+ return rows.map((r) => ({ ...r, cells: r.cells.map((x) => x.trim()) })).filter((r) => r.cells.some((c) => c));+}++const norm = (s) => s.toLowerCase().replace(/[\s_-]+/g, " ").trim();++/** The input each header cell names (by its id or its label, as Fuobe matches them), or null. */+export function headerInputs(header, params) {+ const byName = new Map();+ for (const p of params) {+ byName.set(norm(p.id), p.id);+ byName.set(norm(p.label), p.id);+ }+ return header.map((h) => byName.get(norm(h)) ?? null);+}++const quote = (s) => (/[",\n\r]/.test(s) || s !== s.trim() ? `"${s.replace(/"/g, '""')}"` : s);++/**+ * Rows written back as CSV for the server, and the line each row starts on there (a cell with a line break takes more+ * than one), so its answers ("Row 3: …") can name the row's line in the person's own file.+ * @param {string[][]} rows header first+ */+export function toCsv(rows) {+ const lines = [];+ let line = 1;+ const text = rows+ .map((r) => {+ lines.push(line);+ const out = r.map(quote).join(",");+ line += out.split("\n").length;+ return out;+ })+ .join("\n");+ return { text: `${text}\n`, lines };+}++/** $12.40: a skill's price before it runs, to the cent. */+export const exactCost = (usd) => (usd === 0 ? "free" : usd < 0.01 ? "<$0.01" : `$${usd.toFixed(2)}`);++const TYPE_WORDS = { image: "image", video: "video", audio: "audio", text: "text", number: "number", choice: "choice", element: "@element" };++/**+ * A skill's inputs as a table: id, type, needed or its default, and what it takes.+ * @param {{ name: string, title: string, recipe: { params: any[] }, engines: string[], ready: string[], line?: string }} view GET /api/assist/skills/<name>/recipe+ */+export function paramsTable(view) {+ return view.recipe.params.map((p) => {+ const needed = p.required && p.default === undefined ? "needed" : p.default !== undefined ? `default ${p.default}` : "optional";+ const what = [+ p.label,+ p.type === "choice" ? (p.options ?? []).join(" | ") : null,+ p.type === "number" && (p.min !== undefined || p.max !== undefined) ? `${p.min ?? "…"}–${p.max ?? "…"}` : null,+ p.type === "text" && p.max ? `up to ${p.max} characters` : null,+ isFileInput(p) ? "a file, an https:// link or a /api/files/… URL" : null,+ p.example !== undefined && p.example !== null && p.example !== "" && !isFileInput(p) ? `e.g. ${p.example}` : null,+ ].filter(Boolean);+ return [p.id, TYPE_WORDS[p.type] ?? p.type, needed, what.join(" · ")];+ });+}++const ENGINE_WORDS = { cloud: "the cloud", open: "your GPU (open source)" };++/** "on the cloud", "on your GPU (open source)". */+export const engineWords = (engine) => ENGINE_WORDS[engine] ?? engine;++/**+ * A skill's price in words: the steps of one run, then the total. With `rows` (a --rows file), a row's problem names+ * its line in that file (`lineOf`).+ * @param {any} est POST /api/assist/skills/<name>/estimate+ * @param {string} title+ * @param {{ rows?: boolean, lineOf?: (line: number) => number }} [o]+ */+export function estimateLines(est, title, { rows = false, lineOf = (l) => l } = {}) {+ const runs = est.runs.length;+ const out = [`${title} on ${engineWords(est.engine)}: ${est.jobs.length} step${est.jobs.length === 1 ? "" : "s"}${runs > 1 ? " a run" : ""}`];+ for (const [i, j] of est.jobs.entries()) {+ const price = j.demo ? "demo, free" : j.costUsd === null ? "price varies" : exactCost(j.costUsd);+ out.push(` ${i + 1}. ${j.modelName}${j.note ? ` · ${j.note}` : ""}${j.count > 1 ? ` · ${j.count} outputs` : ""} · ${price}${j.error ? ` — ${j.error}` : ""}`);+ }+ out.push(...estimateProblems(est, { rows, lineOf }, false));+ if (est.runnable) out.push(priceWords(est, runs));+ return out;+}++/** What stops a skill's run, row by row (`jobs`: a step's own problem too, when nothing else says why). */+export function estimateProblems(est, { rows = false, lineOf = (l) => l } = {}, jobs = true) {+ const out = [...est.errors];+ for (const r of est.runs) for (const e of r.errors) out.push(rows ? `Row ${lineOf(r.line)}: ${e}` : e);+ if (jobs && !out.length) for (const j of est.jobs) if (j.error) out.push(`${j.modelName}: ${j.error}`);+ return out;+}++/** "20 runs · $12.40 in all", "Free on your GPU", "A demo: free". */+export function priceWords(est, runs) {+ if (est.demo) return `${runs > 1 ? `${runs} runs · ` : ""}a demo (nothing connected), free`;+ if (est.total === null) return `${runs > 1 ? `${runs} runs · ` : ""}some prices vary`;+ if (est.total === 0) return `${runs > 1 ? `${runs} runs · ` : ""}free`;+ return runs > 1 ? `${runs} runs · ${exactCost(est.total)} in all` : `about ${exactCost(est.total)}`;+}diff --git a/docs/cli.md b/docs/cli.mdindex af8ae0b7..675faf1d 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -195,8 +195,38 @@ else `skills/`, `.agents/skills/`, `.claude/skills/` and the folders right underlevels), else any `SKILL.md` a few levels down; skills marked `metadata.internal: true` are left outunless named with `--skill`. Each skill is uploaded as a zip with its text files (binaries anddot-files are left out, and listed). Git sources need `git`. A skill's `recipe.json` (a skill that runs-by itself; see `skills/README.md`) goes up with it but starts unchecked: check it in **Assist → Skills**-before you run it. The CLI has no command to run a skill yet.+by itself; see `skills/README.md`) goes up with it but starts unchecked: `skills run` checks it for free+before its first run, or check it in **Assist → Skills**.++#### Running a skill that runs by itself++A skill with a recipe runs its saved steps with new inputs, with no AI model planning them: priced+first, the same steps every time.++```bash+fuobe skills params weekly-promo # its inputs: id, type, needed or default, what it takes+fuobe skills estimate weekly-promo -p product=lamp.png -p name="Lumen desk lamp"+fuobe skills run weekly-promo -p product=lamp.png -p name="Lumen desk lamp" --wait+fuobe skills run weekly-promo --rows products.csv --engine cloud --out renders/+fuobe skills export weekly-promo --out weekly-promo.zip # SKILL.md and its files, to add elsewhere+```++- `-p input=value` gives one input (repeat it; `fuobe skills params` lists the ids). A file input takes a+ local file, an `https://` link or a `/api/files/…` URL. Local files are uploaded only when it runs:+ `estimate` prices with stand-ins, as `fuobe estimate` does.+- `--rows rows.csv` runs it once per row (up to 50; `-` reads the table from stdin). The first row names+ the inputs by id or label, as the **Many** tab of the Run dialog reads it; a spreadsheet's paste (tabs)+ works too. A file path in a cell is read from the table's folder, and each file goes up once. `-p` fills+ what the rows leave empty. A row that doesn't fit is named by its line, and then nothing starts.+- `run` prices the whole batch first and asks `Run 20 for $12.40? [y/N]` when it costs money. `--yes`+ starts it without asking; so does `--json` (for scripts). Without a terminal to ask on, it stops and+ says to add `--yes`. Free runs (your GPU, or a demo) start without asking.+- `--engine open|cloud` picks where it runs, among the engines its steps run on (by default: where it+ was checked). A skill not yet checked on that engine gets its free plan check first.+- `--wait` and `--out <dir>` wait for the results and save them, as `fuobe generate` does; without them,+ `run` prints the ids to pass to `fuobe wait` or `fuobe download`.+- `export` saves the skill as a zip (`SKILL.md`, `recipe.json` and its other files); `--examples` keeps+ the values it was made with, which are left out by default.### `fuobe tools`, `fuobe tool` — the MCP tools@@ -317,6 +347,8 @@ retired runs on the model that replaced it, and the answer gives that `modelId``GET /api/generations[/<id>]`,`POST /api/generations/<id>/cancel`, `POST /api/uploads` (multipart `file`), `GET /api/files/…`,`GET /api/status`, `GET|PATCH /api/assist/skills[/<name>]`, `POST /api/assist/skills/upload`-(`?replace=1`) and `POST /api/mcp` (JSON-RPC). Every call carries `Authorization: Bearer <token>`+(`?replace=1`), a skill's `GET …/recipe`, `POST …/estimate`, `…/run` and `…/verify` (`{level: "plan"}`)+and `GET …/download?format=zip` under `/api/assist/skills/<name>` (estimate and run take `values`, or+`csv`, and `engine`), and `POST /api/mcp` (JSON-RPC). Every call carries `Authorization: Bearer <token>`when there is one, and only to the Fuobe server (never to a link elsewhere, and the saved token onlyto the server it was saved for).diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.tsindex bbf432fe..e8d4fa7b 100644--- a/tests/cli-run.test.ts+++ b/tests/cli-run.test.ts@@ -48,6 +48,21 @@ const generation = (status: string, extra: Record<string, unknown> = {}) => ({...extra,});+const PROMO = {+ name: "weekly-promo",+ title: "Weekly promo",+ engines: ["cloud"],+ ready: [],+ recipe: {+ params: [+ { id: "product", label: "Product photo", type: "image", required: true },+ { id: "name", label: "Product name", type: "text", required: true, max: 200, example: "Lumen desk lamp" },+ { id: "aspect", label: "Shape", type: "choice", options: ["1:1", "9:16"], default: "1:1" },+ ],+ },+};+const job = { tool: "skill", modelId: "nano-banana-pro", modelName: "Nano Banana Pro", kind: "image", op: "edit", note: "Edit", prompt: "", count: 1, costUsd: 0.62, demo: false };+async function body(req: http.IncomingMessage): Promise<Buffer> {const chunks: Buffer[] = [];for await (const c of req) chunks.push(c as Buffer);@@ -115,6 +130,23 @@ beforeAll(async () => {const name = /name:\s*(\S+)/.exec(md)![1];return send(201, { skill: { name, title: name }, skipped: [], replaced: false });}+ // A skill that runs by itself (W4): its recipe, a price per row, a run per row, and its zip.+ const skill = /^\/api\/assist\/skills\/weekly-promo\/(recipe|verify|estimate|run|download)$/.exec(url.pathname)?.[1];+ if (skill === "recipe") return send(200, PROMO);+ if (skill === "verify") return send(200, { ok: true, engines: [{ engine: "cloud", plan: { ok: true, errors: [] } }] });+ if (skill === "estimate" || skill === "run") {+ const b = s.json as { values?: Record<string, string>; csv?: string; engine?: string };+ // The CSV the CLI sent, read as the server would: header first, one run per line.+ const rows = b.csv ? b.csv.trim().split("\n").slice(1).map((l, i) => ({ line: i + 2, name: l.split(",")[1] ?? "" })) : [{ line: 1, name: b.values?.name ?? "" }];+ if (skill === "run") return send(201, { engine: b.engine ?? "cloud", demo: false, runs: rows.map((_, i) => ({ batchId: `b${i}`, ids: i ? [`gen${i + 1}`] : ["gen1"], href: "/library" })) });+ const runs = rows.map((r) => ({ line: r.line, jobs: [job], total: r.name === "bad" ? null : 0.62, errors: r.name === "bad" ? ["Product name: at most 200 characters"] : [] }));+ const ok = runs.every((r) => !r.errors.length);+ return send(200, { engine: b.engine ?? "cloud", runs, jobs: [job], total: ok ? Math.round(0.62 * runs.length * 100) / 100 : null, demo: false, runnable: ok, errors: [] });+ }+ if (skill === "download") {+ res.writeHead(200, { "content-type": "application/zip" });+ return res.end(Buffer.from(`zip${url.search}`));+ }send(404, { error: "Not found" });});await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));@@ -382,3 +414,121 @@ describe("fuobe CLI against a Fuobe server", () => {expect(seen).toHaveLength(0);});});++describe("fuobe skills: a skill that runs by itself (W4)", () => {+ const posts = (what: string) => seen.filter((s) => s.method === "POST" && s.path === `/api/assist/skills/weekly-promo/${what}`);++ it("params lists the inputs; estimate prices with stand-ins and uploads nothing", async () => {+ const p = await run(["skills", "params", "weekly-promo"]);+ expect(p.code).toBe(0);+ expect(p.stdout).toMatch(/^Weekly promo \(\/weekly-promo\) · runs on the cloud$/m);+ expect(p.stdout).toMatch(/^product\s+image\s+needed\s+Product photo · a file, an https:\/\/ link or a \/api\/files\/… URL$/m);+ expect(p.stdout).toMatch(/^name\s+text\s+needed\s+Product name · up to 200 characters · e\.g\. Lumen desk lamp$/m);+ expect(p.stdout).toMatch(/^aspect\s+choice\s+default 1:1\s+Shape · 1:1 \| 9:16$/m);+ expect(p.stderr).toContain("Run it: fuobe skills run weekly-promo -p product=photo.png -p name=\"…\"");+ fs.writeFileSync(path.join(tmp, "my lamp.png"), PNG);+ const e = await run(["skills", "estimate", "weekly-promo", "-p", "product=my lamp.png", "-p", "name=Lumen=Desk"]);+ expect(e.code).toBe(0);+ expect(e.stdout).toBe("Weekly promo on the cloud: 1 step\n 1. Nano Banana Pro · Edit · $0.62\nabout $0.62\n");+ expect(seen.some((s) => s.path === "/api/uploads")).toBe(false);+ // A value keeps everything after the first "=", and a file is a stand-in with a name the server takes.+ expect(posts("estimate")[0].json).toEqual({ values: { product: "/api/files/uploads/estimate/my_lamp.png", name: "Lumen=Desk" }, engine: "cloud" });+ const bad = await run(["skills", "estimate", "weekly-promo", "-p", "colour=red"]);+ expect(bad.code).toBe(2);+ expect(bad.stderr).toMatch(/^\/weekly-promo has no input “colour”\. It takes product, name, aspect \(fuobe skills params weekly-promo\)\./);+ const engine = await run(["skills", "estimate", "weekly-promo", "--engine", "open"]);+ expect(engine.code).toBe(2);+ expect(engine.stderr).toMatch(/^\/weekly-promo runs on the cloud only: leave out --engine/);+ });++ it("run won't spend without a yes; with --yes it checks the skill, uploads the file, runs, waits and saves", async () => {+ fs.writeFileSync(path.join(tmp, "lamp.png"), PNG);+ const asked = await run(["skills", "run", "weekly-promo", "-p", "product=lamp.png", "-p", "name=Lumen"]);+ expect(asked.code).toBe(2);+ expect(asked.stderr.trim()).toBe("Running it costs $0.62: add --yes to run without asking");+ expect(seen.some((s) => s.path === "/api/uploads" || s.path.endsWith("/run") || s.path.endsWith("/verify"))).toBe(false);+ seen = [];+ const r = await run(["skills", "run", "weekly-promo", "-p", "product=lamp.png", "-p", "name=Lumen", "--yes", "--out", "promo", "--interval", "0.2"]);+ expect(r.code).toBe(0);+ expect(r.stderr).toContain("Checking /weekly-promo on the cloud first (free: it prices each step, nothing runs)…");+ expect(r.stdout).toMatch(/^Saved promo\/gen1\.png \(1 KB\)$/m);+ // Priced with a stand-in, checked, then the file went up once and the run used its URL.+ expect(seen.filter((s) => s.method === "POST").map((s) => s.path)).toEqual([+ "/api/assist/skills/weekly-promo/estimate",+ "/api/assist/skills/weekly-promo/verify",+ "/api/uploads",+ "/api/assist/skills/weekly-promo/run",+ ]);+ expect(posts("verify")[0].json).toEqual({ level: "plan", engine: "cloud" });+ expect(posts("run")[0].json).toEqual({ values: { product: "/api/files/uploads/2026-10-22/up1.png", name: "Lumen" }, engine: "cloud" });+ });++ it("--rows: one run per row, -p fills the empty cells, files beside the table go up once, and --json skips the question", async () => {+ const dir = path.join(tmp, "products");+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "lamp.png"), PNG);+ fs.writeFileSync(path.join(dir, "rows.csv"), "Product photo,Product name,Notes\nlamp.png,\"Lumen, desk\",first\n\nlamp.png,,second\n");+ const r = await run(["skills", "run", "weekly-promo", "--rows", "products/rows.csv", "-p", "name=Halo", "--json"]);+ expect(r.code).toBe(0);+ expect(JSON.parse(r.stdout).runs).toHaveLength(2);+ expect(r.stderr).toContain("“Notes” isn't an input of /weekly-promo, so that column is left out.");+ expect(seen.filter((s) => s.path === "/api/uploads")).toHaveLength(1);+ const up = "/api/files/uploads/2026-10-22/up1.png";+ expect(posts("estimate")[0].json).toEqual({ csv: 'Product photo,Product name,Notes\n/api/files/uploads/estimate/lamp.png,"Lumen, desk",first\n/api/files/uploads/estimate/lamp.png,Halo,second\n', engine: "cloud" });+ expect(posts("run")[0].json).toEqual({ csv: `Product photo,Product name,Notes\n${up},"Lumen, desk",first\n${up},Halo,second\n`, engine: "cloud" });+ });++ it("a row that doesn't fit is named by its line in the file, and nothing starts", async () => {+ fs.writeFileSync(path.join(tmp, "bad.csv"), "product,name\nhttps://cdn.test/a.png,Lumen\n\nhttps://cdn.test/b.png,bad\n");+ const est = await run(["skills", "estimate", "weekly-promo", "--rows", "bad.csv"]);+ expect(est.code).toBe(1);+ expect(est.stdout).toContain("Row 4: Product name: at most 200 characters");+ const r = await run(["skills", "run", "weekly-promo", "--rows", "bad.csv", "--yes"]);+ expect(r.code).toBe(1);+ expect(r.stderr.trim()).toBe("Row 4: Product name: at most 200 characters");+ expect(seen.some((s) => s.path.endsWith("/run") || s.path === "/api/uploads")).toBe(false);+ });++ it("asks on a terminal: no starts nothing, yes runs", async () => {+ const { main } = await import("../bin/lib/cli.mjs");+ const out: string[] = [];+ const questions: string[] = [];+ let answer = "n";+ const io = {+ stdout: { write: (t: string) => out.push(t) },+ stderr: { write: (t: string) => out.push(t) },+ env: { FUOBE_URL: base, FUOBE_TOKEN: TOKEN, FUOBE_CONFIG: path.join(tmp, "config.json") },+ cwd: tmp,+ home: tmp,+ fetch: globalThis.fetch,+ columns: 100,+ stdinIsTTY: true,+ stderrIsTTY: false,+ now: () => Date.now(),+ sleep: (ms: number) => new Promise((r) => setTimeout(r, ms)),+ onInterrupt: () => () => {},+ ask: async (q: string) => (questions.push(q), answer),+ readStdin: async () => "",+ };+ fs.writeFileSync(path.join(tmp, "two.csv"), "product,name\nhttps://cdn.test/a.png,Lumen\nhttps://cdn.test/b.png,Halo\n");+ expect(await main(["skills", "run", "weekly-promo", "--rows", "two.csv"], io)).toBe(1);+ expect(questions).toEqual(["Run 2 for $1.24? [y/N] "]);+ expect(out.join("")).toContain("Nothing was started.");+ expect(seen.some((s) => s.path.endsWith("/run"))).toBe(false);+ answer = "y";+ expect(await main(["skills", "run", "weekly-promo", "--rows", "two.csv"], io)).toBe(0);+ expect(out.join("")).toContain("Started 2 runs of Weekly promo on the cloud: gen1 gen2");+ expect(out.join("")).toContain("Wait for them: fuobe wait gen1 gen2");+ });++ it("export saves the skill as a zip, with its examples when asked", async () => {+ const r = await run(["skills", "export", "weekly-promo", "--examples"]);+ expect(r.code).toBe(0);+ expect(r.stdout).toMatch(/^Saved weekly-promo\.zip \(1 KB\): SKILL\.md and its files, with the values it was made with\.$/m);+ expect(fs.readFileSync(path.join(tmp, "weekly-promo.zip"), "utf8")).toBe("zip?format=zip&examples=1");+ fs.mkdirSync(path.join(tmp, "exports"), { recursive: true });+ const into = await run(["skills", "export", "weekly-promo", "--out", "exports", "--json"]);+ expect(JSON.parse(into.stdout)).toMatchObject({ name: "weekly-promo", path: path.join(tmp, "exports", "weekly-promo.zip"), examples: false });+ expect(fs.readFileSync(path.join(tmp, "exports", "weekly-promo.zip"), "utf8")).toBe("zip?format=zip");+ });+});diff --git a/tests/cli.test.ts b/tests/cli.test.tsindex 39674b93..f9996e92 100644--- a/tests/cli.test.ts+++ b/tests/cli.test.ts@@ -8,7 +8,7 @@ import { createClient, networkMessage, statusMessage } from "../bin/lib/client.mimport { 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 { csvCells, estimateLines, exactCost, findSkillDirs, headerInputs, packSkill, parseSource, priceWords, skillHead, skillValues, toCsv } from "../bin/lib/skills.mjs";import { crc32, zipFiles } from "../bin/lib/zip.mjs";import { unzip } from "@/server/assist/unzip";@@ -444,3 +444,51 @@ describe("the CLI package", () => {expect(fs.readFileSync(path.join(root, "fuobe.mjs"), "utf8").startsWith("#!/usr/bin/env node\n")).toBe(true);});});++describe("running a skill from the CLI (W4)", () => {+ const params = [+ { id: "product", label: "Product photo", type: "image" },+ { id: "name", label: "Product name", type: "text" },+ ];++ it("reads -p input=value as text, keeping everything after the first =", () => {+ expect(skillValues(["product=lamp.png", "name=Lumen = desk", "takes=2", "aspect="])).toEqual({ product: "lamp.png", name: "Lumen = desk", takes: "2", aspect: "" });+ expect(usage(() => skillValues(["lamp.png"]))).toMatch(/^-p takes input=value, not “lamp\.png”/);+ expect(usage(() => skillValues(["name=a", "name=b"]))).toBe("-p name is given twice");+ });++ it("reads a table as Fuobe does: quotes, line breaks in quotes, a BOM, tabs, empty rows skipped", () => {+ expect(csvCells('\uFEFFproduct,name\n"a.png","Lumen, ""desk"""\n\n b.png ,"two\nlines"\n')).toEqual([+ { cells: ["product", "name"], line: 1 },+ { cells: ["a.png", 'Lumen, "desk"'], line: 2 },+ { cells: ["b.png", "two\nlines"], line: 4 },+ ]);+ expect(csvCells("Product photo\tProduct name\na.png\tLumen").map((r) => r.cells)).toEqual([+ ["Product photo", "Product name"],+ ["a.png", "Lumen"],+ ]);+ // A header names an input by its id or its label, whatever the case and spacing.+ expect(headerInputs(["PRODUCT_photo", "name", "notes"], params)).toEqual(["product", "name", null]);+ });++ it("writes rows back as CSV and knows the line each starts on", () => {+ const csv = toCsv([+ ["product", "name"],+ ["/api/files/a.png", "Lumen, desk"],+ ["/api/files/b.png", "two\nlines"],+ ["/api/files/c.png", 'say "hi"'],+ ]);+ expect(csv.text).toBe('product,name\n/api/files/a.png,"Lumen, desk"\n/api/files/b.png,"two\nlines"\n/api/files/c.png,"say ""hi"""\n');+ expect(csv.lines).toEqual([1, 2, 3, 5]);+ expect(csvCells(csv.text).map((r) => r.cells[1])).toEqual(["name", "Lumen, desk", "two\nlines", 'say "hi"']);+ });++ it("prices to the cent before asking, and names a row's problem by its line", () => {+ expect([exactCost(12.4), exactCost(0), exactCost(0.004)]).toEqual(["$12.40", "free", "<$0.01"]);+ expect(priceWords({ demo: false, total: 12.4 }, 20)).toBe("20 runs · $12.40 in all");+ expect(priceWords({ demo: true, total: 0 }, 1)).toBe("a demo (nothing connected), free");+ const job = { modelName: "Nano Banana Pro", note: "Edit", count: 1, costUsd: 0.62, demo: false };+ const est = { engine: "open", jobs: [job], errors: [], runs: [{ line: 3, errors: ["Product name is needed"] }], runnable: false, total: null, demo: false };+ expect(estimateLines(est, "Weekly promo", { rows: true, lineOf: (l: number) => l + 1 })).toEqual(["Weekly promo on your GPU (open source): 1 step", " 1. Nano Banana Pro · Edit · $0.62", "Row 4: Product name is needed"]);+ });+});