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: the recipe format, a pure module to check, fill and compile a skill's recipe.json

Claude4f5639cc687c
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 78300e72..6201b138 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -872,6 +872,17 @@ export interface GenerationRequest {
title?: string;
/** Server-set: the name of the batch it belongs to (an Assist plan's summary): the Library stack's title. */
batchTitle?: string;
+ /**
+ * Server-set: made by a run of a skill's recipe (src/lib/recipe.ts): the skill's name and the run's id (its batch), so
+ * a run's history can be read back. Stripped from API input, like chainFilled.
+ */
+ skill?: { name: string; run: string };
+ /**
+ * Server-set: run on the demo provider whatever Settings → Demo mode says (a recipe's free dry run): chooseRoute
+ * returns the demo route, and a waiting step runs as a demo after demo steps even with Demo mode off. Stripped from
+ * API input.
+ */
+ demo?: boolean;
/**
* The Image studio's style signature (Color signature + Moodboard chips): what was picked, the
* sentences the server adds to the prompt (`prompt` keeps the user's own words), and the request as
diff --git a/src/lib/recipe.ts b/src/lib/recipe.ts
new file mode 100644
index 00000000..d537f7fa
--- /dev/null
+++ b/src/lib/recipe.ts
@@ -0,0 +1,804 @@
+/**
+ * Skill recipes (`recipe.json`): the part of a user skill Fuobe runs by itself, with new inputs and no LLM
+ * (docs/research/work2skill-7.md §9, package W1). `SKILL.md` stays the playbook people and agents read; a skill
+ * "runs by itself" when its files hold a valid `recipe.json`.
+ *
+ * A recipe has typed inputs (`params`) and either a graph of generate steps (one `createPipeline`) or one call of a
+ * gated Assist tool (`dub_video`, `add_captions`…). A string that is exactly `"{{id}}"` takes the input with its type;
+ * `{{id}}` inside a longer string inserts its text. Unknown or unused placeholders are refused when the recipe is
+ * saved (`recipeProblems`), never at run time. Step outputs travel only through `after` and `chain`, exactly as
+ * createPipeline takes them.
+ *
+ * Pure and browser-safe: the Run form validates a row and parses a CSV with it, the server compiles the requests
+ * (src/server/recipes.ts). Nothing here reads the catalog: the server checks models, prices and engines.
+ */
+import { z } from "zod";
+import type { ChainSlot, GenerationRequest, MediaKind, OutputFile } from "./catalog/types";
+import type { MediaInfo } from "./media-probe";
+
+export const RECIPE_FILE = "recipe.json";
+
+/** Sane caps (a guess, W1): a form of 12 fields and a graph of 24 steps; rows as a Canvas table (TABLE_LIMITS.rows). */
+export const RECIPE_LIMITS = { params: 12, steps: 24, rows: 50, text: 2000, options: 24 } as const;
+
+export const PARAM_TYPES = ["image", "video", "audio", "text", "number", "choice", "element"] as const;
+export type ParamType = (typeof PARAM_TYPES)[number];
+export const MEDIA_TYPES: readonly ParamType[] = ["image", "video", "audio"];
+export const isMediaType = (t: ParamType): t is "image" | "video" | "audio" => MEDIA_TYPES.includes(t);
+
+const PARAM_ID = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
+const STEP_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
+/** A placeholder anywhere in a string, and a string that is exactly one. */
+const PLACEHOLDER = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g;
+const EXACT = /^\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}$/;
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+const ELEMENT = /^@[\p{L}\p{N}_-]{1,40}$/u;
+
+/** A media input: a file saved in Fuobe or a public http(s) link (read through remote-fetch.ts). */
+export const isMediaRef = (v: string): boolean => /^\/api\/files\/[^\s]+$/.test(v) || /^https?:\/\/[^\s]+$/i.test(v);
+
+const Scalar = z.union([z.string().max(RECIPE_LIMITS.text), z.number()]);
+
+export const ParamSchema = z.object({
+ id: z.string().regex(PARAM_ID, "an input's id is a letter, then letters, digits or _ (up to 32)"),
+ label: z.string().trim().min(1).max(60),
+ type: z.enum(PARAM_TYPES),
+ required: z.boolean().optional(),
+ default: Scalar.optional(),
+ /** The value from the original run (stripped from exports). */
+ example: Scalar.nullable().optional(),
+ /** Text: the longest it may be; number: the largest. */
+ max: z.number().optional(),
+ min: z.number().optional(),
+ step: z.number().positive().optional(),
+ options: z.array(z.string().trim().min(1).max(80)).min(1).max(RECIPE_LIMITS.options).optional(),
+ /** One line under the field. */
+ hint: z.string().trim().max(200).optional(),
+});
+export type RecipeParam = z.infer<typeof ParamSchema>;
+
+const SLOTS = ["images", "endImage", "video", "videos", "audio", "voiceAudio", "audio2", "audios", "model3d", "mask", "prompt"] as const satisfies readonly ChainSlot["slot"][];
+
+const ChainSlotSchema = z.object({
+ slot: z.enum(SLOTS),
+ position: z.enum(["first", "last"]).optional(),
+ stem: z.string().max(40).optional(),
+ index: z.number().int().min(0).optional(),
+ of: z.number().int().positive().optional(),
+ optional: z.object({ prompt: z.string().max(RECIPE_LIMITS.text).optional(), notice: z.string().max(300) }).optional(),
+});
+
+/**
+ * Fields the server sets on a request (the run's stamp, the demo flag, what the runner filled in, a step's label):
+ * a recipe never carries them, whatever its file says.
+ */
+export const SERVER_FIELDS = ["skill", "demo", "chainFilled", "chainSkipped", "notice", "step", "batchTitle"] as const;
+
+/** A GenerationRequest with placeholders in it: checked for its shape here, for its models and values on the server. */
+const RequestSchema = z
+ .object({ feature: z.string().trim().min(1).max(60), modelId: z.string().trim().min(1).max(120) })
+ .catchall(z.unknown())
+ .transform((r) => Object.fromEntries(Object.entries(r).filter(([k]) => !(SERVER_FIELDS as readonly string[]).includes(k))) as RecipeRequest);
+
+/** A request as a recipe holds it: any field may still be a placeholder until it is filled. */
+export type RecipeRequest = GenerationRequest & Record<string, unknown>;
+
+const StepBase = { key: z.string().regex(STEP_KEY, "a step's key is letters, digits, - or _ (up to 40)"), label: z.string().trim().min(1).max(80).optional() };
+
+const GenerateStepSchema = z.object({
+ ...StepBase,
+ kind: z.literal("generate"),
+ after: z.union([z.string(), z.array(z.string()).max(RECIPE_LIMITS.steps)]).optional(),
+ chain: z.array(ChainSlotSchema).max(RECIPE_LIMITS.steps).optional(),
+ request: RequestSchema,
+});
+const ToolStepSchema = z.object({
+ ...StepBase,
+ kind: z.literal("tool"),
+ tool: z.string().regex(/^[a-z][a-z0-9_]{1,40}$/, "an Assist tool's name, e.g. dub_video"),
+ input: z.record(z.string(), z.unknown()),
+});
+const StepSchema = z.discriminatedUnion("kind", [GenerateStepSchema, ToolStepSchema]);
+export type RecipeStep = z.infer<typeof StepSchema>;
+export type GenerateStep = z.infer<typeof GenerateStepSchema>;
+export type ToolStep = z.infer<typeof ToolStepSchema>;
+
+const KINDS = ["image", "video", "audio", "text", "model3d"] as const satisfies readonly MediaKind[];
+
+export const CheckSchema = z.object({
+ /** What the step makes. */
+ kind: z.enum(KINDS).optional(),
+ /** How many outputs (a number, or a number input's placeholder). */
+ count: z.union([z.number().int().min(1).max(64), z.string().regex(EXACT)]).optional(),
+ /** "16:9", or a choice input's placeholder. */
+ aspect: z.string().max(40).optional(),
+ /** Seconds: a range, or one length (±10%). */
+ seconds: z.union([z.number().positive(), z.tuple([z.number().min(0), z.number().positive()])]).optional(),
+ /** Whether a clip has sound. */
+ sound: z.boolean().optional(),
+ /** A sentence a model that sees images judges (only when one is available). */
+ look: z.string().trim().min(1).max(300).optional(),
+});
+export type RecipeCheck = z.infer<typeof CheckSchema>;
+
+/** One engine's checks: the day each passed (null: not yet), and the hash of what the plan ran when it was checked. */
+const VerifiedEngineSchema = z.object({
+ plan: z.string().regex(DAY).nullable(),
+ dryRun: z.string().regex(DAY).nullable().optional(),
+ real: z.string().regex(DAY).nullable().optional(),
+ /** sha256 of each step's model, operation, route provider and price (src/server/recipes.ts planHash). */
+ catalog: z.string().max(100).optional(),
+ /** What the last check found that isn't a failure ("look not judged: no model that sees images"). */
+ notes: z.array(z.string().max(300)).max(12).optional(),
+});
+export type VerifiedEngine = z.infer<typeof VerifiedEngineSchema>;
+
+export const RecipeSchema = z.object({
+ fuobeRecipe: z.literal(1),
+ params: z.array(ParamSchema).max(RECIPE_LIMITS.params, `at most ${RECIPE_LIMITS.params} inputs`),
+ steps: z.array(StepSchema).min(1, "a recipe needs a step").max(RECIPE_LIMITS.steps, `at most ${RECIPE_LIMITS.steps} steps`),
+ checks: z.record(z.string(), CheckSchema).optional(),
+ verified: z.object({ cloud: VerifiedEngineSchema.nullable().optional(), open: VerifiedEngineSchema.nullable().optional() }).optional(),
+ source: z
+ .object({
+ from: z.string().trim().min(1).max(40),
+ generations: z.array(z.string().max(40)).max(200).optional(),
+ thread: z.string().max(40).optional(),
+ canvas: z.string().max(40).optional(),
+ at: z.string().regex(DAY).optional(),
+ })
+ .optional(),
+});
+export type Recipe = z.infer<typeof RecipeSchema>;
+
+export type RecipeValue = string | number;
+export type RecipeValues = Record<string, RecipeValue | undefined>;
+export type RecipeEngine = "cloud" | "open";
+
+const issueText = (issues: z.core.$ZodIssue[]) => issues.map((i) => (i.path.length ? `${i.path.map(String).join(".")}: ${i.message}` : i.message)).join("; ");
+
+/** A recipe.json's text as a recipe, or what is wrong with its shape (recipeProblems checks the rest). */
+export function parseRecipe(text: string): { ok: true; recipe: Recipe } | { ok: false; error: string } {
+ let json: unknown;
+ try {
+ json = JSON.parse(text.replace(/^/, ""));
+ } catch {
+ return { ok: false, error: "recipe.json isn't valid JSON" };
+ }
+ const parsed = RecipeSchema.safeParse(json);
+ return parsed.success ? { ok: true, recipe: parsed.data } : { ok: false, error: `recipe.json: ${issueText(parsed.error.issues)}` };
+}
+
+// ---------------------------------------------------------------------------
+// Placeholders
+
+/** Every placeholder id in a value (strings, lists and objects, all the way down). */
+export function placeholders(v: unknown, out = new Set<string>()): Set<string> {
+ if (typeof v === "string") for (const m of v.matchAll(PLACEHOLDER)) out.add(m[1]);
+ else if (Array.isArray(v)) for (const x of v) placeholders(x, out);
+ else if (v && typeof v === "object") for (const x of Object.values(v)) placeholders(x, out);
+ return out;
+}
+
+const asList = (a: string | string[] | undefined): string[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);
+const stepBody = (s: RecipeStep): unknown => (s.kind === "tool" ? s.input : s.request);
+
+/** Steps that wait for nothing later: the only ones whose output count may change (createPipeline's rule). */
+export function leafKeys(recipe: Pick<Recipe, "steps">): Set<string> {
+ const fed = new Set(recipe.steps.flatMap((s) => (s.kind === "generate" ? asList(s.after) : [])));
+ return new Set(recipe.steps.filter((s) => !fed.has(s.key)).map((s) => s.key));
+}
+
+// ---------------------------------------------------------------------------
+// Values
+
+const blank = (v: unknown) => (v === null || v === undefined || (typeof v === "string" && !v.trim()) ? undefined : v);
+
+/** The values one input takes, its limits and options applied (a choice is matched without minding case). */
+function valueSchema(p: RecipeParam): z.ZodType<RecipeValue | undefined> {
+ const label = p.label;
+ let base: z.ZodType<RecipeValue>;
+ switch (p.type) {
+ case "image":
+ case "video":
+ case "audio":
+ base = z.string({ error: `${label}: add a file` }).trim().refine(isMediaRef, `${label}: a file from Fuobe (/api/files/…) or an http(s) link`);
+ break;
+ case "text": {
+ const max = Math.min(p.max ?? RECIPE_LIMITS.text, RECIPE_LIMITS.text);
+ base = z.string({ error: `${label}: write some text` }).max(max, `${label}: at most ${max} characters`);
+ break;
+ }
+ case "number": {
+ let n = z.number({ error: `${label}: a number` }).refine(Number.isFinite, `${label}: a number`);
+ if (p.min !== undefined) n = n.refine((x) => x >= p.min!, `${label}: at least ${p.min}`);
+ if (p.max !== undefined) n = n.refine((x) => x <= p.max!, `${label}: at most ${p.max}`);
+ base = z.union([z.number(), z.string().trim().regex(/^-?\d+(\.\d+)?$/, `${label}: a number`).transform(Number)]).pipe(n);
+ break;
+ }
+ case "choice": {
+ const options = p.options ?? [];
+ base = z
+ .union([z.string(), z.number().transform(String)])
+ .transform((v) => options.find((o) => o.toLowerCase() === v.trim().toLowerCase()) ?? v)
+ .refine((v) => options.includes(v), `${label}: one of ${options.join(", ")}`);
+ break;
+ }
+ case "element":
+ base = z
+ .string({ error: `${label}: pick an element` })
+ .trim()
+ .transform((v) => (v.startsWith("@") ? v : `@${v}`))
+ .refine((v) => ELEMENT.test(v), `${label}: an element's @handle, e.g. @Maya`);
+ break;
+ }
+ const missing = `${label} is needed`;
+ if (p.default !== undefined) return z.preprocess((v) => blank(v) ?? p.default, base);
+ if (p.required) return z.preprocess(blank, z.custom<unknown>((v) => v !== undefined, missing).pipe(base));
+ return z.preprocess(blank, base.optional());
+}
+
+/** A zod object for one set of values: required inputs, defaults, limits, options; media and @handles by shape. */
+export function valuesSchema(recipe: Pick<Recipe, "params">) {
+ return z.object(Object.fromEntries(recipe.params.map((p) => [p.id, valueSchema(p)])));
+}
+
+/** One set of values checked: the values with defaults applied, or an error per input id. */
+export function checkValues(recipe: Pick<Recipe, "params">, values: Record<string, unknown>): { values: RecipeValues; errors: Record<string, string> } | { values?: undefined; errors: Record<string, string> } {
+ const parsed = valuesSchema(recipe).safeParse(values ?? {});
+ if (parsed.success) return { values: parsed.data as RecipeValues, errors: {} };
+ const errors: Record<string, string> = {};
+ for (const i of parsed.error.issues) {
+ const id = String(i.path[0] ?? "");
+ const p = recipe.params.find((x) => x.id === id);
+ errors[id] ??= i.message.startsWith(p?.label ?? "\0") ? i.message : p?.required && blank(values?.[id]) === undefined ? `${p.label} is needed` : `${p?.label ?? id}: ${i.message}`;
+ }
+ return { errors };
+}
+
+/** The values a check runs with: each input's example, else its default; a media input with neither gets `standIn`. */
+export function exampleValues(recipe: Pick<Recipe, "params">, standIn: (type: "image" | "video" | "audio") => string): RecipeValues {
+ return Object.fromEntries(
+ recipe.params.map((p) => {
+ const v = blank(p.example) ?? blank(p.default);
+ if (v !== undefined) return [p.id, v as RecipeValue];
+ if (isMediaType(p.type)) return [p.id, standIn(p.type)];
+ if (p.type === "number") return [p.id, p.min ?? 1];
+ if (p.type === "choice") return [p.id, p.options?.[0]];
+ // An unknown @handle stays plain words in the prompt: enough to price and dry-run the steps.
+ if (p.type === "element") return [p.id, p.required ? `@${p.label.replace(/[^\p{L}\p{N}_-]+/gu, "_").slice(0, 40)}` : undefined];
+ return [p.id, p.required ? p.label : undefined];
+ }),
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Filling and compiling
+
+/** A value with the inputs put in: an exact placeholder keeps the input's type; a missing one drops the field. */
+function fillValue(v: unknown, values: RecipeValues): unknown {
+ if (typeof v === "string") {
+ const exact = EXACT.exec(v);
+ if (exact) return values[exact[1]];
+ if (!v.includes("{{")) return v;
+ let emptied = false;
+ const out = v.replace(PLACEHOLDER, (_, id: string) => {
+ const x = values[id];
+ if (x === undefined || x === "") emptied = true;
+ return x === undefined ? "" : String(x);
+ });
+ // An optional input left empty: no double spaces or dangling commas where it was.
+ return emptied ? out.replace(/\s+([,.;:])/g, "$1").replace(/([,;:])(\s*[,;:])+/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/^[\s,;:]+|[\s,;:]+$/g, "") : out;
+ }
+ if (Array.isArray(v)) {
+ const out = v.map((x) => fillValue(x, values)).filter((x) => x !== undefined);
+ return v.length && !out.length ? undefined : out;
+ }
+ if (v && typeof v === "object") {
+ const out = Object.fromEntries(Object.entries(v).flatMap(([k, x]) => {
+ const f = fillValue(x, values);
+ return f === undefined ? [] : [[k, f]];
+ }));
+ return Object.keys(v).length && !Object.keys(out).length ? undefined : out;
+ }
+ return v;
+}
+
+const defaultsOf = (recipe: Pick<Recipe, "params">): RecipeValues => Object.fromEntries(recipe.params.flatMap((p) => (p.default === undefined ? [] : [[p.id, p.default]])));
+
+/** The recipe's steps and checks with the values put in (defaults for what isn't given). */
+export function fill(recipe: Recipe, values: RecipeValues): { steps: RecipeStep[]; checks: Record<string, FilledCheck> } {
+ const all = { ...defaultsOf(recipe), ...Object.fromEntries(Object.entries(values).filter(([, v]) => v !== undefined)) };
+ const steps = recipe.steps.map((s): RecipeStep =>
+ s.kind === "tool" ? { ...s, input: (fillValue(s.input, all) as Record<string, unknown>) ?? {} } : { ...s, request: fillValue(s.request, all) as RecipeRequest },
+ );
+ const checks = Object.fromEntries(Object.entries(recipe.checks ?? {}).map(([k, c]) => [k, fillCheck(c, all)]));
+ return { steps, checks };
+}
+
+/** A check with its placeholders filled: a count and an aspect as values. */
+export interface FilledCheck {
+ kind?: MediaKind;
+ count?: number;
+ aspect?: string;
+ seconds?: number | [number, number];
+ sound?: boolean;
+ look?: string;
+}
+
+function fillCheck(c: RecipeCheck, values: RecipeValues): FilledCheck {
+ const count = typeof c.count === "string" ? Number(fillValue(c.count, values)) : c.count;
+ const aspect = c.aspect === undefined ? undefined : String(fillValue(c.aspect, values) ?? "");
+ return {
+ ...(c.kind && { kind: c.kind }),
+ ...(count !== undefined && Number.isFinite(count) && count > 0 && { count }),
+ ...(aspect && /^\d+(\.\d+)?:\d+(\.\d+)?$/.test(aspect) && { aspect }),
+ ...(c.seconds !== undefined && { seconds: c.seconds }),
+ ...(c.sound !== undefined && { sound: c.sound }),
+ ...(c.look && { look: c.look }),
+ };
+}
+
+/** A step of a compiled pipeline: createPipeline's PipelineStep. */
+export interface CompiledStep {
+ key: string;
+ request: GenerationRequest;
+ after?: string | string[];
+ chain?: ChainSlot[];
+}
+
+export type Compiled = { kind: "pipeline"; steps: CompiledStep[]; checks: Record<string, FilledCheck> } | { kind: "tool"; key: string; tool: string; input: Record<string, unknown>; checks: Record<string, FilledCheck> };
+
+export interface CompileOptions {
+ /** The skill's name and this run's id: the server-set stamp on every request. */
+ skill: string;
+ run: string;
+ /** The skill's title: the Library stack's name (batchTitle). */
+ title: string;
+ /** The free dry run: every job on the demo provider, as a hidden helper row (feature skill-check). */
+ demo?: boolean;
+}
+
+/** The feature of a dry run's rows: a helper the Library hides (HELPER_FEATURES). */
+export const SKILL_CHECK_FEATURE = "skill-check";
+
+/** One run of a recipe: a pipeline of generate steps, or one tool call. Values are checked first (checkValues). */
+export function compile(recipe: Recipe, values: RecipeValues, o: CompileOptions): Compiled {
+ const { steps, checks } = fill(recipe, values);
+ const tool = steps.find((s): s is ToolStep => s.kind === "tool");
+ if (tool) return { kind: "tool", key: tool.key, tool: tool.tool, input: tool.input, checks };
+ const n = steps.length;
+ return {
+ kind: "pipeline",
+ checks,
+ steps: (steps as GenerateStep[]).map((s, i) => ({
+ key: s.key,
+ request: {
+ ...s.request,
+ batchTitle: o.title.slice(0, 200),
+ skill: { name: o.skill, run: o.run },
+ ...(s.label && { step: { label: s.label, index: i, of: n } }),
+ ...(o.demo && { demo: true, feature: SKILL_CHECK_FEATURE }),
+ },
+ ...(s.after !== undefined && { after: s.after }),
+ ...(s.chain && { chain: s.chain as ChainSlot[] }),
+ })),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Save-time problems
+
+/**
+ * What would make a recipe fail or mislead, said when it is saved (never at run time): unknown or unused placeholders,
+ * a count that varies on a step others wait for, duplicate ids and keys, a tool step that isn't alone, a graph
+ * createPipeline would refuse, and inputs whose default, example or options don't fit their type.
+ */
+export function recipeProblems(recipe: Recipe): string[] {
+ const out: string[] = [];
+ const ids = recipe.params.map((p) => p.id);
+ const keys = recipe.steps.map((s) => s.key);
+ const dup = (list: string[]) => [...new Set(list.filter((x, i) => list.indexOf(x) !== i))];
+ for (const d of dup(ids)) out.push(`Two inputs are called “${d}”`);
+ for (const d of dup(keys)) out.push(`Two steps are called “${d}”`);
+ const known = new Set(ids);
+ const used = new Set<string>();
+ for (const s of recipe.steps) {
+ for (const id of placeholders(stepBody(s))) {
+ if (known.has(id)) used.add(id);
+ else out.push(`Step “${s.key}” uses {{${id}}}, which isn't an input`);
+ }
+ }
+ for (const [k, c] of Object.entries(recipe.checks ?? {})) {
+ if (!keys.includes(k)) out.push(`The checks name a step “${k}” the recipe doesn't have`);
+ for (const id of placeholders(c)) if (!known.has(id)) out.push(`The check on “${k}” uses {{${id}}}, which isn't an input`);
+ }
+ for (const p of recipe.params) if (!used.has(p.id)) out.push(`The input “${p.label}” ({{${p.id}}}) isn't used by any step`);
+
+ // One tool step alone (a tool feeding later steps is W7's orchestrator).
+ const tools = recipe.steps.filter((s) => s.kind === "tool");
+ if (tools.length && recipe.steps.length > 1) out.push(`The tool step “${tools[0].key}” must be the recipe's only step (a tool that feeds other steps isn't supported yet)`);
+
+ // The graph, as createPipeline checks it.
+ const keySet = new Set(keys);
+ for (const s of recipe.steps) {
+ if (s.kind !== "generate") continue;
+ const after = asList(s.after);
+ for (const a of after) {
+ if (a === s.key) out.push(`Step “${s.key}” can't wait for itself`);
+ else if (!keySet.has(a)) out.push(`Step “${s.key}” waits for “${a}”, which isn't a step`);
+ }
+ const chain = s.chain ?? (s.request.chain as ChainSlot[] | undefined);
+ if (chain && chain.length !== after.length) out.push(`Step “${s.key}” has ${chain.length} chain slot${chain.length === 1 ? "" : "s"} for ${after.length} earlier step${after.length === 1 ? "" : "s"}`);
+ }
+ if (!out.some((p) => p.includes("waits for") || p.includes("itself"))) {
+ const loop = loopOf(recipe.steps);
+ if (loop.length) out.push(`These steps wait for each other in a loop: ${loop.map((k) => `“${k}”`).join(", ")}`);
+ }
+ // A count may vary only where nothing waits (createPipeline needs one result from a step that feeds others).
+ const leaves = leafKeys(recipe);
+ for (const s of recipe.steps) {
+ if (s.kind !== "generate" || leaves.has(s.key)) continue;
+ const n = (s.request.params as Record<string, unknown> | undefined)?.numOutputs;
+ if (typeof n === "string" && placeholders(n).size) out.push(`Step “${s.key}” feeds later steps, so its count can't come from an input (${n})`);
+ else if (typeof n === "number" && n > 1) out.push(`Step “${s.key}” feeds later steps, so it must make one result (it asks for ${n})`);
+ }
+
+ // Inputs that can't hold what they say.
+ for (const p of recipe.params) {
+ if (p.type === "choice" && !p.options?.length) out.push(`The choice “${p.label}” needs options`);
+ if (p.min !== undefined && p.max !== undefined && p.min > p.max) out.push(`“${p.label}”: its minimum is above its maximum`);
+ for (const [what, v] of [
+ ["default", p.default],
+ ["example", p.example],
+ ] as const) {
+ if (blank(v) === undefined) continue;
+ const one = valueSchema({ ...p, required: false, default: undefined }).safeParse(v);
+ if (!one.success) out.push(`The ${what} of “${p.label}” doesn't fit: ${one.error.issues[0]?.message.replace(`${p.label}: `, "")}`);
+ }
+ }
+ return [...new Set(out)];
+}
+
+/** Steps caught in a loop of `after`s (Kahn's algorithm), or none. */
+function loopOf(steps: RecipeStep[]): string[] {
+ const keys = new Set(steps.map((s) => s.key));
+ const waits = new Map(steps.map((s) => [s.key, new Set(s.kind === "generate" ? asList(s.after).filter((a) => keys.has(a)) : [])]));
+ const done = new Set<string>();
+ let moved = true;
+ while (moved) {
+ moved = false;
+ for (const [k, w] of waits) {
+ if (done.has(k) || [...w].some((a) => !done.has(a))) continue;
+ done.add(k);
+ moved = true;
+ }
+ }
+ return steps.map((s) => s.key).filter((k) => !done.has(k));
+}
+
+// ---------------------------------------------------------------------------
+// Many runs: rows from a CSV
+
+export interface RecipeRow {
+ /** The row's line in the file (1-based, the header is line 1 when it comes first). */
+ line: number;
+ cells: string[];
+ values?: RecipeValues;
+ errors: string[];
+}
+
+export interface ParsedRows {
+ header: string[];
+ /** The input each column fills (null: a column that isn't an input, left out). */
+ columns: (string | null)[];
+ rows: RecipeRow[];
+ /** What stops every row (no column for a required input, too many rows, an empty file). */
+ errors: string[];
+ /** What was left out without stopping anything (a column that isn't an input). */
+ notes: string[];
+}
+
+/** Cells of a CSV or TSV text (a spreadsheet's paste is tab-separated): quotes, doubled quotes, line breaks in quotes. */
+export function csvCells(text: string): { cells: string[]; line: number }[] {
+ const src = text.replace(/^/, "");
+ const firstLine = src.split(/\r?\n/, 1)[0] ?? "";
+ const sep = firstLine.includes("\t") && !firstLine.includes(",") ? "\t" : firstLine.includes(";") && !firstLine.includes(",") && !firstLine.includes("\t") ? ";" : ",";
+ const rows: { cells: string[]; line: number }[] = [];
+ let row: string[] = [];
+ let cell = "";
+ let quoted = false;
+ let line = 1;
+ let start = 1;
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i];
+ if (quoted) {
+ if (c === '"' && src[i + 1] === '"') {
+ cell += '"';
+ i++;
+ } else if (c === '"') quoted = false;
+ else {
+ if (c === "\n") line++;
+ cell += c;
+ }
+ continue;
+ }
+ if (c === '"' && !cell.trim()) {
+ quoted = true;
+ cell = "";
+ } else if (c === sep) {
+ row.push(cell);
+ cell = "";
+ } else if (c === "\n" || c === "\r") {
+ if (c === "\r" && src[i + 1] === "\n") i++;
+ row.push(cell);
+ rows.push({ cells: row, line: start });
+ row = [];
+ cell = "";
+ line++;
+ start = line;
+ } else cell += c;
+ }
+ if (cell || row.length) {
+ row.push(cell);
+ rows.push({ cells: row, line: start });
+ }
+ return rows.map((r) => ({ ...r, cells: r.cells.map((x) => x.trim()) }));
+}
+
+const norm = (s: string) => s.toLowerCase().replace(/[\s_-]+/g, " ").trim();
+
+/**
+ * Rows of values from a CSV (or a spreadsheet's paste): a header row naming each input by its id or its label, then
+ * one run per row. Empty rows are skipped; at most RECIPE_LIMITS.rows. Each row is checked like the form (checkValues).
+ */
+export function parseRows(csv: string, recipe: Pick<Recipe, "params">): ParsedRows {
+ const all = csvCells(csv).filter((r) => r.cells.some((c) => c));
+ const empty: ParsedRows = { header: [], columns: [], rows: [], errors: [], notes: [] };
+ if (!all.length) return { ...empty, errors: ["Paste a table: a header row with the inputs' names, then one row per run"] };
+ const [head, ...body] = all;
+ const header = head.cells;
+ const byName = new Map<string, string>();
+ for (const p of recipe.params) {
+ byName.set(norm(p.id), p.id);
+ byName.set(norm(p.label), p.id);
+ }
+ const columns = header.map((h) => byName.get(norm(h)) ?? null);
+ const errors: string[] = [];
+ const notes: string[] = [];
+ header.forEach((h, i) => {
+ if (!columns[i] && h) notes.push(`“${h}” isn't an input of this skill, so it's left out`);
+ });
+ for (const id of new Set(columns.filter((c): c is string => !!c))) {
+ if (columns.filter((c) => c === id).length > 1) errors.push(`Two columns fill “${recipe.params.find((p) => p.id === id)!.label}”`);
+ }
+ if (!columns.some(Boolean)) errors.push(`The first row names no input: use ${recipe.params.map((p) => `“${p.label}”`).join(", ")}`);
+ else
+ for (const p of recipe.params) {
+ if (p.required && p.default === undefined && !columns.includes(p.id)) errors.push(`No column for “${p.label}”`);
+ }
+ if (body.length > RECIPE_LIMITS.rows) errors.push(`At most ${RECIPE_LIMITS.rows} rows at a time — this has ${body.length}`);
+ const rows = body.slice(0, RECIPE_LIMITS.rows).map((r): RecipeRow => {
+ const raw: Record<string, unknown> = {};
+ columns.forEach((id, i) => {
+ if (id && raw[id] === undefined) raw[id] = r.cells[i] ?? "";
+ });
+ const checked = checkValues(recipe, raw);
+ return { line: r.line, cells: r.cells, ...(checked.values && { values: checked.values }), errors: Object.values(checked.errors) };
+ });
+ return { header, columns, rows, errors, notes };
+}
+
+// ---------------------------------------------------------------------------
+// Checking outputs (a real test): structure only, never pixels
+
+export interface OutputCheck {
+ ok: boolean;
+ problems: string[];
+ /** Checks that couldn't be read (a container probeMedia doesn't know). */
+ skipped: string[];
+}
+
+const ratioOf = (a: string) => {
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(a);
+ return m ? Number(m[1]) / Number(m[2]) : NaN;
+};
+
+/**
+ * A step's outputs against its check: kind, count, aspect from width and height (±2%), seconds (a range, or one
+ * length ±10%), and sound. Pure: `infos` are each output's probeMedia (null when it couldn't be read).
+ */
+export function checkOutputs(check: FilledCheck, outputs: Pick<OutputFile, "kind" | "width" | "height">[], infos: (MediaInfo | null | undefined)[] = []): OutputCheck {
+ const problems: string[] = [];
+ const skipped: string[] = [];
+ const main = check.kind ? outputs.filter((o) => o.kind === check.kind) : outputs;
+ if (check.kind && !main.length) problems.push(`it made no ${check.kind}${outputs.length ? ` (got ${[...new Set(outputs.map((o) => o.kind))].join(", ")})` : ""}`);
+ if (check.count !== undefined && main.length !== check.count) problems.push(`it made ${main.length} ${check.kind ?? "output"}${main.length === 1 ? "" : "s"}, not ${check.count}`);
+ const at = (o: (typeof outputs)[number]) => infos[outputs.indexOf(o)] ?? null;
+ if (check.aspect) {
+ const want = ratioOf(check.aspect);
+ for (const [i, o] of main.entries()) {
+ const info = at(o);
+ const w = o.width ?? info?.width;
+ const h = o.height ?? info?.height;
+ if (!w || !h) {
+ skipped.push(`the shape of output ${i + 1}`);
+ continue;
+ }
+ if (Math.abs(w / h - want) / want > 0.02) problems.push(`output ${i + 1} is ${w}×${h}, not ${check.aspect}`);
+ }
+ }
+ if (check.seconds !== undefined) {
+ const [lo, hi] = Array.isArray(check.seconds) ? check.seconds : [check.seconds * 0.9, check.seconds * 1.1];
+ for (const [i, o] of main.entries()) {
+ const d = at(o)?.duration;
+ if (d === undefined) skipped.push(`the length of output ${i + 1}`);
+ else if (d < lo - 1e-6 || d > hi + 1e-6) problems.push(`output ${i + 1} is ${Math.round(d * 10) / 10} s, not ${Array.isArray(check.seconds) ? `${lo}–${hi}` : check.seconds} s`);
+ }
+ }
+ if (check.sound !== undefined) {
+ for (const [i, o] of main.entries()) {
+ const info = at(o);
+ if (!info) skipped.push(`the sound of output ${i + 1}`);
+ else if (info.hasAudio !== check.sound) problems.push(`output ${i + 1} ${info.hasAudio ? "has sound" : "is silent"}`);
+ }
+ }
+ return { ok: !problems.length, problems, skipped };
+}
+
+// ---------------------------------------------------------------------------
+// Export and reading
+
+const FILE_KIND: [RegExp, "image" | "video" | "audio"][] = [
+ [/\.(png|jpe?g|webp|gif|avif)$/i, "image"],
+ [/\.(mp4|webm|mov|m4v)$/i, "video"],
+ [/\.(mp3|wav|m4a|ogg|flac|aac|opus)$/i, "audio"],
+];
+
+/**
+ * The recipe as it is shared: no examples, no source and no checks of this install (the other install checks it
+ * again). Files fixed in its steps (a logo, a music bed) are files of this Fuobe and don't travel in the zip, so each
+ * becomes a required input the form asks for on the first run there.
+ */
+export function stripExamples(recipe: Recipe): Recipe {
+ const params = recipe.params.map((p) => {
+ const q = { ...p };
+ delete q.example;
+ return q;
+ });
+ const taken = new Set(params.map((p) => p.id));
+ const files = new Map<string, string>();
+ const swap = (v: unknown, where: string): unknown => {
+ if (typeof v === "string" && v.startsWith("/api/files/") && !/\s/.test(v)) {
+ const kind = FILE_KIND.find(([re]) => re.test(v.split("?")[0]))?.[1];
+ if (!kind || params.length >= RECIPE_LIMITS.params) return v;
+ let id = files.get(v);
+ if (!id) {
+ let n = files.size + 1;
+ while (taken.has(`file_${n}`)) n++;
+ id = `file_${n}`;
+ taken.add(id);
+ files.set(v, id);
+ params.push({ id, label: `${kind === "image" ? "Image" : kind === "video" ? "Video" : "Audio"} for “${where}”`.slice(0, 60), type: kind, required: true });
+ }
+ return `{{${id}}}`;
+ }
+ if (Array.isArray(v)) return v.map((x) => swap(x, where));
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, swap(x, where)]));
+ return v;
+ };
+ const steps = recipe.steps.map((s): RecipeStep => (s.kind === "tool" ? { ...s, input: swap(s.input, s.label ?? s.key) as Record<string, unknown> } : { ...s, request: swap(s.request, s.label ?? s.key) as RecipeRequest }));
+ const out: Recipe = { ...recipe, params, steps };
+ delete out.source;
+ delete out.verified;
+ return out;
+}
+
+const TYPE_WORDS: Record<ParamType, string> = { image: "an image", video: "a video", audio: "an audio file", text: "text", number: "a number", choice: "one of", element: "an element's @handle" };
+
+function paramLine(p: RecipeParam): string {
+ const what = p.type === "choice" ? `${TYPE_WORDS.choice} ${(p.options ?? []).map((o) => `\`${o}\``).join(", ")}` : TYPE_WORDS[p.type];
+ const limits = [
+ p.type === "number" && p.min !== undefined ? `from ${p.min}` : "",
+ p.type === "number" && p.max !== undefined ? `to ${p.max}` : "",
+ p.type === "text" && p.max !== undefined ? `up to ${p.max} characters` : "",
+ ].filter(Boolean);
+ const need = p.required && p.default === undefined ? "required" : p.default !== undefined ? `default \`${p.default}\`` : "optional";
+ return `- \`${p.id}\` — ${p.label}: ${what}${limits.length ? ` (${limits.join(" ")})` : ""}; ${need}${p.hint ? `. ${p.hint}` : ""}`;
+}
+
+/** A step as a line: its model and operation, its words with the inputs as {{id}}, what it waits for. */
+function stepLine(s: RecipeStep, i: number, keys: string[]): string {
+ if (s.kind === "tool") return `${i + 1}. \`${s.tool}\` with ${JSON.stringify(s.input)}`;
+ const r = s.request;
+ const waits = asList(s.after).map((a) => `step ${keys.indexOf(a) + 1}`);
+ return `${i + 1}. ${s.label ? `${s.label}: ` : ""}\`${r.modelId}\`${r.op ? ` (${r.op})` : ""}${r.prompt ? ` — “${r.prompt}”` : ""}${waits.length ? `, from the result of ${waits.join(" and ")}` : ""}`;
+}
+
+/**
+ * The equivalent `generate` call, when every step waits for at most one earlier step (Assist's `after`), with the
+ * inputs left as {{id}} for the agent to fill in.
+ */
+function generateCall(recipe: Recipe): string | null {
+ const steps = recipe.steps as GenerateStep[];
+ if (steps.some((s) => s.kind !== "generate" || asList(s.after).length > 1)) return null;
+ const keys = steps.map((s) => s.key);
+ const jobs = steps.map((s) => {
+ const r = s.request;
+ const p = (r.params ?? {}) as Record<string, unknown>;
+ const inputs = (r.inputs ?? {}) as Record<string, unknown>;
+ const after = asList(s.after)[0];
+ return Object.fromEntries(
+ Object.entries({
+ model_id: r.modelId,
+ op: r.op,
+ prompt: r.prompt,
+ images: inputs.images,
+ end_image: inputs.endImage,
+ video: inputs.video,
+ audio: inputs.audio,
+ aspect_ratio: p.aspectRatio,
+ resolution: p.resolution,
+ duration: p.duration,
+ outputs: p.numOutputs,
+ engine: r.engine,
+ after: after === undefined ? undefined : keys.indexOf(after),
+ }).filter(([, v]) => v !== undefined),
+ );
+ });
+ return JSON.stringify({ summary: "…", jobs }, null, 2);
+}
+
+/**
+ * The "Run it" section for agents (load_skill appends it): the inputs, the steps, and how another agent runs the
+ * same job with Fuobe's tools: the `run_skill` call (Assist and MCP, W3), else the equivalent `generate` or studio
+ * tool call.
+ */
+export function recipeMarkdown(recipe: Recipe, skill?: { name: string }): string {
+ const keys = recipe.steps.map((s) => s.key);
+ const tool = recipe.steps.find((s): s is ToolStep => s.kind === "tool");
+ const call = tool ? JSON.stringify({ tool: tool.tool, input: tool.input }, null, 2) : generateCall(recipe);
+ const values = Object.fromEntries(recipe.params.map((p) => [p.id, `{{${p.id}}}`]));
+ return [
+ "## Run it",
+ "",
+ `This skill runs by itself in Fuobe: the same steps with new inputs, priced first, no LLM needed (Skills → ${skill ? `/${skill.name}` : "this skill"} → Run…).`,
+ "",
+ recipe.params.length ? "**Inputs**" : "It takes no inputs.",
+ ...recipe.params.map(paramLine),
+ "",
+ "**Steps**",
+ ...recipe.steps.map((s, i) => stepLine(s, i, keys)),
+ "",
+ "**From an agent**",
+ "",
+ `With Fuobe's MCP server, \`run_skill\` runs it with values for the inputs${skill ? `: \`${JSON.stringify({ name: skill.name, values })}\`` : ""}. Where that tool isn't available, ${tool ? `call the studio tool \`${tool.tool}\` the same way` : call ? "make the same `generate` call" : "run the steps with `generate`, in order"}, with the inputs put in for {{id}}${call ? ":" : "."}`,
+ ...(call ? ["", "```json", call, "```"] : []),
+ "",
+ "Price it first with `estimate_cost` (or `estimate_job` for a studio tool) and confirm with the user.",
+ ].join("\n");
+}
+
+/** "29 Oct" from a stored day. */
+export const shortDay = (day: string): string => {
+ const d = new Date(`${day}T12:00:00Z`);
+ return Number.isNaN(d.getTime()) ? day : d.toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
+};
+
+/** The day a check passed, for `verified` (UTC, so every install agrees). */
+export const today = (now = Date.now()): string => new Date(now).toISOString().slice(0, 10);
+
+export const ENGINE_WORDS: Record<RecipeEngine, string> = { cloud: "Cloud", open: "GPU" };
+
+/**
+ * "Checked 29 Oct · Cloud ✓ · GPU not checked": the line under a recipe skill's description. `engines` are the ones
+ * its steps allow on this install.
+ */
+export function verifiedLine(recipe: Pick<Recipe, "verified">, engines: RecipeEngine[]): string {
+ const v = recipe.verified ?? {};
+ const days = engines.map((e) => v[e]?.dryRun ?? v[e]?.plan).filter((d): d is string => !!d);
+ if (!days.length) return "Not checked yet — check it once (free) before the first run";
+ const last = days.sort().at(-1)!;
+ const parts = engines.map((e) => (v[e]?.dryRun ? `${ENGINE_WORDS[e]} ✓` : v[e]?.plan ? `${ENGINE_WORDS[e]} priced` : `${ENGINE_WORDS[e]} not checked`));
+ return [`Checked ${shortDay(last)}`, ...parts].join(" · ");
+}
diff --git a/tests/recipe.test.ts b/tests/recipe.test.ts
new file mode 100644
index 00000000..49c72f5b
--- /dev/null
+++ b/tests/recipe.test.ts
@@ -0,0 +1,345 @@
+import { describe, expect, it } from "vitest";
+import { TABLE_LIMITS } from "@/lib/catalog/canvas";
+import {
+ checkOutputs,
+ checkValues,
+ compile,
+ csvCells,
+ exampleValues,
+ fill,
+ leafKeys,
+ parseRecipe,
+ parseRows,
+ RECIPE_LIMITS,
+ recipeMarkdown,
+ recipeProblems,
+ RecipeSchema,
+ stripExamples,
+ valuesSchema,
+ verifiedLine,
+ type Recipe,
+} from "@/lib/recipe";
+
+/** The research's illustrative recipe (§9): a cut-out, a scene, a turntable clip. */
+const lamp = (): Recipe =>
+ RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: [
+ { id: "product", label: "Product photo", type: "image", required: true, example: "/api/files/uploads/2026-10-20/lamp.png" },
+ { 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",
+ label: "Turntable",
+ 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", count: "{{takes}}", aspect: "{{aspect}}", seconds: [4.5, 5.5], sound: false, look: "the product turns on a plain plinth" } },
+ verified: { cloud: { plan: "2026-10-29", dryRun: "2026-10-29", real: null, catalog: "sha256:abc" }, open: null },
+ source: { from: "library", generations: ["V1StGXR8_Z5j"], at: "2026-10-29" },
+ });
+
+const opts = { skill: "lamp-turntable", run: "run123", title: "Lamp turntable" };
+
+describe("the recipe format", () => {
+ it("parses the research's example and keeps it clean", () => {
+ const r = lamp();
+ expect(r.params).toHaveLength(4);
+ expect(recipeProblems(r)).toEqual([]);
+ expect(leafKeys(r)).toEqual(new Set(["spin"]));
+ expect(parseRecipe(JSON.stringify(r))).toMatchObject({ ok: true });
+ });
+
+ it("refuses what isn't a recipe: a version, caps, an empty graph, bad JSON", () => {
+ expect(parseRecipe("{")).toEqual({ ok: false, error: "recipe.json isn't valid JSON" });
+ expect(parseRecipe(JSON.stringify({ ...lamp(), fuobeRecipe: 2 }))).toMatchObject({ ok: false, error: expect.stringContaining("fuobeRecipe") });
+ expect(parseRecipe(JSON.stringify({ ...lamp(), steps: [] }))).toMatchObject({ ok: false, error: expect.stringContaining("a recipe needs a step") });
+ const many = Array.from({ length: RECIPE_LIMITS.params + 1 }, (_, i) => ({ id: `p${i}`, label: `P ${i}`, type: "text" }));
+ expect(parseRecipe(JSON.stringify({ ...lamp(), params: many }))).toMatchObject({ ok: false, error: expect.stringContaining("at most 12 inputs") });
+ const steps = Array.from({ length: RECIPE_LIMITS.steps + 1 }, (_, i) => ({ key: `s${i}`, kind: "generate", request: { feature: "skill", modelId: "flux-2" } }));
+ expect(parseRecipe(JSON.stringify({ ...lamp(), steps }))).toMatchObject({ ok: false, error: expect.stringContaining("at most 24 steps") });
+ expect(parseRecipe(JSON.stringify({ ...lamp(), params: [{ id: "1bad", label: "x", type: "text" }] }))).toMatchObject({ ok: false });
+ });
+
+ it("drops fields only the server sets, whatever the file says", () => {
+ const r = RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: [],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "flux-2", prompt: "x", demo: true, skill: { name: "other", run: "x" }, chainFilled: true, batchTitle: "no" } }],
+ });
+ const req = (r.steps[0] as Extract<Recipe["steps"][number], { kind: "generate" }>).request;
+ expect(req).toEqual({ feature: "skill", modelId: "flux-2", prompt: "x" });
+ });
+});
+
+describe("save-time problems", () => {
+ const base = lamp();
+ const withSteps = (steps: unknown[], extra: Partial<Recipe> = {}) => RecipeSchema.parse({ ...base, ...extra, steps });
+ const [cutout, scene, spin] = base.steps;
+
+ it("names unknown and unused placeholders", () => {
+ const r = withSteps([cutout, { ...scene, request: { ...(scene as { request: object }).request, prompt: "{{nme}} on a plinth" } }, spin]);
+ expect(recipeProblems(r)).toEqual(expect.arrayContaining([expect.stringContaining("uses {{nme}}, which isn't an input")]));
+ const unused = RecipeSchema.parse({ ...base, params: [...base.params, { id: "mood", label: "Mood", type: "text" }] });
+ expect(recipeProblems(unused)).toEqual([expect.stringContaining("“Mood” ({{mood}}) isn't used")]);
+ const badCheck = RecipeSchema.parse({ ...base, checks: { spin: { count: "{{many}}" }, nope: { kind: "image" } } });
+ expect(recipeProblems(badCheck)).toEqual(expect.arrayContaining([expect.stringContaining("{{many}}"), expect.stringContaining("“nope”")]));
+ });
+
+ it("refuses a count from an input on a step that feeds others", () => {
+ const sceneN = { ...scene, request: { ...(scene as { request: { params: object } }).request, params: { aspectRatio: "{{aspect}}", numOutputs: "{{takes}}" } } };
+ expect(recipeProblems(withSteps([cutout, sceneN, spin]))).toEqual([expect.stringContaining("Step “scene” feeds later steps, so its count can't come from an input")]);
+ const sceneTwo = { ...scene, request: { ...(scene as { request: { params: object } }).request, params: { aspectRatio: "{{aspect}}", numOutputs: 2 } } };
+ expect(recipeProblems(withSteps([cutout, sceneTwo, spin]))).toEqual([expect.stringContaining("must make one result")]);
+ });
+
+ it("refuses duplicate keys and ids, a tool step that isn't alone, and a broken graph", () => {
+ expect(recipeProblems(withSteps([cutout, { ...scene, key: "cutout", after: undefined, chain: undefined }, spin]))).toEqual(expect.arrayContaining(["Two steps are called “cutout”"]));
+ expect(recipeProblems(RecipeSchema.parse({ ...base, params: [...base.params, base.params[0]] }))).toEqual(expect.arrayContaining(["Two inputs are called “product”"]));
+ const tool = { key: "dub", kind: "tool", tool: "dub_video", input: { video: "{{product}}", languages: ["Spanish"] } };
+ expect(recipeProblems(withSteps([cutout, scene, spin, tool]))).toEqual(expect.arrayContaining([expect.stringContaining("must be the recipe's only step")]));
+ expect(recipeProblems(withSteps([cutout, { ...scene, after: ["ghost"] }, spin]))).toEqual(expect.arrayContaining([expect.stringContaining("waits for “ghost”")]));
+ expect(recipeProblems(withSteps([cutout, { ...scene, chain: [{ slot: "images" }, { slot: "images" }] }, spin]))).toEqual(expect.arrayContaining([expect.stringContaining("2 chain slots for 1 earlier step")]));
+ const loop = withSteps([{ ...cutout, after: ["spin"], chain: [{ slot: "images" }] }, scene, spin]);
+ expect(recipeProblems(loop)).toEqual(expect.arrayContaining([expect.stringContaining("in a loop")]));
+ });
+
+ it("checks each input's own default, example and options", () => {
+ const r = RecipeSchema.parse({
+ ...base,
+ params: [
+ { ...base.params[0], example: "C:\\photos\\lamp.png" },
+ base.params[1],
+ { ...base.params[2], default: "4:3" },
+ { ...base.params[3], min: 5, max: 2 },
+ { id: "who", label: "Who", type: "choice" },
+ ],
+ steps: [...base.steps, { key: "x", kind: "generate", request: { feature: "skill", modelId: "flux-2", prompt: "{{who}}" } }],
+ });
+ const p = recipeProblems(r);
+ expect(p).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("The example of “Product photo” doesn't fit"),
+ expect.stringContaining("The default of “Shape” doesn't fit"),
+ "“Takes”: its minimum is above its maximum",
+ "The choice “Who” needs options",
+ ]),
+ );
+ });
+});
+
+describe("values", () => {
+ const r = lamp();
+
+ it("applies defaults, limits and options, and says what's missing", () => {
+ expect(checkValues(r, { product: "/api/files/uploads/a.png", name: "Desk lamp" })).toEqual({ values: { product: "/api/files/uploads/a.png", name: "Desk lamp", aspect: "1:1", takes: 1 }, errors: {} });
+ const bad = checkValues(r, { product: "file:///etc/passwd", name: "", aspect: "4:3", takes: 9 });
+ expect(bad.values).toBeUndefined();
+ expect(bad.errors).toEqual({
+ product: "Product photo: a file from Fuobe (/api/files/…) or an http(s) link",
+ name: "Product name is needed",
+ aspect: "Shape: one of 1:1, 9:16, 16:9",
+ takes: "Takes: at most 4",
+ });
+ expect(checkValues(r, { product: "https://example.com/a.jpg", name: "x".repeat(201) }).errors.name).toBe("Product name: at most 200 characters");
+ expect(checkValues(r, { product: "https://example.com/a.jpg", name: "Lamp", takes: "0" }).errors.takes).toBe("Takes: at least 1");
+ });
+
+ it("reads text from a form or a CSV: numbers as numbers, choices without minding case, @handles", () => {
+ const withEl = RecipeSchema.parse({ ...r, params: [...r.params, { id: "hero", label: "Hero", type: "element", required: true }] });
+ const ok = checkValues(withEl, { product: "/api/files/a.png", name: "Lamp", takes: "3", aspect: "16:9", hero: "Maya_Lopez" });
+ expect(ok.values).toMatchObject({ takes: 3, aspect: "16:9", hero: "@Maya_Lopez" });
+ expect(checkValues(withEl, { product: "/api/files/a.png", name: "Lamp", hero: "@two words" }).errors.hero).toBe("Hero: an element's @handle, e.g. @Maya");
+ expect(checkValues(withEl, { product: "/api/files/a.png", name: "Lamp", hero: "@Maya", aspect: "9:16".toUpperCase() }).values?.aspect).toBe("9:16");
+ // valuesSchema is a plain zod object, one field per input.
+ expect(Object.keys(valuesSchema(withEl).shape)).toEqual(["product", "name", "aspect", "takes", "hero"]);
+ });
+
+ it("gives a check its examples, and a stand-in file for a media input with none", () => {
+ const noEx = RecipeSchema.parse({ ...r, params: r.params.map((p) => ({ ...p, example: undefined })) });
+ expect(exampleValues(noEx, (t) => `/api/files/stand-in.${t}`)).toEqual({ product: "/api/files/stand-in.image", name: "Product name", aspect: "1:1", takes: 1 });
+ expect(exampleValues(r, () => "x")).toMatchObject({ product: "/api/files/uploads/2026-10-20/lamp.png", name: "Lumen desk lamp" });
+ });
+});
+
+describe("fill and compile", () => {
+ const r = lamp();
+ const values = { product: "/api/files/uploads/new.png", name: "Arc floor lamp", aspect: "9:16", takes: 3 };
+
+ it("keeps types for exact placeholders and puts text into longer strings", () => {
+ const { steps, checks } = fill(r, values);
+ const [cut, scene, spin] = steps as Extract<Recipe["steps"][number], { kind: "generate" }>[];
+ expect(cut.request.inputs).toEqual({ images: ["/api/files/uploads/new.png"] });
+ expect(scene.request.prompt).toBe("Arc floor lamp on a travertine plinth, soft window light");
+ expect(scene.request.params).toEqual({ aspectRatio: "9:16" });
+ expect(spin.request.params).toEqual({ duration: 5, numOutputs: 3 });
+ expect(checks.spin).toEqual({ kind: "video", count: 3, aspect: "9:16", seconds: [4.5, 5.5], sound: false, look: "the product turns on a plain plinth" });
+ });
+
+ it("drops a field whose optional input is empty, and tidies the words around it", () => {
+ const r2 = RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: [
+ { id: "ref", label: "Reference", type: "image" },
+ { id: "mood", label: "Mood", type: "text" },
+ ],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "flux-2", prompt: "A lamp, {{mood}}, studio light", inputs: { images: ["{{ref}}"] } } }],
+ });
+ const [a] = fill(r2, {}).steps as Extract<Recipe["steps"][number], { kind: "generate" }>[];
+ expect(a.request.prompt).toBe("A lamp, studio light");
+ expect(a.request.inputs).toBeUndefined();
+ });
+
+ it("compiles to createPipeline's steps with after, chain, batchTitle and the skill stamp", () => {
+ const c = compile(r, values, opts);
+ expect(c.kind).toBe("pipeline");
+ if (c.kind !== "pipeline") return;
+ expect(c.steps.map((s) => s.key)).toEqual(["cutout", "scene", "spin"]);
+ expect(c.steps[1]).toMatchObject({ after: ["cutout"], chain: [{ slot: "images", position: "first" }] });
+ for (const s of c.steps) {
+ expect(s.request.batchTitle).toBe("Lamp turntable");
+ expect(s.request.skill).toEqual({ name: "lamp-turntable", run: "run123" });
+ expect(s.request.demo).toBeUndefined();
+ expect(s.request.feature).toBe("skill");
+ }
+ // A labelled step keeps its label on the tile; the others get createPipeline's "Step i of n".
+ expect(c.steps[2].request.step).toEqual({ label: "Turntable", index: 2, of: 3 });
+ expect(c.steps[0].request.step).toBeUndefined();
+ // The count varies only on the leaf.
+ expect(c.steps.map((s) => s.request.params?.numOutputs)).toEqual([undefined, undefined, 3]);
+ });
+
+ it("compiles a dry run onto the demo provider as hidden helper rows", () => {
+ const c = compile(r, values, { ...opts, demo: true });
+ if (c.kind !== "pipeline") throw new Error("pipeline expected");
+ expect(c.steps.every((s) => s.request.demo === true && s.request.feature === "skill-check")).toBe(true);
+ });
+
+ it("compiles a tool recipe to one tool call", () => {
+ const t = RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: [
+ { id: "clip", label: "Clip", type: "video", required: true },
+ { id: "lang", label: "Language", type: "choice", options: ["Spanish", "German"], default: "Spanish" },
+ ],
+ steps: [{ key: "captions", kind: "tool", tool: "add_captions", input: { video: "{{clip}}", translate_to: "{{lang}}" } }],
+ });
+ expect(recipeProblems(t)).toEqual([]);
+ expect(compile(t, { clip: "/api/files/a.mp4" }, opts)).toMatchObject({ kind: "tool", tool: "add_captions", input: { video: "/api/files/a.mp4", translate_to: "Spanish" } });
+ });
+});
+
+describe("rows from a CSV", () => {
+ const r = lamp();
+
+ it("reads headers by id or label, quotes, a BOM and empty rows", () => {
+ const csv = '\uFEFFProduct photo,name,Shape,Notes\r\n/api/files/a.png,"Lamp, brass",16:9,x\n\n/api/files/b.png,"The ""Arc"" lamp",,\n,,,\n';
+ const p = parseRows(csv, r);
+ expect(p.errors).toEqual([]);
+ expect(p.columns).toEqual(["product", "name", "aspect", null]);
+ expect(p.notes).toEqual(["“Notes” isn't an input of this skill, so it's left out"]);
+ expect(p.rows.map((x) => x.values)).toEqual([
+ { product: "/api/files/a.png", name: "Lamp, brass", aspect: "16:9", takes: 1 },
+ { product: "/api/files/b.png", name: 'The "Arc" lamp', aspect: "1:1", takes: 1 },
+ ]);
+ expect(p.rows.map((x) => x.line)).toEqual([2, 4]);
+ });
+
+ it("reads a spreadsheet's paste (tabs) and line breaks inside quotes", () => {
+ expect(csvCells('a\tb\n"one\ntwo"\tthree').map((x) => x.cells)).toEqual([
+ ["a", "b"],
+ ["one\ntwo", "three"],
+ ]);
+ });
+
+ it("says what's wrong per row, and what stops every row", () => {
+ const p = parseRows("product,name,takes\nnot-a-link,Lamp,2\n/api/files/a.png,,9", r);
+ expect(p.errors).toEqual([]);
+ expect(p.rows[0].errors).toEqual(["Product photo: a file from Fuobe (/api/files/…) or an http(s) link"]);
+ expect(p.rows[1].errors).toEqual(["Product name is needed", "Takes: at most 4"]);
+ expect(parseRows("name\nLamp", r).errors).toEqual(["No column for “Product photo”"]);
+ expect(parseRows("", r).errors[0]).toMatch(/Paste a table/);
+ expect(parseRows("foo,bar\n1,2", r).errors[0]).toMatch(/names no input/);
+ });
+
+ it("takes at most 50 rows, as a Canvas table does", () => {
+ expect(RECIPE_LIMITS.rows).toBe(TABLE_LIMITS.rows);
+ const rows = (n: number) => ["product,name", ...Array.from({ length: n }, (_, i) => `/api/files/${i}.png,Lamp ${i}`)].join("\n");
+ expect(parseRows(rows(50), r).errors).toEqual([]);
+ const over = parseRows(rows(51), r);
+ expect(over.errors).toEqual(["At most 50 rows at a time — this has 51"]);
+ expect(over.rows).toHaveLength(50);
+ });
+});
+
+describe("checking outputs", () => {
+ const video = (w: number, h: number) => ({ kind: "video" as const, width: w, height: h });
+ const info = (duration: number, hasAudio: boolean) => ({ container: "mp4" as const, duration, width: 720, height: 1280, hasVideo: true, hasAudio });
+
+ it("passes the right kind, count, shape, length and sound", () => {
+ const c = { kind: "video" as const, count: 2, aspect: "9:16", seconds: [4.5, 5.5] as [number, number], sound: false };
+ expect(checkOutputs(c, [video(720, 1280), video(1080, 1920)], [info(5, false), info(5.2, false)])).toEqual({ ok: true, problems: [], skipped: [] });
+ });
+
+ it("names each thing that's off, within the tolerances", () => {
+ const c = { kind: "video" as const, count: 1, aspect: "16:9", seconds: 5, sound: true };
+ const out = checkOutputs(c, [video(720, 1280), video(720, 1280)], [info(6, false), info(5.4, true)]);
+ expect(out.ok).toBe(false);
+ expect(out.problems).toEqual(["it made 2 videos, not 1", "output 1 is 720×1280, not 16:9", "output 2 is 720×1280, not 16:9", "output 1 is 6 s, not 5 s", "output 1 is silent"]);
+ // ±2% on the shape: 1280×722 is still 16:9.
+ expect(checkOutputs({ aspect: "16:9" }, [video(1280, 722)]).ok).toBe(true);
+ expect(checkOutputs({ kind: "image" }, [video(10, 10)]).problems).toEqual(["it made no image (got video)"]);
+ });
+
+ it("skips what it can't read instead of failing it", () => {
+ const out = checkOutputs({ kind: "video", seconds: 5, sound: false, aspect: "1:1" }, [{ kind: "video" }], [null]);
+ expect(out).toEqual({ ok: true, problems: [], skipped: ["the shape of output 1", "the length of output 1", "the sound of output 1"] });
+ });
+});
+
+describe("sharing and reading", () => {
+ it("strips examples, source and this install's checks, and asks for fixed files as inputs", () => {
+ const base = lamp();
+ const withLogo = RecipeSchema.parse({
+ ...base,
+ steps: [...base.steps.slice(0, 2), { ...base.steps[2], request: { ...(base.steps[2] as { request: object }).request, inputs: { audio: "/api/files/uploads/2026-10-20/bed.mp3" } } }],
+ });
+ const s = stripExamples(withLogo);
+ expect(s.source).toBeUndefined();
+ expect(s.verified).toBeUndefined();
+ expect(s.params.every((p) => p.example === undefined)).toBe(true);
+ expect(s.params.at(-1)).toEqual({ id: "file_1", label: "Audio for “Turntable”", type: "audio", required: true });
+ expect(JSON.stringify(s.steps)).not.toContain("/api/files/");
+ expect(recipeProblems(s)).toEqual([]);
+ });
+
+ it("writes a Run it section with the inputs, the steps and the equivalent generate call", () => {
+ const md = recipeMarkdown(lamp(), { name: "lamp-turntable" });
+ expect(md).toMatch(/^## Run it/);
+ expect(md).toContain("- `product` — Product photo: an image; required");
+ expect(md).toContain("- `aspect` — Shape: one of `1:1`, `9:16`, `16:9`; default `1:1`");
+ expect(md).toContain("3. Turntable: `kling-3` (i2v) — “slow turntable of the {{name}}”, from the result of step 2");
+ expect(md).toContain('"model_id": "kling-3"');
+ expect(md).toContain('"after": 1');
+ expect(md).toContain("run_skill");
+ });
+
+ it("says when and where it was checked", () => {
+ expect(verifiedLine(lamp(), ["cloud", "open"])).toBe("Checked 29 Oct · Cloud ✓ · GPU not checked");
+ expect(verifiedLine({}, ["cloud"])).toMatch(/Not checked yet/);
+ });
+});