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 W2: draft a skill from results in the Library, checked before it is saved

Claudea616d69068d1
diff --git a/src/app/api/assist/skills/draft/check/route.ts b/src/app/api/assist/skills/draft/check/route.ts
new file mode 100644
index 00000000..1389f737
--- /dev/null
+++ b/src/app/api/assist/skills/draft/check/route.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+import { badBody, recipeFailure } from "@/server/recipe-routes";
+import { checkDraft } from "@/server/recipes";
+
+const Body = z.object({
+ recipe: z.unknown(),
+ /** `plan` prices it (quick); `demo` adds the free dry run on the demo provider. */
+ level: z.enum(["plan", "demo"]).default("plan"),
+ title: z.string().trim().max(80).optional(),
+});
+
+/** Check a drafted skill's recipe before it is saved: free, with or without keys. What passed is kept for its save. */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ return Response.json(await checkDraft(parsed.data.recipe, parsed.data.level, parsed.data.title || undefined));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/draft/name/route.ts b/src/app/api/assist/skills/draft/name/route.ts
new file mode 100644
index 00000000..3881b2ab
--- /dev/null
+++ b/src/app/api/assist/skills/draft/name/route.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+import { badBody, recipeFailure } from "@/server/recipe-routes";
+import { draftFromGenerations, nameDraft } from "@/server/recipe-builder";
+
+const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });
+
+/**
+ * The optional naming pass for a draft (Claude or Ollama, whichever this install allows): names for its inputs, slots in
+ * its prompts, a title, a description and a SKILL.md body. `naming` is null when there's no LLM or its answer was malformed.
+ */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ const { draft } = draftFromGenerations(parsed.data.generations);
+ return Response.json({ naming: draft ? await nameDraft(draft) : null });
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.ts
new file mode 100644
index 00000000..85db57d6
--- /dev/null
+++ b/src/app/api/assist/skills/draft/route.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+import { badBody, recipeFailure } from "@/server/recipe-routes";
+import { draftFromGenerations } from "@/server/recipe-builder";
+
+const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });
+
+/**
+ * A skill drafted from results in the Library (W2): the steps behind them rebuilt from their requests, every input
+ * Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks couldn't be used and why.
+ */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ return Response.json(draftFromGenerations(parsed.data.generations));
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/app/api/assist/skills/draft/save/route.ts b/src/app/api/assist/skills/draft/save/route.ts
new file mode 100644
index 00000000..d2835d89
--- /dev/null
+++ b/src/app/api/assist/skills/draft/save/route.ts
@@ -0,0 +1,17 @@
+import { z } from "zod";
+import { SkillBody } from "@/server/assist/schemas";
+import { badBody, recipeFailure } from "@/server/recipe-routes";
+import { saveDraft } from "@/server/recipes";
+
+const Body = SkillBody.extend({ recipe: z.unknown() });
+
+/** Save a drafted skill: its SKILL.md and recipe.json, once its plan passes on an engine (checked again here, free). */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return badBody(parsed.error.issues);
+ try {
+ return Response.json(await saveDraft(parsed.data), { status: 201 });
+ } catch (e) {
+ return recipeFailure(e);
+ }
+}
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 97c6d145..f0903edf 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -3,6 +3,7 @@
import {
ArchiveRestore,
AudioLines,
+ BookmarkPlus,
Box,
CircleDot,
Clapperboard,
@@ -96,6 +97,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
finalize: Sparkles,
compare: Columns2,
reuse: RotateCcw,
+ "make-skill": BookmarkPlus,
"copy-prompt": Copy,
share: Share2,
pin: Pin,
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 89c2753e..28fc836c 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -906,6 +906,13 @@ export interface GenerationRequest {
* API input.
*/
demo?: boolean;
+ /**
+ * Server-set on the row a request that expanded into several rows returns first (a multi-shot film, a Frames film, an
+ * extend on a model with no extend API, open text-to-3D, a DoP relight: src/server/chains.ts): the request as it was
+ * asked, so a skill made from the result rebuilds that one request, not the steps it became (their number changes
+ * with the input). Stripped from API input.
+ */
+ asked?: GenerationRequest;
/**
* 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/output-actions.ts b/src/lib/output-actions.ts
index 71eeeeb1..c482b7af 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -38,6 +38,7 @@ export type OutputActionId =
| "finalize"
| "compare"
| "reuse"
+ | "make-skill"
| "copy-prompt"
| "share"
| "pin"
@@ -150,6 +151,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
if (o.draftId) out.push({ id: "finalize", label: "Render this draft in 1080p", placement: "menu" });
if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });
if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });
+ // The steps behind a finished result, as a skill that runs again with new inputs (src/components/skills).
+ if (g.status === "succeeded") out.push({ id: "make-skill", label: "Make a skill from this…", placement: "menu" });
if (g.prompt) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });
// A read-only link (src/lib/share.ts): finished results whose files Fuobe keeps.
if (g.status === "succeeded" && g.outputs.some((x) => storedPath(x.url))) out.push({ id: "share", label: "Share link…", placement: "menu" });
diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.ts
new file mode 100644
index 00000000..fbb1c2fd
--- /dev/null
+++ b/src/lib/recipe-builder.ts
@@ -0,0 +1,453 @@
+/**
+ * Making a skill from results already made (package W2, docs/research/work2skill-7.md §10): Work2Skill's induction
+ * without the screen recording. The server rebuilds the steps behind the picked results from Fuobe's exact records
+ * (src/server/recipe-builder.ts: requests, `depends_on`, chain slots) into a draft whose every input is Fixed; the review
+ * screen (src/components/skills/skill-builder.tsx) says which inputs vary next time and which words in a prompt are a
+ * slot, and this module turns those choices into the recipe (src/lib/recipe.ts) and a SKILL.md body.
+ *
+ * Pure and browser-safe: the review screen builds the recipe live as the choices change; the server checks and saves it.
+ */
+import { z } from "zod";
+import { SKILL_LIMITS } from "./assist";
+import type { Engine, MediaKind } from "./catalog/types";
+import { isMediaType, leafKeys, RECIPE_LIMITS, type ParamType, type Recipe, type RecipeParam, type RecipeStep } from "./recipe";
+
+// ---------------------------------------------------------------------------
+// What the draft holds
+
+/** One step of the draft as the review screen shows it. */
+export interface DraftStep {
+ key: string;
+ kind: "generate" | "tool";
+ /** "Image to video", "Translate & dub". */
+ label: string;
+ /** The model (a generate step) or the studio (a tool step). */
+ modelName: string;
+ /** The engine the result ran on. */
+ engine?: Engine;
+ /** The result the step was rebuilt from, and a still of it. */
+ generation: string;
+ thumb?: { url: string; kind: MediaKind; poster?: string };
+ /** The labels of the steps it waits for, in order. */
+ waits: string[];
+ /** Nothing waits for it: its count may vary. */
+ leaf: boolean;
+ /** What changed when it was rebuilt ("Kling 3 was replaced by Kling 3.1"). */
+ notes: string[];
+}
+
+export type CandidateKind = "media" | "element" | "text" | "setting";
+
+/** Where a candidate's value sits: a step, and the path in its request (or a tool step's input). */
+export interface CandidateSpot {
+ step: string;
+ path: (string | number)[];
+}
+
+/** An input that could vary next time. Every one starts Fixed (a templated prompt can lose what made the result good). */
+export interface DraftCandidate {
+ /** Its input id when it varies (unique in the draft). */
+ id: string;
+ label: string;
+ type: ParamType;
+ kind: CandidateKind;
+ /** The value it had: a file link, an @handle, the words, a setting. */
+ example: string | number;
+ /** A media value, a setting or a whole prompt: the value at each spot; an element: the prompts naming it. */
+ at: CandidateSpot[];
+ /** A setting: an optional input whose default is what it was. */
+ optional?: boolean;
+ options?: string[];
+ min?: number;
+ max?: number;
+ step?: number;
+ /** The setting it is (numOutputs, aspectRatio, duration, resolution). */
+ setting?: SettingId;
+ /** Why it can't vary. */
+ locked?: string;
+}
+
+export type SettingId = "numOutputs" | "aspectRatio" | "duration" | "resolution";
+
+export interface SkillDraft {
+ /** The recipe with every candidate Fixed: no inputs, each value where it was. */
+ recipe: Recipe;
+ steps: DraftStep[];
+ candidates: DraftCandidate[];
+ /** Prefilled: a name (/name), a title, a description and when to use it. */
+ name: string;
+ title: string;
+ description: string;
+ whenToUse: string;
+ /** Made from results the demo provider made: check it on a real engine before trusting it. */
+ demo: boolean;
+ /** What the review screen says once (a model that moved, a step left as a fixed input). */
+ notes: string[];
+ /** The LLM the optional naming pass would ask (null: none, so there is none). */
+ llm: "claude" | "ollama" | null;
+}
+
+/** A picked result the builder couldn't use, and why. */
+export interface DraftRefusal {
+ id: string;
+ title: string;
+ reason: string;
+}
+
+export const DEMO_NOTE = "Made from demo results: check it on your engine before trusting it";
+export const STEPS_REFUSAL = "This was made in steps from one request: open it, press Reuse settings, run it again, then make the skill";
+
+// ---------------------------------------------------------------------------
+// Studios: work that plans its own steps from its input
+
+interface StudioInfo {
+ name: string;
+ /** The Assist tool that makes the same thing from the studio's input. */
+ tool?: string;
+}
+
+const STUDIOS: [RegExp, StudioInfo][] = [
+ [/^dub$/, { name: "Translate & dub", tool: "dub_video" }],
+ [/^katana$/, { name: "Katana", tool: "katana" }],
+ [/^captions$/, { name: "Captions", tool: "add_captions" }],
+ [/^layers$/, { name: "Layers", tool: "split_layers" }],
+ [/^shorts$/, { name: "Shorts Studio", tool: "restyle_footage" }],
+ [/^faceless/, { name: "Faceless Studio", tool: "faceless_episode" }],
+ [/^ads$/, { name: "Ads Studio", tool: "create_ads" }],
+ [/^ad-multiplier$/, { name: "Ad Multiplier" }],
+ [/^click-to-ad$/, { name: "Click to Ad" }],
+ [/^storyboard/, { name: "Storyboard" }],
+ [/^cinema/, { name: "Cinema Studio" }],
+ [/^genjutsu$/, { name: "Genjutsu" }],
+ [/^remove-object$/, { name: "Remove object" }],
+ [/^content-factory$/, { name: "Content Factory" }],
+ [/^influencer$/, { name: "AI Influencer" }],
+ [/^swap-studio$/, { name: "Character Swap Studio" }],
+ [/^photodump$/, { name: "Photodump" }],
+ [/^character-sheet$/, { name: "Character Sheet" }],
+ [/^fashion$/, { name: "Fashion Factory" }],
+ [/^mixed-media/, { name: "Mixed Media" }],
+ [/^evolution/, { name: "Evolution" }],
+ [/^canvas/, { name: "Canvas" }],
+ [/^audio-(loop|join)$/, { name: "Audio tools" }],
+ [/^moodboard$/, { name: "Moodboards" }],
+ [/^eval$/, { name: "the evaluation harness" }],
+ [/^skill-check$/, { name: "a skill's check" }],
+];
+
+/**
+ * The studio a feature belongs to when that studio plans its own steps (a helper step `<feature>-step` belongs to its
+ * feature's studio), or undefined for a plain request (Image, Video, Edit, Assist, an app…).
+ */
+export function studioOf(feature: string): StudioInfo | undefined {
+ const base = feature.replace(/(-frame)?-step$/, "").replace(/-(preview|avatar|voice)$/, "");
+ return STUDIOS.find(([re]) => re.test(base))?.[1] ?? (base !== feature ? { name: "another studio" } : undefined);
+}
+
+export const notSupported = (studio: string) => `Made in ${studio}: making a skill from it isn't supported yet`;
+
+/**
+ * Step labels an expansion gave its rows before it kept the request as asked (createShotFilm, createKeyframeFilm,
+ * createExtendChain, createStillTo3d, createRelitClip in src/server/chains.ts). A heuristic for rows made before W2.
+ */
+const EXPANSION_LABELS = [/^Shot \d+ of \d+$/, /^Film · \d+ (shots|frames)$/, /^Frames \d+ → \d+$/, /^After frame \d+$/, /^Joining clips$/, /^(Last frame|Continuation|Extended video)$/, /^(Still|3D model)$/, /^(Relit start frame|Relit clip)$/];
+export const isExpansionLabel = (label: string | undefined): boolean => !!label && EXPANSION_LABELS.some((re) => re.test(label));
+
+// ---------------------------------------------------------------------------
+// The optional naming pass's answer (src/server/recipe-builder.ts nameDraft)
+
+const PARAM_ID = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
+
+export const NamingSchema = z.object({
+ name: z.string().trim().max(SKILL_LIMITS.name).optional(),
+ title: z.string().trim().min(1).max(SKILL_LIMITS.title).optional(),
+ description: z.string().trim().min(1).max(SKILL_LIMITS.description).optional(),
+ when_to_use: z.string().trim().min(1).max(SKILL_LIMITS.whenToUse).optional(),
+ body: z.string().trim().min(1).max(SKILL_LIMITS.body).optional(),
+ inputs: z.array(z.object({ candidate: z.string(), id: z.string().regex(PARAM_ID), label: z.string().trim().min(1).max(60) })).max(40).optional(),
+ slots: z.array(z.object({ step: z.string(), text: z.string().min(2).max(200), id: z.string().regex(PARAM_ID), label: z.string().trim().min(1).max(60) })).max(20).optional(),
+});
+
+/** A word or phrase in a step's prompt that becomes an input of its own ("a matte black desk lamp" → {{product}}). */
+export interface Slot {
+ step: string;
+ text: string;
+ id: string;
+ label: string;
+}
+
+/** What the naming pass suggests: each shown as a change, each off until ticked. */
+export interface Naming {
+ name?: string;
+ title?: string;
+ description?: string;
+ whenToUse?: string;
+ body?: string;
+ inputs: { candidate: string; id: string; label: string }[];
+ slots: Slot[];
+}
+
+/** The first JSON object in a model's answer (in a ```json fence or not), or null. */
+function firstObject(text: string): unknown {
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text)?.[1];
+ const src = fenced ?? text;
+ const start = src.indexOf("{");
+ const end = src.lastIndexOf("}");
+ if (start < 0 || end <= start) return null;
+ try {
+ return JSON.parse(src.slice(start, end + 1));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The naming pass's JSON, checked against the draft: a suggestion for an input or a step the draft doesn't have, or a
+ * slot whose words aren't in that step's prompt, is left out. Malformed output gives null (it's ignored).
+ */
+export function parseNaming(text: string | null | undefined, draft: Pick<SkillDraft, "candidates" | "recipe">): Naming | null {
+ if (!text) return null;
+ const parsed = NamingSchema.safeParse(firstObject(text));
+ if (!parsed.success) return null;
+ const n = parsed.data;
+ const ids = new Set(draft.candidates.filter((c) => !c.locked).map((c) => c.id));
+ const prompts = new Map(draft.recipe.steps.flatMap((s) => (s.kind === "generate" && typeof s.request.prompt === "string" ? [[s.key, s.request.prompt]] : [])));
+ const name = n.name ? slugify(n.name) : undefined;
+ return {
+ ...(name && { name }),
+ ...(n.title && { title: n.title }),
+ ...(n.description && { description: n.description }),
+ ...(n.when_to_use && { whenToUse: n.when_to_use }),
+ ...(n.body && { body: n.body }),
+ inputs: (n.inputs ?? []).filter((i) => ids.has(i.candidate)),
+ slots: (n.slots ?? []).filter((s) => prompts.get(s.step)?.includes(s.text)),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Names
+
+/** A skill name from words: lowercase, digits and single hyphens (SKILL_NAME_RE), at most 64 characters. */
+export function slugify(words: string): string {
+ return words
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, SKILL_LIMITS.name)
+ .replace(/-+$/, "");
+}
+
+/** An input id from a label ("Product photo" → product_photo), unique among `taken`. */
+export function paramIdFrom(label: string, taken: Iterable<string>): string {
+ const used = new Set(taken);
+ const base =
+ label
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .replace(/^(\d)/, "n$1")
+ .slice(0, 28) || "input";
+ let id = base;
+ for (let i = 2; used.has(id); i++) id = `${base}_${i}`;
+ return id;
+}
+
+// ---------------------------------------------------------------------------
+// Choices → the recipe
+
+export interface BuilderChoices {
+ /** Candidate id → it varies next time (absent: Fixed). */
+ varies: Record<string, boolean>;
+ /** Candidate id → its label and its input id, when changed. */
+ labels?: Record<string, string>;
+ ids?: Record<string, string>;
+ /** Candidate id → whether the form requires it (media, element and text; default yes). */
+ required?: Record<string, boolean>;
+ /** Words in prompts that become inputs of their own, accepted one by one. */
+ slots?: Slot[];
+}
+
+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;
+
+const bodyOf = (s: RecipeStep): Record<string, unknown> => (s.kind === "tool" ? s.input : (s.request as Record<string, unknown>));
+
+/** Set the value at `path` in `obj` (lists and objects), creating objects on the way. */
+function setAt(obj: Record<string, unknown>, path: (string | number)[], value: unknown): void {
+ let cur: Record<string | number, unknown> = obj;
+ for (const [i, k] of path.entries()) {
+ if (i === path.length - 1) {
+ cur[k] = value;
+ return;
+ }
+ if (cur[k] === undefined || cur[k] === null || typeof cur[k] !== "object") cur[k] = typeof path[i + 1] === "number" ? [] : {};
+ cur = cur[k] as Record<string | number, unknown>;
+ }
+}
+
+export function getAt(obj: unknown, path: (string | number)[]): unknown {
+ let cur = obj;
+ for (const k of path) {
+ if (!cur || typeof cur !== "object") return undefined;
+ cur = (cur as Record<string | number, unknown>)[k];
+ }
+ return cur;
+}
+
+const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+/** An @handle as a whole word (not inside a longer handle or an e-mail address). */
+const handleRe = (handle: string) => new RegExp(`(?<![\\p{L}\\p{N}[email protected]])${escapeRe(handle)}(?![\\p{L}\\p{N}_-])`, "gu");
+
+/** The input id a candidate gets: the one typed, else its own. */
+const idOf = (c: DraftCandidate, choices: BuilderChoices) => choices.ids?.[c.id]?.trim() || c.id;
+
+/**
+ * The recipe the choices make: each candidate that varies becomes an input and `{{id}}` where its value was (an element
+ * is put in for its @handle in the words), each accepted slot replaces its words in every prompt that still has them,
+ * and the checks follow (a count or a shape that varies is checked against the input; a length that varies isn't
+ * checked). An element or slot that ends up nowhere (its prompt varies as a whole) adds no input.
+ */
+export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, choices: BuilderChoices): Recipe {
+ const recipe = clone(draft.recipe);
+ const params: RecipeParam[] = [];
+ const byKey = new Map(recipe.steps.map((s) => [s.key, s]));
+ const checks = recipe.checks ?? {};
+ const varying = draft.candidates.filter((c) => choices.varies[c.id] && !c.locked);
+ // Elements first: their @handles are put in before a prompt that varies as a whole replaces the words.
+ const order = [...varying.filter((c) => c.kind === "element"), ...varying.filter((c) => c.kind !== "element")];
+ const placed: RecipeParam[] = [];
+ for (const c of order) {
+ const id = idOf(c, choices);
+ const label = (choices.labels?.[c.id]?.trim() || c.label).slice(0, 60);
+ let used = 0;
+ for (const spot of c.at) {
+ const step = byKey.get(spot.step);
+ if (!step) continue;
+ const body = bodyOf(step);
+ if (c.kind === "element") {
+ const words = getAt(body, spot.path);
+ if (typeof words !== "string") continue;
+ const next = words.replace(handleRe(String(c.example)), `{{${id}}}`);
+ if (next !== words) {
+ setAt(body, spot.path, next);
+ used++;
+ }
+ continue;
+ }
+ setAt(body, spot.path, `{{${id}}}`);
+ used++;
+ // A count that varies is checked against the input when one job made every result (else it isn't checked).
+ if (c.setting === "numOutputs") {
+ const cur = checks[spot.step]?.count;
+ const rest = { ...checks[spot.step] };
+ delete rest.count;
+ checks[spot.step] = cur === undefined || cur === c.example ? { ...rest, count: `{{${id}}}` } : rest;
+ }
+ if (c.setting === "aspectRatio" && checks[spot.step]) checks[spot.step] = { ...checks[spot.step], aspect: `{{${id}}}` };
+ if (c.setting === "duration" && checks[spot.step]) {
+ const rest = { ...checks[spot.step] };
+ delete rest.seconds;
+ checks[spot.step] = rest;
+ }
+ }
+ if (!used) continue;
+ const required = c.optional ? false : (choices.required?.[c.id] ?? true);
+ placed.push({
+ id,
+ label,
+ type: c.type,
+ ...(required && { required: true }),
+ ...(c.optional ? { default: c.example } : { example: c.example }),
+ ...(c.options && { options: c.options }),
+ ...(c.min !== undefined && { min: c.min }),
+ ...(c.max !== undefined && { max: c.max }),
+ ...(c.step !== undefined && { step: c.step }),
+ });
+ }
+ // Slots: their words in every prompt that still has them (the same words are the same input everywhere).
+ const slotParams: RecipeParam[] = [];
+ for (const slot of choices.slots ?? []) {
+ if (!slot.text.trim() || slotParams.some((p) => p.id === slot.id)) continue;
+ let used = 0;
+ for (const s of recipe.steps) {
+ if (s.kind !== "generate" || typeof s.request.prompt !== "string" || !s.request.prompt.includes(slot.text)) continue;
+ s.request.prompt = s.request.prompt.split(slot.text).join(`{{${slot.id}}}`);
+ used++;
+ }
+ if (used) slotParams.push({ id: slot.id, label: slot.label.slice(0, 60), type: "text", required: true, example: slot.text, max: Math.max(200, slot.text.length) });
+ }
+ // The form's order: files first, then elements, words, settings.
+ const rank = (p: RecipeParam) => (isMediaType(p.type) ? 0 : p.type === "element" ? 1 : p.type === "text" ? 2 : 3);
+ params.push(...[...placed, ...slotParams].sort((a, b) => rank(a) - rank(b)));
+ recipe.params = params.slice(0, RECIPE_LIMITS.params);
+ if (Object.keys(checks).length) recipe.checks = checks;
+ return recipe;
+}
+
+// ---------------------------------------------------------------------------
+// SKILL.md
+
+const TYPE_WORDS: Record<ParamType, string> = { image: "an image", video: "a video", audio: "an audio file", text: "words", number: "a number", choice: "one of", element: "a saved element (@handle)" };
+const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
+
+function inputLine(p: RecipeParam): string {
+ const what = p.type === "choice" ? `${TYPE_WORDS.choice} ${(p.options ?? []).join(", ")}` : TYPE_WORDS[p.type];
+ const need = p.default !== undefined ? `default ${String(p.default)}` : p.required ? "required" : "optional";
+ const was = p.example !== undefined && p.example !== null && !isMediaType(p.type) ? `; first made with “${cut(String(p.example), 120)}”` : "";
+ return `- **${p.label}** (\`${p.id}\`) — ${what}, ${need}${was}.`;
+}
+
+function checkLine(key: string, steps: Pick<DraftStep, "key" | "label">[], c: NonNullable<Recipe["checks"]>[string]): string | null {
+ const parts = [
+ c.count !== undefined ? `${typeof c.count === "number" ? c.count : c.count} ${c.kind ?? "result"}${c.count === 1 ? "" : "s"}` : c.kind ? `a ${c.kind}` : "",
+ c.aspect ? `${c.aspect}` : "",
+ c.seconds !== undefined ? (Array.isArray(c.seconds) ? `${c.seconds[0]}–${c.seconds[1]} s` : `about ${c.seconds} s`) : "",
+ c.sound === undefined ? "" : c.sound ? "with sound" : "silent",
+ c.look ? `showing ${c.look}` : "",
+ ].filter(Boolean);
+ if (!parts.length) return null;
+ const label = steps.find((s) => s.key === key)?.label ?? key;
+ return `- ${label}: ${parts.join(", ")}.`;
+}
+
+/**
+ * The SKILL.md body written from the recipe, with no LLM: the inputs, the steps in order with what each waits for, the
+ * checks of a finished run, and how an agent runs it. Deterministic: the same recipe gives the same text.
+ */
+export function skillBody(recipe: Recipe, draft: Pick<SkillDraft, "steps">, meta: { title: string; description: string; name?: string }): string {
+ const info = new Map(draft.steps.map((s) => [s.key, s]));
+ const keys = recipe.steps.map((s) => s.key);
+ const leaves = leafKeys(recipe);
+ const stepLines = recipe.steps.map((s, i) => {
+ const d = info.get(s.key);
+ if (s.kind === "tool") return `${i + 1}. **${d?.label ?? s.tool}** — the studio tool \`${s.tool}\`, with the inputs below.`;
+ const r = s.request;
+ const waits = (Array.isArray(s.after) ? s.after : s.after ? [s.after] : []).map((a) => `step ${keys.indexOf(a) + 1}`);
+ const words = typeof r.prompt === "string" && r.prompt.trim() ? ` — “${cut(r.prompt.trim(), 280)}”` : "";
+ return `${i + 1}. **${d?.label ?? r.op ?? "Generate"}** with ${d?.modelName ?? r.modelId}${words}${waits.length ? `, from the result of ${waits.join(" and ")}` : ""}${leaves.has(s.key) && recipe.steps.length > 1 ? " (a result you keep)" : ""}.`;
+ });
+ const checkLines = Object.entries(recipe.checks ?? {}).flatMap(([k, c]) => {
+ const line = checkLine(k, draft.steps, c);
+ return line ? [line] : [];
+ });
+ const values = Object.fromEntries(recipe.params.map((p) => [p.id, `<${p.label.toLowerCase()}>`]));
+ return [
+ `# ${meta.title}`,
+ "",
+ meta.description,
+ "",
+ "## Inputs",
+ ...(recipe.params.length ? recipe.params.map(inputLine) : ["It takes no inputs: each run makes the same thing again, as a new take."]),
+ "",
+ "## Steps",
+ "Run them in this order; each one takes the result of the step it names.",
+ ...stepLines,
+ "",
+ ...(checkLines.length ? ["## When it's done", "A finished run is checked by its structure, never by its pixels:", ...checkLines, ""] : []),
+ "## Using Fuobe from an agent",
+ `In Fuobe this skill runs by itself: Skills → ${meta.name ? `/${meta.name}` : "this skill"} → Run…, priced before anything starts, with no LLM. Over Fuobe's MCP server, \`run_skill\` runs it${meta.name ? ` (\`${JSON.stringify({ name: meta.name, values })}\`)` : ""}; where that tool isn't available, the "Run it" section Fuobe adds when the skill is loaded gives the equivalent \`generate\` or studio tool call. Price it first with \`estimate_cost\` (\`estimate_job\` for a studio tool) and confirm with the user.`,
+ ].join("\n");
+}
diff --git a/src/lib/recipe.ts b/src/lib/recipe.ts
index d3fac550..a5cb4cdc 100644
--- a/src/lib/recipe.ts
+++ b/src/lib/recipe.ts
@@ -73,7 +73,7 @@ const ChainSlotSchema = z.object({
* 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;
+export const SERVER_FIELDS = ["skill", "demo", "chainFilled", "chainSkipped", "notice", "step", "batchTitle", "asked"] as const;
/** A GenerationRequest with placeholders in it: checked for its shape here, for its models and values on the server. */
const RequestSchema = z
@@ -147,6 +147,8 @@ export const RecipeSchema = z.object({
thread: z.string().max(40).optional(),
canvas: z.string().max(40).optional(),
at: z.string().regex(DAY).optional(),
+ /** Made from results the demo provider made (W2): nothing has shown it works on a real engine yet. */
+ demo: z.boolean().optional(),
})
.optional(),
});
diff --git a/src/server/chains.ts b/src/server/chains.ts
index d3a139a9..77563904 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -53,6 +53,21 @@ export function assertOneMode(steps: ModeStep[]): void {
}
}
+/**
+ * Keep the request as it was asked on the row an expansion returns first (GenerationRequest.asked): a skill made from
+ * the result (src/server/recipe-builder.ts) rebuilds that one request, not the rows it expanded into, whose number
+ * changes with the input (a film of 3 shots is 4 rows, of 5 shots 6).
+ */
+function withAsked(made: Generation[], asked: GenerationRequest): Generation[] {
+ const [first, ...rest] = made;
+ if (!first) return made;
+ const request = { ...asked };
+ for (const k of ["asked", "chainFilled", "chainSkipped", "notice"] as const) delete request[k];
+ const stored: GenerationRequest = { ...first.request, asked: request };
+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify(stored), first.id);
+ return [{ ...first, request: stored }, ...rest];
+}
+
/** Steps still waiting for their inputs (nothing spent yet) are canceled when the chain they feed can't be made. */
function cancelWaiting(ids: string[]): void {
for (const id of ids) {
@@ -185,7 +200,7 @@ export function createShotFilm(original: GenerationRequest, model: ModelDef): Ge
step: { label: `Film · ${n} shots`, index: n, of: n + 1 },
},
);
- return [film, ...clips];
+ return withAsked([film, ...clips], original);
} catch (e) {
// Don't leave shots rendering for a film that can't be made.
for (const g of clips) void cancelGeneration(g.id);
@@ -240,7 +255,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
};
made.push(createGenerations(request, { batchId })[0]);
}
- if (n === 1) return made;
+ if (n === 1) return withAsked(made, original);
const film = joinClips(
made.map((c) => c.id),
{
@@ -254,7 +269,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
step: { label: `Film · ${images.length} frames`, index: n, of: n + 1 },
},
);
- return [film, ...made];
+ return withAsked([film, ...made], original);
} catch (e) {
// Don't leave half a film rendering.
for (const g of made) void cancelGeneration(g.id);
@@ -305,7 +320,7 @@ export function createExtendChain(original: GenerationRequest, model: ModelDef):
before: [video],
step: { label: "Extended video", index: 2, of: 3 },
});
- return [film, clip, frame];
+ return withAsked([film, clip, frame], original);
} catch (e) {
for (const g of made) void cancelGeneration(g.id);
throw e;
@@ -358,7 +373,7 @@ export function createStillTo3d(original: GenerationRequest, model: ModelDef, ro
},
{ batchId, dependsOn: still.id },
)[0];
- return [built, still];
+ return withAsked([built, still], original);
} catch (e) {
void cancelGeneration(still.id);
throw e;
@@ -411,7 +426,7 @@ export function createRelitClip(
},
{ batchId, dependsOn: relit.id },
)[0];
- return [clip, relit];
+ return withAsked([clip, relit], original);
} catch (e) {
void cancelGeneration(relit.id);
throw e;
diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.ts
new file mode 100644
index 00000000..d9f6d516
--- /dev/null
+++ b/src/server/recipe-builder.ts
@@ -0,0 +1,717 @@
+import "server-only";
+import fs from "node:fs";
+import { getModel } from "@/lib/catalog";
+import { OPERATION_LABELS, type ChainSlot, type Generation, type GenerationRequest, type OutputFile } from "@/lib/catalog/types";
+import { dubLanguageFor } from "@/lib/assist-studios";
+import { isHelperFeature } from "@/lib/library";
+import { probeMedia } from "@/lib/media-probe";
+import { videoPoster } from "@/lib/output-actions";
+import { isMediaRef, leafKeys, RECIPE_LIMITS, today, type ParamType, type Recipe, type RecipeCheck, type RecipeStep } from "@/lib/recipe";
+import {
+ DEMO_NOTE,
+ isExpansionLabel,
+ notSupported,
+ paramIdFrom,
+ parseNaming,
+ skillBody,
+ slugify,
+ STEPS_REFUSAL,
+ studioOf,
+ type DraftCandidate,
+ type DraftRefusal,
+ type DraftStep,
+ type Naming,
+ type SettingId,
+ type SkillDraft,
+} from "@/lib/recipe-builder";
+import { db } from "./db";
+import { llmText, llmTextBackend, type LlmImage } from "./enhance";
+import { listElements } from "./elements";
+import { currentRequest, getGeneration, unfilledRequest } from "./generations";
+import { getSkill } from "./skills";
+import { absolutePath, readRef } from "./storage";
+
+/**
+ * Make a skill from results already made (package W2): walk the picked results back through `depends_on` to the
+ * requests that made them, and turn them into a recipe (src/lib/recipe.ts) whose every input is still Fixed, with
+ * the candidate inputs, proposed checks and a SKILL.md body. No recording, no LLM: Fuobe's records are the exact
+ * requests. An optional naming pass (nameDraft) asks Claude or Ollama for names, slots in the words and prose.
+ *
+ * What changes shape with its input is never replayed as the steps it became: a request that expanded into several
+ * rows (src/server/chains.ts) comes back as the request it was asked as (GenerationRequest.asked), a studio's work as
+ * its Assist tool when its record holds that tool's input (Translate & dub, Katana, Captions), and everything else
+ * that planned its own steps is refused with the studio's name.
+ */
+
+class Refused extends Error {}
+
+const depIds = (v: string | null | undefined): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);
+
+/** The row a generation is stored as: its dependencies and batch (the Generation object leaves `depends_on` out). */
+function rowOf(id: string): { depends_on: string | null; batch_id: string | null } | undefined {
+ return db().prepare("SELECT depends_on, batch_id FROM generations WHERE id = ?").get(id) as { depends_on: string | null; batch_id: string | null } | undefined;
+}
+
+/** Rows of a batch, as generations (the Trash included: a step of a kept result may be trashed). */
+function batchRows(batch: string | null): Generation[] {
+ if (!batch) return [];
+ const ids = (db().prepare("SELECT id FROM generations WHERE batch_id = ?").all(batch) as { id: string }[]).map((r) => r.id);
+ return ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);
+}
+
+/** Request fields a step keeps (GenerationRequestSchema's, less the server's own): everything else is dropped. */
+const KEEP: (keyof GenerationRequest)[] = ["feature", "presetId", "modelId", "op", "prompt", "negativePrompt", "inputs", "params", "presetOptions", "presetStrength", "mix", "loras", "engine", "signature"];
+
+function stepRequest(req: GenerationRequest): Record<string, unknown> {
+ const out = Object.fromEntries(KEEP.flatMap((k) => (req[k] === undefined ? [] : [[k, JSON.parse(JSON.stringify(req[k]))]]))) as Record<string, unknown> & GenerationRequest;
+ // A draft render's handle belongs to that run (its finalize), not to a new one.
+ if (out.params?.draftId) {
+ const params = { ...out.params };
+ delete params.draftId;
+ out.params = params;
+ }
+ if (out.inputs && !Object.keys(out.inputs).length) delete out.inputs;
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// The graph behind the picks
+
+interface Node {
+ key: string;
+ /** The result the step stands for (its thumbnail, its checks). */
+ gen: Generation;
+ /** Every row the step covers (an expansion's rows, a face mosaic's picture). */
+ rows: string[];
+ step: RecipeStep;
+ label: string;
+ modelName: string;
+ notes: string[];
+ /** A tool step: its studio, the record it was rebuilt from, and where its media inputs are. */
+ tool?: { studio: string; record: string; inputs: { path: (string | number)[]; type: ParamType; label: string }[]; texts: { path: (string | number)[]; label: string }[] };
+}
+
+/** The single image a step without `chain` takes from each earlier step (createGenerations' slotsFor). */
+const chainOf = (req: GenerationRequest, n: number): ChainSlot[] => Array.from({ length: n }, (_, i) => req.chain?.[i] ?? { slot: "images" as const, position: req.chainFrom ?? "last" });
+
+const opLabel = (op: string | undefined) => (op ? (OPERATION_LABELS[op as keyof typeof OPERATION_LABELS] ?? op) : "Generate");
+
+class Walk {
+ nodes = new Map<string, Node>();
+ /** Generation id → the node that covers it. */
+ covered = new Map<string, Node>();
+ keys = new Set<string>();
+ notes: string[] = [];
+
+ key(base: string): string {
+ const clean = base.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32) || "step";
+ let k = /^[a-z0-9]/.test(clean) ? clean : `s${clean}`;
+ for (let i = 2; this.keys.has(k); i++) k = `${clean}-${i}`;
+ this.keys.add(k);
+ return k;
+ }
+
+ /** A model that moved (REPLACED_BY): said on its step and once on the review screen. */
+ moved(note: string | undefined): string[] {
+ if (!note) return [];
+ if (!this.notes.includes(note)) this.notes.push(note);
+ return [note];
+ }
+
+ /** The node for a generation: built once, its dependencies first. Throws Refused with the reason. */
+ visit(g: Generation, path: Set<string> = new Set()): Node {
+ const known = this.covered.get(g.id);
+ if (known) return known;
+ if (path.has(g.id)) throw new Refused("Its steps wait for each other in a loop");
+ path.add(g.id);
+ const req = g.request;
+ const helper = isHelperFeature(g.feature);
+ const studio = studioOf(g.feature);
+ // 1. A studio that plans its own steps from its input (Cinema, Storyboard, Genjutsu…): never replayed step by step.
+ if (studio && !helper) throw new Refused(notSupported(studio.name));
+ // 2. A request that expanded into several rows: the request as asked, its rows covered. A row of an expansion other
+ // than the one it returned first (a film's shot, a text-to-3D's still) stands for the same request.
+ if (req.asked) return this.fromAsked(g);
+ const row = rowOf(g.id);
+ const batch = row?.batch_id ? batchRows(row.batch_id) : [];
+ const head = batch.find((b) => b.request.asked && b.id !== g.id);
+ if (head) return this.fromAsked(head);
+ // 3. Made in steps before the request as asked was kept (a heuristic on the labels the expansions gave their rows).
+ if (!req.skill && batch.length > 1 && isExpansionLabel(req.step?.label)) throw new Refused(STEPS_REFUSAL);
+ // 4. Work whose shape follows its input: a storyboard frame, a frame-by-frame step, a helper of a studio.
+ if (req.frame) throw new Refused(notSupported(studio?.name ?? "Storyboard"));
+ if (req.chain?.some((c) => c.index !== undefined)) throw new Refused(`Made frame by frame${studio ? ` in ${studio.name}` : ""}: making a skill from it isn't supported yet`);
+ if (helper) throw new Refused(notSupported(studio?.name ?? "another studio"));
+ // 5. A plain request: its dependencies first.
+ const deps = depIds(row?.depends_on).map((id) => getGeneration(id, { includeDeleted: true }));
+ // Fuobe Soul's PixeletedFace look: the picture and its face mosaic are one request (createMosaicRun).
+ const picture = deps.length === 1 && deps[0]?.request.postMade ? deps[0] : null;
+ if (picture) return this.plain(g, picture, path);
+ return this.plain(g, null, path, deps);
+ }
+
+ /** One step from the request a run of rows was asked as. */
+ fromAsked(head: Generation): Node {
+ const moved = currentRequest(head.request.asked!);
+ const rows = [head.id, ...this.batchAncestors(head)];
+ const node = this.add(head, rows, { request: moved.request }, this.moved(moved.note));
+ node.notes.push(`Rebuilt as the one request it was asked as (it ran as ${rows.length} steps)`);
+ return node;
+ }
+
+ /** Rows of an expansion behind its head: its ancestors in its own batch (an expansion's batch is its own). */
+ batchAncestors(head: Generation): string[] {
+ const batch = rowOf(head.id)?.batch_id;
+ const out: string[] = [];
+ const todo = depIds(rowOf(head.id)?.depends_on);
+ while (todo.length) {
+ const id = todo.pop()!;
+ const r = rowOf(id);
+ if (!r || r.batch_id !== batch || out.includes(id)) continue;
+ out.push(id);
+ todo.push(...depIds(r.depends_on));
+ }
+ return out;
+ }
+
+ plain(g: Generation, picture: Generation | null, path: Set<string>, given?: (Generation | null)[]): Node {
+ const source = picture ?? g;
+ const deps = given ?? depIds(rowOf(source.id)?.depends_on).map((id) => getGeneration(id, { includeDeleted: true }));
+ const moved = currentRequest(source.request);
+ const notes = this.moved(moved.note);
+ const rows = picture ? [g.id, picture.id] : [g.id];
+ if (picture) {
+ const req = { ...moved.request };
+ delete req.postMade;
+ moved.request = req;
+ }
+ if (!deps.length) return this.add(g, rows, { request: moved.request }, notes);
+ if (deps.some((d) => !d)) {
+ // A step it waited for is gone: what it gave this one stays as a fixed input.
+ notes.push("A step before it is gone, so what it gave this step is used as it is");
+ const filled = { ...moved.request };
+ delete filled.chain;
+ delete filled.chainFrom;
+ return this.add(g, rows, { request: filled }, notes);
+ }
+ const before = deps.map((d) => this.visit(d!, new Set(path)));
+ const chain = chainOf(moved.request, deps.length);
+ const request = unfilledRequest(moved.request, deps.length);
+ return this.add(g, rows, { request, after: before.map((n) => n.key), chain }, notes);
+ }
+
+ add(gen: Generation, rows: string[], s: { request: GenerationRequest; after?: string[]; chain?: ChainSlot[] }, notes: string[]): Node {
+ const req = s.request;
+ const m = getModel(req.modelId);
+ const label = opLabel(req.op ?? gen.op);
+ const step: RecipeStep = {
+ key: this.key(req.op ?? gen.op ?? "step"),
+ kind: "generate",
+ label,
+ ...(s.after?.length && { after: s.after.length === 1 ? s.after[0] : s.after }),
+ ...(s.after?.length && s.chain && { chain: s.chain }),
+ request: stepRequest(req) as never,
+ };
+ const node: Node = { key: step.key, gen, rows, step, label, modelName: m?.name ?? gen.modelName ?? req.modelId, notes };
+ this.nodes.set(node.key, node);
+ for (const id of rows) this.covered.set(id, node);
+ return node;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Studio work rebuilt as its Assist tool's call
+
+/** A studio record that names a generation (the instr lookup assetRefSql uses), as its id and data. */
+function recordNaming(table: "dub_sessions" | "katana_jobs", id: string): { id: string; data: Record<string, unknown> } | null {
+ try {
+ const r = db().prepare(`SELECT id, data_json FROM ${table} WHERE instr(data_json, ?) > 0 ORDER BY updated_at DESC LIMIT 1`).get(JSON.stringify(id)) as { id: string; data_json: string } | undefined;
+ return r ? { id: r.id, data: JSON.parse(r.data_json) as Record<string, unknown> } : null;
+ } catch {
+ return null;
+ }
+}
+
+const langName = (code: unknown) => (typeof code === "string" && code && code !== "auto" ? (dubLanguageFor(code)?.name ?? code) : undefined);
+
+interface Lifted {
+ tool: string;
+ studio: string;
+ record: string;
+ input: Record<string, unknown>;
+ inputs: { path: (string | number)[]; type: ParamType; label: string }[];
+ texts: { path: (string | number)[]; label: string }[];
+}
+
+/** A studio's result as one call of its Assist tool, when the studio's record holds that tool's input. */
+function liftStudio(g: Generation, tool: string, studio: string): Lifted | null {
+ if (tool === "dub_video") {
+ const rec = recordNaming("dub_sessions", g.id);
+ if (!rec) return null;
+ const d = rec.data as { video?: string; source?: string; targets?: string[]; mode?: string; model?: string; voices?: Record<string, { lipsync?: boolean }[]> };
+ if (!d.video || !d.targets?.length) return null;
+ const runs = Object.values(d.voices ?? {}).flat();
+ const lipsync = d.mode === "oneshot" ? d.model !== "elevenlabs-dubbing" : (runs.at(-1)?.lipsync ?? true);
+ const input = {
+ video: d.video,
+ languages: d.targets.map((c) => langName(c) ?? c),
+ ...(langName(d.source) && { source_language: langName(d.source) }),
+ lipsync,
+ review: d.mode !== "oneshot",
+ };
+ return { tool, studio, record: `dub:${rec.id}`, input, inputs: [{ path: ["video"], type: "video", label: "Video to dub" }], texts: [] };
+ }
+ if (tool === "katana") {
+ const rec = recordNaming("katana_jobs", g.id);
+ if (!rec) return null;
+ const j = rec.data as { reference?: string; photos?: string[]; instructions?: string; motionModel?: string; keepAudio?: boolean; segments?: { start: number; end: number }[] };
+ if (!j.reference || !j.photos?.length) return null;
+ const seg = j.segments && j.segments.length > 1 ? Math.round((j.segments[0].end - j.segments[0].start) * 10) / 10 : undefined;
+ const input = {
+ reference: j.reference,
+ photos: j.photos,
+ ...(j.instructions?.trim() && { instructions: j.instructions }),
+ ...(seg && { segment_seconds: seg }),
+ ...(j.motionModel && { motion_model: j.motionModel }),
+ keep_audio: j.keepAudio !== false,
+ };
+ return {
+ tool,
+ studio,
+ record: `katana:${rec.id}`,
+ input,
+ inputs: [{ path: ["reference"], type: "video", label: "Reference edit" }, ...j.photos.map((_, i) => ({ path: ["photos", i], type: "image" as const, label: j.photos!.length > 1 ? `Subject photo ${i + 1}` : "Subject photo" }))],
+ texts: j.instructions?.trim() ? [{ path: ["instructions"], label: "What to keep in mind" }] : [],
+ };
+ }
+ if (tool === "add_captions") {
+ // The Captions editor keeps no session: its captioned video's own request holds the input.
+ const burn = g.op === "captions" ? g : batchRows(rowOf(g.id)?.batch_id ?? null).find((b) => b.op === "captions" && b.feature === g.feature);
+ const video = burn?.request.inputs?.video;
+ if (!burn || !video) return null;
+ const p = burn.request.params ?? {};
+ const input = { video, ...(langName(p.sourceLanguage) && { spoken_language: langName(p.sourceLanguage) }), ...(p.targetLanguage && { translate_to: langName(p.targetLanguage) ?? p.targetLanguage }) };
+ return { tool, studio, record: `captions:${burn.id}`, input, inputs: [{ path: ["video"], type: "video", label: "Video to caption" }], texts: [] };
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Candidates
+
+const MEDIA_SLOTS: { key: keyof NonNullable<GenerationRequest["inputs"]>; type: "image" | "video" | "audio"; label: (op?: string) => string }[] = [
+ { key: "images", type: "image", label: (op) => (op === "i2v" || op === "flf2v" ? "Start frame" : "Image") },
+ { key: "endImage", type: "image", label: () => "End frame" },
+ { key: "video", type: "video", label: () => "Video" },
+ { key: "videos", type: "video", label: () => "Clip" },
+ { key: "audio", type: "audio", label: () => "Audio" },
+ { key: "audio2", type: "audio", label: () => "Background audio" },
+ { key: "voiceAudio", type: "audio", label: () => "Voice sample" },
+ { key: "voiceAudio2", type: "audio", label: () => "Second voice sample" },
+ { key: "audios", type: "audio", label: () => "Reference audio" },
+];
+
+const SETTING_LABELS: Record<SettingId, string> = { numOutputs: "Takes", aspectRatio: "Shape", duration: "Length (seconds)", resolution: "Quality" };
+
+function candidates(walk: Walk, leaves: Set<string>): DraftCandidate[] {
+ const out: DraftCandidate[] = [];
+ const taken = new Set<string>();
+ const labelsUsed = new Map<string, number>();
+ const uniqueLabel = (label: string) => {
+ const n = (labelsUsed.get(label) ?? 0) + 1;
+ labelsUsed.set(label, n);
+ return n === 1 ? label : `${label} ${n}`;
+ };
+ const add = (c: Omit<DraftCandidate, "id"> & { id?: string }) => {
+ const id = paramIdFrom(c.id ?? c.label, taken);
+ taken.add(id);
+ out.push({ ...c, id } as DraftCandidate);
+ };
+ const nodes = [...walk.nodes.values()];
+ // Files: uploads, Library picks and earlier results that aren't a step here. The same file in several steps is one input.
+ const media = new Map<string, DraftCandidate & { id?: string }>();
+ for (const n of nodes) {
+ if (n.tool) {
+ for (const i of n.tool.inputs) {
+ const v = getAtPath((n.step as Extract<RecipeStep, { kind: "tool" }>).input, i.path);
+ if (typeof v !== "string" || !isMediaRef(v)) continue;
+ const hit = media.get(v);
+ if (hit) hit.at.push({ step: n.key, path: i.path });
+ else media.set(v, { id: "", label: i.label, type: i.type, kind: "media", example: v, at: [{ step: n.key, path: i.path }] });
+ }
+ continue;
+ }
+ const r = (n.step as Extract<RecipeStep, { kind: "generate" }>).request;
+ const inputs = (r.inputs ?? {}) as Record<string, unknown>;
+ for (const slot of MEDIA_SLOTS) {
+ const v = inputs[slot.key];
+ const list = Array.isArray(v) ? v.map((x, i) => [x, ["inputs", slot.key, i]] as const) : v === undefined ? [] : [[v, ["inputs", slot.key]] as const];
+ for (const [value, path] of list) {
+ if (typeof value !== "string" || !isMediaRef(value)) continue;
+ const hit = media.get(value);
+ if (hit) hit.at.push({ step: n.key, path: [...path] });
+ else media.set(value, { id: "", label: slot.label(r.op), type: slot.type, kind: "media", example: value, at: [{ step: n.key, path: [...path] }] });
+ }
+ }
+ }
+ for (const c of media.values()) add({ ...c, id: undefined, label: uniqueLabel(c.label) });
+ // Elements: @handles of saved elements named in the words.
+ const elements = listElements();
+ const named = new Map<string, DraftCandidate>();
+ for (const n of nodes) {
+ if (n.tool) continue;
+ const words = (n.step as Extract<RecipeStep, { kind: "generate" }>).request.prompt;
+ if (typeof words !== "string") continue;
+ for (const m of words.matchAll(/@([\p{L}\p{N}_-]{1,40})/gu)) {
+ const el = elements.find((e) => e.handle.toLowerCase() === m[1].toLowerCase());
+ if (!el) continue;
+ const handle = `@${m[1]}`;
+ const hit = named.get(handle);
+ if (hit) {
+ if (!hit.at.some((a) => a.step === n.key)) hit.at.push({ step: n.key, path: ["prompt"] });
+ } else named.set(handle, { id: "", label: el.name.slice(0, 60), type: "element", kind: "element", example: handle, at: [{ step: n.key, path: ["prompt"] }] });
+ }
+ }
+ for (const c of named.values()) add({ ...c, id: c.label });
+ // Words: each step's prompt as a whole (a slot inside it is chosen on the review screen).
+ const several = nodes.length > 1;
+ for (const n of nodes) {
+ if (n.tool) {
+ for (const t of n.tool.texts) {
+ const v = getAtPath((n.step as Extract<RecipeStep, { kind: "tool" }>).input, t.path);
+ if (typeof v === "string" && v.trim()) add({ label: t.label, type: "text", kind: "text", example: v, at: [{ step: n.key, path: t.path }], max: RECIPE_LIMITS.text, ...(v.length > RECIPE_LIMITS.text && { locked: `Too long to change in a form (over ${RECIPE_LIMITS.text} characters)` }) });
+ }
+ continue;
+ }
+ const words = (n.step as Extract<RecipeStep, { kind: "generate" }>).request.prompt;
+ if (typeof words !== "string" || !words.trim()) continue;
+ add({
+ id: several ? `prompt_${n.key}` : "prompt",
+ label: several ? `Words for “${n.label}”` : "Prompt",
+ type: "text",
+ kind: "text",
+ example: words,
+ at: [{ step: n.key, path: ["prompt"] }],
+ max: RECIPE_LIMITS.text,
+ ...(words.length > RECIPE_LIMITS.text && { locked: `Too long to change in a form (over ${RECIPE_LIMITS.text} characters)` }),
+ });
+ }
+ // Settings: the count of a result you keep, its shape, length and quality (optional, the original as the default).
+ const settings = new Map<string, DraftCandidate>();
+ for (const n of nodes) {
+ if (n.tool) continue;
+ const r = (n.step as Extract<RecipeStep, { kind: "generate" }>).request;
+ const m = getModel(r.modelId);
+ const p = (r.params ?? {}) as Record<string, unknown>;
+ const o = m?.options;
+ const found: { id: SettingId; value: string | number; extra: Partial<DraftCandidate> }[] = [];
+ if (leaves.has(n.key) && n.gen.kind !== "text") {
+ const max = Math.min(8, o?.maxOutputs ?? 4);
+ if (max > 1) found.push({ id: "numOutputs", value: typeof p.numOutputs === "number" ? p.numOutputs : 1, extra: { type: "number", min: 1, max, step: 1 } });
+ }
+ if (typeof p.aspectRatio === "string" && o?.aspectRatios && o.aspectRatios.length > 1 && o.aspectRatios.includes(p.aspectRatio)) found.push({ id: "aspectRatio", value: p.aspectRatio, extra: { type: "choice", options: o.aspectRatios.slice(0, RECIPE_LIMITS.options) } });
+ if (typeof p.duration === "number" && o?.durations && o.durations.length > 1) found.push({ id: "duration", value: p.duration, extra: { type: "number", min: Math.min(...o.durations), max: Math.max(...o.durations), step: 1 } });
+ if (typeof p.resolution === "string" && o?.resolutions && o.resolutions.length > 1 && o.resolutions.includes(p.resolution)) found.push({ id: "resolution", value: p.resolution, extra: { type: "choice", options: o.resolutions.slice(0, RECIPE_LIMITS.options) } });
+ for (const f of found) {
+ const k = `${f.id}:${f.value}`;
+ const hit = settings.get(k);
+ if (hit) {
+ hit.at.push({ step: n.key, path: ["params", f.id] });
+ // Choices every step's model takes.
+ if (hit.options && f.extra.options) hit.options = hit.options.filter((x) => f.extra.options!.includes(x));
+ continue;
+ }
+ settings.set(k, { id: "", label: SETTING_LABELS[f.id], kind: "setting", setting: f.id, optional: true, example: f.value, at: [{ step: n.key, path: ["params", f.id] }], type: "number", ...f.extra });
+ }
+ }
+ for (const c of settings.values()) {
+ if (c.type === "choice" && (c.options?.length ?? 0) < 2) continue;
+ add({ ...c, id: c.setting === "numOutputs" ? "takes" : c.setting === "aspectRatio" ? "shape" : c.setting === "duration" ? "seconds" : "quality", label: uniqueLabel(c.label) });
+ }
+ return out;
+}
+
+function getAtPath(obj: unknown, path: (string | number)[]): unknown {
+ let cur = obj;
+ for (const k of path) {
+ if (!cur || typeof cur !== "object") return undefined;
+ cur = (cur as Record<string | number, unknown>)[k];
+ }
+ return cur;
+}
+
+// ---------------------------------------------------------------------------
+// Checks from the results
+
+const RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "4:5", "5:4", "21:9", "9:21"];
+const ratioOf = (a: string) => {
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(a);
+ return m ? Number(m[1]) / Number(m[2]) : NaN;
+};
+
+/** The shape of a width and height as "16:9" (the one asked for when it matches), within 2%. */
+function aspectOf(w: number, h: number, asked?: unknown): string | undefined {
+ const r = w / h;
+ const fits = (a: string) => Math.abs(r - ratioOf(a)) / ratioOf(a) <= 0.02;
+ if (typeof asked === "string" && Number.isFinite(ratioOf(asked)) && fits(asked)) return asked;
+ return RATIOS.find(fits);
+}
+
+/** A stored file's header facts (duration, sound), read from disk; null for anything else. */
+function probeStored(url: string): ReturnType<typeof probeMedia> {
+ if (!url.startsWith("/api/files/")) return null;
+ try {
+ const abs = absolutePath(decodeURIComponent(url.slice("/api/files/".length).split("?")[0]));
+ const st = fs.statSync(abs);
+ // A header is near the start (or the end for some MP4s); a very large file is skipped rather than read whole.
+ if (st.size > 256 * 1024 * 1024) return null;
+ return probeMedia(new Uint8Array(fs.readFileSync(abs)));
+ } catch {
+ return null;
+ }
+}
+
+/** What a finished run of a step should look like, from the result it was made from (kind, count, shape, length, sound). */
+function proposeCheck(n: Node): RecipeCheck {
+ const g = n.gen;
+ const main = g.outputs.filter((o) => o.kind === g.kind);
+ const check: RecipeCheck = { kind: g.kind as RecipeCheck["kind"] };
+ if (main.length) check.count = main.length;
+ const asked = (n.step.kind === "generate" ? (n.step.request.params as Record<string, unknown> | undefined)?.aspectRatio : undefined) ?? undefined;
+ // The demo provider's stand-ins say nothing about a real result's shape or length: only what was asked.
+ if (g.provider === "mock") {
+ if (typeof asked === "string" && Number.isFinite(ratioOf(asked)) && (g.kind === "image" || g.kind === "video")) check.aspect = asked;
+ return check;
+ }
+ const first = main[0] as OutputFile | undefined;
+ if (!first) return check;
+ const info = g.kind === "video" || g.kind === "audio" ? probeStored(first.url) : null;
+ const w = first.width ?? info?.width;
+ const h = first.height ?? info?.height;
+ if ((g.kind === "image" || g.kind === "video") && w && h) {
+ const a = aspectOf(w, h, asked);
+ if (a) check.aspect = a;
+ }
+ if (info?.duration && info.duration > 0) check.seconds = Math.round(info.duration * 10) / 10;
+ if (info && g.kind === "video") check.sound = info.hasAudio;
+ return check;
+}
+
+// ---------------------------------------------------------------------------
+// The draft
+
+const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
+const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
+/** A short title from the result: its batch's name, else the first words of its prompt, else what it is. */
+function titleFor(g: Generation, label: string): string {
+ const named = g.request.batchTitle?.trim() || g.request.title?.trim();
+ if (named) return cut(named, 60);
+ const words = (g.request.prompt ?? "").replace(/@\S+/g, "").replace(/\s+/g, " ").trim();
+ if (words) return cut(capital(words.split(" ").slice(0, 6).join(" ").replace(/[,.;:]+$/, "")), 60);
+ return `${label} skill`;
+}
+
+/** A free skill name like the title: "lamp-turntable", "lamp-turntable-2"… */
+function freeName(title: string): string {
+ const base = slugify(title).slice(0, 56).replace(/-+$/, "") || "my-skill";
+ let name = base;
+ for (let i = 2; getSkill(name) || ["upload", "new", "draft"].includes(name); i++) name = `${base}-${i}`;
+ return name;
+}
+
+const dayOf = (ts: number) => new Date(ts).toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
+
+export interface DraftResult {
+ draft: SkillDraft | null;
+ refusals: DraftRefusal[];
+}
+
+/**
+ * The draft of a skill from picked results (Library ids): walk `depends_on` back from each to its roots (the picks are
+ * the leaves; unrelated picks become parallel steps), rebuild each generation as a generate step (its request as it
+ * runs now, chain-filled inputs taken out, server fields dropped), or a studio's result as its tool step, and propose
+ * the inputs that could vary (all Fixed) and the checks. A pick that can't be used is a refusal with the reason.
+ */
+export function draftFromGenerations(ids: string[]): DraftResult {
+ const refusals: DraftRefusal[] = [];
+ const walk = new Walk();
+ const tools: { node: Node; pick: Generation }[] = [];
+ const generated: Generation[] = [];
+ const unique = [...new Set(ids)].slice(0, 200);
+ for (const id of unique) {
+ const g = getGeneration(id);
+ const title = g ? cut(g.request.title || g.request.prompt || g.modelName || opLabel(g.op), 80) : id;
+ if (!g) {
+ refusals.push({ id, title, reason: "It's gone (deleted, or in the Trash)" });
+ continue;
+ }
+ if (g.status !== "succeeded") {
+ refusals.push({ id, title, reason: g.status === "failed" || g.status === "canceled" ? "It didn't finish, so there's nothing to repeat" : "It's still running: make the skill once it's done" });
+ continue;
+ }
+ if (g.feature === "upload") {
+ refusals.push({ id, title, reason: "It's an upload: pick a result made from it" });
+ continue;
+ }
+ const studio = studioOf(g.feature);
+ if (studio?.tool && !g.request.frame) {
+ const lifted = liftStudio(g, studio.tool, studio.name);
+ if (!lifted) {
+ refusals.push({ id, title, reason: notSupported(studio.name) });
+ continue;
+ }
+ if (tools.some((t) => t.node.tool?.record === lifted.record)) continue;
+ const key = walk.key(lifted.tool.replace(/_/g, "-"));
+ const node: Node = {
+ key,
+ gen: g,
+ rows: [g.id],
+ step: { key, kind: "tool", label: lifted.studio, tool: lifted.tool, input: lifted.input },
+ label: lifted.studio,
+ modelName: lifted.studio,
+ notes: [`Runs ${lifted.studio} again with the same settings`],
+ tool: { studio: lifted.studio, record: lifted.record, inputs: lifted.inputs, texts: lifted.texts },
+ };
+ tools.push({ node, pick: g });
+ continue;
+ }
+ // A plain result: its graph, all or nothing (a refused step refuses the result that needs it).
+ const before = new Map(walk.nodes);
+ const covered = new Map(walk.covered);
+ const keys = new Set(walk.keys);
+ const notes = [...walk.notes];
+ try {
+ walk.visit(g);
+ generated.push(g);
+ } catch (e) {
+ walk.nodes = before;
+ walk.covered = covered;
+ walk.keys = keys;
+ walk.notes = notes;
+ if (!(e instanceof Refused)) throw e;
+ refusals.push({ id, title, reason: e.message });
+ }
+ }
+ // Version 1 runs a graph of generate steps or one studio tool, not both (a tool feeding later steps is W7).
+ if (tools.length && (walk.nodes.size || tools.length > 1)) {
+ const keep = walk.nodes.size ? [] : tools.slice(0, 1);
+ for (const t of tools.filter((x) => !keep.includes(x))) {
+ refusals.push({ id: t.pick.id, title: cut(t.pick.request.title || t.pick.request.prompt || t.node.label, 80), reason: walk.nodes.size ? "A studio step can't be in a skill with other steps yet: make a skill from it on its own" : "One studio step per skill for now: make a skill from each" });
+ }
+ tools.splice(0, tools.length, ...keep);
+ }
+ if (tools.length) walk.nodes.set(tools[0].node.key, tools[0].node);
+ const nodes = [...walk.nodes.values()];
+ if (!nodes.length) return { draft: null, refusals };
+ if (nodes.length > RECIPE_LIMITS.steps) return { draft: null, refusals: [...refusals, { id: ids[0], title: "These results", reason: `They take ${nodes.length} steps; a skill has at most ${RECIPE_LIMITS.steps}` }] };
+
+ // Steps in an order where every step comes after the ones it waits for (the walk added dependencies first).
+ const steps = nodes.map((n) => n.step);
+ const recipe: Recipe = { fuobeRecipe: 1, params: [], steps };
+ const leaves = leafKeys(recipe);
+ const checks: Record<string, RecipeCheck> = {};
+ for (const n of nodes) if (leaves.has(n.key) && n.step.kind === "generate") checks[n.key] = proposeCheck(n);
+ if (Object.keys(checks).length) recipe.checks = checks;
+ const all = nodes.flatMap((n) => n.rows.map((id) => getGeneration(id, { includeDeleted: true }))).filter((g): g is Generation => !!g);
+ const demo = all.length > 0 && all.every((g) => g.provider === "mock");
+ recipe.source = { from: "library", generations: unique.filter((id) => !refusals.some((r) => r.id === id)), at: today(), ...(demo && { demo: true }) };
+
+ const labelOf = new Map(nodes.map((n) => [n.key, n.label]));
+ const draftSteps: DraftStep[] = nodes.map((n) => {
+ const after = n.step.kind === "generate" ? (Array.isArray(n.step.after) ? n.step.after : n.step.after ? [n.step.after] : []) : [];
+ const o = n.gen.outputs.find((x) => x.kind === n.gen.kind) ?? n.gen.outputs[0];
+ return {
+ key: n.key,
+ kind: n.step.kind,
+ label: n.label,
+ modelName: n.modelName,
+ ...(n.gen.engine && { engine: n.gen.engine }),
+ generation: n.gen.id,
+ ...(o && { thumb: { url: o.url, kind: o.kind, ...(videoPoster(n.gen, o) && { poster: videoPoster(n.gen, o) }) } }),
+ waits: after.map((a) => labelOf.get(a) ?? a),
+ leaf: leaves.has(n.key),
+ notes: n.notes,
+ };
+ });
+ const lead = nodes.find((n) => leaves.has(n.key)) ?? nodes[0];
+ const title = titleFor(lead.gen, lead.label);
+ const flow = nodes.map((n) => n.label).join(" → ");
+ const models = [...new Set(nodes.map((n) => n.modelName))];
+ const kinds = [...new Set(nodes.filter((n) => leaves.has(n.key)).map((n) => n.gen.kind))];
+ const description = cut(`${nodes.length === 1 ? flow : `${nodes.length} steps: ${flow}`}, with ${models.join(", ")}. Made from results in the Library and run again with new inputs.`, 1000);
+ const whenToUse = cut(`When you want another ${kinds.join(" and ")} made the way “${title}” was (${dayOf(lead.gen.createdAt)}), with new inputs.`, 1000);
+ const draft: SkillDraft = {
+ recipe,
+ steps: draftSteps,
+ candidates: candidates(walk, leaves),
+ name: freeName(title),
+ title,
+ description,
+ whenToUse,
+ demo,
+ notes: [...(demo ? [DEMO_NOTE] : []), ...walk.notes],
+ llm: llmTextBackend(),
+ };
+ return { draft, refusals };
+}
+
+/** The deterministic SKILL.md body of a draft as it stands (every input Fixed). */
+export const draftBody = (draft: SkillDraft) => skillBody(draft.recipe, draft, { title: draft.title, description: draft.description, name: draft.name });
+
+// ---------------------------------------------------------------------------
+// The optional naming pass
+
+/**
+ * Adapted from Work2Skill's skill-creator policy (AgenticSkillInduction/skills/skill-creator/SKILL.md, MIT licence,
+ * © the Work2Skill authors): separate the procedure from the trace, generalise without losing what relates values,
+ * keep only completion checks that can be observed, never invent one.
+ */
+const NAMING_SYSTEM = `You turn a record of media generation steps that a person liked into a reusable skill for Fuobe, an AI image, video and audio studio. You only name things and suggest what could change; Fuobe runs the steps itself.
+Rules:
+- Separate the procedure from the trace: the models, settings, step order, the prompt's craft words (light, lens, style, camera) are the procedure; the subject, product names, people and places are the trace and may become inputs.
+- Generalise a value only when the next run would really change it, and never lose counts, order, relationships between steps or selection rules. If the same words appear in several prompts, they are one input.
+- Suggest a slot only for words that appear verbatim in a step's prompt. Prefer few inputs: a skill with fewer inputs is easier to run.
+- Keep observable completion checks only (what kind of result, how many, its shape, length, sound). Never invent a success condition the record doesn't show.
+- Prefer Fuobe's own tools in the body (run_skill, generate, the studio tools) over describing other software.
+Answer with one JSON object and nothing else:
+{"name": "kebab-case-name", "title": "Short Title", "description": "One sentence on what it makes and from what.", "when_to_use": "When to pick it.", "inputs": [{"candidate": "<candidate id>", "id": "snake_case_id", "label": "Form label"}], "slots": [{"step": "<step key>", "text": "exact words from that step's prompt", "id": "snake_case_id", "label": "Form label"}], "body": "A SKILL.md body in Markdown: a # title, what it makes, ## Inputs, ## Steps, ## Using Fuobe from an agent."}`;
+
+/** Up to 4 stills of the results a skill keeps (pictures, a clip's poster frame), as an LLM that sees reads them. */
+async function leafStills(draft: SkillDraft): Promise<LlmImage[]> {
+ const out: LlmImage[] = [];
+ for (const s of draft.steps.filter((x) => x.leaf)) {
+ if (out.length >= 4) break;
+ const url = s.thumb?.kind === "image" ? s.thumb.url : s.thumb?.poster;
+ if (!url?.startsWith("/api/files/")) continue;
+ try {
+ const f = await readRef(url);
+ if (/^image\/(jpeg|png|gif|webp)$/.test(f.contentType)) out.push({ data: f.data, contentType: f.contentType });
+ } catch {
+ // A file that is gone: the words alone.
+ }
+ }
+ return out;
+}
+
+/**
+ * The optional naming pass: Claude or Ollama (whichever this install allows; none, no pass) names the inputs, suggests
+ * slots in the prompts, a title, a description, when to use it and a SKILL.md body. Malformed output is ignored (null).
+ */
+export async function nameDraft(draft: SkillDraft): Promise<Naming | null> {
+ if (!llmTextBackend()) return null;
+ const record = {
+ steps: draft.recipe.steps.map((s) => {
+ const d = draft.steps.find((x) => x.key === s.key);
+ return s.kind === "tool"
+ ? { key: s.key, studio_tool: s.tool, input: s.input }
+ : { key: s.key, does: d?.label, model: d?.modelName, prompt: s.request.prompt, waits_for: d?.waits, keeps_result: d?.leaf };
+ }),
+ candidates: draft.candidates.filter((c) => !c.locked).map((c) => ({ candidate: c.id, kind: c.kind, type: c.type, label: c.label, example: typeof c.example === "string" && c.kind === "media" ? `(a ${c.type} file)` : c.example })),
+ checks: draft.recipe.checks ?? {},
+ current: { name: draft.name, title: draft.title, description: draft.description },
+ };
+ const images = await leafStills(draft);
+ const text = await llmText(NAMING_SYSTEM, `${images.length ? "The pictures are the results the person kept.\n" : ""}The record:\n${JSON.stringify(record, null, 2)}`, images);
+ return parseNaming(text, draft);
+}
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
index 5f7584ac..510c769c 100644
--- a/src/server/recipes.ts
+++ b/src/server/recipes.ts
@@ -47,7 +47,7 @@ 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 { createSkill, deleteSkill, getSkill, setSkillFile, skillFile, SkillError } from "./skills";
import { absolutePath, readRef, saveFile } from "./storage";
/**
@@ -589,7 +589,7 @@ 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"]>> {
+async function dryRun(skill: { name: string; title: string }, 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` };
@@ -660,7 +660,7 @@ async function frameOf(video: string, engine: Engine): Promise<{ url?: string; i
}
/** 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"]>> {
+async function realRun(skill: { name: string; title: string }, 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) });
@@ -709,34 +709,16 @@ async function realRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<No
}
/**
- * 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.
+ * Check a recipe on each engine given, whether or not it is saved yet (a draft from the Library, W2): the plan, then at
+ * `demo` the free dry run, at `real` the real test. Returns what each check found and the `verified` it earns, built on
+ * `prev` (checks made against the same plan hash are kept). Writes nothing.
*/
-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 };
+async function checkEngines(skill: { name: string; title: string }, recipe: Recipe, level: VerifyLevel, engines: Engine[], prev: Recipe["verified"] = {}): Promise<{ checks: EngineCheck[]; verified: NonNullable<Recipe["verified"]> }> {
+ const verified: NonNullable<Recipe["verified"]> = { ...prev };
const day = today();
const checks: EngineCheck[] = [];
for (const e of engines) {
- const prev = recipe.verified?.[e] ?? null;
+ const before = prev?.[e] ?? null;
let check: EngineCheck;
let hash: string | undefined;
try {
@@ -753,8 +735,8 @@ export async function verifyRecipe(name: string, level: VerifyLevel, asked?: Eng
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 }) };
+ const same = before?.catalog === hash;
+ const next: VerifiedEngine = { plan: day, dryRun: same ? (before?.dryRun ?? null) : null, real: same ? (before?.real ?? null) : null, catalog: hash, ...(same && before?.notes && { notes: before.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] }));
@@ -769,12 +751,172 @@ export async function verifyRecipe(name: string, level: VerifyLevel, asked?: Eng
verified[e] = next;
checks.push(check);
}
+ return { checks, verified };
+}
+
+/** A recipe as every run reads it: a step naming a model Fuobe retired runs on what replaced it. */
+const asRunsNow = (recipe: Recipe): Recipe => ({
+ ...recipe,
+ steps: recipe.steps.map((s) => (s.kind === "generate" ? { ...s, request: currentRequest(s.request).request as typeof s.request } : s)),
+});
+
+/** Whether checks passed: every plan, and every dry run and real test that ran. */
+const allPassed = (checks: EngineCheck[]) => checks.every((c) => c.plan.ok && (c.dryRun?.ok ?? true) && (c.real?.ok ?? true));
+
+/**
+ * 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 = asRunsNow(found.recipe);
+ 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 { checks, verified } = await checkEngines(skill, recipe, level, engines, recipe.verified);
// A check takes a while (a dry run, a real test): a recipe saved or uploaded meanwhile is never overwritten, and what
// was checked is never written onto it. Checks of other engines that finished meanwhile are kept.
const now = getRecipe(name).recipe;
if (!sameRecipe(now, found.recipe)) throw new SkillError("The recipe changed while it was being checked — check it again", 409);
const merged: NonNullable<Recipe["verified"]> = { ...now.verified, ...Object.fromEntries(engines.map((e) => [e, verified[e] ?? null])) };
saveRecipe(name, { ...recipe, verified: merged }, { 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) };
+ return { ok: allPassed(checks), engines: checks, view: recipeView(name) };
+}
+
+// ---------------------------------------------------------------------------
+// A skill made from results (W2): its recipe is checked before it is saved
+
+interface DraftChecks {
+ verified: NonNullable<Recipe["verified"]>;
+ at: number;
+ /** The skill it was saved as, while its dry run was still going (that run's result is written into it). */
+ saved?: string;
+}
+
+declare global {
+ var __fuobeDraftChecks: Map<string, DraftChecks> | undefined;
+}
+
+const DRAFT_TTL_MS = 6 * 60 * 60_000;
+
+/** What drafts' checks found, by recipe (kept a few hours, in memory: the server's own word, never the browser's). */
+function draftChecks(): Map<string, DraftChecks> {
+ const m = (globalThis.__fuobeDraftChecks ??= new Map());
+ for (const [k, v] of m) if (Date.now() - v.at > DRAFT_TTL_MS) m.delete(k);
+ return m;
+}
+
+/** A recipe's identity for its checks: its JSON with sorted keys, without what was checked. */
+export function draftKey(recipe: Recipe): string {
+ const stable = (v: unknown): unknown =>
+ Array.isArray(v)
+ ? v.map(stable)
+ : v && typeof v === "object"
+ ? Object.fromEntries(
+ Object.entries(v)
+ .filter(([, x]) => x !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([k, x]) => [k, stable(x)]),
+ )
+ : v;
+ return crypto.createHash("sha256").update(JSON.stringify(stable({ ...recipe, verified: undefined }))).digest("hex");
+}
+
+/** A draft's recipe as it would be saved: its shape, then everything a save refuses. */
+function draftRecipe(input: unknown): Recipe {
+ 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 };
+ delete recipe.verified;
+ const problems = allProblems(recipe);
+ if (problems.length) throw new RecipeError(problems);
+ return recipe;
+}
+
+export interface DraftCheck {
+ ok: boolean;
+ engines: EngineCheck[];
+ /** Engines whose plan check passed: the skill runs there once saved. */
+ ready: Engine[];
+ /** Why it runs on no engine of this install. */
+ why?: string;
+}
+
+/** Write a draft's finished checks into the skill it was saved as, when that skill still holds the same recipe. */
+function adoptChecks(name: string, recipe: Recipe, verified: NonNullable<Recipe["verified"]>): void {
+ try {
+ const now = getRecipe(name).recipe;
+ if (draftKey(now) !== draftKey(recipe)) return;
+ const merged: NonNullable<Recipe["verified"]> = { ...now.verified };
+ for (const e of ENGINES) {
+ const v = verified[e];
+ const cur = now.verified?.[e];
+ // Only what was checked against the plan it holds (a later re-check stands).
+ if (v?.catalog && (!cur || cur.catalog === v.catalog)) merged[e] = { ...cur, ...v };
+ }
+ saveRecipe(name, { ...now, verified: merged }, { keepVerified: true });
+ } catch {
+ // Deleted or changed meanwhile: it is checked again from the Skills page.
+ }
+}
+
+/**
+ * Check a draft's recipe before it is saved (the review screen's Check it): `plan` prices it on each engine its steps
+ * allow (free, quick); `demo` adds the free dry run on the demo provider. What passed is kept for the save; a draft saved
+ * while its dry run was going gets the result when it ends.
+ */
+export async function checkDraft(input: unknown, level: "plan" | "demo", title = "Skill check"): Promise<DraftCheck> {
+ const recipe = draftRecipe(input);
+ const engines = recipeEngines(recipe);
+ if (!engines.length) return { ok: false, engines: [], ready: [], why: noEngine(recipe) };
+ const key = draftKey(recipe);
+ const { checks, verified } = await checkEngines({ name: "draft", title }, recipe, level, engines, draftChecks().get(key)?.verified);
+ const entry = draftChecks().get(key);
+ draftChecks().set(key, { verified: { ...entry?.verified, ...verified }, at: Date.now(), ...(entry?.saved && { saved: entry.saved }) });
+ if (entry?.saved) adoptChecks(entry.saved, recipe, verified);
+ return { ok: allPassed(checks), engines: checks, ready: engines.filter((e) => !!verified[e]?.plan) };
+}
+
+export interface DraftSave {
+ name: string;
+ title: string;
+ description: string;
+ whenToUse?: string;
+ body: string;
+ icon?: string;
+ recipe: unknown;
+}
+
+/**
+ * Save a draft as a user skill: SKILL.md (createSkill) with its recipe.json (saveRecipe), once its plan passes on an
+ * engine (checked again here: free). The draft's checks of this same recipe come with it; anything else starts unchecked.
+ */
+export async function saveDraft(input: DraftSave): Promise<RecipeView> {
+ const recipe = draftRecipe(input.recipe);
+ const engines = recipeEngines(recipe);
+ if (!engines.length) throw new SkillError(noEngine(recipe), 422);
+ const key = draftKey(recipe);
+ const known = draftChecks().get(key)?.verified;
+ const { checks, verified } = await checkEngines({ name: input.name, title: input.title }, recipe, "plan", engines, known);
+ if (!checks.some((c) => c.plan.ok)) throw new RecipeError([...new Set(checks.flatMap((c) => c.plan.errors))]);
+ createSkill({ name: input.name, title: input.title, description: input.description, whenToUse: input.whenToUse, body: input.body, ...(input.icon && { icon: input.icon }) });
+ try {
+ saveRecipe(input.name, { ...recipe, verified }, { keepVerified: true });
+ } catch (e) {
+ deleteSkill(input.name);
+ throw e;
+ }
+ draftChecks().set(key, { verified: { ...known, ...verified }, at: Date.now(), saved: input.name });
+ return recipeView(input.name);
}
diff --git a/src/server/skills.ts b/src/server/skills.ts
index c5c6ac00..090586b4 100644
--- a/src/server/skills.ts
+++ b/src/server/skills.ts
@@ -246,8 +246,8 @@ function validated(input: SkillInput & { name: string }) {
return parsed.skill;
}
-/** Names the API routes use. */
-const RESERVED = new Set(["upload", "new"]);
+/** Names the API routes use (static routes beside /api/assist/skills/[name]). */
+const RESERVED = new Set(["upload", "new", "draft"]);
function taken(name: string): string | null {
if (RESERVED.has(name)) return `“${name}” is reserved — pick another name`;
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 08ea713b..5d602053 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -77,6 +77,7 @@ describe("outputActions", () => {
"menu:genjutsu",
"menu:save-character",
"menu:reuse",
+ "menu:make-skill",
"menu:copy-prompt",
"menu:share",
"menu:pin",
@@ -91,7 +92,7 @@ describe("outputActions", () => {
it("gives SVG results no raster hand-offs, but keeps them on demo placeholders", () => {
const svg = (p: Partial<Generation>, o: Partial<Generation["outputs"][number]> = {}) => gen({ provider: "fal", outputs: [{ url: "/api/files/outputs/d/logo.svg", kind: "image", contentType: "image/svg+xml", ...o }], ...p });
- expect(ids(svg({}))).toEqual(["bar:download", "bar:favorite", "menu:copy-prompt", "menu:share", "menu:pin", "menu:review", "menu:delete"]);
+ expect(ids(svg({}))).toEqual(["bar:download", "bar:favorite", "menu:make-skill", "menu:copy-prompt", "menu:share", "menu:pin", "menu:review", "menu:delete"]);
expect(ids(svg({}, { url: "https://v3.fal.media/files/x/logo.svg", contentType: undefined }))[0]).toBe("bar:download");
expect(ids(svg({ feature: "upload", provider: "local" }))).toEqual(["bar:download", "menu:delete-upload"]);
// A demo picture is an SVG standing in for a raster result: it can still be animated (a demo Vectorize result can't).
@@ -113,6 +114,7 @@ describe("outputActions", () => {
"menu:grade",
"menu:genjutsu",
"menu:finalize",
+ "menu:make-skill",
"menu:copy-prompt",
"menu:share",
"menu:pin",
@@ -121,6 +123,16 @@ describe("outputActions", () => {
]);
});
+ it("offers Make a skill right after Reuse settings, on finished results only", () => {
+ const menu = (g: Generation, ctx = {}) => outputActions(g, 0, ctx).filter((a) => a.placement === "menu").map((a) => a.id);
+ const m = menu(gen(), { reuse: true });
+ expect(m.indexOf("make-skill")).toBe(m.indexOf("reuse") + 1);
+ expect(outputActions(gen(), 0).find((a) => a.id === "make-skill")).toEqual({ id: "make-skill", label: "Make a skill from this…", placement: "menu" });
+ for (const status of ["queued", "running", "failed", "canceled"] as const) expect(menu(gen({ status }))).not.toContain("make-skill");
+ expect(menu(gen({ deletedAt: 5 }))).not.toContain("make-skill");
+ expect(menu(gen({ feature: "upload" }))).not.toContain("make-skill");
+ });
+
it("handles audio, text, 3D, layers, favorites and the Trash", () => {
expect(ids(gen({ kind: "audio", outputs: [{ url: "/a.wav", kind: "audio" }] }))[0]).toBe("primary:lipsync");
const text = gen({ kind: "text", op: "transcribe", outputs: [{ url: "/t.txt", kind: "text", text: "Hi", meta: { cues: [{ start: 0, end: 1.5, text: "Hi" }] } }] });
diff --git a/tests/recipe-builder.test.ts b/tests/recipe-builder.test.ts
new file mode 100644
index 00000000..8b1bce96
--- /dev/null
+++ b/tests/recipe-builder.test.ts
@@ -0,0 +1,341 @@
+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-recipe-builder-"));
+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 gens = await import("@/server/generations");
+const { createPipeline } = await import("@/server/chains");
+const { db } = await import("@/server/db");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const builder = await import("@/server/recipe-builder");
+const recipes = await import("@/server/recipes");
+const skills = await import("@/server/skills");
+const lib = await import("@/lib/recipe-builder");
+const { recipeProblems } = await import("@/lib/recipe");
+const draftRoute = await import("@/app/api/assist/skills/draft/route");
+const checkRoute = await import("@/app/api/assist/skills/draft/check/route");
+const saveRoute = await import("@/app/api/assist/skills/draft/save/route");
+const nameRoute = await import("@/app/api/assist/skills/draft/name/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;
+});
+
+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));
+ }
+}
+
+/** A finished row written straight into the table (an old run, a studio's step): only what the builder reads. */
+function row(o: { id: string; request: Record<string, unknown>; feature?: string; op?: string; kind?: string; batch?: string | null; dependsOn?: string | string[]; provider?: string; outputs?: { url: string; kind: string; width?: number; height?: number }[] }) {
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, provider_input_json, external_id, external_meta_json, outputs_json, error, cost_usd, favorite, created_at, updated_at, completed_at, depends_on)
+ VALUES (@id, @batch, @feature, NULL, @model, 'cloud', @provider, @op, @kind, 'succeeded', NULL, NULL, @prompt, @request, NULL, NULL, NULL, @outputs, NULL, 0, 0, @now, @now, @now, @deps)`,
+ )
+ .run({
+ id: o.id,
+ batch: o.batch ?? null,
+ feature: o.feature ?? (o.request.feature as string),
+ model: o.request.modelId as string,
+ provider: o.provider ?? "mock",
+ op: o.op ?? (o.request.op as string) ?? "t2i",
+ kind: o.kind ?? "image",
+ prompt: (o.request.prompt as string) ?? null,
+ request: JSON.stringify(o.request),
+ outputs: JSON.stringify(o.outputs ?? [{ url: photo, kind: o.kind ?? "image", width: 64, height: 48 }]),
+ now,
+ deps: o.dependsOn === undefined ? null : Array.isArray(o.dependsOn) ? JSON.stringify(o.dependsOn) : o.dependsOn,
+ });
+ return o.id;
+}
+
+/** The research's turntable as it was made in the composer: a cut-out, a scene from it, a clip of the scene. */
+async function turntable() {
+ const p = createPipeline([
+ { key: "cutout", request: { feature: "image", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: [photo] } } },
+ { key: "scene", after: "cutout", chain: [{ slot: "images", position: "first" }], request: { feature: "edit", modelId: "nano-banana-pro", op: "edit", prompt: "a matte black desk lamp on a travertine plinth, soft window light", params: { aspectRatio: "1:1" } } },
+ { key: "spin", after: "scene", chain: [{ slot: "images" }], request: { feature: "video", modelId: "kling-3", op: "i2v", prompt: "slow turntable of the matte black desk lamp", params: { duration: 5 } } },
+ ]);
+ await settle(p.items.map((g) => g.id));
+ return p;
+}
+
+const json = (body: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+describe("draftFromGenerations", () => {
+ it("rebuilds a cut-out → edit → image-to-video chain as 3 steps with after and chain, and one image input", async () => {
+ const p = await turntable();
+ const { draft, refusals } = builder.draftFromGenerations([p.byKey.spin.id]);
+ expect(refusals).toEqual([]);
+ expect(draft).not.toBeNull();
+ const steps = draft!.recipe.steps;
+ expect(steps.map((s) => (s.kind === "generate" ? s.request.modelId : s.tool))).toEqual(["birefnet-cloud", "nano-banana-pro", "kling-3"]);
+ const [cut, scene, spin] = steps as Extract<(typeof steps)[number], { kind: "generate" }>[];
+ expect(cut.after).toBeUndefined();
+ expect(scene.after).toBe(cut.key);
+ expect(scene.chain).toEqual([{ slot: "images", position: "first" }]);
+ expect(spin.after).toBe(scene.key);
+ expect(spin.chain).toEqual([{ slot: "images" }]);
+ // Chain-filled inputs are taken out: the scene and the clip get their pictures from the steps before.
+ expect(scene.request.inputs).toBeUndefined();
+ expect(spin.request.inputs).toBeUndefined();
+ // Server fields are dropped.
+ for (const s of [cut, scene, spin]) for (const k of ["chainFilled", "step", "batchTitle", "title", "skill", "demo", "asked", "chain"]) expect(s.request).not.toHaveProperty(k);
+ const media = draft!.candidates.filter((c) => c.kind === "media");
+ expect(media).toHaveLength(1);
+ expect(media[0]).toMatchObject({ type: "image", example: photo, at: [{ step: cut.key, path: ["inputs", "images", 0] }] });
+ // Every candidate starts Fixed: the draft's recipe has no inputs, and its values are where they were.
+ expect(draft!.recipe.params).toEqual([]);
+ expect(draft!.candidates.some((c) => c.kind === "text" && c.example === "slow turntable of the matte black desk lamp")).toBe(true);
+ expect(draft!.candidates.find((c) => c.setting === "numOutputs")?.at).toEqual([{ step: spin.key, path: ["params", "numOutputs"] }]);
+ // The leaf's check: what it made (a demo result says nothing about a real one's length).
+ expect(draft!.recipe.checks).toEqual({ [spin.key]: { kind: "video", count: 1 } });
+ expect(draft!.steps.map((s) => s.waits)).toEqual([[], [draft!.steps[0].label], [draft!.steps[1].label]]);
+ expect(draft!.demo).toBe(true);
+ expect(draft!.notes).toContain(lib.DEMO_NOTE);
+ expect(draft!.recipe.source).toMatchObject({ from: "library", generations: [p.byKey.spin.id], demo: true });
+ expect(recipeProblems(draft!.recipe)).toEqual([]);
+ });
+
+ it("makes the same upload used by two steps one input", async () => {
+ const p = createPipeline([
+ { key: "a", request: { feature: "edit", modelId: "nano-banana-pro", op: "edit", prompt: "the lamp in red", inputs: { images: [photo] } } },
+ { key: "b", after: "a", request: { feature: "edit", modelId: "nano-banana-pro", op: "edit", prompt: "both lamps side by side", inputs: { images: [photo] } } },
+ ]);
+ await settle(p.items.map((g) => g.id));
+ const { draft } = builder.draftFromGenerations([p.byKey.b.id]);
+ const media = draft!.candidates.filter((c) => c.kind === "media");
+ expect(media).toHaveLength(1);
+ expect(media[0].at).toHaveLength(2);
+ // The second step keeps its own picture; the first step's result comes back through the chain.
+ const b = draft!.recipe.steps[1] as Extract<NonNullable<typeof draft>["recipe"]["steps"][number], { kind: "generate" }>;
+ expect(b.request.inputs).toEqual({ images: [photo] });
+ expect(b.chain).toEqual([{ slot: "images", position: "last" }]);
+ // Varying it puts the input in both places.
+ const recipe = lib.buildRecipe(draft!, { varies: { [media[0].id]: true } });
+ expect(recipe.params).toEqual([{ id: media[0].id, label: media[0].label, type: "image", required: true, example: photo }]);
+ expect(JSON.stringify(recipe.steps).match(new RegExp(`\\{\\{${media[0].id}\\}\\}`, "g"))).toHaveLength(2);
+ expect(recipeProblems(recipe)).toEqual([]);
+ });
+
+ it("moves a retired model to what replaced it, and says so", () => {
+ row({ id: "old-soul-1", request: { feature: "image", modelId: "soul-1", op: "t2i", prompt: "a ceramicist at her wheel", params: { aspectRatio: "3:4" } } });
+ const { draft } = builder.draftFromGenerations(["old-soul-1"]);
+ const step = draft!.recipe.steps[0] as { request: { modelId: string } };
+ expect(step.request.modelId).toBe("fuobe-soul");
+ expect(draft!.notes.some((n) => /Fuobe Soul/.test(n))).toBe(true);
+ expect(draft!.steps[0].notes.some((n) => /Fuobe Soul/.test(n))).toBe(true);
+ });
+
+ it("rebuilds a multi-shot film from the request as asked, and refuses one made before it was kept", async () => {
+ const [film] = gens.createGenerations({
+ feature: "video",
+ modelId: "oss-wan22-14b-fast",
+ op: "t2v",
+ prompt: "a fox in the snow",
+ params: { shots: [{ prompt: "it sniffs the air", duration: 3 }, { prompt: "it runs off", duration: 3 }] },
+ });
+ expect(film.request.asked?.params?.shots).toHaveLength(2);
+ await settle([film.id]);
+ const { draft, refusals } = builder.draftFromGenerations([film.id]);
+ expect(refusals).toEqual([]);
+ expect(draft!.recipe.steps).toHaveLength(1);
+ const step = draft!.recipe.steps[0] as { request: Record<string, unknown> & { params?: { shots?: unknown[] } } };
+ expect(step.request.modelId).toBe("oss-wan22-14b-fast");
+ expect(step.request.params?.shots).toHaveLength(2);
+ expect(step.request).not.toHaveProperty("asked");
+ expect(draft!.steps[0].notes.some((n) => /asked as/.test(n))).toBe(true);
+ // A shot of the same film stands for the film too.
+ const shot = gens.listGenerations({ batchId: film.batchId! }).find((g) => g.request.step?.label === "Shot 1 of 2")!;
+ expect(builder.draftFromGenerations([shot.id]).draft!.recipe.steps).toHaveLength(1);
+
+ // The same film made before W2: the rows, labelled, and no `asked`.
+ row({ id: "old-shot-1", batch: "oldfilm", feature: "video", kind: "video", request: { feature: "video", modelId: "oss-wan22-14b-fast", op: "t2v", prompt: "a fox. it sniffs", step: { label: "Shot 1 of 2", index: 0, of: 3 } } });
+ row({ id: "old-shot-2", batch: "oldfilm", feature: "video", kind: "video", request: { feature: "video", modelId: "oss-wan22-14b-fast", op: "t2v", prompt: "a fox. it runs", step: { label: "Shot 2 of 2", index: 1, of: 3 } } });
+ row({ id: "old-film", batch: "oldfilm", feature: "video", kind: "video", op: "concat", dependsOn: ["old-shot-1", "old-shot-2"], request: { feature: "video", modelId: "oss-join-clips", op: "concat", chain: [{ slot: "videos" }, { slot: "videos" }], step: { label: "Film · 2 shots", index: 2, of: 3 } } });
+ const old = builder.draftFromGenerations(["old-film"]);
+ expect(old.draft).toBeNull();
+ expect(old.refusals).toEqual([expect.objectContaining({ id: "old-film", reason: lib.STEPS_REFUSAL })]);
+ });
+
+ it("refuses a storyboard frame, a per-frame Mixed Media step and a helper step with the studio's name", () => {
+ row({ id: "frame-1", feature: "storyboard", request: { feature: "storyboard", modelId: "nano-banana-pro", op: "t2i", prompt: "scene 1", frame: { scene: "s1", index: 0, of: 4 } } });
+ row({ id: "mm-frame", feature: "mixed-media-frame-step", request: { feature: "mixed-media-frame-step", modelId: "nano-banana-pro", op: "edit", prompt: "in clay", chain: [{ slot: "images", index: 3 }] }, dependsOn: "frame-1" });
+ row({ id: "fl-voice", feature: "faceless-voice", kind: "audio", request: { feature: "faceless-voice", modelId: "oss-chatterbox", op: "tts", prompt: "Hello" } });
+ row({ id: "dub-plain", feature: "image", request: { feature: "image", modelId: "nano-banana-pro", op: "t2i", prompt: "x" }, dependsOn: "fl-voice" });
+ const { draft, refusals } = builder.draftFromGenerations(["frame-1", "mm-frame", "fl-voice", "dub-plain"]);
+ expect(draft).toBeNull();
+ const why = Object.fromEntries(refusals.map((r) => [r.id, r.reason]));
+ expect(why["frame-1"]).toBe(lib.notSupported("Storyboard"));
+ expect(why["mm-frame"]).toBe("Made frame by frame in Mixed Media: making a skill from it isn't supported yet");
+ expect(why["fl-voice"]).toBe(lib.notSupported("Faceless Studio"));
+ // A plain result is refused with the reason of a step it needs.
+ expect(why["dub-plain"]).toBe(lib.notSupported("Faceless Studio"));
+ });
+
+ it("lifts a dub to one dub_video step from its session, and refuses a studio with no tool", () => {
+ row({ id: "dub-film", feature: "dub", kind: "video", op: "mux", request: { feature: "dub", modelId: "oss-mux", op: "mux" }, outputs: [{ url: clip, kind: "video" }] });
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO dub_sessions (id, data_json, created_at, updated_at) VALUES (?, ?, ?, ?)")
+ .run("dub1", JSON.stringify({ title: "talk", engine: "open", mode: "steps", video: clip, source: "en", targets: ["es", "de"], batchId: "b", prepare: { stems: "x" }, voices: { es: [{ ids: { film: "dub-film" }, at: now, lipsync: false }] } }), now, now);
+ const { draft, refusals } = builder.draftFromGenerations(["dub-film"]);
+ expect(refusals).toEqual([]);
+ expect(draft!.recipe.steps).toEqual([expect.objectContaining({ kind: "tool", tool: "dub_video", input: { video: clip, languages: ["Spanish", "German"], source_language: "English", lipsync: false, review: true } })]);
+ expect(draft!.candidates.filter((c) => c.kind === "media")).toEqual([expect.objectContaining({ type: "video", example: clip, at: [{ step: draft!.recipe.steps[0].key, path: ["video"] }] })]);
+
+ row({ id: "cinema-1", feature: "cinema", kind: "video", request: { feature: "cinema", modelId: "fuobe-cinema", op: "t2v", prompt: "a chase" } });
+ row({ id: "dub-orphan", feature: "dub", kind: "video", request: { feature: "dub", modelId: "oss-mux", op: "mux" } });
+ const no = builder.draftFromGenerations(["cinema-1", "dub-orphan"]);
+ expect(no.refusals.map((r) => r.reason)).toEqual([lib.notSupported("Cinema Studio"), lib.notSupported("Translate & dub")]);
+ // A studio step and generate steps don't mix yet.
+ const mixed = builder.draftFromGenerations(["dub-film", "old-soul-1"]);
+ expect(mixed.draft!.recipe.steps).toHaveLength(1);
+ expect(mixed.refusals).toEqual([expect.objectContaining({ id: "dub-film", reason: expect.stringContaining("on its own") })]);
+ });
+
+ it("makes unrelated picks parallel steps", async () => {
+ const [a] = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", op: "t2i", prompt: "a red chair" });
+ const [b] = gens.createGenerations({ feature: "image", modelId: "flux-2-pro", op: "t2i", prompt: "a blue sofa" });
+ await settle([a.id, b.id]);
+ const { draft } = builder.draftFromGenerations([a.id, b.id]);
+ expect(draft!.recipe.steps).toHaveLength(2);
+ expect(draft!.recipe.steps.every((s) => s.kind === "generate" && s.after === undefined)).toBe(true);
+ expect(draft!.steps.every((s) => s.leaf)).toBe(true);
+ expect(Object.keys(draft!.recipe.checks ?? {})).toHaveLength(2);
+ });
+
+ it("answers over the API, refusing what isn't there", async () => {
+ const res = await draftRoute.POST(json({ generations: ["nope"] }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ draft: null, refusals: [{ id: "nope", title: "nope", reason: "It's gone (deleted, or in the Trash)" }] });
+ expect((await draftRoute.POST(json({ generations: [] }))).status).toBe(400);
+ });
+});
+
+describe("the naming pass", () => {
+ const draft = () => ({
+ candidates: [{ id: "image", label: "Image", type: "image" as const, kind: "media" as const, example: "/api/files/x.png", at: [] }],
+ recipe: { fuobeRecipe: 1 as const, params: [], steps: [{ key: "edit", kind: "generate" as const, request: { feature: "edit", modelId: "m", prompt: "a matte black desk lamp on a plinth" } }] },
+ });
+
+ it("keeps what fits the draft and drops the rest", () => {
+ const n = lib.parseNaming(
+ 'Here you go:\n```json\n{"name": "Lamp Turntable!", "title": "Lamp turntable", "inputs": [{"candidate": "image", "id": "product", "label": "Product photo"}, {"candidate": "nope", "id": "x", "label": "X"}], "slots": [{"step": "edit", "text": "a matte black desk lamp", "id": "product_name", "label": "Product"}, {"step": "edit", "text": "not in the prompt", "id": "y", "label": "Y"}]}\n```',
+ draft(),
+ );
+ expect(n).toEqual({ name: "lamp-turntable", title: "Lamp turntable", inputs: [{ candidate: "image", id: "product", label: "Product photo" }], slots: [{ step: "edit", text: "a matte black desk lamp", id: "product_name", label: "Product" }] });
+ });
+
+ it("ignores malformed output", () => {
+ expect(lib.parseNaming("no json here", draft())).toBeNull();
+ expect(lib.parseNaming('{"title": 42}', draft())).toBeNull();
+ expect(lib.parseNaming('{"inputs": [{"candidate": "image", "id": "1bad", "label": "x"}]}', draft())).toBeNull();
+ expect(lib.parseNaming(null, draft())).toBeNull();
+ });
+
+ it("is skipped without an LLM", async () => {
+ const p = await turntable();
+ const res = await nameRoute.POST(json({ generations: [p.byKey.scene.id] }));
+ expect(await res.json()).toEqual({ naming: null });
+ expect(builder.draftFromGenerations([p.byKey.scene.id]).draft!.llm).toBeNull();
+ });
+});
+
+describe("choices, body, check and save", () => {
+ it("turns slots and Varies into inputs and keeps the body deterministic", async () => {
+ const p = await turntable();
+ const { draft } = builder.draftFromGenerations([p.byKey.spin.id]);
+ const image = draft!.candidates.find((c) => c.kind === "media")!;
+ const takes = draft!.candidates.find((c) => c.setting === "numOutputs")!;
+ const recipe = lib.buildRecipe(draft!, {
+ varies: { [image.id]: true, [takes.id]: true },
+ ids: { [image.id]: "product" },
+ labels: { [image.id]: "Product photo" },
+ slots: [{ step: draft!.recipe.steps[1].key, text: "matte black desk lamp", id: "name", label: "Product name" }],
+ });
+ expect(recipe.params.map((x) => x.id)).toEqual(["product", "name", takes.id]);
+ expect(recipe.params.find((x) => x.id === takes.id)).toMatchObject({ type: "number", default: 1, min: 1 });
+ // The same words in both prompts are one input.
+ const prompts = recipe.steps.flatMap((s) => (s.kind === "generate" && typeof s.request.prompt === "string" ? [s.request.prompt] : []));
+ expect(prompts).toEqual(["a {{name}} on a travertine plinth, soft window light", "slow turntable of the {{name}}"]);
+ const leaf = recipe.steps[2].key;
+ expect(recipe.checks?.[leaf]?.count).toBe(`{{${takes.id}}}`);
+ expect(recipeProblems(recipe)).toEqual([]);
+ const meta = { title: "Lamp turntable", description: "A product turntable from a photo.", name: "lamp-turntable" };
+ const body = lib.skillBody(recipe, draft!, meta);
+ expect(lib.skillBody(recipe, draft!, meta)).toBe(body);
+ expect(body).toContain("## Inputs");
+ expect(body).toContain("**Product photo** (`product`)");
+ expect(body).toContain("## Steps");
+ expect(body).toContain("## Using Fuobe from an agent");
+ });
+
+ it("checks a draft for free with Demo mode off and no keys, saves it with what passed, and runs it", async () => {
+ const p = await turntable();
+ const { draft } = builder.draftFromGenerations([p.byKey.spin.id]);
+ const image = draft!.candidates.find((c) => c.kind === "media")!;
+ const recipe = lib.buildRecipe(draft!, { varies: { [image.id]: true } });
+ setSetting("demoMode", "off");
+ try {
+ const plan = await (await checkRoute.POST(json({ recipe, level: "plan" }))).json();
+ expect(plan.ok).toBe(true);
+ expect(plan.ready).toEqual(["cloud"]);
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const demo = await (await checkRoute.POST(json({ recipe, level: "demo" }))).json();
+ expect(demo.ok).toBe(true);
+ expect(demo.engines[0].dryRun).toEqual({ ok: true, problems: [] });
+ // The dry run's rows are hidden helpers, in the Trash once it ends.
+ const made = db().prepare("SELECT g.feature, g.provider, t.deleted_at FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id ORDER BY g.created_at DESC LIMIT ?").all((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n - before) as { feature: string; provider: string; deleted_at: number | null }[];
+ expect(made.length).toBe(3);
+ expect(made.every((r) => r.feature === "skill-check" && r.provider === "mock" && r.deleted_at)).toBe(true);
+ const res = await saveRoute.POST(json({ name: "lamp-turntable", title: "Lamp turntable", description: "A product turntable from a photo.", body: lib.skillBody(recipe, draft!, { title: "Lamp turntable", description: "x" }), recipe }));
+ expect(res.status).toBe(201);
+ const view = await res.json();
+ expect(view.ready).toEqual(["cloud"]);
+ // The dry run that passed on the draft comes with it.
+ expect(view.recipe.verified.cloud.dryRun).toBeTruthy();
+ expect(view.recipe.source.demo).toBe(true);
+ } finally {
+ setSetting("demoMode", "auto");
+ }
+ const run = await recipes.runRecipe("lamp-turntable", { values: { [image.id]: photo } });
+ expect(run.runs[0].ids).toHaveLength(3);
+ // Saving the same name twice, or a reserved one, is refused.
+ expect((await saveRoute.POST(json({ name: "lamp-turntable", title: "x", description: "x", body: "x", recipe }))).status).toBe(409);
+ expect(() => skills.createSkill({ name: "draft", title: "Draft", description: "x", body: "x" })).toThrow(/reserved/);
+ });
+
+ it("refuses to save a recipe whose plan fails, and keeps no half-made skill", async () => {
+ const bad = { fuobeRecipe: 1, params: [], steps: [{ key: "a", kind: "generate", request: { feature: "image", modelId: "no-such-model", prompt: "x" } }] };
+ const res = await saveRoute.POST(json({ name: "broken-draft", title: "Broken", description: "x", body: "x", recipe: bad }));
+ expect(res.status).toBe(422);
+ expect(skills.getSkill("broken-draft")).toBeNull();
+ });
+});