The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Assist and MCP: studio tools open their studios — a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor
Claudeb5453ed67d33
diff --git a/src/lib/assist-studios.ts b/src/lib/assist-studios.tsnew file mode 100644index 00000000..73e6d04b--- /dev/null+++ b/src/lib/assist-studios.ts@@ -0,0 +1,80 @@+import { DUB_LANGUAGES, type DubLanguage } from "./av/languages";+import { FACELESS_STYLE_IDS, STYLES } from "./catalog/faceless";+import { SHORTS_PRESETS, type ShortsPreset } from "./catalog/shorts";++/**+ * How an Assist / MCP studio call's words map onto a studio's own choices: a Shorts preset, a+ * Faceless style, a dub language. Pure (the adapters in src/server/assist/studio-routes.ts use it).+ */++const norm = (s: string) =>+ s+ .toLowerCase()+ .replace(/colour/g, "color")+ .replace(/&/g, " ")+ .replace(/[^a-z0-9]+/g, " ")+ .trim();++/** The Shorts preset a style names outright ("Claymation", "pencil sketch", "shorts-watercolor"); other words are a look of their own. */+export function shortsPresetFor(style: string): ShortsPreset | undefined {+ const s = norm(style);+ if (!s) return undefined;+ return SHORTS_PRESETS.find((p) => p.id === style.trim().toLowerCase() || norm(p.name) === s);+}++/** Words that point at each Faceless / Explainer style (whole words or phrases, after norm()). */+const STYLE_WORDS: Record<string, string[]> = {+ "editorial-motion-graphics": ["editorial", "motion graphics", "documentary", "infographic", "diagrams", "explainer"],+ "stickman-cartoon": ["stickman", "stick figure", "stick figures", "stick man"],+ "watercolor-chronicle": ["watercolor", "painterly", "aquarelle"],+ "fairy-tale-myth": ["fairy", "fairy tale", "myth", "mythology", "legend", "fable", "fantasy"],+ "paper-diorama": ["diorama", "papercut", "paper cut", "layered paper"],+ "pastel-flat-2d": ["pastel", "flat", "flat 2d", "2d", "flat illustration"],+ "colorful-3d": ["colorful 3d", "toy", "toylike", "3d render", "pixar", "3d"],+ "hand-drawn": ["hand drawn", "handdrawn", "sketch", "sketched", "pencil", "ink", "storybook"],+ "poster-vector": ["poster", "vector"],+ mannequin: ["mannequin", "mannequins"],+ "whiteboard-doodle": ["whiteboard", "doodle", "doodles", "marker"],+ "3d-papercraft": ["papercraft", "folded paper", "origami"],+ "mixed-media": ["mixed media"],+ "low-poly": ["low poly", "lowpoly", "polygonal"],+ "2d-illustrator": ["2d illustration", "illustrator", "illustration"],+ "pixel-art": ["pixel", "pixel art", "8 bit", "16 bit"],+ claymotion: ["clay", "claymation", "claymotion", "plasticine", "stop motion"],+ "isometric-flat-vector": ["isometric"],+ "3d-mix": ["3d mix"],+ "studio-3d": ["studio 3d", "studio lit", "clean 3d"],+ "fluffy-toy": ["plush", "fluffy", "felt", "stuffed"],+ "paper-collage": ["collage", "torn paper", "cutout", "cut out"],+};++/**+ * The Faceless style a description points at: an exact style id or name, else the style with the most+ * matching words (ties: the longest matching phrase, then Faceless Studio's own 12 before the+ * Explainer's). Null when nothing matches — the words describe a look the studio doesn't have.+ */+export function facelessStyleFor(style: string): string | null {+ const raw = style.trim().toLowerCase();+ const s = ` ${norm(style)} `;+ const exact = STYLES.find((x) => x.id === raw || ` ${norm(x.name)} ` === s);+ if (exact) return exact.id;+ let best: { id: string; hits: number; longest: number; own: boolean } | null = null;+ for (const x of STYLES) {+ const hits = (STYLE_WORDS[x.id] ?? []).filter((w) => s.includes(` ${w} `));+ if (!hits.length) continue;+ const cand = { id: x.id, hits: hits.length, longest: Math.max(...hits.map((w) => w.length)), own: FACELESS_STYLE_IDS.includes(x.id) };+ if (!best || cand.hits > best.hits || (cand.hits === best.hits && (cand.longest > best.longest || (cand.longest === best.longest && cand.own && !best.own)))) best = cand;+ }+ return best?.id ?? null;+}++/** Other names people use for a language Translate & dub lists. */+const LANGUAGE_ALIASES: Record<string, string> = { mandarin: "zh", "mandarin chinese": "zh", castilian: "es", "brazilian portuguese": "pt", tagalog: "fil", bokmal: "no", "bokmål": "no" };++/** The dub language a name or code means ("Spanish", "es", "spanish (mexico)", "Mandarin"), if Translate & dub has it. */+export function dubLanguageFor(name: string): DubLanguage | undefined {+ const s = name.trim().toLowerCase();+ const base = s.replace(/\s*\(.*\)\s*$/, "").trim();+ const code = LANGUAGE_ALIASES[s] ?? LANGUAGE_ALIASES[base];+ return DUB_LANGUAGES.find((l) => l.code === code || l.code === s || l.code === base || l.name.toLowerCase() === s || l.name.toLowerCase() === base);+}diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 31ffbfc1..264611d9 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -37,8 +37,10 @@ export const planRunnable = (jobs: PlannedJob[]): boolean => jobs.some((j) => !jexport type AssistItem =| { id: string; role: "user"; text: string; attachments?: string[]; skills?: string[] }| { id: string; role: "assistant"; text: string }- | { id: string; role: "tool"; text: string; href?: string }- | { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined" }+ /** `studio`: a job a studio took ("Layers"); its card offers "Open in Layers" (href). */+ | { id: string; role: "tool"; text: string; href?: string; studio?: string }+ /** `opens`: the studios the plan's jobs open in; `notes`: why a studio job runs in the Library instead. */+ | { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined"; opens?: string[]; notes?: string[] }| { id: string; role: "generations"; ids: string[]; storyboard?: boolean }| { id: string; role: "notice"; text: string; tone: "info" | "error" };diff --git a/src/lib/image-size.ts b/src/lib/image-size.tsnew file mode 100644index 00000000..48a1390f--- /dev/null+++ b/src/lib/image-size.ts@@ -0,0 +1,78 @@+/**+ * An image's pixel size from its first bytes: PNG, JPEG, WebP (lossy, lossless and extended), GIF and+ * SVG (width / height, else the viewBox). Enough for the server to open a picture in a studio that+ * needs its size before any browser has loaded it (Assist starting a Layers project). Null when the+ * format isn't one of these or the header is cut short.+ */+export function imageSize(data: Uint8Array): { width: number; height: number } | null {+ try {+ const size = png(data) ?? jpeg(data) ?? webp(data) ?? gif(data) ?? svg(data);+ return size && size.width > 0 && size.height > 0 ? size : null;+ } catch {+ return null;+ }+}++const ascii = (b: Uint8Array, o: number, n: number) => String.fromCharCode(...b.subarray(o, o + n));+const u16be = (b: Uint8Array, o: number) => (b[o] << 8) | b[o + 1];+const u16le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8);+const u24le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16);+const u32be = (b: Uint8Array, o: number) => ((b[o] << 24) >>> 0) + ((b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]);++function png(b: Uint8Array) {+ if (b.length < 24 || b[0] !== 0x89 || ascii(b, 1, 3) !== "PNG" || ascii(b, 12, 4) !== "IHDR") return null;+ return { width: u32be(b, 16), height: u32be(b, 20) };+}++/** The first start-of-frame marker (SOF0–SOF15, not DHT / JPG / DAC) holds the size. */+function jpeg(b: Uint8Array) {+ if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return null;+ let o = 2;+ while (o + 9 < b.length) {+ if (b[o] !== 0xff) return null;+ const marker = b[o + 1];+ // Fill bytes and markers without a length.+ if (marker === 0xff) {+ o += 1;+ continue;+ }+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {+ o += 2;+ continue;+ }+ const len = u16be(b, o + 2);+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) return { width: u16be(b, o + 7), height: u16be(b, o + 5) };+ if (len < 2) return null;+ o += 2 + len;+ }+ return null;+}++function webp(b: Uint8Array) {+ if (b.length < 30 || ascii(b, 0, 4) !== "RIFF" || ascii(b, 8, 4) !== "WEBP") return null;+ const chunk = ascii(b, 12, 4);+ if (chunk === "VP8X") return { width: u24le(b, 24) + 1, height: u24le(b, 27) + 1 };+ if (chunk === "VP8 ") return { width: u16le(b, 26) & 0x3fff, height: u16le(b, 28) & 0x3fff };+ if (chunk === "VP8L") {+ const bits = b[21] | (b[22] << 8) | (b[23] << 16) | (b[24] << 24);+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };+ }+ return null;+}++function gif(b: Uint8Array) {+ if (b.length < 10 || ascii(b, 0, 4) !== "GIF8") return null;+ return { width: u16le(b, 6), height: u16le(b, 8) };+}++function svg(b: Uint8Array) {+ const text = new TextDecoder().decode(b.subarray(0, 4096));+ const tag = /<svg\b[^>]*>/i.exec(text)?.[0];+ if (!tag) return null;+ const attr = (name: string) => new RegExp(`\\s${name}\\s*=\\s*["']\\s*([\\d.]+)(px)?\\s*["']`, "i").exec(tag);+ const w = attr("width");+ const h = attr("height");+ if (w && h) return { width: Math.round(Number(w[1])), height: Math.round(Number(h[1])) };+ const box = /\sviewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*["']/i.exec(tag);+ return box ? { width: Math.round(Number(box[1])), height: Math.round(Number(box[2])) } : null;+}diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 66932be4..a2d43f3a 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -515,7 +515,7 @@ How you work:- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.- For multi-step work (an image, then animate it; transcribe, translate, then voice it), put the steps in one generate call and set "after" on each later job: it starts by itself when the earlier job finishes and gets its result as input. When you need to judge a result before deciding the next step, wait with check_generations instead (look=true to see images) and pass the output URL into the next call.- Besides images, video and audio, models can transcribe speech, translate or write text (scripts, captions, ad copy), split images into layers, separate voice from background, trim, caption or re-sound clips, and turn an image into a 3D model: search_models with kind "text" or "model3d" finds the text and 3D ones.-- Whole studio jobs have their own tools — split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions: use them instead of chaining those steps by hand.+- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).- Use the user's files by the URLs listed in their message. Earlier outputs are found with list_recent. Saved characters and products are Elements: check list_elements and write their @handle in prompts.- Results show up in the chat by themselves, so don't repeat URLs back. After starting jobs, say briefly what's coming; after they finish, give a short take and suggest a next step.- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.@@ -938,7 +938,9 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const jobs = plans.flatMap((p) => p.jobs);const total = plans.some((p) => p.total === null) ? null : plans.reduce((n, p) => n + (p.total ?? 0), 0);const summary = [...new Set(gated.map((g) => cardTitle(g.name, g.input)))].join(" · ");- const item = push(s, { role: "approval", summary, jobs, totalUsd: total, status: "pending" });+ const opens = [...new Set(plans.flatMap((p) => (p.studio ? [p.studio] : [])))];+ const notes = plans.flatMap((p) => (p.fallback ? [`${p.fallback}.`] : []));+ const item = push(s, { role: "approval", summary, jobs, totalUsd: total, status: "pending", ...(opens.length && { opens }), ...(notes.length && { notes }) });offlineNote();s.pending = { approvalItemId: item.id, results, gated, order };s.thread.status = "waiting";diff --git a/src/server/assist/define.ts b/src/server/assist/define.tsindex fedf3732..f1513631 100644--- a/src/server/assist/define.ts+++ b/src/server/assist/define.ts@@ -27,6 +27,13 @@ export interface ToolOutcome {items?: AssistItem[];}+/** Where a studio tool's job opens: its studio and that studio's page, or why it runs in the Library instead. */+export interface JobPlace {+ studio?: string;+ href?: string;+ fallback?: string;+}+export interface ToolDef<S extends z.ZodType> {name: string;description: string;@@ -39,6 +46,8 @@ export interface ToolDef<S extends z.ZodType> {plan?: (input: z.infer<S>, ctx: ToolContext) => PlannedJob[];/** The approval card's heading for this call (default: its summary field, else the tool's name). */title?: (input: z.infer<S>) => string;+ /** Studio tools: where the job will open (shown on the card, returned by MCP's estimate_job). */+ place?: (input: z.infer<S>, ctx: ToolContext) => JobPlace;}export const defineTool = <S extends z.ZodType>(def: ToolDef<S>) => def;diff --git a/src/server/assist/studio-routes.ts b/src/server/assist/studio-routes.tsnew file mode 100644index 00000000..474ed169--- /dev/null+++ b/src/server/assist/studio-routes.ts@@ -0,0 +1,617 @@+import "server-only";+import fs from "node:fs";+import type { PlannedJob } from "@/lib/assist";+import { dubLanguageFor, facelessStyleFor, shortsPresetFor } from "@/lib/assist-studios";+import { BURN_MODELS, burnPricePerMinute, burnRequest, CAPTIONS_FEATURE, lookFor, OPEN_FONT_SIZE, styleById, transcribeRequest, type BurnRoute, type CaptionLook } from "@/lib/av/captions";+import { DUB_STEP_MODELS, translateKey, type OneShotModel } from "@/lib/av/dub";+import { getModel } from "@/lib/catalog";+import { defaultSettings, genreInfo, PART_LABELS, type EpisodeAspect, type EpisodeSettings, type NarratorVoice, type StepPart } from "@/lib/catalog/faceless";+import { AD_RATIOS, emptyKit, type AdRatio, type BrandKit, type Product } from "@/lib/catalog/marketing";+import { lookFromPreset, SHORTS, SHORTS_MODELS, type ShortsLook } from "@/lib/catalog/shorts";+import type { Engine, GenerationRequest, MediaKind, Operation } from "@/lib/catalog/types";+import { modeHref } from "@/lib/hubs";+import { imageSize } from "@/lib/image-size";+import { clampLayers, decomposeCost, defaultLayers, TOOL_MODELS, TOOL_LABELS, type LayerJobInput } from "@/lib/layers";+import { createBatch, estimateBatch, listCreatives, type BatchInput } from "../ads";+import { createManualBrand, createProduct, DuplicateProductError, getBrand, getProduct, heuristicManualKit, listProducts, updateProduct } from "../brand";+import { createPipeline, type PipelineStep } from "../chains";+import { createDubSession, previewDub, videoLength, type CreateDubInput } from "../dub";+import { createChannel, createEpisode, estimateEpisode, listChannels } from "../faceless";+import { createProject, deleteProject, FileUrl, jobSteps, startJob } from "../layers";+import { engineMode } from "../settings";+import { createSession, estimateWith, sourceInfo, type ShortsBody, type SourceInfo } from "../shorts";+import { absolutePath, getAsset } from "../storage";+import type { ToolContext } from "./define";+import { planSteps, STUDIO_ROUTES, type AdsToolInput, type CaptionsToolInput, type DubToolInput, type FacelessToolInput, type LayersToolInput, type RestyleToolInput, type StudioRoute } from "./studio-tools";++/**+ * The Assist / MCP studio tools, wired to the studios' own server modules: each adapter turns a tool+ * call into the studio's input, prices it with the studio's estimate, refuses what the studio can't+ * take (the tool then runs its own pipeline in the Library) and starts the job there, so it opens as+ * a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch or the+ * Captions editor. Imported for its effect by tools.ts (and so by the MCP server).+ */++const engineOf = (ctx: ToolContext): Engine => (engineMode() === "both" ? ctx.engine : (engineMode() as Engine));++// ---------------------------------------------------------------------------+// Files++/** A file saved in Fuobe, read from disk (null: not an /api/files/ path, or gone). */+function localFile(ref: string, maxBytes?: number): Buffer | null {+ if (!ref.startsWith("/api/files/")) return null;+ try {+ const abs = absolutePath(decodeURIComponent(ref.slice("/api/files/".length)));+ if (!maxBytes) return fs.readFileSync(abs);+ const fd = fs.openSync(abs, "r");+ try {+ const buf = Buffer.alloc(Math.min(maxBytes, fs.fstatSync(fd).size));+ fs.readSync(fd, buf, 0, buf.length, 0);+ return buf;+ } finally {+ fs.closeSync(fd);+ }+ } catch {+ return null;+ }+}++/** Clip headers by URL: a call is checked, priced and run, and a stored file never changes, so it's read once. */+const clips = new Map<string, SourceInfo | null>();++function clipInfo(ref: string): SourceInfo | null {+ if (!clips.has(ref)) {+ const data = localFile(ref);+ clips.set(ref, data ? sourceInfo(data) : null);+ if (clips.size > 32) clips.delete(clips.keys().next().value!);+ }+ return clips.get(ref)!;+}++/** The name the file was uploaded with, without its extension ("beach day"). */+function fileTitle(ref: string): string | undefined {+ const id = /\/([A-Za-z0-9_-]+)\.[a-z0-9]+$/i.exec(ref)?.[1];+ const name = id ? getAsset(id)?.name : null;+ return name?.replace(/\.[a-z0-9]{2,4}$/i, "").replace(/[_-]+/g, " ").trim().slice(0, 80) || undefined;+}++/** A description's first words as a name, capitalised ("claymation, warm light" → "Claymation, warm light"; longer ones end in "…"). */+const shortName = (words: string, max = 40) => {+ const s = words.replace(/\s+/g, " ").trim();+ const cut = s.length > max ? `${s.slice(0, max).replace(/\s+\S*$/, "")}…` : s;+ return cut.charAt(0).toUpperCase() + cut.slice(1);+};++type Checked<T> = T | { problem: string };+const problemOf = <T extends object>(c: Checked<T>): string | null => ("problem" in c ? c.problem : null);+function ok<T extends object>(c: Checked<T>): T {+ if ("problem" in c) throw new Error(c.problem);+ return c;+}++// ---------------------------------------------------------------------------+// Layers: a project on the image, decomposed at once (src/server/layers.ts)++/** The shape the Layers editor sends with a job ("3:2", or "1.78:1" for odd sizes). */+function ratioOf(w: number, h: number): string {+ const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);+ const g = gcd(w, h) || 1;+ return w / g <= 64 && h / g <= 64 ? `${w / g}:${h / g}` : `${(w / h).toFixed(2)}:1`;+}++function layersJob(i: LayersToolInput, ctx: ToolContext): Checked<{ input: LayerJobInput; width: number; height: number; layers: number }> {+ const engine = engineOf(ctx);+ if (!FileUrl.safeParse(i.image).success) return { problem: "Layers opens pictures saved in Fuobe (an upload or a result)" };+ // PNG, JPEG, WebP and GIF keep their size in the first bytes; SVG in its root tag.+ const head = localFile(i.image, 512 * 1024);+ if (!head) return { problem: "That image is gone — upload it again" };+ const size = imageSize(head);+ if (!size) return { problem: "Layers couldn't read that image's size (PNG, JPEG, WebP, GIF or SVG)" };+ const models = TOOL_MODELS.decompose[engine];+ if (i.model_id && !models.includes(i.model_id)) return { problem: `${getModel(i.model_id)?.name ?? i.model_id} isn't one of Layers' decomposition models on this engine` };+ const modelId = i.model_id ?? models[0];+ const layers = clampLayers(modelId, i.layers ?? defaultLayers("decompose", modelId));+ return {+ width: size.width,+ height: size.height,+ layers,+ input: {+ tool: "decompose",+ engine,+ modelId,+ image: i.image,+ prompt: i.focus?.trim() || undefined,+ frame: [0, 0, size.width, size.height],+ label: TOOL_LABELS.decompose,+ settings: { layers, resolution: "1K", mode: "standard", aspect: ratioOf(size.width, size.height) },+ },+ };+}++const layersRoute: StudioRoute<LayersToolInput> = {+ studio: "Layers",+ page: "/layers",+ refuse: (i, ctx) => problemOf(layersJob(i, ctx)),+ plan: (i, ctx) => {+ const job = ok(layersJob(i, ctx));+ // Priced like the editor: Seedream bills each layer it returns (decomposeCost), up to the count asked for.+ const usd = decomposeCost(job.input.modelId!, job.layers, "1K");+ return planSteps("split_layers", jobSteps(job.input)).map((j) =>+ j.op === "layers" ? { ...j, note: `Layer decomposition · up to ${job.layers} layers`, ...(!j.demo && !j.error && usd !== null && { costUsd: usd }) } : j,+ );+ },+ async run(i, ctx) {+ const job = ok(layersJob(i, ctx));+ const view = createProject({ source: i.image, width: job.width, height: job.height });+ const id = view.project.id;+ try {+ const started = startJob(id, job.input);+ return {+ ids: started.generationIds.slice(-1),+ href: `/layers/${id}`,+ info: { project: id, note: "The layers are laid out on the project when it's opened in Layers; each can then be moved, edited, relit or exported." },+ };+ } catch (e) {+ deleteProject(id);+ throw e;+ }+ },+};++// ---------------------------------------------------------------------------+// Shorts Studio: a session on the clip (src/server/shorts.ts)++/** The look: a preset the words name outright, else the words themselves (with any reference images). */+function shortsLook(i: RestyleToolInput): ShortsLook {+ const refs = [...new Set(i.references ?? [])].slice(0, SHORTS.maxReferences);+ const preset = shortsPresetFor(i.style);+ if (preset && !refs.length) return lookFromPreset(preset);+ const words = preset?.look ?? i.style.trim();+ return { presetId: "assist", name: preset?.name ?? shortName(i.style), look: words, ...(refs.length && { references: refs }), custom: true, described: true };+}++function shortsJob(i: RestyleToolInput, ctx: ToolContext): Checked<{ body: ShortsBody; info: SourceInfo; notes: string[] }> {+ const engine = engineOf(ctx);+ if (!i.video.startsWith("/api/files/")) return { problem: "Shorts Studio restyles clips saved in Fuobe (an upload or a result)" };+ if (i.model_id && !SHORTS_MODELS[engine].includes(i.model_id)) return { problem: `${getModel(i.model_id)?.name ?? i.model_id} isn't one of Shorts Studio's restyle models on this engine` };+ const info = clipInfo(i.video);+ if (!info) return { problem: "That clip is gone — upload it again" };+ if (!info.duration) return { problem: "Shorts Studio couldn't read how long the clip is (it reads MP4, MOV and WebM)" };+ if (info.duration < SHORTS.minSeconds - 0.05) return { problem: `Shorts Studio restyles clips of ${SHORTS.minSeconds} s or more` };+ const notes: string[] = [];+ const end = Math.min(info.duration, SHORTS.maxSeconds);+ if (end < info.duration) notes.push(`Shorts Studio restyles up to ${SHORTS.maxSeconds / 60} minutes: the first ${SHORTS.maxSeconds / 60} of this clip`);+ const look = shortsLook(i);+ const body: ShortsBody = {+ engine,+ presetId: look.presetId,+ look,+ source: { url: i.video, name: fileTitle(i.video), duration: info.duration, width: info.width, height: info.height },+ range: { start: 0, end },+ // The clip keeps its orientation.+ aspectRatio: info.width && info.height && info.width > info.height ? "16:9" : "9:16",+ language: "auto",+ modelId: i.model_id,+ };+ try {+ notes.push(...estimateWith(body, info).notes);+ } catch (e) {+ return { problem: (e as Error).message };+ }+ return { body, info, notes };+}++const shortsRoute: StudioRoute<RestyleToolInput> = {+ studio: "Shorts Studio",+ page: "/shorts",+ refuse: (i, ctx) => problemOf(shortsJob(i, ctx)),+ plan: (i, ctx) => {+ const { body, info, notes } = ok(shortsJob(i, ctx));+ const est = estimateWith(body, info);+ const modelId = body.modelId ?? SHORTS_MODELS[body.engine][0];+ const job: PlannedJob = {+ tool: "restyle_footage",+ modelId,+ modelName: getModel(modelId)?.name ?? modelId,+ kind: "video",+ op: "v2v",+ prompt: body.look!.look,+ count: 1,+ costUsd: est.costUsd,+ demo: est.demo,+ note: [`${est.segments} segment${est.segments === 1 ? "" : "s"} of ${est.seconds} s, stitched under the original sound`, ...notes].join(" · "),+ atomic: true,+ };+ return [job];+ },+ async run(i, ctx) {+ const { body, info } = ok(shortsJob(i, ctx));+ const s = await createSession(body, info);+ return {+ ids: [s.stitches[0].final],+ href: `/shorts/${s.id}`,+ info: { session: s.id, segments: s.segments.length, note: "Each segment can be regenerated or swapped for another take in Shorts Studio, then stitched again." },+ };+ },+};++// ---------------------------------------------------------------------------+// Translate & dub: a dub session, reviewed in Audio → Translate (src/server/dub.ts)++const ONE_SHOT_NAMES: Record<OneShotModel, string> = { "heygen-translate": "HeyGen Translate", "heygen-translate-fast": "HeyGen Translate Speed", "elevenlabs-dubbing": "ElevenLabs Dubbing" };++function dubJob(i: DubToolInput, ctx: ToolContext): Checked<{ input: CreateDubInput; names: string[] }> {+ const engine = engineOf(ctx);+ if (!i.video.startsWith("/api/files/")) return { problem: "Translate & dub works on videos saved in Fuobe (an upload or a result)" };+ const asked = [...new Set(i.languages.map((l) => l.trim()).filter(Boolean))].slice(0, 4);+ if (!asked.length) return { problem: "Name the language to dub into" };+ const langs = asked.map((l) => ({ asked: l, lang: dubLanguageFor(l) }));+ const unknown = langs.find((l) => !l.lang);+ if (unknown) return { problem: `Translate & dub doesn't list ${unknown.asked}` };+ const review = i.review !== false;+ if (!review && engine === "open") return { problem: "Dubbing in one go is a cloud service; on the open engine Translate & dub reviews the lines first" };+ const model: OneShotModel | undefined = review ? undefined : i.lipsync === false ? "elevenlabs-dubbing" : "heygen-translate";+ const input: CreateDubInput = {+ engine,+ mode: review ? "steps" : "oneshot",+ video: i.video,+ title: fileTitle(i.video),+ source: (i.source_language && dubLanguageFor(i.source_language)?.code) || "auto",+ targets: [...new Set(langs.map((l) => l.lang!.code))],+ ...(model && { model }),+ };+ try {+ previewDub(input);+ } catch (e) {+ return { problem: (e as Error).message };+ }+ return { input, names: langs.map((l) => l.lang!.name) };+}++const dubRoute: StudioRoute<DubToolInput> = {+ studio: "Translate & dub",+ page: modeHref("audio", "translate"),+ refuse: (i, ctx) => problemOf(dubJob(i, ctx)),+ plan: (i, ctx) => {+ const { input, names } = ok(dubJob(i, ctx));+ const price = previewDub(input);+ const oneshot = input.mode === "oneshot";+ const extra = price.unpriced.length ? ` · plus ${price.unpriced.join(" and ")} at the provider's own rate` : "";+ const job: PlannedJob = {+ tool: "dub_video",+ modelId: input.model ?? DUB_STEP_MODELS[input.engine].translate,+ modelName: oneshot ? ONE_SHOT_NAMES[input.model!] : "Translate & dub",+ kind: oneshot ? "video" : "text",+ op: oneshot ? "dub" : "translate",+ prompt: `Into ${names.join(", ")}`,+ count: input.targets.length,+ costUsd: price.costUsd,+ demo: price.demo,+ note: oneshot+ ? `Dubbed in one go${input.model === "elevenlabs-dubbing" ? ", no lip re-sync" : ", lip-synced"}${extra}`+ : `Transcribe and translate (${price.steps} steps)${extra} · then review every line and voice it in Translate & dub, priced there`,+ atomic: true,+ };+ return [job];+ },+ async run(i, ctx) {+ const { input } = ok(dubJob(i, ctx));+ const s = createDubSession(input);+ const steps = s.mode === "steps";+ const ids = steps ? s.targets.map((c) => s.prepare?.[translateKey(c)]).filter((x): x is string => !!x) : Object.values(s.oneshot ?? {});+ return {+ ids,+ href: modeHref("audio", "translate", { dub: s.id }),+ info: {+ dub: s.id,+ ...(steps && {+ next: `Once the translation is ready, the user reviews every line in Translate & dub and presses Voice${i.lipsync === false ? " (with Lip sync switched off)" : ""}; the dubbed video is made then.`,+ }),+ },+ };+ },+};++// ---------------------------------------------------------------------------+// Faceless Studio: an episode on the "Assist" channel (src/server/faceless.ts)++/** The channel Assist's episodes go to, made the first time (no avatar is drawn for it). */+export const ASSIST_CHANNEL = "Assist";++async function assistChannel(engine: Engine): Promise<string> {+ const found = listChannels().find((c) => c.name === ASSIST_CHANNEL);+ if (found) return found.id;+ const c = await createChannel({ idea: "Narrated episodes made from Fuobe Assist chats", genre: "education", engine, name: ASSIST_CHANNEL, avatar: false });+ return c.id;+}++function facelessJob(i: FacelessToolInput, ctx: ToolContext): Checked<{ settings: EpisodeSettings; blocks: { narration: string; visual: string }[]; title: string }> {+ const engine = engineOf(ctx);+ const aspect = (i.aspect_ratio ?? "9:16") as EpisodeAspect;+ if (aspect !== "9:16" && aspect !== "16:9") return { problem: "Faceless Studio makes 16:9 and 9:16 episodes" };+ const styleId = i.style_id ?? facelessStyleFor(i.style);+ if (!styleId) return { problem: `“${shortName(i.style, 60)}” isn't one of Faceless Studio's styles (pass style_id to open it there)` };+ const blocks = i.scenes.filter((s) => s.visual.trim() || s.narration.trim()).slice(0, 8);+ if (blocks.length < 2) return { problem: "Give at least 2 scenes" };+ const sample = i.voice_sample?.trim();+ const base = defaultSettings(engine, genreInfo("education"));+ const voice: NarratorVoice | null = sample ? { kind: "sample", url: sample } : engine === "cloud" && i.voice ? { kind: "preset", id: i.voice } : base.voice;+ return {+ settings: { ...base, aspect, styleId, voice },+ blocks: blocks.map((b) => ({ narration: b.narration, visual: b.visual })),+ title: i.title?.trim() || blocks[0].narration.trim().slice(0, 80) || "Faceless episode",+ };+}++const PART_JOB: Record<StepPart, { kind: MediaKind; op: Operation }> = {+ still: { kind: "image", op: "t2i" },+ clip: { kind: "video", op: "i2v" },+ join: { kind: "video", op: "concat" },+ narration: { kind: "audio", op: "tts" },+ music: { kind: "audio", op: "music" },+ mix: { kind: "video", op: "mux" },+ words: { kind: "text", op: "transcribe" },+ captions: { kind: "video", op: "captions" },+};++const facelessRoute: StudioRoute<FacelessToolInput> = {+ studio: "Faceless Studio",+ page: "/faceless",+ refuse: (i, ctx) => problemOf(facelessJob(i, ctx)),+ plan: (i, ctx) => {+ const { settings, blocks, title } = ok(facelessJob(i, ctx));+ // The studio's own estimate: every step of the episode graph, by part (pictures, animation, narration…).+ const est = estimateEpisode({ kind: "faceless", settings, blocks, genre: "education" });+ const parts = Object.entries(est.estimate.parts) as [StepPart, number][];+ const jobs: PlannedJob[] = parts.map(([part, usd], k) => ({+ tool: "faceless_episode",+ modelId: `faceless-${part}`,+ modelName: PART_LABELS[part],+ ...PART_JOB[part],+ prompt: k === 0 ? `${title} · ${est.blocks} scenes, about ${Math.round(est.seconds)} s` : PART_LABELS[part],+ count: part === "still" ? est.blocks : 1,+ costUsd: usd,+ demo: est.demo,+ note: `Faceless Studio · ${PART_LABELS[part]}`,+ atomic: true,+ }));+ if (!jobs.length) jobs.push({ tool: "faceless_episode", modelId: "faceless", modelName: "Faceless episode", kind: "video", op: "concat", prompt: title, count: 1, costUsd: null, demo: est.demo, atomic: true });+ if (est.error) jobs[0] = { ...jobs[0], error: est.error };+ if (est.notes?.length) jobs[jobs.length - 1] = { ...jobs[jobs.length - 1], note: `${jobs[jobs.length - 1].note} · ${est.notes.join(" ")}` };+ return jobs;+ },+ async run(i, ctx) {+ const { settings, blocks, title } = ok(facelessJob(i, ctx));+ const channelId = await assistChannel(settings.engine);+ const ep = createEpisode({ kind: "faceless", channelId, topic: title, settings, blocks, autoRender: true, saveLook: false });+ const href = `/faceless/${channelId}/${ep.id}`;+ if (ep.status !== "rendering") throw new Error(`${ep.error ?? "The episode couldn't start"} — it's in Faceless Studio to fix: ${href}`);+ const stills = Object.entries(ep.plan?.ids ?? {})+ .filter(([k]) => k.startsWith("still-"))+ .map(([, id]) => id);+ return {+ ids: stills.slice(0, 8),+ href,+ info: {+ episode: ep.id,+ channel: channelId,+ style: settings.styleId,+ note: "The pictures and the narration come first; once the narration is timed, each scene is animated and cut to its lines, then music and subtitles are mixed in. The finished episode is in Faceless Studio.",+ },+ };+ },+};++// ---------------------------------------------------------------------------+// Ads Studio: a batch for a product, on its brand kit (src/server/ads.ts)++/** The kit "Describe your business" would make from the brief, before the LLM fills it in (for pricing only). */+function draftKit(brief: string, name: string): BrandKit {+ const h = heuristicManualKit(brief);+ return {+ ...emptyKit(h.name || name),+ tagline: h.tagline,+ overview: brief,+ colors: h.colors ?? [],+ fonts: h.fonts ?? {},+ aesthetics: h.aesthetics ?? [],+ tone: h.tone ?? [],+ id: "draft",+ status: "ready",+ source: "manual",+ createdAt: 0,+ updatedAt: 0,+ };+}++/** A product's name from the brief: its first words ("Oat milk for runners"). */+const productName = (brief: string) => shortName(brief.split(/[.,;:!?\n—–]/)[0] || brief, 48).replace(/…$/, "");++function adsJob(i: AdsToolInput, ctx: ToolContext): Checked<{ input: BatchInput; brand: BrandKit | null; product: Product | null; draft: { brand: BrandKit; product: Product | null }; name: string }> {+ const engine = engineOf(ctx);+ const ratios = [...new Set(i.aspect_ratios?.length ? i.aspect_ratios : ["4:5"])];+ const odd = ratios.filter((r) => !(AD_RATIOS as readonly string[]).includes(r));+ if (odd.length) return { problem: `Ads Studio makes 1:1, 4:5 and 9:16 ads (not ${odd.join(", ")})` };+ if (i.product_image && !i.product_image.startsWith("/api/files/")) return { problem: "Ads Studio uses product photos saved in Fuobe (an upload or a result)" };+ const brand = i.brand_id ? getBrand(i.brand_id) : null;+ if (i.brand_id && !brand) return { problem: "That brand kit isn't in Ads Studio" };+ if (brand?.status === "researching") return { problem: "That brand's research is still running" };+ const product = i.product_id ? getProduct(i.product_id) : null;+ if (i.product_id && (!product || (brand && product.brandId !== brand.id))) return { problem: "That product isn't in Ads Studio" };+ const name = product?.name ?? productName(i.brief);+ // Before anything is saved, the price is worked out on stand-ins: the kit a description gives, the product as it'll be.+ const kit = brand ?? (product?.brandId ? getBrand(product.brandId) : null);+ const draftBrand: BrandKit = kit ?? draftKit(i.brief, name);+ const draftProduct: Product = product ?? { id: "draft", brandId: kit?.id ?? null, name, description: i.brief, sellingPoints: [], images: i.product_image ? [i.product_image] : [], createdAt: 0, updatedAt: 0 };+ const direction = [i.brief.trim(), i.headline && `Headline: “${i.headline.trim()}”`, i.cta && `Call to action: “${i.cta.trim()}”`].filter(Boolean).join(". ").slice(0, 1000);+ const input: BatchInput = {+ brandId: kit?.id ?? "draft",+ engine,+ // Several formats need Fuobe's compositor (every ad in 1:1, 4:5 and 9:16); Higgsfield renders one format per ad.+ ...(ratios.length > 1 && { route: "fuobe" as const }),+ items: [{ productId: draftProduct.id, count: Math.max(1, Math.min(8, i.count ?? 4)) }],+ direction,+ ratio: ratios[0] as AdRatio,+ };+ try {+ estimateBatch(input, { brand: draftBrand, product: draftProduct });+ } catch (e) {+ return { problem: (e as Error).message };+ }+ return { input, brand: kit, product, draft: { brand: draftBrand, product: draftProduct }, name };+}++/** The product the ads are for: the one named, else one made from the brief (a product of the same name gets the new photo). */+function adsProduct(brandId: string, name: string, i: AdsToolInput): Product {+ const images = i.product_image ? [i.product_image] : [];+ try {+ return createProduct({ name, brandId, description: i.brief, images });+ } catch (e) {+ if (!(e instanceof DuplicateProductError)) throw e;+ const same = listProducts(brandId).find((p) => p.name.toLowerCase() === name.toLowerCase())!;+ return images.length ? (updateProduct(same.id, { images: [...images, ...same.images.filter((u) => !images.includes(u))] }) ?? same) : same;+ }+}++const adsRoute: StudioRoute<AdsToolInput> = {+ studio: "Ads Studio",+ page: "/ads",+ refuse: (i, ctx) => problemOf(adsJob(i, ctx)),+ plan: (i, ctx) => {+ const { input, draft } = ok(adsJob(i, ctx));+ const est = estimateBatch(input, draft);+ const job: PlannedJob = {+ tool: "create_ads",+ modelId: est.modelId,+ modelName: est.route === "higgsfield" ? "Higgsfield Ads Studio" : est.modelName,+ kind: "image",+ op: draft.product?.images.length ? "edit" : "t2i",+ prompt: i.brief,+ count: est.total,+ costUsd: est.costUsd,+ demo: est.demo,+ note:+ est.route === "higgsfield"+ ? `${est.total} finished ad${est.total === 1 ? "" : "s"} in ${input.ratio}`+ : `${est.total} ad${est.total === 1 ? "" : "s"} · copy by ${est.copyBy === "llm" ? "the AI copywriter" : "the offline copywriter"} · each in 1:1, 4:5 and 9:16`,+ atomic: true,+ };+ return [job];+ },+ async run(i, ctx) {+ const job = ok(adsJob(i, ctx));+ // A brief without a brand kit gets one of its own, the way Ads Studio's "Describe your business" makes+ // it; the same product asked for again goes back to the kit it's in.+ const again = job.brand ? null : listProducts().find((p) => p.brandId && p.name.toLowerCase() === job.name.toLowerCase());+ const brand = job.brand ?? (again ? getBrand(again.brandId!) : null) ?? (await createManualBrand({ description: i.brief }));+ const product = job.product ?? adsProduct(brand.id, job.name, i);+ const { batchId, run } = createBatch({ ...job.input, brandId: brand.id, items: [{ productId: product.id, count: job.input.items[0].count }] }, { headline: i.headline, cta: i.cta });+ // The copy is written first (one LLM call), then each ad's picture starts: wait for that, not for the pictures.+ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([run, new Promise((r) => (timer = setTimeout(r, 30_000)))]).finally(() => clearTimeout(timer));+ const ads = listCreatives({ brandId: brand.id, batchId });+ return {+ ids: ads.flatMap((c) => (c.generationId ? [c.generationId] : [])),+ href: `/ads/${brand.id}`,+ info: {+ brand: brand.id,+ product: product.id,+ batch: batchId,+ ads: ads.map((c) => ({ headline: c.headline, cta: c.cta, status: c.status })),+ note: "In Ads Studio each ad is laid out with the headline, body and call to action in 1:1, 4:5 and 9:16; the words can be edited there and everything downloaded at once.",+ },+ };+ },+};++// ---------------------------------------------------------------------------+// Captions (Video tools → Captions): the studio's jobs, then its editor opened on the video++const CAPTION_LOOK: CaptionLook = { style: "clean", size: "M", position: "bottom" };++/** Per-second and per-minute steps priced for the video's length, as the studio's notes price them. */+const timed = (r: GenerationRequest, seconds?: number): GenerationRequest => {+ const unit = getModel(r.modelId)?.pricing?.unit;+ return seconds && (unit === "second" || unit === "minute") && r.params?.duration === undefined ? { ...r, params: { ...r.params, duration: seconds } } : r;+};++function captionsJob(i: CaptionsToolInput, ctx: ToolContext): Checked<{ steps: PipelineStep[]; route: BurnRoute; transcript?: string; seconds?: number }> {+ const engine = engineOf(ctx);+ if (!i.video.startsWith("/api/files/")) return { problem: "Captions works on videos saved in Fuobe (an upload or a result)" };+ const spoken = i.spoken_language ? dubLanguageFor(i.spoken_language)?.code : undefined;+ const seconds = videoLength(i.video);+ const route: BurnRoute = engine === "open" ? "open" : i.translate_to ? "veed" : "auto";+ const steps: PipelineStep[] = [];+ let transcript: string | undefined;+ if (engine === "cloud") {+ if (i.translate_to) {+ // VEED Subtitles transcribes, translates and burns in one job.+ steps.push({+ key: "captions",+ request: { feature: CAPTIONS_FEATURE, modelId: BURN_MODELS.veed, op: "captions", inputs: { video: i.video }, params: { sourceLanguage: i.spoken_language, targetLanguage: i.translate_to }, title: `Captions · ${i.translate_to}`, step: { label: `Captions in ${i.translate_to}`, index: 0, of: 1 } },+ });+ } else {+ // The studio's quick karaoke burn, plus the transcript its editor opens with (fix a line, burn again).+ steps.push(+ { key: "words", request: { ...transcribeRequest({ engine, video: i.video, sourceLanguage: spoken }), step: { label: "Transcript", index: 0, of: 2 } } },+ { key: "captions", request: { ...burnRequest({ route, video: i.video, cues: [], look: lookFor(route, CAPTION_LOOK), sourceLanguage: spoken }), step: { label: "Captioned video", index: 1, of: 2 } } },+ );+ transcript = "words";+ }+ } else {+ // Open engine: Qwen3-ASR's timed lines (translated by the local LLM when asked) burned in by ComfyUI.+ const n = i.translate_to ? 3 : 2;+ steps.push({ key: "words", request: { ...transcribeRequest({ engine, video: i.video, sourceLanguage: spoken }), step: { label: "Transcript", index: 0, of: n } } });+ if (i.translate_to) {+ steps.push({ key: "tr", after: "words", chain: [{ slot: "prompt" }], request: { feature: CAPTIONS_FEATURE, modelId: "oss-text-llm", op: "translate", params: { targetLanguage: i.translate_to }, step: { label: `Translation · ${i.translate_to}`, index: 1, of: n } } });+ }+ const look = lookFor(route, CAPTION_LOOK);+ const style = styleById(look.style);+ transcript = i.translate_to ? "tr" : "words";+ steps.push({+ key: "captions",+ after: transcript,+ chain: [{ slot: "prompt" }],+ request: {+ feature: CAPTIONS_FEATURE,+ modelId: BURN_MODELS.open,+ op: "captions",+ inputs: { video: i.video },+ params: { extra: { fontSize: OPEN_FONT_SIZE[look.size], fontColor: style.color, captionPosition: look.position === "top" ? "top" : "bottom", wordsPerCaption: style.karaoke ? 3 : 0 } },+ title: `Captions · ${style.name}`,+ step: { label: "Captioned video", index: n - 1, of: n },+ },+ });+ }+ return { steps: steps.map((s) => ({ ...s, request: timed(s.request, seconds) })), route, transcript, seconds };+}++const captionsRoute: StudioRoute<CaptionsToolInput> = {+ studio: "Captions",+ page: modeHref("video-tools", "captions"),+ refuse: (i, ctx) => problemOf(captionsJob(i, ctx)),+ plan: (i, ctx) => {+ const { steps, route, seconds } = ok(captionsJob(i, ctx));+ // The burn at the studio's own rate per minute (VEED's dynamic styles cost double).+ const burn = seconds && route !== "open" ? Math.round(burnPricePerMinute(route, CAPTION_LOOK.style) * (seconds / 60) * 1000) / 1000 : null;+ return planSteps("add_captions", steps).map((j) => (j.op === "captions" && burn !== null && !j.demo && !j.error ? { ...j, costUsd: burn } : j));+ },+ async run(i, ctx) {+ const { steps, transcript } = ok(captionsJob(i, ctx));+ const p = createPipeline(steps.map((s) => ({ ...s, request: { ...s.request, batchTitle: i.translate_to ? `Captions in ${i.translate_to}` : "Captions" } })));+ const words = transcript ? p.byKey[transcript].id : undefined;+ return {+ ids: [p.byKey.captions.id],+ // The Captions editor opens on the video with these lines loaded (it keeps no session of its own).+ href: modeHref("video-tools", "captions", { video: i.video, ...(words && { transcript: words }) }),+ info: { note: "The captioned video is listed under Captioned videos in Captions; the editor there opens on this video with its lines, to fix any line or restyle and burn again." },+ };+ },+};++STUDIO_ROUTES.split_layers = layersRoute;+STUDIO_ROUTES.restyle_footage = shortsRoute;+STUDIO_ROUTES.dub_video = dubRoute;+STUDIO_ROUTES.faceless_episode = facelessRoute;+STUDIO_ROUTES.create_ads = adsRoute;+STUDIO_ROUTES.add_captions = captionsRoute;diff --git a/src/server/assist/studio-tools.ts b/src/server/assist/studio-tools.tsindex 86179b75..308464ba 100644--- a/src/server/assist/studio-tools.ts+++ b/src/server/assist/studio-tools.ts@@ -4,37 +4,46 @@ import { z } from "zod";import type { PlannedJob } from "@/lib/assist";import { getModel } from "@/lib/catalog";import { routesFor } from "@/lib/catalog/plan";+import { FACELESS_STYLE_IDS, STYLES } from "@/lib/catalog/faceless";import type { ChainSlot, Engine, GenerationRequest, Operation } from "@/lib/catalog/types";import { createPipeline, type PipelineStep } from "../chains";import { db } from "../db";import { chooseRoute, createGenerations, outputKind, previewChained } from "../generations";import { engineMode } from "../settings";import { fileUrl, saveFile } from "../storage";-import { defineTool, type ToolContext, type ToolOutcome } from "./define";+import { defineTool, type JobPlace, type ToolContext, type ToolOutcome } from "./define";/*** Agent access to whole studios: split an image into layers, restyle footage, dub a video, make a- * faceless episode, a batch of ads, captions. Each tool runs the studio's own module when one is- * wired into STUDIO_ROUTES (so the job shows up in that studio), and otherwise builds the same job- * from catalog models with createPipeline — the studios that aren't in this build still work- * from Assist and MCP, just without their own page.+ * faceless episode, a batch of ads, captions. Each tool runs the studio's own module through its+ * STUDIO_ROUTES entry (filled by ./studio-routes.ts), so the job opens in that studio: a Layers+ * project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions+ * editor. When the studio can't take a call (an input or engine it doesn't offer: its `refuse` says+ * why), or no entry is wired in, the tool builds the same job from catalog models with createPipeline+ * and the results land in the Library.*/// ----------------------------------------------------------------------------// Wiring for the studio modules (set at merge; see the report for each adapter)+// Wiring for the studio modules (src/server/assist/studio-routes.ts fills STUDIO_ROUTES)/** What a studio module returns when it takes a job: the generations to show and its page. */export interface StudioRun {/** Generation ids to show in the chat (the finished results first). */ids: string[];/** The studio page for this job, e.g. /layers/<id>. */- href?: string;- /** Extra facts for the agent (session id, segments, steps). */+ href: string;+ /** Extra facts for the agent (session id, segments, steps, what to do next). */info?: Record<string, unknown>;}export interface StudioRoute<I> {- /** Price the job; the built-in plan is used when absent. */+ /** The studio as the chat names it: "Open in Layers". */+ studio: string;+ /** Its page before the job exists ("/layers"), for estimates. */+ page: string;+ /** Why the studio can't take this call (the tool then runs its own pipeline, in the Library), or null. */+ refuse?: (input: I, ctx: ToolContext) => string | null;+ /** Price the job the way the studio prices it; the built-in plan is used when absent. */plan?: (input: I, ctx: ToolContext) => PlannedJob[];run: (input: I, ctx: ToolContext) => Promise<StudioRun>;}@@ -43,7 +52,7 @@ const ref = z.string().describe("A file URL from the chat: an attachment, a projconst LayersInput = z.object({image: ref.describe("The image to split."),- layers: z.number().int().optional().describe("How many layers (2–8, default 4)."),+ layers: z.number().int().optional().describe("How many layers (2–8; the Layers studio starts at 8, Seedream decides how many it returns)."),focus: z.string().optional().describe("What to separate, e.g. 'the person, the product, the headline text, the background'."),model_id: z.string().optional().describe("A layers model from search_models (task layers); default: the engine's best."),});@@ -58,6 +67,12 @@ const DubInput = z.object({languages: z.array(z.string()).describe("1–4 languages to dub into, e.g. ['Spanish', 'German']."),lipsync: z.boolean().optional().describe("Re-sync the lips to the new speech (default true)."),source_language: z.string().optional().describe("The language spoken in the video, if known."),+ review: z+ .boolean()+ .optional()+ .describe(+ "Default true: transcribe and translate, then the user reviews every line in Translate & dub and voices it there. false: dub in one go (cloud: HeyGen Translate, or ElevenLabs Dubbing without lip sync; open source: every step as one pipeline in the Library).",+ ),});const FacelessInput = z.object({title: z.string().optional().describe("The episode title."),@@ -70,7 +85,13 @@ const FacelessInput = z.object({).describe("2–8 scenes in order."),style: z.string().describe("The visual style for every scene, e.g. 'flat 2D illustration, muted palette'."),- aspect_ratio: z.string().optional().describe("9:16 (default), 16:9 or 1:1."),+ style_id: z+ .enum(STYLES.map((x) => x.id) as [string, ...string[]])+ .optional()+ .describe(+ `Faceless Studio's style for the episode (the faceless-video skill describes them): ${FACELESS_STYLE_IDS.join(", ")}; the Explainer's ${STYLES.filter((x) => !FACELESS_STYLE_IDS.includes(x.id)).map((x) => x.id).join(", ")} work too. Without it the style is matched from your words.`,+ ),+ aspect_ratio: z.string().optional().describe("9:16 (default) or 16:9; 1:1 runs outside Faceless Studio."),voice: z.string().optional().describe("A premade narrator voice id for the cloud engine (search_models kind audio lists them)."),voice_sample: ref.optional()@@ -373,6 +394,55 @@ function adRequests(i: AdsToolInput, ctx: ToolContext): GenerationRequest[] {// ---------------------------------------------------------------------------// The tools+/** The studio route that takes a call, or why the call runs as the tool's own pipeline (neither: no route is wired in). */+function routeFor<I>(route: StudioRoute<I> | undefined, input: I, ctx: ToolContext): { route?: StudioRoute<I>; why?: string } {+ if (!route) return {};+ let why: string | null;+ try {+ why = route.refuse?.(input, ctx) ?? null;+ } catch (e) {+ why = (e as Error).message;+ }+ return why ? { why } : { route };+}++/** Where a call's job will open, for the approval card and estimate_job. */+function placeFor<I>(route: StudioRoute<I> | undefined, input: I, ctx: ToolContext): JobPlace {+ const r = routeFor(route, input, ctx);+ if (r.route) return { studio: r.route.studio, href: r.route.page };+ return r.why ? { fallback: inLibrary(r.why) } : {};+}++const inLibrary = (why: string) => `${why.replace(/[.\s]+$/, "")} — so it runs as separate steps in your Library`;++/** The studio's price when it takes the call, else the tool's own plan. Never throws: a failure is the card's error. */+function planVia<I>(tool: string, route: StudioRoute<I> | undefined, input: I, ctx: ToolContext, own: () => PlannedJob[]): PlannedJob[] {+ const r = routeFor(route, input, ctx).route;+ if (!r?.plan) return own();+ try {+ return r.plan(input, ctx);+ } catch (e) {+ return [{ tool, modelId: tool, modelName: r.studio, kind: "video", op: "v2v", prompt: r.studio, note: r.studio, count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];+ }+}++/** Run through the studio when it takes the call; otherwise the tool's own job, with the reason. */+async function runVia<I>(route: StudioRoute<I> | undefined, input: I, ctx: ToolContext, label: string, own: () => ToolOutcome | Promise<ToolOutcome>): Promise<ToolOutcome> {+ const r = routeFor(route, input, ctx);+ if (r.route) return viaStudio(r.route, input, ctx, label);+ const out = await own();+ if (!r.why || out.isError) return out;+ // Say why it isn't in the studio: to the agent in the result, to the user under the cards.+ const why = inLibrary(r.why);+ let body: Record<string, unknown> | null = null;+ try {+ body = typeof out.content === "string" ? (JSON.parse(out.content) as Record<string, unknown>) : null;+ } catch {+ body = null;+ }+ return { ...out, ...(body && { content: JSON.stringify({ ...body, ranIn: "Library", why }) }), items: [...(out.items ?? []), { id: "", role: "notice", tone: "info", text: `${why}.` }] };+}+function startPipeline(tool: string, steps: PipelineStep[], title: string, show: "last" | "all" = "last"): ToolOutcome {const p = createPipeline(steps.map((s) => ({ ...s, request: { ...s.request, batchTitle: title.slice(0, 200) } })));const final = p.items.at(-1)!;@@ -392,129 +462,135 @@ function startPipeline(tool: string, steps: PipelineStep[], title: string, show:};}-async function viaStudio<I>(route: StudioRoute<I> | undefined, input: I, ctx: ToolContext, label: string): Promise<ToolOutcome | null> {- if (!route) return null;+async function viaStudio<I>(route: StudioRoute<I>, input: I, ctx: ToolContext, label: string): Promise<ToolOutcome> {const r = await route.run(input, ctx);return {- content: JSON.stringify({ results: r.ids, ...(r.href && { open: r.href }), ...r.info }),- items: [{ id: "", role: "tool", text: label, ...(r.href && { href: r.href }) }, ...(r.ids.length ? [{ id: "", role: "generations" as const, ids: r.ids }] : [])],+ // href is a path on this Fuobe server: the job's page in its studio.+ content: JSON.stringify({ studio: route.studio, href: r.href, results: r.ids, ...r.info }),+ items: [{ id: "", role: "tool", text: label, href: r.href, studio: route.studio }, ...(r.ids.length ? [{ id: "", role: "generations" as const, ids: r.ids }] : [])],};}const splitLayers = defineTool({name: "split_layers",description:- "Split an image into separate transparent layers (person, product, text, background…) for editing — Fuobe's Layers studio. Use it for 'separate the layers', 'make this editable', 'cut everything out into layers'. Gated by the same approval card as generate.",+ "Split an image into separate transparent layers (person, product, text, background…) for editing — opens a project in Fuobe's Layers studio, where the user moves, edits and exports them. Use it for 'separate the layers', 'make this editable', 'cut everything out into layers'. Gated by the same approval card as generate.",schema: LayersInput,gated: true,title: () => "Split into layers",- plan: (i, ctx) => STUDIO_ROUTES.split_layers?.plan?.(i, ctx) ?? planSteps("split_layers", layerSteps(i, ctx)),+ place: (i, ctx) => placeFor(STUDIO_ROUTES.split_layers, i, ctx),+ plan: (i, ctx) => planVia("split_layers", STUDIO_ROUTES.split_layers, i, ctx, () => planSteps("split_layers", layerSteps(i, ctx))),async run(i, ctx) {- return (await viaStudio(STUDIO_ROUTES.split_layers, i, ctx, "Opened a Layers project")) ?? startPipeline("Layers", layerSteps(i, ctx), "Layers", "all");+ return runVia(STUDIO_ROUTES.split_layers, i, ctx, "Opened a Layers project", () => startPipeline("Layers", layerSteps(i, ctx), "Layers", "all"));},});const restyleFootage = defineTool({name: "restyle_footage",description:- "Restyle the user's own footage into a new look (anime, claymation, oil paint, a reference image's style) while keeping its motion — Fuobe's Shorts / Mixed Media studio. Use it for 'turn my clip into…', 'restyle this video'. Gated by the same approval card as generate.",+ "Restyle the user's own footage into a new look (anime, claymation, oil paint, a reference image's style) while keeping its motion — a session in Fuobe's Shorts Studio: the clip is cut into segments, each restyled, then stitched under the original sound; the user can regenerate a segment there. Use it for 'turn my clip into…', 'restyle this video'. Gated by the same approval card as generate.",schema: RestyleInput,gated: true,title: (i) => `Restyle: ${i.style.slice(0, 60)}`,- plan: (i, ctx) => STUDIO_ROUTES.restyle_footage?.plan?.(i, ctx) ?? planSteps("restyle_footage", restyleSteps(i, ctx)),+ place: (i, ctx) => placeFor(STUDIO_ROUTES.restyle_footage, i, ctx),+ plan: (i, ctx) => planVia("restyle_footage", STUDIO_ROUTES.restyle_footage, i, ctx, () => planSteps("restyle_footage", restyleSteps(i, ctx))),async run(i, ctx) {- return (await viaStudio(STUDIO_ROUTES.restyle_footage, i, ctx, "Started a Shorts restyle")) ?? startPipeline("Restyle", restyleSteps(i, ctx), `Restyle: ${i.style}`);+ return runVia(STUDIO_ROUTES.restyle_footage, i, ctx, "Started a Shorts restyle", () => startPipeline("Restyle", restyleSteps(i, ctx), `Restyle: ${i.style}`));},});const dubVideo = defineTool({name: "dub_video",description:- "Dub a video into 1–4 other languages in the speaker's own voice, optionally lip-synced, keeping the background sound — Fuobe's Translate & dub studio. One approval runs every step (voice separation, transcript, translation, voice, lip sync, mix). Gated by the same approval card as generate.",+ "Dub a video into 1–4 other languages in the speaker's own voice, optionally lip-synced, keeping the background sound — a dub in Fuobe's Translate & dub studio (Audio → Translate). By default the speech is transcribed and translated, then the user reviews every line there and voices it (that step is priced there); review=false dubs in one go. Gated by the same approval card as generate.",schema: DubInput,gated: true,title: (i) => `Dub into ${i.languages.join(", ")}`,- plan: (i, ctx) => {- if (STUDIO_ROUTES.dub_video?.plan) return STUDIO_ROUTES.dub_video.plan(i, ctx);- try {- return planSteps("dub_video", dubSteps(i, ctx));- } catch (e) {- return [{ tool: "dub_video", modelId: "dub", modelName: "Translate & dub", kind: "video", op: "dub", prompt: i.languages.join(", "), count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];- }- },+ place: (i, ctx) => placeFor(STUDIO_ROUTES.dub_video, i, ctx),+ plan: (i, ctx) =>+ planVia("dub_video", STUDIO_ROUTES.dub_video, i, ctx, () => {+ try {+ return planSteps("dub_video", dubSteps(i, ctx));+ } catch (e) {+ return [{ tool: "dub_video", modelId: "dub", modelName: "Translate & dub", kind: "video", op: "dub", prompt: i.languages.join(", "), count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];+ }+ }),async run(i, ctx) {- return (await viaStudio(STUDIO_ROUTES.dub_video, i, ctx, "Started a dub")) ?? startPipeline("Dub", dubSteps(i, ctx), `Dub into ${i.languages.join(", ")}`);+ return runVia(STUDIO_ROUTES.dub_video, i, ctx, "Started a dub", () => startPipeline("Dub", dubSteps(i, ctx), `Dub into ${i.languages.join(", ")}`));},});const facelessEpisode = defineTool({name: "faceless_episode",description:- "Make a narrated faceless video from scenes you wrote: a still and an animated clip per scene in one style, the narration, joined into one episode — Fuobe's Faceless studio. Write the narration and visuals first (load the faceless-video skill), then call this once. On the open-source engine the narration clones voice_sample, so ask the user for a recording (or a saved voice) when there is none. Gated by the same approval card as generate.",+ "Make a narrated faceless video from scenes you wrote — an episode in Fuobe's Faceless Studio: a picture and an animated clip per scene in one style, the narration, a music bed and subtitles, cut to where each line is spoken; the user can change any scene there. Write the narration and visuals first (load the faceless-video skill), pick style_id, then call this once. On the open-source engine the narration clones voice_sample, so ask the user for a recording (or a saved voice) when there is none. Gated by the same approval card as generate.",schema: FacelessInput,gated: true,title: (i) => i.title?.trim() || "Faceless episode",- plan: (i, ctx) => {- if (STUDIO_ROUTES.faceless_episode?.plan) return STUDIO_ROUTES.faceless_episode.plan(i, ctx);- try {- return planSteps("faceless_episode", facelessSteps(i, ctx), { voice: narratorVoice(i, ctx).missing });- } catch (e) {- return [{ tool: "faceless_episode", modelId: "faceless", modelName: "Faceless episode", kind: "video", op: "concat", prompt: i.title ?? "Episode", count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];- }- },+ place: (i, ctx) => placeFor(STUDIO_ROUTES.faceless_episode, i, ctx),+ plan: (i, ctx) =>+ planVia("faceless_episode", STUDIO_ROUTES.faceless_episode, i, ctx, () => {+ try {+ return planSteps("faceless_episode", facelessSteps(i, ctx), { voice: narratorVoice(i, ctx).missing });+ } catch (e) {+ return [{ tool: "faceless_episode", modelId: "faceless", modelName: "Faceless episode", kind: "video", op: "concat", prompt: i.title ?? "Episode", count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];+ }+ }),async run(i, ctx) {- const studio = await viaStudio(STUDIO_ROUTES.faceless_episode, i, ctx, "Started a faceless episode");- if (studio) return studio;- const missing = narratorVoice(i, ctx).missing;- if (missing) return { content: JSON.stringify({ error: missing }), isError: true };- return startPipeline("Faceless episode", facelessSteps(i, ctx, "run"), i.title?.trim() || "Faceless episode");+ return runVia(STUDIO_ROUTES.faceless_episode, i, ctx, "Started a faceless episode", () => {+ const missing = narratorVoice(i, ctx).missing;+ if (missing) return { content: JSON.stringify({ error: missing }), isError: true };+ return startPipeline("Faceless episode", facelessSteps(i, ctx, "run"), i.title?.trim() || "Faceless episode");+ });},});const createAds = defineTool({name: "create_ads",description:- "Make a batch of different ad creatives (1–8 concepts × up to 4 formats) for a product: varied layouts and angles, headline, call to action, the real product from its photo — Fuobe's Ads studio. Use it for 'ads for my product', 'a set of Meta ads', 'creatives to test'. Gated by the same approval card as generate.",+ "Make a batch of different ad creatives (1–8) for a product: varied angles and layouts with a headline, body, call to action and the real product from its photo — a batch in Fuobe's Ads Studio, where every ad comes in 1:1, 4:5 and 9:16 with the brand's logo, colours and fonts, editable and downloadable. Without brand_id the ads go to a brand kit called “Assist”. Use it for 'ads for my product', 'a set of Meta ads', 'creatives to test'. Gated by the same approval card as generate.",schema: AdsInput,gated: true,title: (i) => `${Math.max(1, Math.min(8, i.count ?? 4))} ads: ${i.brief.slice(0, 50)}`,- plan: (i, ctx) => {- if (STUDIO_ROUTES.create_ads?.plan) return STUDIO_ROUTES.create_ads.plan(i, ctx);- return planSteps(- "create_ads",- adRequests(i, ctx).map((r, k) => ({ key: `ad${k}`, request: { ...r, step: { label: `Ad ${k + 1} · ${r.params?.aspectRatio}`, index: k, of: 0 } } })),- {},- true,- );- },+ place: (i, ctx) => placeFor(STUDIO_ROUTES.create_ads, i, ctx),+ plan: (i, ctx) =>+ planVia("create_ads", STUDIO_ROUTES.create_ads, i, ctx, () =>+ planSteps(+ "create_ads",+ adRequests(i, ctx).map((r, k) => ({ key: `ad${k}`, request: { ...r, step: { label: `Ad ${k + 1} · ${r.params?.aspectRatio}`, index: k, of: 0 } } })),+ {},+ true,+ ),+ ),async run(i, ctx) {- const studio = await viaStudio(STUDIO_ROUTES.create_ads, i, ctx, "Started an ads batch");- if (studio) return studio;- const batchId = nanoid(10);- const ids: string[] = [];- const errors: string[] = [];- for (const r of adRequests(i, ctx)) {- try {- ids.push(...createGenerations({ ...r, batchTitle: `Ads: ${i.brief.slice(0, 120)}` }, { batchId }).map((g) => g.id));- } catch (e) {- errors.push((e as Error).message);+ return runVia(STUDIO_ROUTES.create_ads, i, ctx, "Started an ads batch", () => {+ const batchId = nanoid(10);+ const ids: string[] = [];+ const errors: string[] = [];+ for (const r of adRequests(i, ctx)) {+ try {+ ids.push(...createGenerations({ ...r, batchTitle: `Ads: ${i.brief.slice(0, 120)}` }, { batchId }).map((g) => g.id));+ } catch (e) {+ errors.push((e as Error).message);+ }}- }- if (!ids.length) return { content: JSON.stringify({ error: errors[0] ?? "Nothing could start" }), isError: true };- return { content: JSON.stringify({ started: ids, ...(errors.length && { errors }) }), items: [{ id: "", role: "generations", ids }] };+ if (!ids.length) return { content: JSON.stringify({ error: errors[0] ?? "Nothing could start" }), isError: true };+ return { content: JSON.stringify({ started: ids, ...(errors.length && { errors }) }), items: [{ id: "", role: "generations", ids }] };+ });},});const addCaptions = defineTool({name: "add_captions",description:- "Burn captions into a video from its speech, optionally translated into another language — Fuobe's Captions tool. Gated by the same approval card as generate.",+ "Burn captions into a video from its speech, optionally translated into another language — Fuobe's Captions tool (Video tools → Captions), where the captioned video lands and the user can fix any line and burn it again. Gated by the same approval card as generate.",schema: CaptionsInput,gated: true,title: (i) => (i.translate_to ? `Captions in ${i.translate_to}` : "Captions"),- plan: (i, ctx) => STUDIO_ROUTES.add_captions?.plan?.(i, ctx) ?? planSteps("add_captions", captionSteps(i, ctx)),+ place: (i, ctx) => placeFor(STUDIO_ROUTES.add_captions, i, ctx),+ plan: (i, ctx) => planVia("add_captions", STUDIO_ROUTES.add_captions, i, ctx, () => planSteps("add_captions", captionSteps(i, ctx))),async run(i, ctx) {- return (await viaStudio(STUDIO_ROUTES.add_captions, i, ctx, "Started captions")) ?? startPipeline("Captions", captionSteps(i, ctx), i.translate_to ? `Captions in ${i.translate_to}` : "Captions");+ return runVia(STUDIO_ROUTES.add_captions, i, ctx, "Started captions", () => startPipeline("Captions", captionSteps(i, ctx), i.translate_to ? `Captions in ${i.translate_to}` : "Captions"));},});diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsindex a757c1f4..daca19a3 100644--- a/src/server/assist/tools.ts+++ b/src/server/assist/tools.ts@@ -16,7 +16,9 @@ import { readRef } from "../storage";import { katanaTool } from "../katana";import { createStoryboard } from "../storyboard";import { CONTEXT_TOOLS } from "./context-tools";-import { defineTool, type ResultContent, type ToolContext, type ToolDef, type ToolOutcome } from "./define";+import { defineTool, type JobPlace, type ResultContent, type ToolContext, type ToolDef, type ToolOutcome } from "./define";+// Fills STUDIO_ROUTES with the studio modules (Layers, Shorts, dub, Faceless, Ads, Captions).+import "./studio-routes";import { STUDIO_TOOLS } from "./studio-tools";export type { ToolContext, ToolOutcome };@@ -535,14 +537,17 @@ export function validateInput(name: string, input: unknown): string | null {return parsed.success ? null : describeIssues(parsed.error.issues);}-/** Price a gated call. Arguments are validated first: plan() only ever sees input its schema accepts. */-export function planFor(name: string, input: unknown, ctx: ToolContext): { jobs: PlannedJob[]; total: number | null; error?: string } {+/**+ * Price a gated call. Arguments are validated first: plan() only ever sees input its schema accepts.+ * Studio tools also say where the job opens (studio and its page) or why it runs in the Library.+ */+export function planFor(name: string, input: unknown, ctx: ToolContext): { jobs: PlannedJob[]; total: number | null; error?: string } & JobPlace {const t = getTool(name);if (!t?.plan) return { jobs: [], total: 0 };const parsed = t.schema.safeParse(input);if (!parsed.success) return { jobs: [], total: 0, error: describeIssues(parsed.error.issues) };const jobs = t.plan(parsed.data, ctx);- return { jobs, total: totalCost(jobs) };+ return { jobs, total: totalCost(jobs), ...t.place?.(parsed.data, ctx) };}/** Validate and run a tool. Never throws: failures come back as an error result. */diff --git a/src/server/katana.ts b/src/server/katana.tsindex 4cdeba80..a4ecd719 100644--- a/src/server/katana.ts+++ b/src/server/katana.ts@@ -269,12 +269,17 @@ export const katanaTool = {return [{ ...job, error: e instanceof z.ZodError ? "Give the reference video and 1–5 photos as /api/files/… URLs" : (e as Error).message }];}},+ /** Where the job opens (the approval card, MCP's estimate_job). */+ place: () => ({ studio: "Katana", href: "/katana" }),async run(s: z.infer<typeof KatanaToolInput>, ctx: { engine: Engine }) {const job = createKatana(toBody(s, ctx.engine));const final = job.steps[job.final];return {- content: JSON.stringify({ katana: job.id, segments: job.segments, final, note: `Open /katana to follow it. ${Object.keys(job.steps).length} steps; the finished video is generation ${final}.` }),- items: [{ id: "", role: "generations" as const, ids: [final] }],+ content: JSON.stringify({ studio: "Katana", href: "/katana", katana: job.id, segments: job.segments, final, note: `${Object.keys(job.steps).length} steps; the finished video is generation ${final}. Katana lists the run with its steps, Retry and Run again.` }),+ items: [+ { id: "", role: "tool" as const, text: "Started a Katana edit", href: "/katana", studio: "Katana" },+ { id: "", role: "generations" as const, ids: [final] },+ ],};},};diff --git a/src/server/mcp.ts b/src/server/mcp.tsindex 46c44d8d..40b88171 100644--- a/src/server/mcp.ts+++ b/src/server/mcp.ts@@ -1,5 +1,7 @@import "server-only";import { z } from "zod";+// The studio modules behind the studio tools (tools.ts imports them too; named here so MCP never runs without them).+import "./assist/studio-routes";import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";import { engineMode } from "./settings";import { enabledSkills, getSkill } from "./skills";@@ -13,12 +15,13 @@ import { enabledSkills, getSkill } from "./skills";*/const PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];-const SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.1.0" };+const SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.2.0" };const INSTRUCTIONS ="Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows); it also transcribes, translates and writes text and turns images into 3D models. " +"Look up models with search_models (kinds image, video, audio, text, model3d), price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " +'Chain steps in one generate call with "after" (a still, then animate it). ' +- "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions): price them with estimate_job first. " ++ "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " ++ "Each studio job opens in that Fuobe studio (a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor, Katana): the result's href is its page on this Fuobe server, so give the user that link; a call the studio can't take runs as plain steps and says why. " +"Skills are playbooks for kinds of jobs (product photos, UGC videos, thumbnails…): list_skills, then load_skill to read one — they're also offered as prompts. " +"Generations run in the background: poll check_generations (wait_seconds up to 120) for output URLs; text results come back inline. Output URLs are paths on this Fuobe server.";diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.tsindex c4af7866..f028b4b3 100644--- a/tests/assist-context.test.ts+++ b/tests/assist-context.test.ts@@ -251,9 +251,12 @@ describe("studio tools", () => {expect(noLips.map((s) => s.request.op)).toEqual(["separate-audio", "transcribe", "translate", "tts", "mux"]);// Cloud: one HeyGen job per language.expect(studio.fallbackSteps.dub({ video, languages: ["Spanish"] }, { engine: "cloud" }).map((s) => [s.request.modelId, s.request.params?.targetLanguage])).toEqual([["heygen-translate", "Spanish"]]);- const jobs = plan("dub_video", { video, languages: ["Spanish"] });+ // Dubbing in one go on the open engine is the one case the dub studio can't take: the card says so.+ const jobs = plan("dub_video", { video, languages: ["Spanish"], review: false });expect(jobs.jobs).toHaveLength(6);expect(jobs.jobs.every((j) => !j.error)).toBe(true);+ expect(jobs).toMatchObject({ fallback: expect.stringMatching(/cloud service.*Library/) });+ expect(jobs.studio).toBeUndefined();});it("a faceless episode joins its clips in groups of four on the open engine", () => {@@ -319,14 +322,20 @@ describe("studio tools", () => {});it("an open-source narrator needs a voice sample to clone once it runs for real", () => {- // No sample on a real open engine: the narration step says what to add, and the card can't run.+ // No sample on a real open engine: the card says what to add and can't run, in Faceless Studio+ // and in the pipeline it falls back to (a square episode).setSetting("demoMode", "off");try {const p = plan("faceless_episode", { scenes, style: "flat 2D" }, "open");- const voice = p.jobs.find((j) => j.note === "Narration")!;+ expect(p.studio).toBe("Faceless Studio");+ expect(p.jobs.find((j) => j.error)?.error).toMatch(/Pick the narrator's voice/);+ expect(planRunnable(p.jobs)).toBe(false);+ const square = plan("faceless_episode", { scenes, style: "flat 2D", aspect_ratio: "1:1" }, "open");+ expect(square.fallback).toMatch(/16:9 and 9:16/);+ const voice = square.jobs.find((j) => j.note === "Narration")!;expect(voice).toMatchObject({ modelId: "oss-chatterbox", atomic: true });expect(voice.error).toMatch(/Add a voice sample for the narrator/);- expect(planRunnable(p.jobs)).toBe(false);+ expect(planRunnable(square.jobs)).toBe(false);} finally {setSetting("demoMode", "auto");}@@ -341,11 +350,19 @@ describe("studio tools", () => {});it("a demo faceless episode on the open engine clones a saved demo voice", async () => {+ // In Faceless Studio…const out = await tools.executeTool("faceless_episode", { scenes, style: "flat 2D" }, { engine: "open" });expect(out.isError).toBeFalsy();- const body = JSON.parse(out.content as string) as { steps: { step: string; id: string }[]; demo: boolean };- expect(body.demo).toBe(true);- const voiceId = body.steps.find((s) => s.step === "Narration")!.id;+ const body = JSON.parse(out.content as string) as { episode: string };+ const plan_ = JSON.parse((db().prepare("SELECT plan_json FROM faceless_episodes WHERE id = ?").get(body.episode) as { plan_json: string }).plan_json) as { ids: Record<string, string> };+ const narration = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(plan_.ids.narration) as { request_json: string };+ expect(JSON.parse(narration.request_json).inputs.voiceAudio).toMatch(/^\/api\/files\/uploads\/.+\.wav$/);+ // …and in the pipeline a square episode falls back to.+ const square = await tools.executeTool("faceless_episode", { scenes, style: "flat 2D", aspect_ratio: "1:1" }, { engine: "open" });+ expect(square.isError).toBeFalsy();+ const steps = JSON.parse(square.content as string) as { steps: { step: string; id: string }[]; demo: boolean; ranIn: string };+ expect(steps).toMatchObject({ demo: true, ranIn: "Library" });+ const voiceId = steps.steps.find((s) => s.step === "Narration")!.id;const row = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(voiceId) as { request_json: string };expect(JSON.parse(row.request_json).inputs.voiceAudio).toMatch(/^\/api\/files\/uploads\/.+\.wav$/);});@@ -360,7 +377,7 @@ describe("studio tools", () => {});it("runs as one demo pipeline, final result in the chat", async () => {- const out = await tools.executeTool("dub_video", { video, languages: ["Spanish"], lipsync: false }, { engine: "open" });+ const out = await tools.executeTool("dub_video", { video, languages: ["Spanish"], lipsync: false, review: false }, { engine: "open" });expect(out.isError).toBeFalsy();const body = JSON.parse(out.content as string) as { steps: { id: string; waitsFor: string[] }[]; results: string[]; demo: boolean };expect(body.steps).toHaveLength(5);@@ -371,16 +388,18 @@ describe("studio tools", () => {expect(JSON.parse(deps.depends_on)).toEqual(body.steps.at(-1)!.waitsFor);});- it("hands the job to a studio module once one is wired in", async () => {+ it("hands the job to the studio module in STUDIO_ROUTES", async () => {const seen: unknown[] = [];- studio.STUDIO_ROUTES.split_layers = { run: async (i) => (seen.push(i), { ids: [], href: "/layers/abc", info: { project: "abc" } }) };+ const real = studio.STUDIO_ROUTES.split_layers;+ expect(real?.studio).toBe("Layers");+ studio.STUDIO_ROUTES.split_layers = { studio: "Layers", page: "/layers", run: async (i) => (seen.push(i), { ids: [], href: "/layers/abc", info: { project: "abc" } }) };try {const out = await tools.executeTool("split_layers", { image: "/api/files/uploads/a.png" }, { engine: "open" });expect(seen).toEqual([{ image: "/api/files/uploads/a.png" }]);- expect(JSON.parse(out.content as string)).toEqual({ results: [], open: "/layers/abc", project: "abc" });- expect(out.items).toEqual([{ id: "", role: "tool", text: "Opened a Layers project", href: "/layers/abc" }]);+ expect(JSON.parse(out.content as string)).toEqual({ studio: "Layers", href: "/layers/abc", results: [], project: "abc" });+ expect(out.items).toEqual([{ id: "", role: "tool", text: "Opened a Layers project", href: "/layers/abc", studio: "Layers" }]);} finally {- delete studio.STUDIO_ROUTES.split_layers;+ studio.STUDIO_ROUTES.split_layers = real;}});});@@ -429,9 +448,13 @@ describe("MCP", () => {expect(by.dub_video.description).not.toMatch(/approval card/);expect(by.remember.description).toMatch(/confirm with the user first/);expect(by.remember.description).not.toMatch(/estimate/);- const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "add_captions", arguments: { video } } })) as { result: { structuredContent: { jobs: { modelId: string }[] }; isError: boolean } };+ const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "add_captions", arguments: { video } } })) as {+ result: { structuredContent: { jobs: { modelId: string }[]; studio: string; href: string }; isError: boolean };+ };expect(est.result.isError).toBe(false);- expect(est.result.structuredContent.jobs.map((j) => j.modelId)).toEqual(["auto-subtitle"]);+ // The Captions studio's quick burn, and the transcript its editor opens with.+ expect(est.result.structuredContent).toMatchObject({ studio: "Captions", href: "/video-tools/captions" });+ expect(est.result.structuredContent.jobs.map((j) => j.modelId)).toEqual(["scribe-v2", "auto-subtitle"]);expect(await rpc("tools/call", { name: "estimate_job", arguments: { tool: "remember", arguments: {} } })).toMatchObject({ result: { isError: true } });// Without a chat, load_skill returns the instructions themselves.const ls = (await rpc("tools/call", { name: "load_skill", arguments: { name: "narration" } })) as { result: { content: { text: string }[] } };diff --git a/tests/assist-studio-routes.test.ts b/tests/assist-studio-routes.test.tsnew file mode 100644index 00000000..3bb3618f--- /dev/null+++ b/tests/assist-studio-routes.test.ts@@ -0,0 +1,410 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type Anthropic from "@anthropic-ai/sdk";++vi.setConfig({ testTimeout: 120_000 });+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-studios-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: open models run on the demo provider, and there's no LLM (offline writers run).+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 tools = await import("@/server/assist/tools");+const studio = await import("@/server/assist/studio-tools");+const agent = await import("@/server/assist/agent");+const { handleMcp } = await import("@/server/mcp");+const { db } = await import("@/server/db");+const { saveFile } = await import("@/server/storage");+const { encodePng } = await import("@/server/png");+const gens = await import("@/server/generations");+const layers = await import("@/server/layers");+const shorts = await import("@/server/shorts");+const dub = await import("@/server/dub");+const faceless = await import("@/server/faceless");+const ads = await import("@/server/ads");+const brand = await import("@/server/brand");+const { decomposeCost } = await import("@/lib/layers");+const { burnPricePerMinute } = await import("@/lib/av/captions");+const { defaultSettings, genreInfo, PART_LABELS, STYLES } = await import("@/lib/catalog/faceless");+const { imageSize } = await import("@/lib/image-size");+const { dubLanguageFor, facelessStyleFor, shortsPresetFor } = await import("@/lib/assist-studios");+const dubRoute = await import("@/app/api/dub/route");+const adsEstimateRoute = await import("@/app/api/ads/estimate/route");++type Engine = "cloud" | "open";+const json = (method: string, body?: unknown) => new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+const plan = (name: string, input: unknown, engine: Engine = "cloud") => tools.planFor(name, input, { engine });+const run = (name: string, input: unknown, engine: Engine = "cloud") => tools.executeTool(name, input, { engine });+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const body = (out: { content: unknown }) => JSON.parse(out.content as string) as Record<string, any>;+const gen = (id: string) => gens.getGeneration(id)!;+const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 9, method, params });++/** Paid routes priced as if connected (a fal key); nothing runs with it. */+async function priced<T>(fn: () => T | Promise<T>): Promise<T> {+ setSetting("falKey", "test-key");+ try {+ return await fn();+ } finally {+ setSetting("falKey", "");+ }+}++const fixture = path.join(__dirname, "fixtures/shorts-12s.mp4");+let png = "";+let clip = "";+let notAnImage = "";++beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+ png = saveFile({ data: encodePng({ width: 64, height: 48, data: Buffer.alloc(64 * 48 * 4, 200) }), contentType: "image/png", source: "upload", name: "poster.png" }).url;+ // A 12 s, 16 fps clip with a sound track.+ clip = saveFile({ data: fs.readFileSync(fixture), contentType: "video/mp4", source: "upload", name: "beach day.mp4" }).url;+ notAnImage = saveFile({ data: Buffer.from("not a picture at all"), contentType: "image/png", source: "upload", name: "broken.png" }).url;+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const scenes = [+ { narration: "Tea began as medicine in the mountains of China.", visual: "A misty mountain tea garden at dawn" },+ { narration: "Then it became a ritual shared between friends.", visual: "Hands pouring tea in a quiet wooden room" },+ { narration: "Today it's in every café on every street.", visual: "A busy café counter with steaming cups" },+];++describe("words → a studio's own choices", () => {+ it("reads image sizes from PNG, JPEG, WebP, GIF and SVG headers", () => {+ expect(imageSize(encodePng({ width: 7, height: 3, data: Buffer.alloc(7 * 3 * 4) }))).toEqual({ width: 7, height: 3 });+ // JPEG: SOI, an APP0 segment, then SOF0 with height 300 and width 400.+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x01, 0x2c, 0x01, 0x90, 0x03]);+ expect(imageSize(jpeg)).toEqual({ width: 400, height: 300 });+ const gif = Buffer.concat([Buffer.from("GIF89a"), Buffer.from([0x20, 0x03, 0x58, 0x02])]);+ expect(imageSize(gif)).toEqual({ width: 800, height: 600 });+ const vp8x = Buffer.alloc(30);+ vp8x.write("RIFF", 0);+ vp8x.write("WEBP", 8);+ vp8x.write("VP8X", 12);+ vp8x.writeUIntLE(1023, 24, 3);+ vp8x.writeUIntLE(767, 27, 3);+ expect(imageSize(vp8x)).toEqual({ width: 1024, height: 768 });+ expect(imageSize(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="675"><rect/></svg>'))).toEqual({ width: 1200, height: 675 });+ expect(imageSize(Buffer.from('<?xml version="1.0"?><svg viewBox="0 0 90 160"></svg>'))).toEqual({ width: 90, height: 160 });+ expect(imageSize(Buffer.from("hello"))).toBeNull();+ });++ it("matches styles, presets and languages, and says when nothing matches", () => {+ for (const s of STYLES) expect(facelessStyleFor(s.name), s.name).toBe(s.id);+ expect(facelessStyleFor("flat 2D illustration, muted palette")).toBe("pastel-flat-2d");+ expect(facelessStyleFor("watercolour storybook")).toBe("watercolor-chronicle");+ expect(facelessStyleFor("chunky clay figures, stop motion")).toBe("claymotion");+ expect(facelessStyleFor("pixel-art")).toBe("pixel-art");+ expect(facelessStyleFor("cinematic photoreal drone shots")).toBeNull();+ expect(shortsPresetFor("Claymation")?.id).toBe("shorts-claymation");+ expect(shortsPresetFor("pencil sketch")?.id).toBe("shorts-pencil-sketch");+ expect(shortsPresetFor("claymation, warm studio light")).toBeUndefined();+ expect(dubLanguageFor("Spanish (Mexico)")?.code).toBe("es");+ expect(dubLanguageFor("de")?.name).toBe("German");+ expect(dubLanguageFor("Mandarin")?.code).toBe("zh");+ expect(dubLanguageFor("Klingon")).toBeUndefined();+ });+});++describe("Layers", () => {+ it("prices a decomposition per layer, as the editor does", async () => {+ const p = await priced(() => plan("split_layers", { image: png }));+ expect(p).toMatchObject({ studio: "Layers", href: "/layers" });+ expect(p.jobs).toEqual([expect.objectContaining({ op: "layers", modelId: "seedream-5-layers", costUsd: decomposeCost("seedream-5-layers", 8), demo: false, note: "Layer decomposition · up to 8 layers" })]);+ expect(plan("split_layers", { image: png, layers: 3 }, "open").jobs[0]).toMatchObject({ modelId: "oss-qwen-layered", note: "Layer decomposition · up to 3 layers", demo: true });+ });++ it("opens a project on the image and decomposes it there", async () => {+ const out = await run("split_layers", { image: png, focus: "the poster's headline" }, "open");+ expect(out.isError).toBeFalsy();+ const b = body(out);+ expect(b.href).toBe(`/layers/${b.project}`);+ const view = layers.projectView(b.project)!;+ expect(view.project).toMatchObject({ sourceUrl: png, width: 64, height: 48, name: "Poster" });+ expect(view.jobs).toEqual([expect.objectContaining({ tool: "decompose", state: "pending", generationIds: b.results })]);+ expect(gen(b.results[0])).toMatchObject({ op: "layers", modelId: "oss-qwen-layered", provider: "mock" });+ expect(gen(b.results[0]).request).toMatchObject({ feature: "layers", prompt: "the poster's headline", inputs: { images: [png] } });+ expect(out.items?.[0]).toEqual({ id: "", role: "tool", text: "Opened a Layers project", href: b.href, studio: "Layers" });+ });++ it("falls back to a plain pipeline when it can't read the picture, and says so", async () => {+ const p = plan("split_layers", { image: notAnImage }, "open");+ expect(p.studio).toBeUndefined();+ expect(p.fallback).toMatch(/couldn't read that image's size.*Library/);+ expect(p.jobs).toEqual([expect.objectContaining({ op: "layers", modelId: "oss-qwen-layered" })]);+ const out = await run("split_layers", { image: notAnImage }, "open");+ expect(body(out)).toMatchObject({ ranIn: "Library", why: expect.stringMatching(/image's size/) });+ expect(out.items?.at(-1)).toMatchObject({ role: "notice", tone: "info" });+ expect(db().prepare("SELECT COUNT(*) AS n FROM layer_projects WHERE source_url = ?").get(notAnImage)).toEqual({ n: 0 });+ });+});++describe("Shorts Studio", () => {+ const info = () => shorts.sourceInfo(fs.readFileSync(fixture));++ it("prices the session with the studio's estimate, sound and all", async () => {+ const p = await priced(() => plan("restyle_footage", { video: clip, style: "Claymation" }));+ expect(p).toMatchObject({ studio: "Shorts Studio", href: "/shorts" });+ const i = info();+ const est = await priced(() =>+ shorts.estimateWith(+ { engine: "cloud", presetId: "shorts-claymation", source: { url: clip, duration: i.duration, width: i.width, height: i.height }, range: { start: 0, end: i.duration! }, aspectRatio: i.width! > i.height! ? "16:9" : "9:16", language: "auto" },+ i,+ ),+ );+ expect(p.jobs).toEqual([expect.objectContaining({ modelId: "gemini-omni-flash", op: "v2v", costUsd: est.costUsd, demo: false, atomic: true })]);+ expect(est.costUsd).toBeGreaterThan(0);+ expect(p.jobs[0].note).toMatch(/^2 segments of 12 s, stitched under the original sound/);+ });++ it("starts a session with the agent's own look", async () => {+ const out = await run("restyle_footage", { video: clip, style: "claymation, warm studio light", references: [png] }, "open");+ expect(out.isError).toBeFalsy();+ const b = body(out);+ expect(b.href).toBe(`/shorts/${b.session}`);+ const s = shorts.getSession(b.session);+ expect(s.look).toMatchObject({ look: "claymation, warm studio light", references: [png], custom: true, described: true });+ expect(s.title).toMatch(/beach day/);+ expect(s.segments.length).toBe(b.segments);+ expect(s.segments.length).toBeGreaterThanOrEqual(3);+ expect(b.results).toEqual([s.stitches[0].final]);+ expect(Object.values(s.generations).every((g) => g.provider === "mock")).toBe(true);+ expect(shorts.listSessions().map((x) => x.id)).toContain(b.session);+ });++ it("falls back for a model it doesn't restyle with", () => {+ const p = plan("restyle_footage", { video: clip, style: "anime", model_id: "kling-o3" });+ expect(p.fallback).toMatch(/isn't one of Shorts Studio's restyle models/);+ expect(p.jobs).toEqual([expect.objectContaining({ modelId: "kling-o3", op: "v2v" })]);+ });+});++describe("Translate & dub", () => {+ const preview = async (b: unknown) =>+ (await (await dubRoute.POST(new Request("http://x/api/dub?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) }))).json()) as { costUsd: number; steps: number };++ it("prices the first stage like the studio's preview, and one-go dubs too", async () => {+ const p = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish", "German"] }));+ const route = await priced(() => preview({ engine: "cloud", mode: "steps", video: clip, targets: ["es", "de"] }));+ expect(p).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });+ // (The translation itself needs an LLM, which isn't connected here.)+ expect(p.jobs).toEqual([expect.objectContaining({ op: "translate", costUsd: route.costUsd, prompt: "Into Spanish, German", count: 2 })]);+ expect(route.costUsd).toBeGreaterThan(0);+ expect(p.jobs[0].note).toMatch(/review every line and voice it in Translate & dub/);+ const oneGo = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"], review: false }));+ const oneRoute = await priced(() => preview({ engine: "cloud", mode: "oneshot", model: "heygen-translate", video: clip, targets: ["es"] }));+ expect(oneGo.jobs).toEqual([expect.objectContaining({ modelId: "heygen-translate", op: "dub", costUsd: oneRoute.costUsd })]);+ expect(oneRoute.costUsd).toBeGreaterThan(1); // 12 s at $0.10 a second+ });++ it("opens a dub to review in Audio → Translate", async () => {+ const out = await run("dub_video", { video: clip, languages: ["spanish"] }, "open");+ expect(out.isError).toBeFalsy();+ const b = body(out);+ expect(b.href).toBe(`/audio/translate?dub=${b.dub}`);+ const s = dub.getDubSession(b.dub)!;+ expect(s).toMatchObject({ mode: "steps", engine: "open", targets: ["es"], title: "beach day" });+ expect(b.results).toEqual([s.prepare!["translate:es"]]);+ expect(gen(s.prepare!.stems)).toMatchObject({ op: "separate-audio", provider: "mock" });+ expect(b.next).toMatch(/reviews every line/);+ });++ it("dubs in one go on the cloud when asked, without lip sync", async () => {+ const b = body(await run("dub_video", { video: clip, languages: ["French"], review: false, lipsync: false }));+ const s = dub.getDubSession(b.dub)!;+ expect(s).toMatchObject({ mode: "oneshot", model: "elevenlabs-dubbing", targets: ["fr"] });+ expect(b.results).toEqual(Object.values(s.oneshot!));+ expect(gen(b.results[0])).toMatchObject({ modelId: "elevenlabs-dubbing", op: "dub" });+ });++ it("falls back for a language the studio doesn't list", () => {+ const p = plan("dub_video", { video: clip, languages: ["Klingon"] });+ expect(p.fallback).toMatch(/doesn't list Klingon/);+ expect(p.jobs[0]).toMatchObject({ tool: "dub_video", modelId: "heygen-translate" });+ });+});++describe("Faceless Studio", () => {+ it("prices the episode part by part with the studio's estimate", async () => {+ const p = await priced(() => plan("faceless_episode", { scenes, style: "watercolour storybook", aspect_ratio: "16:9" }));+ expect(p).toMatchObject({ studio: "Faceless Studio", href: "/faceless" });+ const settings = { ...defaultSettings("cloud", genreInfo("education")), aspect: "16:9" as const, styleId: "watercolor-chronicle" };+ const est = await priced(() => faceless.estimateEpisode({ kind: "faceless", settings, blocks: scenes, genre: "education" }));+ expect(p.jobs.map((j) => [j.modelName, j.costUsd])).toEqual(Object.entries(est.estimate.parts).map(([part, usd]) => [PART_LABELS[part as keyof typeof PART_LABELS], usd]));+ expect(p.jobs.every((j) => j.atomic && !j.demo && !j.error)).toBe(true);+ expect(p.total).toBeGreaterThan(0);+ });++ it("renders an episode on the Assist channel, made once and without an avatar", async () => {+ const out = await run("faceless_episode", { title: "A short history of tea", scenes, style: "paper", style_id: "paper-collage" }, "open");+ expect(out.isError).toBeFalsy();+ const b = body(out);+ expect(b.href).toBe(`/faceless/${b.channel}/${b.episode}`);+ await faceless.channelReady(b.channel);+ expect(faceless.getChannel(b.channel)).toMatchObject({ name: "Assist", avatarJob: null });+ const v = faceless.episodeView(b.episode);+ expect(v.episode).toMatchObject({ title: "A short history of tea", status: "rendering", channelId: b.channel, settings: { styleId: "paper-collage", aspect: "9:16", engine: "open" } });+ expect(v.episode.script.blocks.map((x) => x.narration)).toEqual(scenes.map((x) => x.narration));+ expect(b.results).toHaveLength(3);+ expect(b.results.every((id: string) => gen(id).op === "t2i")).toBe(true);+ // A second episode goes to the same channel.+ const again = body(await run("faceless_episode", { scenes, style: "stickman cartoon" }, "open"));+ expect(again.channel).toBe(b.channel);+ expect(faceless.listChannels().filter((c) => c.name === "Assist")).toHaveLength(1);+ expect(faceless.episodeView(again.episode).episode.settings.styleId).toBe("stickman-cartoon");+ });++ it("falls back when no style fits, and for square episodes", () => {+ const p = plan("faceless_episode", { scenes, style: "cinematic photoreal drone shots" }, "open");+ expect(p.fallback).toMatch(/isn't one of Faceless Studio's styles \(pass style_id/);+ expect(p.jobs.some((j) => j.note === "Narration")).toBe(true);+ expect(plan("faceless_episode", { scenes, style: "watercolour", aspect_ratio: "1:1" }).fallback).toMatch(/16:9 and 9:16/);+ });+});++describe("Ads Studio", () => {+ it("prices a batch for a saved brand and product like the studio's estimate", async () => {+ const kit = await brand.createManualBrand({ description: "Oat milk for runners — creamy, high protein", name: "Oat Run" });+ const product = brand.createProduct({ name: "Oat Run Original", brandId: kit.id, images: [png] });+ const p = await priced(() => plan("create_ads", { brief: "Spring race season", brand_id: kit.id, product_id: product.id, count: 3 }));+ const est = await priced(async () => (await adsEstimateRoute.POST(json("POST", { brandId: kit.id, engine: "cloud", items: [{ productId: product.id, count: 3 }], direction: "Spring race season", ratio: "4:5" }))).json());+ expect(p).toMatchObject({ studio: "Ads Studio", href: "/ads" });+ expect(p.jobs).toEqual([expect.objectContaining({ modelId: "nano-banana-pro", op: "edit", count: 3, costUsd: est.costUsd, demo: false })]);+ expect(est.costUsd).toBeGreaterThan(0);+ // A product from another brand isn't taken.+ expect(plan("create_ads", { brief: "x", brand_id: "nope" }).fallback).toMatch(/brand kit isn't in Ads Studio/);+ });++ it("makes a brand kit and product from the brief, then the batch with the exact headline", async () => {+ const brief = "Cold brew coffee for night owls, smooth and strong";+ const out = await run("create_ads", { brief, product_image: png, count: 2, aspect_ratios: ["1:1", "9:16"], headline: "Stay up", cta: "Shop now" });+ expect(out.isError).toBeFalsy();+ const b = body(out);+ expect(b.href).toBe(`/ads/${b.brand}`);+ expect(brand.getBrand(b.brand)).toMatchObject({ source: "manual", status: "ready" });+ expect(brand.getProduct(b.product)).toMatchObject({ name: "Cold brew coffee for night owls", brandId: b.brand, images: [png] });+ const creatives = ads.listCreatives({ brandId: b.brand, batchId: b.batch });+ expect(creatives).toHaveLength(2);+ expect(creatives.every((c) => c.headline === "Stay up" && c.cta === "Shop now")).toBe(true);+ expect(b.results).toEqual(creatives.map((c) => c.generationId));+ expect(gen(b.results[0])).toMatchObject({ op: "edit", provider: "mock" });+ expect(gen(b.results[0]).request.feature).toBe("ads");+ // The same product again goes back to its kit.+ const again = body(await run("create_ads", { brief, count: 1 }));+ expect([again.brand, again.product]).toEqual([b.brand, b.product]);+ });++ it("falls back for formats it doesn't make", () => {+ const p = plan("create_ads", { brief: "Sneakers", aspect_ratios: ["16:9"] });+ expect(p.fallback).toMatch(/1:1, 4:5 and 9:16 ads \(not 16:9\)/);+ expect(p.jobs[0]).toMatchObject({ modelId: "nano-banana-pro", op: "t2i" });+ });+});++describe("Captions", () => {+ it("prices the burn at the studio's rate per minute", async () => {+ const p = await priced(() => plan("add_captions", { video: clip }));+ expect(p).toMatchObject({ studio: "Captions", href: "/video-tools/captions" });+ expect(p.jobs.map((j) => j.modelId)).toEqual(["scribe-v2", "auto-subtitle"]);+ expect(p.jobs[1].costUsd).toBe(Math.round(burnPricePerMinute("auto", "clean") * (12 / 60) * 1000) / 1000);+ expect(p.jobs[0].costUsd).toBeGreaterThan(0);+ });++ it("burns them in and opens the editor on the video with its lines", async () => {+ const out = await run("add_captions", { video: clip, translate_to: "Spanish" }, "open");+ expect(out.isError).toBeFalsy();+ const b = body(out);+ const burn = gen(b.results[0]);+ expect(burn).toMatchObject({ op: "captions", modelId: "oss-captions-burnin" });+ expect(burn.request.feature).toBe("captions");+ const translation = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(burn.id) as { depends_on: string }).depends_on;+ expect(gen(translation)).toMatchObject({ op: "translate", modelId: "oss-text-llm" });+ expect(b.href).toBe(`/video-tools/captions?video=${encodeURIComponent(clip)}&transcript=${translation}`);+ // Cloud: the quick karaoke burn, and the transcript the editor opens with.+ const cloud = body(await run("add_captions", { video: clip, spoken_language: "English" }));+ expect(gen(cloud.results[0])).toMatchObject({ modelId: "auto-subtitle" });+ const words = new URL(cloud.href, "http://x").searchParams.get("transcript")!;+ expect(gen(words)).toMatchObject({ op: "transcribe", modelId: "scribe-v2" });+ expect(gen(words).request).toMatchObject({ feature: "captions", params: { sourceLanguage: "en" } });+ });++ it("falls back for a video that isn't saved in Fuobe", () => {+ const p = plan("add_captions", { video: "https://example.com/a.mp4" }, "open");+ expect(p.fallback).toMatch(/videos saved in Fuobe/);+ expect(p.jobs.map((j) => j.modelId)).toEqual(["oss-qwen3-asr", "oss-captions-burnin"]);+ });+});++describe("MCP", () => {+ it("names katana and the studio links in its instructions", async () => {+ const init = (await rpc("initialize", { protocolVersion: "2025-11-25" })) as { result: { instructions: string; serverInfo: { version: string } } };+ expect(init.result.instructions).toMatch(/katana/);+ expect(init.result.instructions).toMatch(/href/);+ expect(init.result.serverInfo.version).toBe("1.2.0");+ });++ it("estimate_job says where the job opens, or why it runs in the Library", async () => {+ type Est = { result: { structuredContent: { studio?: string; href?: string; fallback?: string; jobs: unknown[] }; isError: boolean } };+ const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "dub_video", arguments: { video: clip, languages: ["Spanish"] } } })) as Est;+ expect(est.result.isError).toBe(false);+ expect(est.result.structuredContent).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });+ const k = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "katana", arguments: { reference: clip, photos: [png] } } })) as Est;+ expect(k.result.structuredContent).toMatchObject({ studio: "Katana", href: "/katana" });+ const off = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "create_ads", arguments: { brief: "x", aspect_ratios: ["16:9"] } } })) as Est;+ expect(off.result.structuredContent.studio).toBeUndefined();+ expect(off.result.structuredContent.fallback).toMatch(/Library/);+ });++ it("tools/call returns the job's page", async () => {+ const r = (await rpc("tools/call", { name: "split_layers", arguments: { image: png } })) as { result: { content: { text: string }[]; isError: boolean } };+ expect(r.result.isError).toBe(false);+ const b = JSON.parse(r.result.content[0].text) as { studio: string; href: string; project: string };+ expect(b).toMatchObject({ studio: "Layers", href: `/layers/${b.project}` });+ expect(layers.projectView(b.project)).toBeTruthy();+ });+});++describe("Assist chat", () => {+ type Msg = Anthropic.Beta.BetaMessage;+ const use = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Anthropic.Beta.BetaContentBlock;+ const reply = (content: Anthropic.Beta.BetaContentBlock[], stop: Anthropic.Beta.BetaStopReason) => ({ content, stop_reason: stop, stop_details: null }) as Msg;+ const said = (t: string) => ({ type: "text", text: t, citations: null }) as Anthropic.Beta.BetaContentBlock;+ const scripted = (...turns: Msg[]): import("@/server/assist/agent").ModelCall => async () => turns.shift() ?? reply([said("Done.")], "end_turn");++ it("the approval card names the studio; the started job links to it", async () => {+ const t = agent.createThread({ engine: "open", agent: "offline", autoApprove: false });+ agent.addMessage(t.id, "Split this poster into layers");+ await agent.run(t.id, scripted(reply([use("u1", "split_layers", { image: png })], "tool_use")));+ const card = agent.getThread(t.id)!.thread.items.find((i) => i.role === "approval");+ expect(card).toMatchObject({ opens: ["Layers"] });+ await agent.answerApproval(t.id, true);+ await agent.run(t.id, scripted(reply([said("It's in Layers.")], "end_turn")));+ const link = agent.getThread(t.id)!.thread.items.find((i) => i.role === "tool" && i.studio);+ expect(link).toMatchObject({ studio: "Layers", href: expect.stringMatching(/^\/layers\/\w+$/) });+ });++ it("a call the studio can't take says why on the card", async () => {+ const t = agent.createThread({ engine: "open", agent: "offline", autoApprove: false });+ agent.addMessage(t.id, "A square tea episode");+ await agent.run(t.id, scripted(reply([use("u1", "faceless_episode", { scenes, style: "watercolour", aspect_ratio: "1:1" })], "tool_use")));+ const card = agent.getThread(t.id)!.thread.items.find((i) => i.role === "approval");+ expect(card).toMatchObject({ notes: [expect.stringMatching(/16:9 and 9:16 episodes — so it runs as separate steps in your Library\./)] });+ expect(card && "opens" in card ? card.opens : undefined).toBeUndefined();+ });++ it("names katana and every studio tool in the system prompt", async () => {+ let system = "";+ const t = agent.createThread({ engine: "cloud", agent: "offline", autoApprove: true });+ agent.addMessage(t.id, "hello");+ await agent.run(t.id, async (req) => {+ system = req.system.stable;+ return reply([said("Hi.")], "end_turn");+ });+ for (const n of [...studio.STUDIO_TOOLS.map((x) => x.name), "katana"]) expect(system, n).toContain(n);+ });+});