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.

Skills W1: run a skill's recipe on the server, price it, and check it before it's trusted

Claudebb84259dd5bb
diff --git a/src/app/api/assist/skills/[name]/download/route.ts b/src/app/api/assist/skills/[name]/download/route.ts
index e967e7b6..0a803b35 100644
--- a/src/app/api/assist/skills/[name]/download/route.ts
+++ b/src/app/api/assist/skills/[name]/download/route.ts
@@ -1,10 +1,25 @@
import { connection } from "next/server";
-import { skillMarkdown } from "@/server/skills";
+import { skillArchive, skillMarkdown } from "@/server/skills";
-/** The skill as SKILL.md, to keep or share (upload it on another Fuobe, or use it with Claude). */
-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) {
+/**
+ * The skill to keep or share: SKILL.md (upload it on another Fuobe, or use it with Claude), or with `?format=zip` the
+ * skill with every bundled file, as Upload reads it. A recipe's examples and source stay out unless `&examples=1`.
+ */
+export async function GET(req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) {
await connection();
const { name } = await ctx.params;
+ const sp = new URL(req.url).searchParams;
+ if (sp.get("format") === "zip") {
+ const data = skillArchive(name, { examples: sp.get("examples") === "1" });
+ if (!data) return Response.json({ error: "No such skill" }, { status: 404 });
+ return new Response(new Uint8Array(data), {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Disposition": `attachment; filename="${name}.zip"`,
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+ }
const md = skillMarkdown(name);
if (md === null) return Response.json({ error: "No such skill" }, { status: 404 });
return new Response(md, {
diff --git a/src/app/api/assist/skills/[name]/estimate/route.ts b/src/app/api/assist/skills/[name]/estimate/route.ts
new file mode 100644
index 00000000..b9a851f9
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/estimate/route.ts
@@ -0,0 +1,14 @@
+import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";
+import { estimateRecipe } from "@/server/recipes";
+
+/** Price a run of a skill's recipe, or many (`rows` or `csv`, priced together with a total). Starts nothing. */
+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) {
+ const parsed = RunBody.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ const { engine, ...input } = parsed.data;
+ return Response.json(estimateRecipe((await ctx.params).name, input, engine));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/[name]/recipe/route.ts b/src/app/api/assist/skills/[name]/recipe/route.ts
new file mode 100644
index 00000000..1dff251a
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/recipe/route.ts
@@ -0,0 +1,26 @@
+import { connection } from "next/server";
+import { recipeFailure } from "@/server/recipe-routes";
+import { recipeView, saveRecipe } from "@/server/recipes";
+
+/** A skill's recipe with where it runs and what was checked (engines, ready, needs a re-check). */
+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) {
+ await connection();
+ try {
+ return Response.json(recipeView((await ctx.params).name));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
+
+/** Save a user skill's recipe.json (it starts unchecked); every problem is named. */
+export async function PUT(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) {
+ const body = await request.json().catch(() => null);
+ if (!body || typeof body !== "object") return Response.json({ error: "Send the recipe as JSON" }, { status: 400 });
+ try {
+ const { name } = await ctx.params;
+ saveRecipe(name, body);
+ return Response.json(recipeView(name));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/[name]/run/route.ts b/src/app/api/assist/skills/[name]/run/route.ts
new file mode 100644
index 00000000..23447463
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/run/route.ts
@@ -0,0 +1,14 @@
+import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";
+import { runRecipe } from "@/server/recipes";
+
+/** Run a skill's recipe with new inputs, once or once per row, with no LLM. Every row is checked before any starts. */
+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/run">) {
+ const parsed = RunBody.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ const { engine, ...input } = parsed.data;
+ return Response.json(await runRecipe((await ctx.params).name, input, engine), { status: 201 });
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/[name]/verify/route.ts b/src/app/api/assist/skills/[name]/verify/route.ts
new file mode 100644
index 00000000..cecb4fa8
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/verify/route.ts
@@ -0,0 +1,22 @@
+import { z } from "zod";
+import { badBody, recipeFailure } from "@/server/recipe-routes";
+import { verifyRecipe } from "@/server/recipes";
+
+const Body = z.object({
+ level: z.enum(["plan", "demo", "real"]).default("demo"),
+ engine: z.enum(["cloud", "open"]).optional(),
+ /** A real test spends money or GPU time: the page asks first, with its price. */
+ confirm: z.boolean().optional(),
+});
+
+/** Check a skill's recipe (plan, a free dry run, or a real test) and record what passed in its `verified`. */
+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/verify">) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ const { level, engine, confirm } = parsed.data;
+ return Response.json(await verifyRecipe((await ctx.params).name, level, engine, { confirm }));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index fc919bd7..f6da8919 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,140 +1,8 @@
import { connection } from "next/server";
-import { z } from "zod";
-import { FORMAT_INFO } from "@/lib/av/formats";
-import { OPERATION_LABELS, type VideoFormat } from "@/lib/catalog/types";
+import { OPERATION_LABELS } from "@/lib/catalog/types";
import { createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
-import { SignatureSchema } from "@/server/palettes";
-
-/** A point on a picture as fractions of its width and height. */
-const Focus = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) });
-
-/**
- * Where a LoRA named in a request may be downloaded from. A file the server doesn't know is fetched from its
- * link before a ComfyUI run (or by fal / Replicate), so an open link would let any token holder make the
- * server fetch an internal address into models/loras. Every research LoRA is on Hugging Face or civitai;
- * trained and mirrored copies live in fal's or Replicate's file stores.
- */
-const LORA_HOSTS = ["huggingface.co", "hf.co", "civitai.com", "fal.media", "replicate.delivery"];
-function loraHostOk(link: string): boolean {
- try {
- const u = new URL(link);
- const host = u.hostname.toLowerCase();
- return u.protocol === "https:" && !u.username && !u.password && LORA_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
- } catch {
- return false;
- }
-}
-
-const RequestSchema = z.object({
- feature: z.string().min(1),
- presetId: z.string().optional(),
- modelId: z.string().min(1),
- op: z.string().optional(),
- prompt: z.string().max(10_000).optional(),
- negativePrompt: z.string().max(4_000).optional(),
- inputs: z
- .object({
- images: z.array(z.string()).max(14).optional(),
- endImage: z.string().optional(),
- mask: z.string().optional(),
- sketch: z.string().optional(),
- video: z.string().optional(),
- audio: z.string().optional(),
- audio2: z.string().optional(),
- voiceAudio: z.string().optional(),
- voiceAudio2: z.string().optional(),
- videos: z.array(z.string()).max(24).optional(),
- // Reference audio clips for reference-to-video (Seedance 2.5 / Cinema Studio take up to 10).
- audios: z.array(z.string()).max(10).optional(),
- // A .glb to rig.
- model3d: z.string().optional(),
- })
- .optional(),
- params: z
- .object({
- aspectRatio: z.string().optional(),
- resolution: z.string().optional(),
- duration: z.number().positive().max(600).optional(),
- numOutputs: z.number().int().min(1).max(8).optional(),
- seed: z.number().int().optional(),
- generateAudio: z.boolean().optional(),
- enhancePrompt: z.boolean().optional(),
- shots: z.array(z.object({ prompt: z.string().max(2000), duration: z.number().positive().max(60) })).max(12).optional(),
- multiShot: z.literal("auto").optional(),
- draft: z.boolean().optional(),
- draftId: z.string().max(8192).optional(),
- voice: z.string().max(200).optional(),
- dialogue: z.array(z.object({ text: z.string().max(5000), voice: z.string().max(200).optional() })).max(200).optional(),
- targetLanguage: z.string().max(80).optional(),
- startTime: z.number().min(0).max(36_000).optional(),
- endTime: z.number().min(0).max(36_000).optional(),
- fps: z.number().positive().max(240).optional(),
- palette: z.array(z.string().regex(/^#?[0-9a-fA-F]{6}$/)).max(16).optional(),
- styleId: z.string().max(200).optional(),
- sourceLanguage: z.string().max(80).optional(),
- numLayers: z.number().int().min(1).max(20).optional(),
- // Round 4: clicked points, keyframe times, output formats, Ken Burns moves, crossfades, retiming, overlays, rigging.
- points: z.array(z.object({ x: z.number(), y: z.number(), label: z.enum(["positive", "negative"]).optional() })).max(64).optional(),
- keyframeTimes: z.array(z.number().min(0).max(600)).max(10).optional(),
- format: z.enum(Object.keys(FORMAT_INFO) as [VideoFormat, ...VideoFormat[]]).optional(),
- zoomFrom: z.number().min(0.1).max(10).optional(),
- zoomTo: z.number().min(0.1).max(10).optional(),
- panFrom: Focus.optional(),
- panTo: Focus.optional(),
- easing: z.enum(["linear", "ease-in-out"]).optional(),
- crossfade: z.number().min(0).max(30).optional(),
- sourceDuration: z.number().positive().max(36_000).optional(),
- frameInterval: z.number().int().min(1).max(10_000).optional(),
- targetFps: z.number().positive().max(240).optional(),
- slowdown: z.number().min(1).max(8).optional(),
- colormap: z.string().max(40).optional(),
- sideBySide: z.boolean().optional(),
- matteOutput: z.enum(["cutout", "matte"]).optional(),
- position: Focus.optional(),
- scale: z.number().positive().max(10).optional(),
- animation: z.union([z.string().max(200), z.number()]).optional(),
- extra: z.record(z.string(), z.unknown()).optional(),
- })
- .optional(),
- presetOptions: z.record(z.string(), z.string()).optional(),
- presetStrength: z.number().min(0).max(1).optional(),
- mix: z.object({ presetId: z.string().max(120), strength: z.number().min(0).max(1) }).optional(),
- // A Fuobe Original runs on both engines: the one to run on (the composer's switch). Unset: the engine mode, else
- // the first connected.
- engine: z.enum(["open", "cloud"]).optional(),
- // A recipe's LoRAs (the evaluation harness, scripts/eval): added after the preset's own. On ComfyUI `file` must
- // already be in models/loras (ComfyUI checks the name against its list); a cloud LoRA endpoint takes `url`.
- loras: z
- .array(
- z.object({
- file: z
- .string()
- .min(1)
- .max(200)
- // Brackets too: Redmond's Z-Image LoRAs are called "[ZImage.Turbo]FilmStill_Redmond.safetensors".
- .regex(/^[\w ()[\]+,.@-]+(\/[\w ()[\]+,.@-]+)*$/, "a file name in ComfyUI's models/loras")
- .refine((f) => !f.split("/").includes(".."), "a file name in ComfyUI's models/loras"),
- // Only the public model hubs and the cloud providers' file stores: the server (or a provider) may fetch it.
- url: z
- .string()
- .max(2000)
- .regex(/^https:\/\//, "an https:// link")
- .refine(loraHostOk, "a LoRA link on Hugging Face, civitai, fal or Replicate")
- .optional(),
- strength: z.number().min(-4).max(4).optional(),
- trigger: z.string().max(200).optional(),
- target: z.enum(["high", "low", "both"]).optional(),
- }),
- )
- .max(8)
- .optional(),
- // Image studio: the Color signature / Moodboard picks (its sentences join the prompt on the server).
- signature: SignatureSchema,
- // What a tool calls its result (Trim · 0:01.0–0:02.5, Captions · Karaoke), shown instead of the prompt.
- title: z.string().max(200).optional(),
- batchTitle: z.string().max(200).optional(),
-});
+import { GenerationRequestSchema } from "@/server/request-schema";
/**
* List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,
@@ -150,7 +18,7 @@ export async function GET(request: Request) {
/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */
export async function POST(request: Request) {
- const parsed = RequestSchema.safeParse(await request.json().catch(() => null));
+ const parsed = GenerationRequestSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });
}
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 5c715a38..3386ee87 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -198,6 +198,8 @@ export interface Skill extends SkillMeta {
enabled: boolean;
/** Extra files that came with an uploaded skill (references, examples), readable with load_skill. */
files: { path: string; size: number }[];
+ /** Its files hold a valid recipe.json: it runs by itself from a form, with no LLM (src/lib/recipe.ts). */
+ recipe?: boolean;
createdAt: number;
updatedAt: number;
}
diff --git a/src/lib/library.ts b/src/lib/library.ts
index 1725e339..7bd6d2e7 100644
--- a/src/lib/library.ts
+++ b/src/lib/library.ts
@@ -124,12 +124,13 @@ export function listOrder(f: Pick<FeedFilter, "trashed" | "pinned">): (a: Genera
* Jobs nobody asked to see on their own: the steps a chain runs before its result (a Shorts cut, a
* Click to Ad voiceover, an Ad Multiplier hook: every "<studio>-step" feature), and helper jobs a
* studio starts by itself (a Mixed Media preview frame, a Faceless channel avatar or narrator sample,
- * a moodboard's cover), and the evaluation harness's runs (scripts/eval: hundreds of test renders). The
+ * a moodboard's cover), the evaluation harness's runs (scripts/eval: hundreds of test renders) and a skill
+ * recipe's free dry runs (skill-check, moved to the Trash when the check ends). The
* Library and the home feed leave them out unless "Show steps" is on; a list that names its features
* (a studio reading its own steps) gets what it asks for.
*/
export const HELPER_SUFFIX = "-step";
-export const HELPER_FEATURES = ["mixed-media-preview", "faceless-avatar", "faceless-voice", "moodboard", "eval"] as const;
+export const HELPER_FEATURES = ["mixed-media-preview", "faceless-avatar", "faceless-voice", "moodboard", "eval", "skill-check"] as const;
export function isHelperFeature(feature: string): boolean {
return feature.endsWith(HELPER_SUFFIX) || (HELPER_FEATURES as readonly string[]).includes(feature);
diff --git a/src/server/assist/context-tools.ts b/src/server/assist/context-tools.ts
index 1eaa8a3d..cd6247a6 100644
--- a/src/server/assist/context-tools.ts
+++ b/src/server/assist/context-tools.ts
@@ -1,7 +1,8 @@
import "server-only";
import { z } from "zod";
import { guessCategory, MEMORY_CATEGORIES, MEMORY_MAX_CHARS, toCategory, type MemoryCategory } from "@/lib/assist";
-import { getSkill, skillFile } from "../skills";
+import { recipeMarkdown } from "@/lib/recipe";
+import { getSkill, skillFile, skillRecipe } from "../skills";
import { canUseSkill, skillsFor } from "./context";
import { defineTool } from "./define";
import { addMemory, deleteMemory } from "./memory";
@@ -53,13 +54,16 @@ const loadSkill = defineTool({
return { content: text.length > 40_000 ? `${text.slice(0, 40_000)}\n… (cut at 40,000 characters)` : text, items: [{ id: "", role: "tool", text: `Read ${file} from ${s.title}` }] };
}
const item = { id: "", role: "tool" as const, text: `Using the ${s.title} skill`, href: `/assist/skills?skill=${s.name}` };
+ // A skill with a recipe also runs by itself: its "Run it" section follows the instructions.
+ const recipe = skillRecipe(n);
+ const runs = recipe ? `\n\n${recipeMarkdown(recipe, { name: n })}` : "";
if (ctx.thread) {
if (ctx.thread.skills.includes(n)) return { content: `/${n} is already loaded — its instructions are in your context. Follow them.` };
ctx.thread.loadSkill(n);
- return { content: `Loaded /${n} (${s.title}). Its instructions are added to your context right after this result — read them, then follow them for this job.`, items: [item] };
+ return { content: `Loaded /${n} (${s.title}). Its instructions are added to your context right after this result — read them, then follow them for this job.${recipe ? " It also runs by itself with new inputs (see its Run it section)." : ""}`, items: [item] };
}
// Over MCP there's no chat context to add to: the instructions come back as the result.
- return { content: `# ${s.title} (/${s.name})\n\n${s.body}`, items: [item] };
+ return { content: `# ${s.title} (/${s.name})\n\n${s.body}${runs}`, items: [item] };
},
});
diff --git a/src/server/assist/context.ts b/src/server/assist/context.ts
index b90402d3..dca4648f 100644
--- a/src/server/assist/context.ts
+++ b/src/server/assist/context.ts
@@ -2,9 +2,10 @@ import "server-only";
import type { AssistMemory, ContextFact, Skill } from "@/lib/assist";
import { describeRule, zoneLabel, type ScheduleRule } from "@/lib/assist-schedule";
import type { Engine } from "@/lib/catalog/types";
+import { recipeMarkdown } from "@/lib/recipe";
import { db } from "../db";
import { engineMode } from "../settings";
-import { enabledSkills, getSkill } from "../skills";
+import { enabledSkills, getSkill, skillRecipe } from "../skills";
import { memoriesFor } from "./memory";
import { getProject } from "./projects";
@@ -150,7 +151,9 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {
const s = getSkill(name);
if (!s) continue;
const files = s.files.length ? `\n\n(Files with this skill, readable with load_skill and file: ${s.files.map((f) => f.path).join(", ")})` : "";
- facts.push({ section: "active", key: s.name, text: `### /${s.name} — ${s.title}\n${clip(s.body, SKILL_BODY)}${files}` });
+ const recipe = s.recipe ? skillRecipe(s.name) : null;
+ const runs = recipe ? `\n\n${recipeMarkdown(recipe, { name: s.name })}` : "";
+ facts.push({ section: "active", key: s.name, text: `### /${s.name} — ${s.title}\n${clip(s.body, SKILL_BODY)}${files}${runs}` });
}
return facts;
}
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 7743433e..22f24d5f 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -71,6 +71,8 @@ export interface JoinOptions {
/** Clips that already exist, placed before the chained ones (extend: the original video). */
before?: string[];
step?: GenerationRequest["step"];
+ /** A recipe's free dry run (GenerationRequest.demo): the join runs on the demo provider too. */
+ demo?: boolean;
}
const joinModelId = (engine: Engine) => (engine === "open" ? "oss-join-clips" : "join-clips");
@@ -104,6 +106,7 @@ export function joinClips(ids: string[], o: JoinOptions): Generation {
feature: o.feature,
modelId,
op: "concat",
+ ...(o.demo && { demo: true }),
prompt: o.title,
inputs: last && o.before?.length ? { videos: o.before } : undefined,
// ComfyUI's join plays at the first clip's frame rate (linked in the workflow).
@@ -174,6 +177,7 @@ export function createShotFilm(original: GenerationRequest, model: ModelDef): Ge
engine: model.engine,
feature: original.feature,
batchId,
+ demo: original.demo,
title: overall || shots.map((s) => tidy(s.prompt)).join(" / "),
aspectRatio: params.aspectRatio,
resolution: params.resolution,
@@ -242,6 +246,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
engine: model.engine,
feature: original.feature,
batchId,
+ demo: original.demo,
title: tidy(original.prompt) || "Keyframe film",
aspectRatio: params.aspectRatio,
resolution: params.resolution,
@@ -294,6 +299,7 @@ export function createExtendChain(original: GenerationRequest, model: ModelDef):
engine: model.engine,
feature: original.feature,
batchId,
+ demo: original.demo,
title: tidy(original.prompt) || "Extended video",
before: [video],
step: { label: "Extended video", index: 2, of: 3 },
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 74eddcec..d698ac25 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -303,6 +303,8 @@ export const ASSET_REFS: AssetRef[] = [
{ table: "assist_schedules", cols: ["attachments_json"], what: "scheduled task", name: "title" },
// Character Swap Studio: the character picture, each clip and its 24 fps copy, masks, anchors, takes and their masters.
{ table: "swap_projects", cols: ["data_json"], what: "Character Swap project", name: "name" },
+ // A user skill's bundled text files: its recipe.json names the files a run starts from (an example, a fixed logo).
+ { table: "skills", cols: ["files_json"], what: "skill", key: "name", name: "title" },
];
/**
@@ -324,7 +326,6 @@ export const ASSET_FREE: Record<string, string> = {
"assist_projects.skills_json": "skill names",
"assist_thread_state.skills_json": "skill names",
"skills.meta_json": "SKILL.md front matter",
- "skills.files_json": "a skill's own text files, stored inline",
"lora_mirrors.source_url": "where a LoRA file downloads from (civitai, Hugging Face), without the key",
"lora_mirrors.hosted_url": "the provider's copy of a LoRA file (fal or Replicate storage), never ours",
"shares.tags_json": "words",
@@ -396,12 +397,13 @@ export function deleteGeneration(id: string): void {
* `loras` and `seconds` (the clip length asked for) prefer a route that carries every LoRA and makes that
* length (Replicate's Wan 2.2 fast renders only 81–121 frames, fal's 17–161).
*/
-export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRef[] = [], seconds?: number): { route: ModelRoute; demo: boolean } {
+export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRef[] = [], seconds?: number, forceDemo = false): { route: ModelRoute; demo: boolean } {
// Honour the preferred cloud aggregator (Settings → API configuration) when a model is on several.
const preferred = getSetting("cloudProvider");
const routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));
const demo = getSetting("demoMode");
- if (demo === "on") return { route: routes[0], demo: true };
+ // A request marked demo (a skill recipe's free dry run) runs on the demo provider whatever Settings says.
+ if (demo === "on" || forceDemo) return { route: routes[0], demo: true };
const takes = (r: ModelRoute) => !r.map?.maxImages || images <= r.map.maxImages;
// A route that carries every LoRA wins (Replicate's Wan 2.2 takes one per expert, fal's takes a Mix), then one
// that makes the length asked; otherwise the first ready one runs and the plan's notes say what it changes.
@@ -548,7 +550,7 @@ function prepare(original: GenerationRequest) {
if (access.dropped.length) plan = { ...plan, loras: access.loras, prompt: withoutTriggers(plan.prompt, plan.loras.filter((l) => !access.loras.some((k) => k.file === l.file)), access.loras) };
else if (access.loras.some((l, i) => l !== plan.loras[i])) plan = { ...plan, loras: access.loras };
// A preset can route to another model than the one asked for: its routes that are on (or the switch that's off).
- const { route, demo } = chooseRoute(offeredRoutes(plan.model, routesFor(plan.model, plan.op)), req.inputs?.images?.length ?? 0, plan.loras, seconds);
+ const { route, demo } = chooseRoute(offeredRoutes(plan.model, routesFor(plan.model, plan.op)), req.inputs?.images?.length ?? 0, plan.loras, seconds, !!worded.demo);
// What the cloud run can carry: a LoRA whose licence doesn't allow hosting stays on the GPU, and an API
// takes at most so many (the plan's notes say which were left out). Open runs carry them all. Without a
// civitai key a look's civitai LoRA the run can't get is left out (and said), rather than failing at the
@@ -889,14 +891,15 @@ const submitting = (): Set<string> => (globalThis.__fuobeSubmitting ??= new Set<
* placeholder, helps nobody). Returns the error for a step that can't match its dependencies, and
* whether it should run as a demo because they did.
*/
-function chainMode(p: { demo: boolean; plan: { model: { name: string } }; route: ModelRoute }, deps: Pick<Row, "provider">[]): { error?: string; forceDemo?: boolean } {
+function chainMode(p: { demo: boolean; plan: { model: { name: string } }; route: ModelRoute }, deps: Pick<Row, "provider">[], asked?: Pick<GenerationRequest, "demo">): { error?: string; forceDemo?: boolean } {
const demoDeps = deps.filter((d) => d.provider === "mock").length;
if (p.demo && demoDeps < deps.length) {
const needs = p.route.provider === "llm" ? "Claude or Ollama" : provider(p.route.provider).label;
return { error: `${p.plan.model.name} needs ${needs} to continue what the earlier steps made for real — connect it in Settings, then retry` };
}
if (!p.demo && demoDeps > 0) {
- if (getSetting("demoMode") === "off") return { error: "An earlier step ran as a demo — retry it with its provider connected" };
+ // A dry run (GenerationRequest.demo) stays a demo even with Settings → Demo mode off.
+ if (getSetting("demoMode") === "off" && !asked?.demo) return { error: "An earlier step ran as a demo — retry it with its provider connected" };
return { forceDemo: true };
}
return {};
@@ -1058,7 +1061,7 @@ async function advanceDependents(): Promise<void> {
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
const prepared = prepare(original);
- const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);
+ const mode = chainMode(prepared, deps as Pick<Row, "provider">[], original);
if (mode.error) throw new Error(mode.error);
const p = mode.forceDemo ? { ...prepared, demo: true, providerId: "mock" as const, cost: 0 } : prepared;
update(r.id, {
diff --git a/src/server/recipe-routes.ts b/src/server/recipe-routes.ts
new file mode 100644
index 00000000..2008a30d
--- /dev/null
+++ b/src/server/recipe-routes.ts
@@ -0,0 +1,20 @@
+import "server-only";
+import { z } from "zod";
+import { RecipeError } from "./recipes";
+import { SkillError } from "./skills";
+
+/** What the recipe routes take: one set of values, rows, or a CSV, and the engine to run on. */
+export const RunBody = z.object({
+ values: z.record(z.string(), z.unknown()).optional(),
+ rows: z.array(z.record(z.string(), z.unknown())).max(200).optional(),
+ csv: z.string().max(500_000).optional(),
+ engine: z.enum(["cloud", "open"]).optional(),
+});
+
+/** A refusal as JSON: the reason, every problem of a recipe, and the status a SkillError carries. */
+export function recipeFailure(e: unknown): Response {
+ const status = e instanceof SkillError ? e.status : 500;
+ return Response.json({ error: (e as Error).message, ...(e instanceof RecipeError && { problems: e.problems }) }, { status });
+}
+
+export const badBody = (issues: z.core.$ZodIssue[]) => Response.json({ error: issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; ") }, { status: 400 });
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
new file mode 100644
index 00000000..5b3936d8
--- /dev/null
+++ b/src/server/recipes.ts
@@ -0,0 +1,774 @@
+import "server-only";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { nanoid } from "nanoid";
+import { planRunnable, totalCost, type PlannedJob } from "@/lib/assist";
+import { getModel } from "@/lib/catalog";
+import { dualEngine } from "@/lib/catalog/engines";
+import { currentModelId, replacedBy } from "@/lib/catalog/replaced";
+import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";
+import { probeMedia, type MediaInfo } from "@/lib/media-probe";
+import {
+ checkOutputs,
+ checkValues,
+ compile,
+ exampleValues,
+ isMediaRef,
+ isMediaType,
+ parseRecipe,
+ parseRows,
+ RECIPE_FILE,
+ RECIPE_LIMITS,
+ recipeProblems,
+ RecipeSchema,
+ SKILL_CHECK_FEATURE,
+ today,
+ verifiedLine,
+ type Compiled,
+ type FilledCheck,
+ type Recipe,
+ type RecipeValues,
+ type VerifiedEngine,
+} from "@/lib/recipe";
+import type { Skill } from "@/lib/assist";
+import { planSteps } from "./assist/studio-tools";
+import { executeTool, getTool, planFor, validateInput } from "./assist/tools";
+import type { JobPlace } from "./assist/define";
+import { createPipeline } from "./chains";
+import { llmText, llmTextBackend } from "./enhance";
+import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained } from "./generations";
+import { trashGenerations } from "./library";
+import { isOffered, modelLicence } from "./model-access";
+import { GenerationRequestSchema } from "./request-schema";
+import { engineMode } from "./settings";
+import { getSkill, setSkillFile, skillFile, SkillError } from "./skills";
+import { absolutePath, readRef, saveFile } from "./storage";
+
+/**
+ * Running a skill's recipe (src/lib/recipe.ts, package W1): price it, run it with new inputs (one createPipeline per
+ * row, or one gated Assist tool call), and check it before it's trusted — the plan on each engine its steps allow, a
+ * free dry run on the demo provider (GenerationRequest.demo, whatever Settings → Demo mode says), and an optional
+ * real test whose outputs are checked by their structure (probeMedia), never by their pixels. What was checked is
+ * written back into the recipe's `verified`; "needs a re-check" is computed when it's read.
+ */
+
+/** A recipe that can't be saved or run as it is, with every reason. */
+export class RecipeError extends SkillError {
+ constructor(
+ readonly problems: string[],
+ status = 422,
+ ) {
+ super(problems.length === 1 ? problems[0] : `Fix the recipe first: ${problems.join("; ")}`, status);
+ }
+}
+
+const ENGINES: Engine[] = ["cloud", "open"];
+const ENGINE_NAME: Record<Engine, string> = { cloud: "the cloud", open: "your GPU" };
+const asList = (a: string | string[] | undefined): string[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);
+
+// ---------------------------------------------------------------------------
+// Reading and saving
+
+/** A skill and its recipe; a skill without one (or with a broken one) is refused with the reason. */
+export function getRecipe(name: string): { skill: Skill; recipe: Recipe } {
+ const skill = getSkill(name);
+ if (!skill) throw new SkillError("No such skill", 404);
+ const text = skillFile(name, RECIPE_FILE);
+ if (text === null) throw new SkillError(`/${name} has no recipe: it runs through Assist`, 404);
+ const parsed = parseRecipe(text);
+ if (!parsed.ok) throw new SkillError(parsed.error, 422);
+ return { skill, recipe: parsed.recipe };
+}
+
+/** Tools a recipe may call: the gated ones that make something (not remember, which changes what Assist knows). */
+const runnableTool = (name: string) => !!getTool(name)?.gated && name !== "remember";
+
+/**
+ * Problems only the server can see: a model the catalog doesn't have (after REPLACED_BY), a tool a recipe can't call,
+ * and a step whose request, filled with the examples, the API itself would refuse (shape and limits).
+ */
+function serverProblems(recipe: Recipe): string[] {
+ const out: string[] = [];
+ for (const s of recipe.steps) {
+ if (s.kind === "tool") {
+ if (!runnableTool(s.tool)) out.push(`Step “${s.key}”: “${s.tool}” isn't a tool a recipe can run`);
+ } else if (!getModel(currentModelId(s.request.modelId))) out.push(`Step “${s.key}”: Fuobe has no model “${s.request.modelId}”`);
+ }
+ if (out.length) return out;
+ try {
+ compileRun({ name: "check", title: "Check" }, recipe, valuesForCheck(recipe), "cloud", { run: "check" });
+ } catch (e) {
+ out.push((e as Error).message);
+ }
+ return out;
+}
+
+/** Everything that keeps a recipe from being saved: its shape (recipeProblems), then the catalog and the API's limits. */
+export function allProblems(recipe: Recipe): string[] {
+ const own = recipeProblems(recipe);
+ return own.length ? own : serverProblems(recipe);
+}
+
+/**
+ * Save a skill's recipe.json (user skills only: "Duplicate it first" for a built-in), refusing one with problems.
+ * `verified` is the server's to write: a recipe saved from outside (an edit, an upload) starts unchecked.
+ */
+export function saveRecipe(name: string, input: unknown, o: { keepVerified?: boolean } = {}): Recipe {
+ const skill = getSkill(name);
+ if (!skill) throw new SkillError("No such skill", 404);
+ if (skill.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then change your copy", 403);
+ const parsed = RecipeSchema.safeParse(input);
+ if (!parsed.success) throw new RecipeError(parsed.error.issues.map((i) => (i.path.length ? `${i.path.map(String).join(".")}: ${i.message}` : i.message)));
+ const recipe: Recipe = { ...parsed.data };
+ if (!o.keepVerified) delete recipe.verified;
+ const problems = allProblems(recipe);
+ if (problems.length) throw new RecipeError(problems);
+ setSkillFile(name, RECIPE_FILE, `${JSON.stringify(recipe, null, 2)}\n`);
+ return recipe;
+}
+
+// ---------------------------------------------------------------------------
+// Engines
+
+/** The engines one step can run on: an Original on both (unless the step names one), any other model on its own. */
+function stepEngines(s: Recipe["steps"][number]): Engine[] {
+ if (s.kind === "tool") return ENGINES;
+ const m = getModel(currentModelId(s.request.modelId));
+ if (!m) return [];
+ if (dualEngine(m)) return s.request.engine ? [s.request.engine] : (m.engines ?? ENGINES);
+ return [m.engine];
+}
+
+/** The engines every step allows on this install (Settings → Engine mode applied). Fuobe never swaps a model across engines. */
+export function recipeEngines(recipe: Recipe): Engine[] {
+ const mode = engineMode();
+ return ENGINES.filter((e) => recipe.steps.every((s) => stepEngines(s).includes(e)) && (mode === "both" || mode === e));
+}
+
+/** Why no engine is left, in words. */
+function noEngine(recipe: Recipe): string {
+ const sides = ENGINES.filter((e) => recipe.steps.every((s) => stepEngines(s).includes(e)));
+ if (!sides.length) return "Its steps need both engines at once (a cloud model and a model on your GPU): run them as two skills";
+ return sides[0] === "open"
+ ? "It runs on your GPU (open source), but this install is set to paid cloud APIs only (Settings → Engine mode)"
+ : "It runs on paid cloud APIs, but this install is set to open source only (Settings → Engine mode)";
+}
+
+// ---------------------------------------------------------------------------
+// Compiling one run
+
+/** Validate and compile one run: each filled request as the API takes it, an Original put on the run's engine. */
+function compileRun(skill: { name: string; title: string }, recipe: Recipe, values: RecipeValues, engine: Engine, o: { run: string; demo?: boolean }): Compiled {
+ const c = compile(recipe, values, { skill: skill.name, run: o.run, title: skill.title, demo: o.demo });
+ if (c.kind === "tool") {
+ const error = validateInput(c.tool, c.input);
+ if (error) throw new SkillError(`Step “${c.key}”: ${error.replace(/^Invalid input: /, "")}`, 422);
+ return c;
+ }
+ return {
+ ...c,
+ steps: c.steps.map((s) => {
+ const { skill: stamp, demo, batchTitle, step, chain, ...asked } = s.request;
+ const parsed = GenerationRequestSchema.safeParse(asked);
+ if (!parsed.success) throw new SkillError(`Step “${s.key}”: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`, 422);
+ const req = parsed.data as GenerationRequest;
+ const m = getModel(currentModelId(req.modelId));
+ const slots = s.chain ?? chain;
+ return {
+ ...s,
+ ...(slots && { chain: slots }),
+ request: { ...req, ...(m && dualEngine(m) && !req.engine && { engine }), batchTitle, skill: stamp, ...(step && { step }), ...(demo && { demo }) },
+ };
+ }),
+ };
+}
+
+interface RunPlan {
+ jobs: PlannedJob[];
+ total: number | null;
+ errors: string[];
+ place?: JobPlace;
+}
+
+/** Price one compiled run the way it would start (planSteps / planFor), with what stops it. */
+function planRun(c: Compiled, engine: Engine): RunPlan {
+ if (c.kind === "tool") {
+ const p = planFor(c.tool, c.input, { engine });
+ const errors = [...(p.error ? [p.error] : []), ...p.jobs.filter((j) => j.error).map((j) => `${j.note ?? j.modelName}: ${j.error}`)];
+ return { jobs: p.jobs, total: p.total, errors, place: { ...(p.studio && { studio: p.studio }), ...(p.href && { href: p.href }), ...(p.fallback && { fallback: p.fallback }) } };
+ }
+ const jobs = planSteps("run_skill", c.steps);
+ const errors = jobs.filter((j) => j.error).map((j) => `${j.note && j.note !== j.modelName ? `${j.note} (${j.modelName})` : j.modelName}: ${j.error}`);
+ if (!errors.length && !planRunnable(jobs)) errors.push("Nothing to run");
+ return { jobs, total: totalCost(jobs), errors };
+}
+
+/** The run with every request on the demo provider: valid and priced the same whether or not a provider is connected. */
+function asDemo(c: Compiled): Compiled {
+ return c.kind === "tool" ? c : { ...c, steps: c.steps.map((s) => ({ ...s, request: { ...s.request, demo: true } })) };
+}
+
+/**
+ * The plan check: the run as it would start. When only this install stops it (no provider connected, with Settings →
+ * Demo mode off), the recipe itself is fine: the same run on the demo provider passes it, and the reason is a note.
+ */
+function planCheck(c: Compiled, engine: Engine): RunPlan & { notes: string[] } {
+ const plan = planRun(c, engine);
+ if (!plan.errors.length || c.kind === "tool") return { ...plan, notes: [] };
+ const demo = planRun(asDemo(c), engine);
+ return demo.errors.length ? { ...plan, notes: [] } : { ...demo, notes: [...new Set(plan.errors.map((e) => e.replace(/^[^:]+: /, "")))] };
+}
+
+/**
+ * sha256 of what a run uses: each step's model, operation, route (the first one on, as the demo provider would name it,
+ * so connecting a key doesn't count as a change) and price table.
+ */
+function planHash(compiled: Compiled, engine: Engine): string {
+ const c = asDemo(compiled);
+ const parts =
+ c.kind === "tool"
+ ? planFor(c.tool, c.input, { engine }).jobs.map((j) => [j.modelId, j.op, getModel(j.modelId)?.pricing ?? null])
+ : c.steps.map((s) => {
+ const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, asList(s.after).length);
+ return [p.model.id, p.op, p.route.provider, p.route.endpoint, p.model.pricing ?? null];
+ });
+ return `sha256:${crypto.createHash("sha256").update(JSON.stringify(parts)).digest("hex")}`;
+}
+
+// ---------------------------------------------------------------------------
+// Stand-in files: a check's media input with no example (or one whose file is gone)
+
+declare global {
+ var __fuobeStandIns: Map<string, string> | undefined;
+}
+
+/** A small real file of a kind, saved once as a hidden (derived) asset: the dry run's providers read their inputs. */
+function standIn(kind: "image" | "video" | "audio"): string {
+ const cache = (globalThis.__fuobeStandIns ??= new Map());
+ const known = cache.get(kind);
+ if (known && fs.existsSync(absolutePath(decodeURIComponent(known.slice("/api/files/".length))))) return known;
+ const samples = path.join(process.cwd(), "public", "samples");
+ const file =
+ kind === "image"
+ ? { data: fs.readFileSync(path.join(samples, "grade-sample.jpg")), contentType: "image/jpeg" }
+ : kind === "video"
+ ? { data: fs.readFileSync(path.join(samples, "demo-landscape.mp4")), contentType: "video/mp4" }
+ : { data: silentWav(2), contentType: "audio/wav" };
+ const url = saveFile({ ...file, source: "derived", name: `skill-check-${kind}` }).url;
+ cache.set(kind, url);
+ return url;
+}
+
+function silentWav(seconds: number): Buffer {
+ const rate = 16000;
+ const n = rate * seconds;
+ const buf = Buffer.alloc(44 + n * 2);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + n * 2, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(1, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 2, 28);
+ buf.writeUInt16LE(2, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(n * 2, 40);
+ return buf;
+}
+
+/** Whether a Fuobe file a recipe names still exists (a link elsewhere counts as there). */
+const fileThere = (ref: string) => {
+ if (!ref.startsWith("/api/files/")) return true;
+ try {
+ return fs.existsSync(absolutePath(decodeURIComponent(ref.slice("/api/files/".length).split("?")[0])));
+ } catch {
+ return false;
+ }
+};
+
+/** A stand-in link to price with, as the CLI's estimate does: nothing reads it. */
+const PRICE_STAND_IN = { image: "/api/files/uploads/estimate/stand-in.png", video: "/api/files/uploads/estimate/stand-in.mp4", audio: "/api/files/uploads/estimate/stand-in.wav" } as const;
+
+/**
+ * The values a check runs with: the examples, with a stand-in for a media input that has none or whose file is gone
+ * (a link to price with; a real small file when the run will read it: `files`).
+ */
+function valuesForCheck(recipe: Recipe, files = false): RecipeValues {
+ const fill = (kind: "image" | "video" | "audio") => (files ? standIn(kind) : PRICE_STAND_IN[kind]);
+ const values = exampleValues(recipe, fill);
+ for (const p of recipe.params) {
+ const v = values[p.id];
+ if (isMediaType(p.type) && (typeof v !== "string" || !isMediaRef(v) || (files && !fileThere(v)))) values[p.id] = fill(p.type);
+ }
+ const checked = checkValues(recipe, values);
+ return checked.values ?? values;
+}
+
+// ---------------------------------------------------------------------------
+// What a page shows
+
+export interface RecipeView {
+ name: string;
+ title: string;
+ builtin: boolean;
+ recipe: Recipe;
+ /** Engines its steps allow on this install. */
+ engines: Engine[];
+ /** Engines it may run on now: its plan check passed there. */
+ ready: Engine[];
+ /** Why it needs a re-check, per engine checked before. */
+ recheck: Partial<Record<Engine, string[]>>;
+ /** "Checked 29 Oct · Cloud ✓ · GPU not checked". */
+ line: string;
+ /** Why it runs nowhere on this install. */
+ why?: string;
+ /** Each step's model and its licence on each engine, as information. */
+ models: { engine: Engine; name: string; licence: string }[];
+}
+
+export function recipeView(name: string): RecipeView {
+ const { skill, recipe } = getRecipe(name);
+ const engines = recipeEngines(recipe);
+ const ready = engines.filter((e) => !!recipe.verified?.[e]?.plan);
+ const models = engines.flatMap((e) =>
+ recipe.steps.flatMap((s) => {
+ if (s.kind === "tool") return [];
+ const m = getModel(currentModelId(s.request.modelId));
+ if (!m) return [];
+ const l = modelLicence(m);
+ return [{ engine: e, name: m.name, licence: (e === "cloud" && dualEngine(m) ? l.cloud : undefined)?.name ?? l.licence.name }];
+ }),
+ );
+ return {
+ name: skill.name,
+ title: skill.title,
+ builtin: skill.source === "builtin",
+ recipe,
+ engines,
+ ready,
+ recheck: needsRecheck(recipe, ready),
+ line: verifiedLine(recipe, engines),
+ ...(!engines.length && { why: noEngine(recipe) }),
+ models: [...new Map(models.map((x) => [`${x.engine}:${x.name}`, x])).values()],
+ };
+}
+
+/**
+ * Why a checked recipe should be checked again, per engine (none: it's fine): a step's model moved by REPLACED_BY, a
+ * model switched off in Settings → Models & licences, a plan that no longer passes, or a plan hash (models, routes,
+ * prices) that differs from the one checked. Computed when read: there is no background job.
+ */
+export function needsRecheck(recipe: Recipe, engines: Engine[] = recipeEngines(recipe).filter((e) => !!recipe.verified?.[e]?.plan)): Partial<Record<Engine, string[]>> {
+ const out: Partial<Record<Engine, string[]>> = {};
+ const replaced = recipe.steps.flatMap((s) => {
+ if (s.kind !== "generate") return [];
+ const r = replacedBy(s.request.modelId);
+ return r ? [`${r.was} was replaced by ${getModel(r.id)?.name ?? r.id}`] : [];
+ });
+ for (const e of engines) {
+ const v = recipe.verified?.[e];
+ if (!v?.plan) continue;
+ const reasons = [...replaced];
+ for (const s of recipe.steps) {
+ if (s.kind !== "generate") continue;
+ const id = currentModelId(s.request.modelId);
+ const m = getModel(id);
+ if (m && !isOffered(id, dualEngine(m) ? e : undefined)) reasons.push(`${m.name} is switched off in Settings → Models & licences`);
+ }
+ if (!reasons.length) {
+ try {
+ const c = compileRun({ name: "check", title: "Check" }, recipe, valuesForCheck(recipe), e, { run: "check" });
+ const plan = planCheck(c, e);
+ if (plan.errors.length) reasons.push(plan.errors[0]);
+ else if (v.catalog && planHash(c, e) !== v.catalog) reasons.push("The models, routes or prices it uses changed since it was checked");
+ } catch (err) {
+ reasons.push((err as Error).message);
+ }
+ }
+ if (reasons.length) out[e] = [...new Set(reasons)];
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Rows
+
+export interface RunInput {
+ values?: Record<string, unknown>;
+ rows?: Record<string, unknown>[];
+ csv?: string;
+}
+
+interface Row {
+ line: number;
+ values?: RecipeValues;
+ errors: string[];
+}
+
+/** The runs asked for: one set of values, a list of rows, or a CSV (parsed and checked like the form). */
+function rowsOf(recipe: Recipe, input: RunInput): { rows: Row[]; errors: string[] } {
+ if (input.csv !== undefined) {
+ const p = parseRows(input.csv, recipe);
+ return { rows: p.rows.map((r) => ({ line: r.line, values: r.values, errors: r.errors })), errors: p.errors };
+ }
+ const list = input.rows ?? [input.values ?? {}];
+ const errors = list.length > RECIPE_LIMITS.rows ? [`At most ${RECIPE_LIMITS.rows} rows at a time — this has ${list.length}`] : list.length ? [] : ["Add a row to run"];
+ return {
+ errors,
+ rows: list.slice(0, RECIPE_LIMITS.rows).map((v, i) => {
+ const c = checkValues(recipe, v ?? {});
+ return { line: i + 1, values: c.values, errors: Object.values(c.errors) };
+ }),
+ };
+}
+
+function engineFor(recipe: Recipe, asked: Engine | undefined): Engine {
+ const engines = recipeEngines(recipe);
+ if (!engines.length) throw new SkillError(noEngine(recipe), 422);
+ if (asked && !engines.includes(asked)) throw new SkillError(`This skill doesn't run on ${ENGINE_NAME[asked]}: its steps run on ${engines.map((e) => ENGINE_NAME[e]).join(" or ")}`, 422);
+ return asked ?? engines[0];
+}
+
+// ---------------------------------------------------------------------------
+// Estimate and run
+
+export interface RecipeEstimate {
+ engine: Engine;
+ /** One entry per row: its jobs priced, and what stops it. */
+ runs: { line: number; jobs: PlannedJob[]; total: number | null; errors: string[] }[];
+ /** The first run's jobs ("What runs"). */
+ jobs: PlannedJob[];
+ /** Every run together (null: a price that varies). */
+ total: number | null;
+ /** Every job would run on the demo provider. */
+ demo: boolean;
+ runnable: boolean;
+ /** What stops every run (no column for an input, too many rows, a recipe that runs nowhere). */
+ errors: string[];
+ place?: JobPlace;
+}
+
+/** Price one run or many (rows priced together, with a total) on an engine, without starting anything. */
+export function estimateRecipe(name: string, input: RunInput, asked?: Engine): RecipeEstimate {
+ const { skill, recipe } = getRecipe(name);
+ const engine = engineFor(recipe, asked);
+ const { rows, errors } = rowsOf(recipe, input);
+ let place: JobPlace | undefined;
+ const runs = rows.map((r) => {
+ if (!r.values) return { line: r.line, jobs: [], total: null, errors: r.errors };
+ try {
+ const plan = planRun(compileRun(skill, recipe, r.values, engine, { run: "estimate" }), engine);
+ place ??= plan.place;
+ return { line: r.line, jobs: plan.jobs, total: plan.total, errors: plan.errors };
+ } catch (e) {
+ return { line: r.line, jobs: [], total: null, errors: [(e as Error).message] };
+ }
+ });
+ const jobs = runs.flatMap((r) => r.jobs);
+ const totals = runs.map((r) => r.total);
+ const total = totals.some((t) => t === null) ? null : Math.round(totals.reduce<number>((s, t) => s + (t ?? 0), 0) * 1000) / 1000;
+ return {
+ engine,
+ runs,
+ jobs: runs.find((r) => r.jobs.length)?.jobs ?? [],
+ total: runs.every((r) => !r.errors.length) ? total : null,
+ demo: jobs.length > 0 && jobs.every((j) => j.demo || j.error),
+ runnable: !errors.length && runs.length > 0 && runs.every((r) => !r.errors.length),
+ errors,
+ ...(place && { place }),
+ };
+}
+
+export interface RecipeRun {
+ /** The run's batch (a pipeline's rows share it), its generations, and the studio page a tool run opens in. */
+ batchId?: string;
+ ids: string[];
+ href?: string;
+}
+
+/**
+ * Run a recipe once or once per row on an engine whose plan check passed. Every row is validated and priced first:
+ * one bad row starts nothing. A pipeline is one createPipeline per row; a tool recipe one executeTool call per row.
+ */
+export async function runRecipe(name: string, input: RunInput, asked?: Engine): Promise<{ engine: Engine; runs: RecipeRun[]; demo: boolean }> {
+ const { skill, recipe } = getRecipe(name);
+ const engine = engineFor(recipe, asked);
+ if (!recipe.verified?.[engine]?.plan) throw new SkillError(`Check this skill on ${ENGINE_NAME[engine]} first — the check is free`, 409);
+ const { rows, errors } = rowsOf(recipe, input);
+ if (errors.length) throw new RecipeError(errors);
+ const bad = rows.flatMap((r) => (r.errors.length ? [`${rows.length > 1 ? `Row ${r.line}: ` : ""}${r.errors.join("; ")}`] : []));
+ if (bad.length) throw new RecipeError(bad);
+ // Compile and price every row before anything starts.
+ const compiled = rows.map((r) => {
+ const run = nanoid(10);
+ const c = compileRun(skill, recipe, r.values!, engine, { run });
+ const plan = planRun(c, engine);
+ if (plan.errors.length) throw new RecipeError(plan.errors.map((e) => `${rows.length > 1 ? `Row ${r.line}: ` : ""}${e}`));
+ return { run, c };
+ });
+ const runs: RecipeRun[] = [];
+ let demo = true;
+ if (compiled[0].c.kind === "tool") {
+ for (const { c } of compiled) {
+ if (c.kind !== "tool") continue;
+ const out = await executeTool(c.tool, c.input, { engine });
+ const text = typeof out.content === "string" ? out.content : "";
+ if (out.isError) {
+ if (!runs.length) throw new SkillError(text.replace(/^\{"error":"(.*)"\}$/, "$1") || "The tool couldn't start", 422);
+ break;
+ }
+ let href: string | undefined;
+ try {
+ href = (JSON.parse(text) as { href?: string }).href;
+ } catch {
+ href = undefined;
+ }
+ const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));
+ demo &&= ids.every((id) => getGeneration(id)?.provider === "mock");
+ runs.push({ ids, ...(href && { href }) });
+ }
+ return { engine, runs, demo };
+ }
+ const made: Generation[] = [];
+ try {
+ for (const { run, c } of compiled) {
+ if (c.kind !== "pipeline") continue;
+ const p = createPipeline(c.steps, { batchId: run });
+ made.push(...p.items);
+ runs.push({ batchId: p.batchId, ids: p.items.map((g) => g.id), href: "/library" });
+ }
+ } catch (e) {
+ // One row couldn't start after all (a race with Settings): stop the rows already started.
+ for (const g of made) void cancelGeneration(g.id);
+ throw e;
+ }
+ demo = made.every((g) => g.provider === "mock");
+ return { engine, runs, demo };
+}
+
+// ---------------------------------------------------------------------------
+// Checks
+
+export type VerifyLevel = "plan" | "demo" | "real";
+
+export interface EngineCheck {
+ engine: Engine;
+ /** `notes`: what stops a real run on this install that isn't the recipe's fault (a provider to connect). */
+ plan: { ok: boolean; total: number | null; demo: boolean; errors: string[]; notes: string[] };
+ dryRun?: { ok: boolean; problems: string[]; skipped?: string };
+ real?: { ok: boolean; problems: string[]; notes: string[]; demo: boolean };
+}
+
+const TERMINAL = new Set(["succeeded", "failed", "canceled"]);
+
+/** Wait for generations to finish (the runner moves them), at most `ms`; cancels what's left when time runs out. */
+async function settle(ids: string[], ms: number): Promise<Generation[]> {
+ const until = Date.now() + ms;
+ for (;;) {
+ const gens = ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);
+ if (gens.length === ids.length && gens.every((g) => TERMINAL.has(g.status))) return gens;
+ if (Date.now() > until) {
+ for (const g of gens) if (!TERMINAL.has(g.status)) await cancelGeneration(g.id);
+ return ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);
+ }
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+/** What a step should make: its check's kind, else the kind of the row it made. */
+const kindOf = (check: FilledCheck | undefined, g: Generation): MediaKind => check?.kind ?? g.kind;
+
+/** A step's own failure, in words. */
+const failure = (key: string, g: Generation | undefined) =>
+ !g ? `Step “${key}” wasn't made` : g.status !== "succeeded" ? `Step “${key}” ${g.status === "canceled" ? "was stopped" : "failed"}${g.error ? `: ${g.error}` : ""}` : null;
+
+const DRY_RUN_MS = 120_000;
+const REAL_RUN_MS = 15 * 60_000;
+
+/** The free dry run: one run on the demo provider, its rows hidden (skill-check) and moved to the Trash at the end. */
+async function dryRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<NonNullable<EngineCheck["dryRun"]>> {
+ const c = compileRun(skill, recipe, valuesForCheck(recipe, true), engine, { run: nanoid(10), demo: true });
+ // A studio step would make a record the user sees (a demo dub, a Layers project): its plan is its check in W1.
+ if (c.kind === "tool") return { ok: true, problems: [], skipped: `A studio step (${c.tool}) is checked by its plan only` };
+ const p = createPipeline(c.steps, { batchId: nanoid(10) });
+ const ids = p.items.map((g) => g.id);
+ try {
+ const done = new Map((await settle(ids, DRY_RUN_MS)).map((g) => [g.id, g]));
+ const problems: string[] = [];
+ for (const s of c.steps) {
+ const g = done.get(p.byKey[s.key]?.id);
+ const why = failure(s.key, g);
+ if (why) {
+ problems.push(why);
+ continue;
+ }
+ const kind = kindOf(c.checks[s.key], g!);
+ if (!g!.outputs.some((o) => o.kind === kind)) problems.push(`Step “${s.key}” made no ${kind}`);
+ }
+ return { ok: !problems.length, problems };
+ } finally {
+ trashGenerations(ids);
+ }
+}
+
+/** A stored output's header facts (duration, size, sound), or null when it can't be read. */
+async function infoOf(url: string, kind: MediaKind): Promise<MediaInfo | null> {
+ if (kind !== "video" && kind !== "audio") return null;
+ try {
+ return probeMedia(new Uint8Array((await readRef(url)).data));
+ } catch {
+ return null;
+ }
+}
+
+/** Whether a picture shows a sentence, by a model that sees images; null when none answers. */
+async function judgeLook(look: string, image: string): Promise<boolean | null> {
+ if (!llmTextBackend()) return null;
+ try {
+ const f = await readRef(image);
+ const answer = await llmText(
+ "You check whether a picture matches a short description. Answer yes or no first, then one short reason.",
+ `Description: ${look}`,
+ [{ data: f.data, contentType: f.contentType }],
+ );
+ if (!answer) return null;
+ return /^\W*yes\b/i.test(answer) ? true : /^\W*no\b/i.test(answer) ? false : null;
+ } catch {
+ return null;
+ }
+}
+
+/** One frame of a clip, through the cloud extract-frame model (the open engine has none to ask). */
+async function frameOf(video: string, engine: Engine): Promise<{ url?: string; ids: string[] }> {
+ if (engine !== "cloud" || !isOffered("extract-frame")) return { ids: [] };
+ try {
+ const [g] = createGenerations({ feature: SKILL_CHECK_FEATURE, modelId: "extract-frame", op: "frame", inputs: { video }, params: { extra: { frame_type: "middle" } } });
+ const [done] = await settle([g.id], 120_000);
+ return { url: done?.outputs.find((o) => o.kind === "image")?.url, ids: [g.id] };
+ } catch {
+ return { ids: [] };
+ }
+}
+
+/** The optional real test: the examples run for real, then each checked step's outputs are measured. */
+async function realRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<NonNullable<EngineCheck["real"]>> {
+ const notes: string[] = [];
+ const problems: string[] = [];
+ const c = compileRun(skill, recipe, valuesForCheck(recipe, true), engine, { run: nanoid(10) });
+ const helpers: string[] = [];
+ let made: Generation[];
+ let byKey: Record<string, string> = {};
+ if (c.kind === "tool") {
+ const out = await executeTool(c.tool, c.input, { engine });
+ if (out.isError) return { ok: false, problems: [typeof out.content === "string" ? out.content : "The tool couldn't start"], notes, demo: false };
+ const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));
+ made = await settle(ids, REAL_RUN_MS);
+ if (ids.length) byKey = { [c.key]: ids[0] };
+ } else {
+ const p = createPipeline(c.steps, { batchId: nanoid(10) });
+ made = await settle(p.items.map((g) => g.id), REAL_RUN_MS);
+ byKey = Object.fromEntries(Object.entries(p.byKey).map(([k, g]) => [k, g.id]));
+ }
+ const demo = made.length > 0 && made.every((g) => g.provider === "mock");
+ if (demo) notes.push(`It ran as a demo (no provider connected for ${ENGINE_NAME[engine]}): connect one in Settings for a real test`);
+ const byId = new Map(made.map((g) => [g.id, g]));
+ for (const [key, check] of Object.entries(c.checks)) {
+ const g = byId.get(byKey[key]);
+ const why = failure(key, g);
+ if (why) {
+ problems.push(why);
+ continue;
+ }
+ // A real check's length is ±10% of one length; a range stays a range.
+ const infos = await Promise.all(g!.outputs.map((o) => infoOf(o.url, o.kind)));
+ const res = checkOutputs(check, g!.outputs, infos);
+ problems.push(...res.problems.map((x) => `Step “${key}”: ${x}`));
+ notes.push(...res.skipped.map((x) => `Step “${key}”: couldn't read ${x}`));
+ if (check.look && res.ok) {
+ const still = g!.outputs.find((o) => o.kind === "image")?.url;
+ const clip = still ? undefined : g!.outputs.find((o) => o.kind === "video")?.url;
+ const frame = clip ? await frameOf(clip, engine) : { url: still, ids: [] };
+ helpers.push(...frame.ids);
+ const verdict = frame.url ? await judgeLook(check.look, frame.url) : null;
+ if (verdict === false) problems.push(`Step “${key}” doesn't look like “${check.look}”`);
+ else if (verdict === null) notes.push(`Step “${key}”: the look wasn't judged (no model that sees images${clip && engine === "open" ? ", and no frame extractor on your GPU" : ""})`);
+ }
+ }
+ if (helpers.length) trashGenerations(helpers);
+ return { ok: !problems.length, problems, notes, demo };
+}
+
+export interface VerifyResult {
+ ok: boolean;
+ engines: EngineCheck[];
+ view: RecipeView;
+}
+
+/**
+ * Check a recipe and write what passed into its `verified`:
+ * - `plan`: compile with the examples (a stand-in file for a media input with none) and price it on each engine its
+ * steps allow (or the one asked). Free.
+ * - `demo`: the plan, then one dry run per engine on the demo provider, with or without keys and whatever Settings →
+ * Demo mode says. Free; its rows are hidden and go to the Trash.
+ * - `real`: the above, then the examples for real (asks first: `confirm`), each checked step measured.
+ */
+export async function verifyRecipe(name: string, level: VerifyLevel, asked?: Engine, o: { confirm?: boolean } = {}): Promise<VerifyResult> {
+ const found = getRecipe(name);
+ const { skill } = found;
+ if (skill.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then check your copy", 403);
+ // A step that names a model Fuobe retired runs on what replaced it (as every run does): the re-check writes that down.
+ const recipe: Recipe = {
+ ...found.recipe,
+ steps: found.recipe.steps.map((s) => (s.kind === "generate" ? { ...s, request: currentRequest(s.request).request as typeof s.request } : s)),
+ };
+ const problems = allProblems(recipe);
+ if (problems.length) throw new RecipeError(problems);
+ const all = recipeEngines(recipe);
+ if (!all.length) throw new SkillError(noEngine(recipe), 422);
+ if (asked && !all.includes(asked)) throw new SkillError(`This skill doesn't run on ${ENGINE_NAME[asked]}`, 422);
+ if (level === "real" && !o.confirm) throw new SkillError("A real test spends money or GPU time: confirm it with its price first", 409);
+ const engines = asked ? [asked] : all;
+ const verified: NonNullable<Recipe["verified"]> = { ...recipe.verified };
+ const day = today();
+ const checks: EngineCheck[] = [];
+ for (const e of engines) {
+ const prev = recipe.verified?.[e] ?? null;
+ let check: EngineCheck;
+ let hash: string | undefined;
+ try {
+ const c = compileRun(skill, recipe, valuesForCheck(recipe), e, { run: "check" });
+ const plan = planCheck(c, e);
+ check = { engine: e, plan: { ok: !plan.errors.length, total: plan.total, demo: plan.jobs.every((j) => j.demo), errors: plan.errors, notes: plan.notes } };
+ if (check.plan.ok) hash = planHash(c, e);
+ } catch (err) {
+ check = { engine: e, plan: { ok: false, total: null, demo: false, errors: [(err as Error).message], notes: [] } };
+ }
+ if (!check.plan.ok || !hash) {
+ verified[e] = null;
+ checks.push(check);
+ continue;
+ }
+ // Checks made against another plan don't count for this one.
+ const same = prev?.catalog === hash;
+ const next: VerifiedEngine = { plan: day, dryRun: same ? (prev?.dryRun ?? null) : null, real: same ? (prev?.real ?? null) : null, catalog: hash, ...(same && prev?.notes && { notes: prev.notes }) };
+ if (check.plan.notes.length) next.notes = check.plan.notes.slice(0, 12);
+ if (level !== "plan") {
+ check.dryRun = await dryRun(skill, recipe, e).catch((err) => ({ ok: false, problems: [(err as Error).message] }));
+ next.dryRun = check.dryRun.ok && !check.dryRun.skipped ? day : check.dryRun.ok ? next.dryRun : null;
+ if (check.dryRun.skipped) next.notes = [...(next.notes ?? []), check.dryRun.skipped].slice(0, 12);
+ }
+ if (level === "real" && check.dryRun?.ok) {
+ check.real = await realRun(skill, recipe, e).catch((err) => ({ ok: false, problems: [(err as Error).message], notes: [], demo: false }));
+ next.real = check.real.ok && !check.real.demo ? day : check.real.ok ? next.real : null;
+ next.notes = check.real.notes.slice(0, 12);
+ }
+ verified[e] = next;
+ checks.push(check);
+ }
+ saveRecipe(name, { ...recipe, verified }, { keepVerified: true });
+ const ok = checks.every((c) => c.plan.ok && (c.dryRun?.ok ?? true) && (c.real?.ok ?? true));
+ return { ok, engines: checks, view: recipeView(name) };
+}
diff --git a/src/server/request-schema.ts b/src/server/request-schema.ts
new file mode 100644
index 00000000..87016c5f
--- /dev/null
+++ b/src/server/request-schema.ts
@@ -0,0 +1,140 @@
+import "server-only";
+import { z } from "zod";
+import { FORMAT_INFO } from "@/lib/av/formats";
+import type { VideoFormat } from "@/lib/catalog/types";
+import { SignatureSchema } from "./palettes";
+
+/** A point on a picture as fractions of its width and height. */
+const Focus = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) });
+
+/**
+ * Where a LoRA named in a request may be downloaded from. A file the server doesn't know is fetched from its
+ * link before a ComfyUI run (or by fal / Replicate), so an open link would let any token holder make the
+ * server fetch an internal address into models/loras. Every research LoRA is on Hugging Face or civitai;
+ * trained and mirrored copies live in fal's or Replicate's file stores.
+ */
+const LORA_HOSTS = ["huggingface.co", "hf.co", "civitai.com", "fal.media", "replicate.delivery"];
+function loraHostOk(link: string): boolean {
+ try {
+ const u = new URL(link);
+ const host = u.hostname.toLowerCase();
+ return u.protocol === "https:" && !u.username && !u.password && LORA_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A generation request as the API takes it (POST /api/generations): every field a client may send, with its limits.
+ * Fields the server sets (chainFilled, chainSkipped, notice, skill, demo…) aren't here, so zod drops them from input.
+ * A skill recipe's filled requests go through it too (src/server/recipes.ts), so a recipe can't send more than the API.
+ */
+export const GenerationRequestSchema = z.object({
+ feature: z.string().min(1),
+ presetId: z.string().optional(),
+ modelId: z.string().min(1),
+ op: z.string().optional(),
+ prompt: z.string().max(10_000).optional(),
+ negativePrompt: z.string().max(4_000).optional(),
+ inputs: z
+ .object({
+ images: z.array(z.string()).max(14).optional(),
+ endImage: z.string().optional(),
+ mask: z.string().optional(),
+ sketch: z.string().optional(),
+ video: z.string().optional(),
+ audio: z.string().optional(),
+ audio2: z.string().optional(),
+ voiceAudio: z.string().optional(),
+ voiceAudio2: z.string().optional(),
+ videos: z.array(z.string()).max(24).optional(),
+ // Reference audio clips for reference-to-video (Seedance 2.5 / Cinema Studio take up to 10).
+ audios: z.array(z.string()).max(10).optional(),
+ // A .glb to rig.
+ model3d: z.string().optional(),
+ })
+ .optional(),
+ params: z
+ .object({
+ aspectRatio: z.string().optional(),
+ resolution: z.string().optional(),
+ duration: z.number().positive().max(600).optional(),
+ numOutputs: z.number().int().min(1).max(8).optional(),
+ seed: z.number().int().optional(),
+ generateAudio: z.boolean().optional(),
+ enhancePrompt: z.boolean().optional(),
+ shots: z.array(z.object({ prompt: z.string().max(2000), duration: z.number().positive().max(60) })).max(12).optional(),
+ multiShot: z.literal("auto").optional(),
+ draft: z.boolean().optional(),
+ draftId: z.string().max(8192).optional(),
+ voice: z.string().max(200).optional(),
+ dialogue: z.array(z.object({ text: z.string().max(5000), voice: z.string().max(200).optional() })).max(200).optional(),
+ targetLanguage: z.string().max(80).optional(),
+ startTime: z.number().min(0).max(36_000).optional(),
+ endTime: z.number().min(0).max(36_000).optional(),
+ fps: z.number().positive().max(240).optional(),
+ palette: z.array(z.string().regex(/^#?[0-9a-fA-F]{6}$/)).max(16).optional(),
+ styleId: z.string().max(200).optional(),
+ sourceLanguage: z.string().max(80).optional(),
+ numLayers: z.number().int().min(1).max(20).optional(),
+ // Round 4: clicked points, keyframe times, output formats, Ken Burns moves, crossfades, retiming, overlays, rigging.
+ points: z.array(z.object({ x: z.number(), y: z.number(), label: z.enum(["positive", "negative"]).optional() })).max(64).optional(),
+ keyframeTimes: z.array(z.number().min(0).max(600)).max(10).optional(),
+ format: z.enum(Object.keys(FORMAT_INFO) as [VideoFormat, ...VideoFormat[]]).optional(),
+ zoomFrom: z.number().min(0.1).max(10).optional(),
+ zoomTo: z.number().min(0.1).max(10).optional(),
+ panFrom: Focus.optional(),
+ panTo: Focus.optional(),
+ easing: z.enum(["linear", "ease-in-out"]).optional(),
+ crossfade: z.number().min(0).max(30).optional(),
+ sourceDuration: z.number().positive().max(36_000).optional(),
+ frameInterval: z.number().int().min(1).max(10_000).optional(),
+ targetFps: z.number().positive().max(240).optional(),
+ slowdown: z.number().min(1).max(8).optional(),
+ colormap: z.string().max(40).optional(),
+ sideBySide: z.boolean().optional(),
+ matteOutput: z.enum(["cutout", "matte"]).optional(),
+ position: Focus.optional(),
+ scale: z.number().positive().max(10).optional(),
+ animation: z.union([z.string().max(200), z.number()]).optional(),
+ extra: z.record(z.string(), z.unknown()).optional(),
+ })
+ .optional(),
+ presetOptions: z.record(z.string(), z.string()).optional(),
+ presetStrength: z.number().min(0).max(1).optional(),
+ mix: z.object({ presetId: z.string().max(120), strength: z.number().min(0).max(1) }).optional(),
+ // A Fuobe Original runs on both engines: the one to run on (the composer's switch). Unset: the engine mode, else
+ // the first connected.
+ engine: z.enum(["open", "cloud"]).optional(),
+ // A recipe's LoRAs (the evaluation harness, scripts/eval): added after the preset's own. On ComfyUI `file` must
+ // already be in models/loras (ComfyUI checks the name against its list); a cloud LoRA endpoint takes `url`.
+ loras: z
+ .array(
+ z.object({
+ file: z
+ .string()
+ .min(1)
+ .max(200)
+ // Brackets too: Redmond's Z-Image LoRAs are called "[ZImage.Turbo]FilmStill_Redmond.safetensors".
+ .regex(/^[\w ()[\]+,.@-]+(\/[\w ()[\]+,.@-]+)*$/, "a file name in ComfyUI's models/loras")
+ .refine((f) => !f.split("/").includes(".."), "a file name in ComfyUI's models/loras"),
+ // Only the public model hubs and the cloud providers' file stores: the server (or a provider) may fetch it.
+ url: z
+ .string()
+ .max(2000)
+ .regex(/^https:\/\//, "an https:// link")
+ .refine(loraHostOk, "a LoRA link on Hugging Face, civitai, fal or Replicate")
+ .optional(),
+ strength: z.number().min(-4).max(4).optional(),
+ trigger: z.string().max(200).optional(),
+ target: z.enum(["high", "low", "both"]).optional(),
+ }),
+ )
+ .max(8)
+ .optional(),
+ // Image studio: the Color signature / Moodboard picks (its sentences join the prompt on the server).
+ signature: SignatureSchema,
+ // What a tool calls its result (Trim · 0:01.0–0:02.5, Captions · Karaoke), shown instead of the prompt.
+ title: z.string().max(200).optional(),
+ batchTitle: z.string().max(200).optional(),
+});
diff --git a/src/server/skills.ts b/src/server/skills.ts
index 691245e9..761ba220 100644
--- a/src/server/skills.ts
+++ b/src/server/skills.ts
@@ -2,8 +2,10 @@ import "server-only";
import fs from "node:fs";
import path from "node:path";
import { parseSkillMd, SKILL_LIMITS, SKILL_NAME_RE, toSkillMd, type Skill, type SkillMeta, type SkillSummary } from "@/lib/assist";
+import { parseRecipe, RECIPE_FILE, stripExamples, type Recipe } from "@/lib/recipe";
import { unzip, ZipError } from "./assist/unzip";
import { db } from "./db";
+import { zip } from "./zip";
/**
* Assist skills: SKILL.md playbooks the agent loads on demand (Supercomputer's Skills).
@@ -54,7 +56,8 @@ function readBuiltin(dir: string): BuiltinEntry {
.filter((f) => f !== "SKILL.md" && TEXT_FILE.test(f))
.slice(0, MAX_FILES)
.map((f) => ({ path: f.split(path.sep).join("/"), size: fs.statSync(path.join(BUILTIN_DIR, dir, f)).size }));
- entry = { mtime, skill: { ...parsed.skill, source: "builtin", files, createdAt: mtime, updatedAt: mtime } };
+ const recipe = files.some((f) => f.path === RECIPE_FILE) && parseRecipe(fs.readFileSync(path.join(BUILTIN_DIR, dir, RECIPE_FILE), "utf8")).ok;
+ entry = { mtime, skill: { ...parsed.skill, source: "builtin", files, ...(recipe && { recipe }), createdAt: mtime, updatedAt: mtime } };
}
cache.set(dir, entry);
if (entry.error) console.warn(`[skills] skills/${dir}/SKILL.md: ${entry.error}`);
@@ -99,6 +102,7 @@ type StoredFile = { path: string; content: string };
function fromRow(r: Row): Skill {
const meta = JSON.parse(r.meta_json) as Pick<SkillMeta, "icon" | "studio" | "tags" | "offline">;
const files = JSON.parse(r.files_json) as StoredFile[];
+ const recipe = files.find((f) => f.path === RECIPE_FILE);
return {
name: r.name,
title: r.title,
@@ -109,6 +113,7 @@ function fromRow(r: Row): Skill {
source: "user",
enabled: !!r.enabled,
files: files.map((f) => ({ path: f.path, size: Buffer.byteLength(f.content) })),
+ ...(recipe && parseRecipe(recipe.content).ok && { recipe: true }),
createdAt: r.created_at,
updatedAt: r.updated_at,
};
@@ -161,6 +166,62 @@ export function skillFile(name: string, file: string): string | null {
return (JSON.parse(r?.files_json ?? "[]") as StoredFile[]).find((f) => f.path === file)?.content ?? null;
}
+/** Every file bundled with a skill, with its text (the .zip download). */
+export function skillFiles(name: string): StoredFile[] {
+ const s = getSkill(name);
+ if (!s) return [];
+ return s.files.flatMap((f) => {
+ const content = skillFile(name, f.path);
+ return content === null ? [] : [{ path: f.path, content }];
+ });
+}
+
+/** A skill's recipe (a valid recipe.json in its files), or null. */
+export function skillRecipe(name: string): Recipe | null {
+ const text = skillFile(name, RECIPE_FILE);
+ if (text === null) return null;
+ const parsed = parseRecipe(text);
+ return parsed.ok ? parsed.recipe : null;
+}
+
+/** A path a skill's file may have: relative, no `..`, a text file. */
+const safeFilePath = (p: string) => p.length <= 200 && TEXT_FILE.test(p) && !p.startsWith("/") && !p.includes("\\") && !p.split("/").some((x) => !x || x === "." || x === "..");
+
+/**
+ * Write (or with null, remove) one of a user skill's files, within its limits (MAX_FILES, MAX_FILES_BYTES). Built-in
+ * skills are read from disk and never change: duplicate one first.
+ */
+export function setSkillFile(name: string, file: string, content: string | null): Skill {
+ const cur = getSkill(name);
+ if (!cur) throw new SkillError("No such skill", 404);
+ if (cur.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then change your copy", 403);
+ if (!safeFilePath(file)) throw new SkillError(`“${file}” isn't a file name a skill can carry (a text file such as notes.md or recipe.json)`);
+ const r = db().prepare("SELECT files_json FROM skills WHERE name = ?").get(name) as { files_json: string };
+ const files = (JSON.parse(r.files_json) as StoredFile[]).filter((f) => f.path !== file);
+ if (content !== null) files.push({ path: file, content });
+ if (files.length > MAX_FILES) throw new SkillError(`A skill carries at most ${MAX_FILES} files`);
+ const bytes = files.reduce((n, f) => n + Buffer.byteLength(f.content), 0);
+ if (bytes > MAX_FILES_BYTES) throw new SkillError(`A skill's files add up to at most ${Math.round(MAX_FILES_BYTES / 1000)} KB`);
+ db().prepare("UPDATE skills SET files_json = ?, updated_at = ? WHERE name = ?").run(JSON.stringify(files), Date.now(), name);
+ return getSkill(name)!;
+}
+
+/**
+ * The skill with its files as a .zip (one folder, as importSkill reads it). A recipe's examples, source and checks
+ * stay home unless `examples` (they name this install's files, faces and words); files fixed in its steps become
+ * inputs the other install asks for (stripExamples).
+ */
+export function skillArchive(name: string, o: { examples?: boolean } = {}): Buffer | null {
+ const s = getSkill(name);
+ if (!s) return null;
+ const files = skillFiles(name).map((f) => {
+ if (f.path !== RECIPE_FILE || o.examples) return f;
+ const parsed = parseRecipe(f.content);
+ return parsed.ok ? { ...f, content: `${JSON.stringify(stripExamples(parsed.recipe), null, 2)}\n` } : f;
+ });
+ return zip([{ name: `${name}/SKILL.md`, data: Buffer.from(toSkillMd(s)) }, ...files.map((f) => ({ name: `${name}/${f.path}`, data: Buffer.from(f.content) }))]);
+}
+
/** The skill as a SKILL.md file (download, duplicate). */
export function skillMarkdown(name: string): string | null {
const s = getSkill(name);
@@ -286,6 +347,18 @@ export function setSkillEnabled(name: string, enabled: boolean): Skill {
return getSkill(name)!;
}
+/**
+ * An uploaded recipe.json without its `verified` dates: they were another install's checks (or anyone's typing), and
+ * a recipe runs here only after it has been checked here (src/server/recipes.ts verifyRecipe).
+ */
+function unverified(text: string): string {
+ const parsed = parseRecipe(text);
+ if (!parsed.ok || !parsed.recipe.verified) return text;
+ const r: Recipe = { ...parsed.recipe };
+ delete r.verified;
+ return `${JSON.stringify(r, null, 2)}\n`;
+}
+
export interface ImportResult {
skill: Skill;
/** Files in the archive that weren't kept (binary, too many, too big). */
@@ -329,7 +402,7 @@ export function importSkill(file: { name: string; data: Buffer }, opts: { replac
continue;
}
bytes += e.data.length;
- files.push({ path: rel, content: e.data.toString("utf8") });
+ files.push({ path: rel, content: rel === RECIPE_FILE ? unverified(e.data.toString("utf8")) : e.data.toString("utf8") });
}
} else {
throw new SkillError("Upload a .zip or .skill archive, or a SKILL.md file");
diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.ts
index be2776b8..d8f9ab3b 100644
--- a/tests/assist-skills.test.ts
+++ b/tests/assist-skills.test.ts
@@ -3,7 +3,7 @@ import http from "node:http";
import os from "node:os";
import path from "node:path";
import zlib from "node:zlib";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
contextUpdate,
factMap,
@@ -21,6 +21,9 @@ import {
type ContextFact,
} from "@/lib/assist";
+// Route handlers call connection() (no request scope in a test).
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-skills-"));
process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9";
@@ -34,6 +37,8 @@ const { createElement } = await import("@/server/elements");
const { saveFile } = await import("@/server/storage");
const agent = await import("@/server/assist/agent");
const { db } = await import("@/server/db");
+const tools = await import("@/server/assist/tools");
+const downloadRoute = await import("@/app/api/assist/skills/[name]/download/route");
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -344,6 +349,61 @@ describe("skills on the server", () => {
expect(() => skills.importSkill({ name: "x.exe", data: Buffer.from("MZ") })).toThrow(/Upload a \.zip/);
});
+ it("exports a skill with its files as a .zip that imports back, recipe examples left out by default", async () => {
+ skills.createSkill({ name: "lamp-turntable", title: "Lamp turntable", description: "A turntable from a product photo.", body: "# Turntable\n\n1. Spin it." });
+ const recipe = {
+ fuobeRecipe: 1,
+ params: [{ id: "product", label: "Product photo", type: "image", required: true, example: "/api/files/uploads/2026-10-20/lamp.png" }],
+ steps: [
+ {
+ key: "spin",
+ kind: "generate",
+ request: { feature: "skill", modelId: "kling-3", op: "i2v", prompt: "slow turntable", inputs: { images: ["{{product}}"], audio: "/api/files/uploads/2026-10-20/bed.mp3" } },
+ },
+ ],
+ verified: { cloud: { plan: "2026-10-29", dryRun: "2026-10-29", real: null, catalog: "sha256:abc" } },
+ source: { from: "library", generations: ["V1StGXR8_Z5j"], at: "2026-10-29" },
+ };
+ skills.setSkillFile("lamp-turntable", "recipe.json", JSON.stringify(recipe));
+ skills.setSkillFile("lamp-turntable", "notes.md", "Keep it under 5 seconds.");
+ expect(skills.getSkill("lamp-turntable")).toMatchObject({ recipe: true });
+ const entries = unzip(skills.skillArchive("lamp-turntable")!);
+ expect(entries.map((e) => e.name).sort()).toEqual(["lamp-turntable/SKILL.md", "lamp-turntable/notes.md", "lamp-turntable/recipe.json"]);
+ const shared = JSON.parse(entries.find((e) => e.name.endsWith("recipe.json"))!.data.toString("utf8"));
+ expect(shared.source).toBeUndefined();
+ expect(shared.verified).toBeUndefined();
+ expect(shared.params[0].example).toBeUndefined();
+ // The fixed music bed is a file of this install: it becomes an input the other one asks for.
+ expect(shared.params[1]).toEqual({ id: "file_1", label: "Audio for “spin”", type: "audio", required: true });
+ expect(shared.steps[0].request.inputs.audio).toBe("{{file_1}}");
+ // &examples=1 keeps them (and the source), but never this install's checks.
+ const full = JSON.parse(unzip(skills.skillArchive("lamp-turntable", { examples: true })!).find((e) => e.name.endsWith("recipe.json"))!.data.toString("utf8"));
+ expect(full).toMatchObject({ params: [{ example: "/api/files/uploads/2026-10-20/lamp.png" }], source: { from: "library" } });
+ // Round trip: Upload reads the zip back, with its recipe (an uploaded recipe is never "checked" here).
+ const back = skills.importSkill({ name: "lamp-turntable.zip", data: skills.skillArchive("lamp-turntable", { examples: true })! }, { replace: true });
+ expect(back.skill).toMatchObject({ name: "lamp-turntable", recipe: true, files: expect.arrayContaining([expect.objectContaining({ path: "recipe.json" }), expect.objectContaining({ path: "notes.md" })]) });
+ const stored = JSON.parse(skills.skillFile("lamp-turntable", "recipe.json")!);
+ expect(stored.verified).toBeUndefined();
+ expect(stored.params[0].example).toBe("/api/files/uploads/2026-10-20/lamp.png");
+ // The download route serves the zip.
+ const res = await downloadRoute.GET(new Request("http://x/api/assist/skills/lamp-turntable/download?format=zip"), { params: Promise.resolve({ name: "lamp-turntable" }) } as never);
+ expect(res.headers.get("Content-Type")).toBe("application/zip");
+ expect(unzip(Buffer.from(await res.arrayBuffer())).map((e) => e.name)).toContain("lamp-turntable/recipe.json");
+ expect((await downloadRoute.GET(new Request("http://x/api/assist/skills/lamp-turntable/download"), { params: Promise.resolve({ name: "lamp-turntable" }) } as never)).headers.get("Content-Type")).toMatch(/markdown/);
+ });
+
+ it("load_skill on a skill with a recipe adds its Run it section", async () => {
+ const out = await tools.executeTool("load_skill", { name: "lamp-turntable" }, { engine: "cloud" });
+ expect(out.isError).toBeFalsy();
+ expect(out.content).toContain("# Lamp turntable (/lamp-turntable)");
+ expect(out.content).toContain("## Run it");
+ expect(out.content).toContain("`product` — Product photo: an image; required");
+ expect(out.content).toContain("run_skill");
+ // A skill without one is unchanged.
+ expect((await tools.executeTool("load_skill", { name: "katana" }, { engine: "cloud" })).content).not.toContain("## Run it");
+ skills.deleteSkill("lamp-turntable");
+ });
+
it("caps what an archive may unpack to", () => {
const big = zipStored([{ name: "SKILL.md", data: Buffer.alloc(3_000_000, 65) }]);
expect(() => unzip(big)).toThrow(/over 2 MB/);
diff --git a/tests/library.test.ts b/tests/library.test.ts
index 383ed754..d376c9a9 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -17,6 +17,7 @@ const lib = await import("@/server/library");
const { saveFile, absolutePath, listAssets } = await import("@/server/storage");
const { zipStream, zipSize } = await import("@/server/zip");
const { TOOLS } = await import("@/server/assist/tools");
+const skills = await import("@/server/skills");
const { POST: bulk } = await import("@/app/api/generations/bulk/route");
const folderRoutes = await import("@/app/api/folders/route");
const folderIdRoutes = await import("@/app/api/folders/[id]/route");
@@ -730,6 +731,25 @@ describe("ASSET_REFS", () => {
expect(fs.existsSync(fileOf(cut.asset.url))).toBe(true);
});
+ it("keeps a file that only a skill's recipe.json names through Empty trash", async () => {
+ const example = made("recipe example photo");
+ skills.createSkill({ name: "keep-example", title: "Keep example", description: "x", body: "x" });
+ const recipe = {
+ fuobeRecipe: 1,
+ params: [{ id: "photo", label: "Photo", type: "image", required: true, example: example.asset.url }],
+ steps: [{ key: "edit", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "warmer", inputs: { images: ["{{photo}}"] } } }],
+ };
+ skills.setSkillFile("keep-example", "recipe.json", JSON.stringify(recipe));
+ expect(gens.assetUses(example.asset.id, { exceptGeneration: example.g.id })).toEqual([{ what: "skill", key: "keep-example", name: "Keep example" }]);
+ lib.trashGenerations([example.g.id]);
+ expect(await lib.emptyTrash()).toBeGreaterThanOrEqual(1);
+ expect(gens.getGeneration(example.g.id, { includeDeleted: true })).toBeNull();
+ expect(fs.existsSync(fileOf(example.asset.url))).toBe(true);
+ // Without the skill, nothing keeps it.
+ skills.deleteSkill("keep-example");
+ expect(gens.assetUses(example.asset.id)).toEqual([]);
+ });
+
it("covers every column that can hold a file, and every entry's query runs", () => {
const tables = (db().prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all() as { name: string }[]).map((t) => t.name);
const columns = new Map(tables.map((t) => [t, (db().prepare(`PRAGMA table_info(${t})`).all() as { name: string }[]).map((c) => c.name)]));
diff --git a/tests/recipes.test.ts b/tests/recipes.test.ts
new file mode 100644
index 00000000..7363e8da
--- /dev/null
+++ b/tests/recipes.test.ts
@@ -0,0 +1,332 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Route handlers call connection() (no request scope in a test).
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-recipes-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: open models run on the demo provider, and there's no LLM.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const skills = await import("@/server/skills");
+const recipes = await import("@/server/recipes");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const { changeAccess } = await import("@/server/model-access");
+const { today } = await import("@/lib/recipe");
+const recipeRoute = await import("@/app/api/assist/skills/[name]/recipe/route");
+const runRoute = await import("@/app/api/assist/skills/[name]/run/route");
+const estimateRoute = await import("@/app/api/assist/skills/[name]/estimate/route");
+const verifyRoute = await import("@/app/api/assist/skills/[name]/verify/route");
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+let photo = "";
+let clip = "";
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+ photo = saveFile({ data: encodePng({ width: 64, height: 48, data: Buffer.alloc(64 * 48 * 4, 180) }), contentType: "image/png", source: "upload", name: "lamp.png" }).url;
+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "talk.mp4" }).url;
+});
+
+/** The research's turntable recipe: a cut-out, a scene, a clip of it (cloud models). */
+const lamp = () => ({
+ fuobeRecipe: 1,
+ params: [
+ { id: "product", label: "Product photo", type: "image", required: true, example: photo },
+ { id: "name", label: "Product name", type: "text", required: true, example: "Lumen desk lamp", max: 200 },
+ { id: "aspect", label: "Shape", type: "choice", options: ["1:1", "9:16", "16:9"], default: "1:1" },
+ { id: "takes", label: "Takes", type: "number", min: 1, max: 4, default: 1 },
+ ],
+ steps: [
+ { key: "cutout", kind: "generate", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{product}}"] } } },
+ {
+ key: "scene",
+ kind: "generate",
+ after: ["cutout"],
+ chain: [{ slot: "images", position: "first" }],
+ request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}} on a travertine plinth, soft window light", params: { aspectRatio: "{{aspect}}" } },
+ },
+ {
+ key: "spin",
+ kind: "generate",
+ after: ["scene"],
+ chain: [{ slot: "images" }],
+ request: { feature: "skill", modelId: "kling-3", op: "i2v", prompt: "slow turntable of the {{name}}", params: { duration: 5, numOutputs: "{{takes}}" } },
+ },
+ ],
+ checks: { spin: { kind: "video" } },
+});
+
+/** Fuobe Soul, an Original: one step that runs on both engines. */
+const soul = (model = "fuobe-soul") => ({
+ fuobeRecipe: 1,
+ params: [{ id: "subject", label: "Subject", type: "text", required: true, example: "a ceramicist at her wheel" }],
+ steps: [{ key: "portrait", kind: "generate", request: { feature: "skill", modelId: model, op: "t2i", prompt: "{{subject}}, editorial portrait", params: { aspectRatio: "4:5" } } }],
+});
+
+const captions = () => ({
+ fuobeRecipe: 1,
+ params: [
+ { id: "video", label: "Clip", type: "video", required: true, example: clip },
+ { id: "lang", label: "Caption language", type: "choice", options: ["Spanish", "German"], default: "Spanish" },
+ ],
+ steps: [{ key: "captions", kind: "tool", tool: "add_captions", input: { video: "{{video}}", translate_to: "{{lang}}" } }],
+});
+
+function makeSkill(name: string, recipe: unknown, title = "Lamp turntable") {
+ skills.createSkill({ name, title, description: "A product turntable from a photo.", body: "# Turntable\n\n1. Cut out, stage, spin." });
+ recipes.saveRecipe(name, recipe);
+}
+
+const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+const rowOf = (id: string) => db().prepare("SELECT batch_id, feature, provider, cost_usd, request_json FROM generations WHERE id = ?").get(id) as { batch_id: string; feature: string; provider: string; cost_usd: number | null; request_json: string };
+
+async function settle(ids: string[], ms = 60_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const all = ids.map((id) => gens.getGeneration(id, { includeDeleted: true })!);
+ if (all.every((g) => ["succeeded", "failed", "canceled"].includes(g.status))) return all;
+ if (Date.now() > until) throw new Error(`timed out: ${all.map((g) => `${g.id} ${g.status} ${g.message}`).join(", ")}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+const json = (body: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+const ctx = (name: string) => ({ params: Promise.resolve({ name }) }) as never;
+
+describe("saving a recipe", () => {
+ it("names every problem, and keeps the server's own fields out", () => {
+ skills.createSkill({ name: "broken", title: "Broken", description: "x", body: "x" });
+ const bad = { ...lamp(), steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "no-such-model", prompt: "{{nme}}" } }] };
+ expect(() => recipes.saveRecipe("broken", bad)).toThrow(recipes.RecipeError);
+ try {
+ recipes.saveRecipe("broken", bad);
+ } catch (e) {
+ expect((e as InstanceType<typeof recipes.RecipeError>).problems).toEqual(expect.arrayContaining([expect.stringContaining("{{nme}}"), expect.stringContaining("“Product photo” ({{product}}) isn't used")]));
+ }
+ // The catalog, the tools a recipe may call, and the API's own limits.
+ const unknown = { ...soul(), steps: [{ ...soul().steps[0], request: { ...soul().steps[0].request, modelId: "no-such-model" } }] };
+ expect(() => recipes.saveRecipe("broken", unknown)).toThrow(/Fuobe has no model “no-such-model”/);
+ expect(() => recipes.saveRecipe("broken", { ...soul(), steps: [{ key: "m", kind: "tool", tool: "remember", input: { text: "{{subject}}" } }] })).toThrow(/isn't a tool a recipe can run/);
+ expect(() => recipes.saveRecipe("broken", { ...soul(), steps: [{ ...soul().steps[0], request: { ...soul().steps[0].request, params: { numOutputs: 20 } } }] })).toThrow(/numOutputs/);
+ // verified is the server's to write: an edit starts unchecked.
+ const saved = recipes.saveRecipe("broken", { ...soul(), verified: { cloud: { plan: "2026-01-01", catalog: "sha256:x" } } });
+ expect(saved.verified).toBeUndefined();
+ expect(skills.getSkill("broken")?.recipe).toBe(true);
+ });
+
+ it("refuses built-in skills: duplicate one first", () => {
+ expect(() => recipes.saveRecipe("product-photoshoot", lamp())).toThrow(/Duplicate it first/);
+ expect(() => skills.setSkillFile("product-photoshoot", "recipe.json", "{}")).toThrow(/Duplicate it first/);
+ expect(() => recipes.recipeView("product-photoshoot")).toThrow(/has no recipe/);
+ expect(skills.getSkill("product-photoshoot")?.recipe).toBeUndefined();
+ });
+
+ it("keeps a skill's files within their limits", () => {
+ skills.createSkill({ name: "files", title: "Files", description: "x", body: "x" });
+ expect(() => skills.setSkillFile("files", "../escape.md", "x")).toThrow(/isn't a file name/);
+ expect(() => skills.setSkillFile("files", "image.png", "x")).toThrow(/isn't a file name/);
+ expect(() => skills.setSkillFile("files", "big.txt", "x".repeat(400_001))).toThrow(/at most 400 KB/);
+ expect(skills.setSkillFile("files", "notes.md", "hello").files).toEqual([{ path: "notes.md", size: 5 }]);
+ expect(skills.setSkillFile("files", "notes.md", null).files).toEqual([]);
+ });
+});
+
+describe("running a recipe", () => {
+ it("runs only on an engine where it was checked", async () => {
+ makeSkill("lamp-unchecked", lamp());
+ await expect(recipes.runRecipe("lamp-unchecked", { values: { product: photo, name: "Lamp" } })).rejects.toThrow(/Check this skill on the cloud first/);
+ expect(recipes.recipeView("lamp-unchecked")).toMatchObject({ engines: ["cloud"], ready: [], line: expect.stringMatching(/Not checked yet/) });
+ });
+
+ it("a 3-step recipe makes one batch of 3 rows with the skill stamp", async () => {
+ makeSkill("lamp", lamp());
+ const check = await recipes.verifyRecipe("lamp", "plan");
+ expect(check.ok).toBe(true);
+ expect(check.view.ready).toEqual(["cloud"]);
+ const out = await recipes.runRecipe("lamp", { values: { product: photo, name: "Arc floor lamp", aspect: "9:16", takes: 2 } });
+ expect(out.runs).toHaveLength(1);
+ const [run] = out.runs;
+ expect(run.ids).toHaveLength(3);
+ const rows = run.ids.map(rowOf);
+ expect(new Set(rows.map((r) => r.batch_id))).toEqual(new Set([run.batchId]));
+ for (const r of rows) {
+ const req = JSON.parse(r.request_json);
+ expect(req.skill).toEqual({ name: "lamp", run: run.batchId });
+ expect(req.batchTitle).toBe("Lamp turntable");
+ expect(req.demo).toBeUndefined();
+ }
+ expect(JSON.parse(rows[1].request_json).prompt).toBe("Arc floor lamp on a travertine plinth, soft window light");
+ expect(JSON.parse(rows[2].request_json).params).toMatchObject({ numOutputs: 2, duration: 5 });
+ // Demo mode on auto with no keys: the whole chain runs on the demo provider, and finishes.
+ const done = await settle(run.ids);
+ expect(done.map((g) => g.status)).toEqual(["succeeded", "succeeded", "succeeded"]);
+ expect(done.every((g) => g.provider === "mock")).toBe(true);
+ expect(out.demo).toBe(true);
+ });
+
+ it("3 CSV rows make 3 batches; one bad row starts nothing", async () => {
+ const csv = `Product photo,Product name,Shape\n${photo},Desk lamp,1:1\n${photo},"Lamp, brass",16:9\n${photo},Floor lamp,9:16\n`;
+ const est = recipes.estimateRecipe("lamp", { csv });
+ expect(est).toMatchObject({ runnable: true, demo: true, errors: [] });
+ expect(est.runs).toHaveLength(3);
+ const out = await recipes.runRecipe("lamp", { csv });
+ expect(out.runs).toHaveLength(3);
+ expect(new Set(out.runs.map((r) => r.batchId)).size).toBe(3);
+ expect(out.runs.every((r) => r.ids.length === 3)).toBe(true);
+ await settle(out.runs.flatMap((r) => r.ids));
+ const before = count();
+ const bad = `product,name\n${photo},Desk lamp\n${photo},Lamp two\nnot-a-link,Floor lamp\n`;
+ await expect(recipes.runRecipe("lamp", { csv: bad })).rejects.toThrow(/Row 4: Product photo: a file from Fuobe/);
+ expect(count()).toBe(before);
+ });
+
+ it("prices rows together, with a total", async () => {
+ setSetting("falKey", "test-key");
+ try {
+ const one = recipes.estimateRecipe("lamp", { values: { product: photo, name: "Lamp" } });
+ expect(one.demo).toBe(false);
+ expect(one.total).toBeGreaterThan(0);
+ expect(one.jobs.map((j) => j.modelId)).toEqual(["birefnet-cloud", "nano-banana-pro", "kling-3"]);
+ const two = recipes.estimateRecipe("lamp", { rows: [{ product: photo, name: "A" }, { product: photo, name: "B" }] });
+ expect(two.total).toBeCloseTo(2 * one.total!, 5);
+ // A row with a problem stops the batch: no total, and the row says why.
+ const mixed = recipes.estimateRecipe("lamp", { rows: [{ product: photo, name: "A" }, { name: "B" }] });
+ expect(mixed).toMatchObject({ runnable: false, total: null });
+ expect(mixed.runs[1].errors).toEqual(["Product photo is needed"]);
+ } finally {
+ setSetting("falKey", "");
+ }
+ });
+
+ it("a tool recipe (add_captions) runs through executeTool and opens its studio", async () => {
+ makeSkill("caption-it", captions(), "Caption it");
+ const check = await recipes.verifyRecipe("caption-it", "demo");
+ expect(check.ok).toBe(true);
+ // A studio step gets the plan check only in W1 (its dry run would make a record the user sees).
+ expect(check.engines.map((e) => e.dryRun?.skipped)).toEqual([expect.stringContaining("checked by its plan only"), expect.stringContaining("checked by its plan only")]);
+ const out = await recipes.runRecipe("caption-it", { values: { video: clip, lang: "German" } }, "open");
+ expect(out.runs).toHaveLength(1);
+ expect(out.runs[0].href).toMatch(/^\/video-tools\/captions\?video=/);
+ expect(out.runs[0].ids.length).toBeGreaterThan(0);
+ expect(gens.getGeneration(out.runs[0].ids[0])).toMatchObject({ op: "captions" });
+ });
+});
+
+describe("checking a recipe", () => {
+ it("plans on each engine the steps allow: an Original on both, a partner model on its own", async () => {
+ makeSkill("portrait", soul(), "Portrait");
+ const r = await recipes.verifyRecipe("portrait", "plan");
+ expect(r.ok).toBe(true);
+ expect(r.engines.map((e) => e.engine)).toEqual(["cloud", "open"]);
+ const v = r.view.recipe.verified!;
+ expect(v.cloud).toMatchObject({ plan: today(), dryRun: null, catalog: expect.stringMatching(/^sha256:/) });
+ expect(v.open).toMatchObject({ plan: today(), catalog: expect.stringMatching(/^sha256:/) });
+ expect(v.cloud!.catalog).not.toBe(v.open!.catalog);
+ expect(r.view.ready).toEqual(["cloud", "open"]);
+ expect(r.view.models.map((m) => m.engine)).toEqual(["cloud", "open"]);
+ // The lamp's models are cloud partners: the cloud only.
+ expect(recipes.recipeView("lamp").engines).toEqual(["cloud"]);
+ // Asked for one engine, only that one is checked.
+ expect((await recipes.verifyRecipe("portrait", "plan", "open")).engines.map((e) => e.engine)).toEqual(["open"]);
+ });
+
+ it("dry-runs for free with Demo mode Off and no keys: all on the mock provider, hidden, then trashed", async () => {
+ setSetting("demoMode", "off");
+ try {
+ makeSkill("lamp-dry", lamp());
+ // A real run can't start here (nothing connected, demo off)…
+ const r = await recipes.verifyRecipe("lamp-dry", "demo");
+ // …but the recipe itself passes: its plan on the demo provider, and a dry run there.
+ expect(r.ok).toBe(true);
+ const [cloud] = r.engines;
+ expect(cloud.plan).toMatchObject({ ok: true, notes: expect.arrayContaining([expect.stringContaining("Connect fal.ai")]) });
+ expect(cloud.dryRun).toEqual({ ok: true, problems: [] });
+ expect(r.view.recipe.verified?.cloud).toMatchObject({ plan: today(), dryRun: today() });
+ const rows = db().prepare("SELECT id, provider, cost_usd, request_json FROM generations WHERE feature = 'skill-check'").all() as { id: string; provider: string; cost_usd: number | null; request_json: string }[];
+ expect(rows).toHaveLength(3);
+ expect(rows.every((x) => x.provider === "mock" && !x.cost_usd)).toBe(true);
+ expect(rows.every((x) => JSON.parse(x.request_json).demo === true)).toBe(true);
+ // Hidden from the Library, and in the Trash.
+ const listed = new Set(gens.listGenerations({ limit: 200 }).map((g) => g.id));
+ expect(rows.some((x) => listed.has(x.id))).toBe(false);
+ const trashed = new Set((db().prepare("SELECT generation_id FROM generation_trash").all() as { generation_id: string }[]).map((t) => t.generation_id));
+ expect(rows.every((x) => trashed.has(x.id))).toBe(true);
+ // Running it for real still says what to connect.
+ await expect(recipes.runRecipe("lamp-dry", { values: { product: photo, name: "Lamp" } })).rejects.toThrow(/Connect/);
+ } finally {
+ setSetting("demoMode", "auto");
+ }
+ });
+
+ it("needs a re-check after a REPLACED_BY move, and after a model is switched off", async () => {
+ // A recipe checked when it named Soul 2.0, which Fuobe retired.
+ skills.createSkill({ name: "old-soul", title: "Old soul", description: "x", body: "x" });
+ const checked = { ...soul("soul-2"), verified: { cloud: { plan: "2026-10-01", dryRun: "2026-10-01", real: null, catalog: "sha256:old" } } };
+ skills.setSkillFile("old-soul", "recipe.json", JSON.stringify(checked));
+ expect(recipes.recipeView("old-soul").recheck.cloud).toEqual(["Soul 2.0 (Higgsfield) was replaced by Fuobe Soul"]);
+ // The re-check moves the step to what replaced it, as every run does.
+ const again = await recipes.verifyRecipe("old-soul", "demo");
+ expect(again.ok).toBe(true);
+ expect(again.view.recipe.steps[0]).toMatchObject({ request: { modelId: "fuobe-soul" } });
+ expect(again.view.recheck).toEqual({});
+
+ // A model switched off in Settings → Models & licences.
+ expect(recipes.recipeView("lamp").recheck).toEqual({});
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: false }]);
+ try {
+ expect(recipes.recipeView("lamp").recheck.cloud).toEqual(["Nano Banana Pro is switched off in Settings → Models & licences"]);
+ await expect(recipes.runRecipe("lamp", { values: { product: photo, name: "Lamp" } })).rejects.toThrow(/turned off|switched off/i);
+ } finally {
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: true }]);
+ }
+ expect(recipes.recipeView("lamp").recheck).toEqual({});
+ // A different plan (another model in a step) no longer matches the hash that was checked.
+ const file = JSON.parse(skills.skillFile("lamp", "recipe.json")!);
+ file.steps[1].request.modelId = "seedream-5-pro";
+ skills.setSkillFile("lamp", "recipe.json", JSON.stringify(file));
+ expect(recipes.recipeView("lamp").recheck.cloud).toEqual(["The models, routes or prices it uses changed since it was checked"]);
+ });
+
+ it("a real test asks first, and measures what it made", async () => {
+ await expect(recipes.verifyRecipe("lamp-unchecked", "real")).rejects.toThrow(/confirm it with its price first/);
+ const r = await recipes.verifyRecipe("lamp-unchecked", "real", undefined, { confirm: true });
+ const [cloud] = r.engines;
+ // No key: it ran as a demo, so it isn't recorded as a real test, and says so.
+ expect(cloud.real).toMatchObject({ ok: true, demo: true, notes: [expect.stringContaining("ran as a demo")] });
+ expect(r.view.recipe.verified?.cloud?.real).toBeNull();
+ });
+});
+
+describe("the recipe routes", () => {
+ it("reads, saves, prices, checks and runs over HTTP", async () => {
+ skills.createSkill({ name: "via-api", title: "Via API", description: "x", body: "x" });
+ const put = await recipeRoute.PUT(new Request("http://x", { method: "PUT", body: JSON.stringify(soul()) }), ctx("via-api"));
+ expect(put.status).toBe(200);
+ const bad = await recipeRoute.PUT(new Request("http://x", { method: "PUT", body: JSON.stringify({ ...soul(), params: [] }) }), ctx("via-api"));
+ expect(bad.status).toBe(422);
+ expect(await bad.json()).toMatchObject({ problems: [expect.stringContaining("{{subject}}")] });
+ expect((await runRoute.POST(json({ values: { subject: "a potter" } }), ctx("via-api"))).status).toBe(409);
+ const verify = await verifyRoute.POST(json({ level: "plan" }), ctx("via-api"));
+ expect(verify.status).toBe(200);
+ const est = await (await estimateRoute.POST(json({ csv: "subject\na potter\na baker", engine: "open" }), ctx("via-api"))).json();
+ expect(est).toMatchObject({ engine: "open", runnable: true, runs: [{ errors: [] }, { errors: [] }] });
+ const run = await runRoute.POST(json({ rows: [{ subject: "a potter" }], engine: "open" }), ctx("via-api"));
+ expect(run.status).toBe(201);
+ const body = (await run.json()) as { runs: { ids: string[] }[] };
+ expect(gens.getGeneration(body.runs[0].ids[0])).toMatchObject({ modelId: "fuobe-soul", engine: "open" });
+ const view = await (await recipeRoute.GET(new Request("http://x"), ctx("via-api"))).json();
+ expect(view).toMatchObject({ name: "via-api", engines: ["cloud", "open"], ready: ["cloud", "open"] });
+ expect((await recipeRoute.GET(new Request("http://x"), ctx("nope"))).status).toBe(404);
+ });
+});