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
Content Factory: series on the server — read a reference into a brief, price it, make the episodes
Claude15bc7280bcd3
diff --git a/src/app/api/content-factory/claude/route.ts b/src/app/api/content-factory/claude/route.tsnew file mode 100644index 00000000..789827f4--- /dev/null+++ b/src/app/api/content-factory/claude/route.ts@@ -0,0 +1,14 @@+import { z } from "zod";+import { claudePrompt, handle, SeriesInputSchema } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Ask = SeriesInputSchema.extend({+ prompt: z.string().trim().min(1, "Say what the video is about").max(2000),+ seriesId: z.string().max(20).optional(),+ presetId: z.string().max(60).optional(),+});++/** "Generate in Claude": the message to paste into Claude Code (Fuobe's MCP server connected); nothing is sent anywhere. */+export async function POST(request: Request) {+ return handle(async () => Response.json(claudePrompt(await body(request, Ask, "Say what the video is about and pick the settings"))));+}diff --git a/src/app/api/content-factory/estimate/route.ts b/src/app/api/content-factory/estimate/route.tsnew file mode 100644index 00000000..e27435c2--- /dev/null+++ b/src/app/api/content-factory/estimate/route.ts@@ -0,0 +1,14 @@+import { z } from "zod";+import { BriefSchema, estimateSeries, handle, SeriesInputSchema } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Ask = SeriesInputSchema.extend({+ seriesId: z.string().max(20).optional(),+ presetId: z.string().max(60).optional(),+ brief: BriefSchema.optional(),+});++/** What the whole series would cost (one episode at the brief's pace × the episodes), and whether it runs as a demo. */+export async function POST(request: Request) {+ return handle(async () => Response.json(estimateSeries(await body(request, Ask, "Those settings aren't valid"))));+}diff --git a/src/app/api/content-factory/series/[id]/episodes/route.ts b/src/app/api/content-factory/series/[id]/episodes/route.tsnew file mode 100644index 00000000..546fc6d9--- /dev/null+++ b/src/app/api/content-factory/series/[id]/episodes/route.ts@@ -0,0 +1,18 @@+import { z } from "zod";+import { MAX_EPISODES } from "@/lib/catalog/content-factory";+import { addEpisodes, handle } from "@/server/content-factory";+import { body } from "@/server/faceless";++const More = z.object({+ count: z.number().int().min(1).max(MAX_EPISODES, `Up to ${MAX_EPISODES} episodes at a time`),+ next: z.string().max(1000).optional(),+ review: z.boolean().optional(),+});++/** "Next episode": plan and start more episodes after the ones already made. */+export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/episodes">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(await addEpisodes(id, await body(request, More, "Say how many episodes to add")));+ });+}diff --git a/src/app/api/content-factory/series/[id]/generate/route.ts b/src/app/api/content-factory/series/[id]/generate/route.tsnew file mode 100644index 00000000..e6d0e8db--- /dev/null+++ b/src/app/api/content-factory/series/[id]/generate/route.ts@@ -0,0 +1,13 @@+import { z } from "zod";+import { generateSeries, handle, SeriesInputSchema } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Generate = SeriesInputSchema.extend({ review: z.boolean().optional() });++/** "Generate here": plan the episodes, make the series' channel and start every episode. */+export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/generate">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(await generateSeries(id, await body(request, Generate, "Say what the video is about and pick the settings")));+ });+}diff --git a/src/app/api/content-factory/series/[id]/read/route.ts b/src/app/api/content-factory/series/[id]/read/route.tsnew file mode 100644index 00000000..17132b58--- /dev/null+++ b/src/app/api/content-factory/series/[id]/read/route.ts@@ -0,0 +1,13 @@+import { z } from "zod";+import { handle, rereadSeries } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Read = z.object({ engine: z.enum(["cloud", "open"]) });++/** Read the reference clip again (on either engine). */+export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/read">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(await rereadSeries(id, (await body(request, Read, "Pick an engine")).engine));+ });+}diff --git a/src/app/api/content-factory/series/[id]/route.ts b/src/app/api/content-factory/series/[id]/route.tsnew file mode 100644index 00000000..a7186ab6--- /dev/null+++ b/src/app/api/content-factory/series/[id]/route.ts@@ -0,0 +1,28 @@+import { connection } from "next/server";+import { z } from "zod";+import { BriefSchema, deleteSeries, handle, seriesView, updateSeries } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Patch = z.object({ brief: BriefSchema.optional(), name: z.string().max(60).optional() });++/** The series: its reference, how far reading it has got, the brief, the plan and the episodes. */+export async function GET(_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+ await connection();+ return handle(async () => Response.json(seriesView((await ctx.params).id)));+}++/** Edit the brief by hand, or rename the series. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(updateSeries(id, await body(request, Patch, "That brief isn't valid")));+ });+}++/** Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library). */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+ return handle(async () => {+ await deleteSeries((await ctx.params).id);+ return new Response(null, { status: 204 });+ });+}diff --git a/src/app/api/content-factory/series/route.ts b/src/app/api/content-factory/series/route.tsnew file mode 100644index 00000000..198cf1d2--- /dev/null+++ b/src/app/api/content-factory/series/route.ts@@ -0,0 +1,27 @@+import { connection } from "next/server";+import { z } from "zod";+import { createSeries, handle, listSeries, ReferenceSchema } from "@/server/content-factory";+import { body } from "@/server/faceless";++const Create = z.object({+ reference: ReferenceSchema.nullable(),+ engine: z.enum(["cloud", "open"]),+ prompt: z.string().max(2000).optional(),+});++/** Series that have been made, newest first. */+export async function GET() {+ await connection();+ return handle(() => Response.json({ items: listSeries() }));+}++/**+ * A new series around a reference: an upload, a link (fetched only through the SSRF-safe fetch; 422 with+ * `needsUpload` when it gives no clip) or a preset. Reading a clip into a style brief starts straight away.+ */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, Create, "Add a reference clip, a link or a preset");+ return Response.json(await createSeries(input), { status: 201 });+ });+}diff --git a/src/lib/catalog/content-factory.ts b/src/lib/catalog/content-factory.tsindex da5d7e90..17920cb7 100644--- a/src/lib/catalog/content-factory.ts+++ b/src/lib/catalog/content-factory.ts@@ -983,6 +983,8 @@ export function briefCostUsd(o: { seconds: number; framesUsd?: number; transcrib/** Research: the composed message is capped at 64 KB. */export const MAX_CLAUDE_MESSAGE = 64 * 1024;+/** faceless_episode (src/server/assist/studio-tools.ts) takes 2–8 scenes a call: a longer episode goes in parts. */+export const TOOL_MAX_SCENES = 8;export function mcpCommand(origin: string, needsToken: boolean): string {return `claude mcp add --transport http fuobe ${origin.replace(/\/+$/, "")}/api/mcp${needsToken ? ' --header "Authorization: Bearer fuobe_…"' : ""}`;@@ -1001,8 +1003,12 @@ export function claudeMessage(o: {reference?: string | null;}): string {const style = animationStyle(o.animation);- const sceneSecs = sceneSecondsFor(style, o.brief.shotSeconds);+ // The tool takes up to 8 scenes: longer scenes first (up to 10 s each), then the episode in parts.+ const sceneSecs = Math.min(BLOCK_SECONDS, Math.max(sceneSecondsFor(style, o.brief.shotSeconds), Math.round(o.length / TOOL_MAX_SCENES)));const scenes = scenesFor(o.length, sceneSecs);+ const parts = Math.ceil(scenes / TOOL_MAX_SCENES);+ const perPart = Math.max(2, Math.ceil(scenes / parts));+ const styleId = getStyle(o.brief.styleId).id;const words = wordsFor(sceneSecs);const look = `${getStyle(o.brief.styleId).look}. ${o.brief.look}`;const n = Math.max(1, Math.min(MAX_EPISODES, o.episodes));@@ -1020,9 +1026,12 @@ export function claudeMessage(o: {"How to make it:",`1. Load the faceless-video skill (load_skill "faceless-video").`,n > 1 ? `2. Plan ${n} episode titles that build on each other, and show them to me.` : "2. Pick a specific, clickable title.",- `3. For each episode write ${scenes} scene${scenes === 1 ? "" : "s"}: narration of at most ${words} words each (about ${sceneSecs} s spoken), the first one a hook as the brief says, and a visual for each in the look above. ${style.writer}`,- `4. Price each episode with estimate_job (tool "faceless_episode") and wait for my OK before running anything.`,- `5. Run faceless_episode once per episode with style "${look.replace(/"/g, "'").slice(0, 600)}", aspect_ratio "${o.aspect}"${o.voice ? ` and voice "${o.voice}"` : ""}, then follow it with check_generations and give me the links when they're done.`,+ `3. For each episode write ${Math.max(2, scenes)} scenes: narration of at most ${words} words each (about ${sceneSecs} s spoken), the first one a hook as the brief says, and a visual for each in the look above. ${style.writer}`,+ parts > 1+ ? ` faceless_episode takes up to ${TOOL_MAX_SCENES} scenes a call, so make each episode as ${parts} parts of about ${perPart} scenes (“Part 1”, “Part 2”…), one call per part.`+ : "",+ `4. Price each ${parts > 1 ? "part" : "episode"} with estimate_job (tool "faceless_episode") and wait for my OK before running anything.`,+ `5. Run faceless_episode once per ${parts > 1 ? "part" : "episode"} with style_id "${styleId}", style "${look.replace(/"/g, "'").slice(0, 600)}", aspect_ratio "${o.aspect}"${o.voice ? ` and voice "${o.voice}"` : ""}, then follow it with check_generations and give me the links when they're done.`,o.engine === "open" ? "The open-source engine clones the narrator's voice: ask me for a 10–60 s voice sample (voice_sample) before running." : "",].filter((l, i, all) => l !== "" || (all[i - 1] !== "" && i > 0));let out = lines.join("\n");@@ -1048,6 +1057,7 @@ export interface SeriesReference {seconds?: number;width?: number;height?: number;+ fps?: number;}export type AnalysisStatus = "reading" | "ready" | "failed";diff --git a/src/server/content-factory.ts b/src/server/content-factory.tsnew file mode 100644index 00000000..7074d753--- /dev/null+++ b/src/server/content-factory.ts@@ -0,0 +1,756 @@+import "server-only";+import { nanoid } from "nanoid";+import { z } from "zod";+import { getModel } from "@/lib/catalog";+import {+ BRIEF_SYSTEM,+ briefCostUsd,+ briefRequest,+ CF_LENGTH_VALUES,+ claudeMessage,+ episodeTopic,+ getPreset,+ MAX_BRIEF_FRAMES,+ MAX_EPISODES,+ MAX_PROMPT,+ MAX_REFERENCE_SECONDS,+ noMediaMessage,+ offlineBrief,+ offlineSeries,+ OPEN_REFERENCE_SECONDS,+ pageMedia,+ parseBrief,+ parseSeries,+ PLATFORM_LABEL,+ referenceLink,+ seriesBrief,+ seriesPrice,+ seriesSettings,+ SERIES_SYSTEM,+ type AnimationStyleId,+ type ReferencePlatform,+ type SeriesAnalysis,+ type SeriesCard,+ type SeriesEpisodePlan,+ type SeriesEstimate,+ type SeriesReference,+ type SeriesSettings,+ type SeriesView,+ type StyleBrief,+} from "@/lib/catalog/content-factory";+import { genreInfo, pickerData, type ChannelSettings, type EpisodeSettings, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";+import { probeMedia } from "@/lib/media-probe";+import { authEnabled } from "./auth";+import { db } from "./db";+import { llmText, llmTextBackend, type LlmImage } from "./enhance";+import { askLlm, createChannel, createEpisode, deleteChannel, estimateEpisode, FacelessError, getChannel, handle as facelessHandle, listEpisodes, VoiceSchema } from "./faceless";+import { cancelGeneration, createGenerations, getGeneration, previewGeneration } from "./generations";+import { fetchRemote, RemoteFetchError } from "./remote-fetch";+import { engineMode } from "./settings";+import { readRef, saveFile } from "./storage";+import { probeWebm } from "./webm-probe";++/*+ * Content Factory on the server: a series (a reference clip, a preset or nothing; the style brief read+ * from it; the planned episodes) whose episodes are Faceless episodes in a channel of its own. Nothing is+ * forked from Faceless: the series makes a channel with the brief in its settings, and every episode is+ * createEpisode with the brief applied (src/lib/catalog/faceless.ts reads EpisodeSettings.brief).+ *+ * Reading a reference:+ * - cloud: extract-frames (fal, about one frame a second, at most 20 sent on) and Scribe v2's transcript run+ * as generations; when both are done Claude (llmText, with the frames as pictures) writes the brief.+ * - open: one generation, oss-reference-brief (reference-brief-gemma4 on ComfyUI: Gemma 4 E4B watches the+ * first 30 s at a frame a second and hears the sound), whose answer is the brief.+ * Whatever can't be read (demo mode, no LLM, an answer that isn't a brief) gives way to the offline brief+ * from the clip's shape, length and narration pace, with a note that says so.+ *+ * The step generations live in the generations table (they survive restarts); the brief is written by+ * whoever reads the series first once they're done (seriesView), in this process.+ */++export class NeedsUpload extends FacelessError {+ constructor(message: string) {+ super(message, 422);+ }+}++// ---------------------------------------------------------------------------+// Rows++interface SeriesData {+ name: string | null;+ prompt: string;+ reference: SeriesReference | null;+ analysis: SeriesAnalysis | null;+ brief: StyleBrief | null;+ settings: SeriesSettings | null;+ plan: SeriesEpisodePlan[];+ /** Its episodes in series order (they're often made in the same millisecond). */+ episodeIds?: string[];+}++interface SeriesRow {+ id: string;+ channel_id: string | null;+ data_json: string;+ created_at: number;+ updated_at: number;+}++const seriesRow = (id: string) => db().prepare("SELECT * FROM content_series WHERE id = ?").get(id) as SeriesRow | undefined;+const dataOf = (r: SeriesRow) => JSON.parse(r.data_json) as SeriesData;++function mustRow(id: string): SeriesRow {+ const r = seriesRow(id);+ if (!r) throw new FacelessError("Series not found", 404);+ return r;+}++function save(id: string, data: SeriesData, channelId?: string | null): void {+ const now = Date.now();+ if (channelId !== undefined) db().prepare("UPDATE content_series SET data_json = ?, channel_id = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), channelId, now, id);+ else db().prepare("UPDATE content_series SET data_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), now, id);+}++/** Change a series' data in place (a re-read, so a brief written meanwhile isn't lost). */+function patch(id: string, fn: (d: SeriesData) => SeriesData | void): SeriesData | null {+ const r = seriesRow(id);+ if (!r) return null;+ const d = dataOf(r);+ const next = fn(d) ?? d;+ save(id, next);+ return next;+}++// ---------------------------------------------------------------------------+// The reference: an upload, a link (fetched through the SSRF-safe fetchRemote), or a preset++const MAX_CLIP_BYTES = 200 * 1024 * 1024;+const VIDEO_TYPE = /^video\/(mp4|quicktime|webm|x-m4v)$/;++/** Length and shape from the clip's own header (MP4/MOV or WebM), when it says. */+function clipFacts(data: Buffer): Pick<SeriesReference, "seconds" | "width" | "height" | "fps"> {+ const info = probeMedia(data);+ if (info?.hasVideo) return { seconds: info.videoDuration ?? info.duration, width: info.width, height: info.height, fps: info.fps };+ const webm = probeWebm(data);+ return webm ? { seconds: webm.duration, width: webm.width, height: webm.height, fps: webm.fps } : {};+}++const round1 = (n: number | undefined) => (n === undefined || !Number.isFinite(n) ? undefined : Math.round(n * 10) / 10);++async function saveClip(data: Buffer, contentType: string, name: string): Promise<Pick<SeriesReference, "url" | "seconds" | "width" | "height" | "fps">> {+ const facts = clipFacts(data);+ const url = saveFile({ data, contentType, name, source: "upload" }).url;+ return { url, seconds: round1(facts.seconds), width: facts.width, height: facts.height, fps: round1(facts.fps) };+}++/** A video behind a link, or null when the answer isn't one. */+async function fetchClip(url: string): Promise<Buffer | null> {+ const res = await fetchRemote(url, { maxBytes: MAX_CLIP_BYTES, timeoutMs: 90_000 });+ const type = res.contentType?.split(";")[0].trim().toLowerCase() ?? "";+ if (VIDEO_TYPE.test(type) || (type === "application/octet-stream" && clipFacts(res.data).seconds)) return res.data;+ return null;+}++const FETCH_FAILED = "Fuobe couldn't fetch that link. Check it opens in a private window, or upload the clip instead.";++/** A pasted link → the clip saved here, with the page's title and picture (fetched only through fetchRemote). */+async function readLink(raw: string): Promise<SeriesReference> {+ const checked = referenceLink(raw);+ if ("error" in checked) throw new FacelessError(checked.error);+ const { url, platform } = checked;+ // YouTube never hands its files out; a page from the platforms may (an og:video), so they're tried.+ if (platform === "youtube") throw new NeedsUpload(noMediaMessage(platform));+ const ref: SeriesReference = { kind: "link", link: url, platform };+ try {+ if (platform === "direct") {+ const clip = await fetchClip(url);+ if (!clip) throw new NeedsUpload(noMediaMessage(platform));+ return { ...ref, ...(await saveClip(clip, "video/mp4", "reference.mp4")), title: decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "").slice(0, 120) || undefined };+ }+ const page = await fetchRemote(url, { maxBytes: 3 * 1024 * 1024, timeoutMs: 15_000 });+ const type = page.contentType?.split(";")[0].trim().toLowerCase() ?? "";+ if (VIDEO_TYPE.test(type)) return { ...ref, ...(await saveClip(page.data, type, "reference.mp4")) };+ const media = pageMedia(page.data.toString("utf8"), page.url);+ if (!media.video) throw new NeedsUpload(noMediaMessage(platform));+ const clip = await fetchClip(media.video);+ if (!clip) throw new NeedsUpload(noMediaMessage(platform));+ const saved = await saveClip(clip, "video/mp4", "reference.mp4");+ let thumbnail: string | undefined;+ if (media.image) {+ try {+ const img = await fetchRemote(media.image, { maxBytes: 4 * 1024 * 1024, timeoutMs: 8000 });+ const t = img.contentType?.split(";")[0] ?? "";+ if (/^image\/(jpeg|png|webp|gif)$/.test(t)) thumbnail = saveFile({ data: img.data, contentType: t, name: "reference-thumbnail.jpg", source: "upload" }).url;+ } catch {+ // The card shows the clip itself.+ }+ }+ return { ...ref, ...saved, ...(media.title && { title: media.title }), ...(thumbnail && { thumbnail }) };+ } catch (e) {+ if (e instanceof FacelessError) throw e;+ // A private address is refused with its own words; anything else (a 404, a timeout, a login wall) reads the same.+ throw new NeedsUpload(e instanceof RemoteFetchError && /private network|this machine/.test(e.message) ? e.message : FETCH_FAILED);+ }+}++/** An uploaded clip (already in this install's files). */+async function readUpload(url: string, title?: string): Promise<SeriesReference> {+ if (!url.startsWith("/api/files/")) throw new FacelessError("Upload the clip first");+ let file: Awaited<ReturnType<typeof readRef>>;+ try {+ file = await readRef(url);+ } catch {+ throw new FacelessError("That upload is gone — add the clip again");+ }+ if (!file.contentType.startsWith("video/")) throw new FacelessError("Add a video clip (MP4, MOV or WebM) as the reference");+ const facts = clipFacts(file.data);+ return { kind: "upload", url, title: title?.trim().slice(0, 120) || file.name, seconds: round1(facts.seconds), width: facts.width, height: facts.height, fps: round1(facts.fps) };+}++export type ReferenceInput = { kind: "upload"; url: string; title?: string } | { kind: "link"; link: string } | { kind: "preset"; presetId: string };++async function resolveReference(input: ReferenceInput): Promise<SeriesReference> {+ if (input.kind === "upload") return readUpload(input.url, input.title);+ if (input.kind === "link") return readLink(input.link);+ const p = getPreset(input.presetId);+ if (!p) throw new FacelessError("That preset isn't there any more — pick another");+ return { kind: "preset", presetId: p.id, title: p.name };+}++// ---------------------------------------------------------------------------+// Reading the reference into a brief++const STEP_LABEL = { frames: "Reference frames", transcript: "Reference transcript", brief: "Reference brief" } as const;++const engineAllowed = (engine: Engine) => engineMode() === "both" || engineMode() === engine;+function checkEngine(engine: Engine): void {+ if (!engineAllowed(engine)) throw new FacelessError(engine === "open" ? "This install is set to paid cloud APIs only (Settings → Engine mode)" : "This install is set to open source only (Settings → Engine mode)");+}++function request(ref: SeriesReference, key: keyof typeof STEP_LABEL, r: Omit<GenerationRequest, "feature">): GenerationRequest {+ return { feature: "content-factory", ...r, step: { label: STEP_LABEL[key], index: 0, of: 1 }, batchTitle: `Content Factory · ${ref.title ?? "reference"}` } as GenerationRequest;+}++/** Every Nth frame for about one a second, at most MAX_BRIEF_FRAMES over the clip (extract-frames counts frames). */+export function frameInterval(seconds: number | undefined, fps: number | undefined): number {+ const secs = Math.max(1, Math.min(MAX_REFERENCE_SECONDS, seconds ?? 30));+ const rate = fps && fps > 0 && fps <= 240 ? fps : 30;+ const frames = Math.max(1, Math.min(MAX_BRIEF_FRAMES, Math.round(secs)));+ return Math.max(1, Math.min(300, Math.round((secs * rate) / frames)));+}++/** The step generations for one read of the clip (none can start: the offline brief, with why). */+function startSteps(ref: SeriesReference, engine: Engine): { steps: SeriesAnalysis["steps"]; costUsd: number | null; demo: boolean; error?: string } {+ const steps: SeriesAnalysis["steps"] = {};+ let cost = 0;+ let demo = false;+ const errors: string[] = [];+ const run = (key: keyof typeof STEP_LABEL, r: GenerationRequest) => {+ try {+ const p = previewGeneration(r);+ const g = createGenerations(r)[0];+ steps[key] = g.id;+ cost += p.costUsd ?? 0;+ demo ||= p.demo;+ } catch (e) {+ errors.push((e as Error).message);+ }+ };+ if (engine === "open") {+ run("brief", request(ref, "brief", { modelId: "oss-reference-brief", op: "write", inputs: { video: ref.url }, params: { duration: Math.min(OPEN_REFERENCE_SECONDS, ref.seconds ?? OPEN_REFERENCE_SECONDS) } }));+ } else {+ run("frames", request(ref, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps) } }));+ run("transcript", request(ref, "transcript", { modelId: "scribe-v2", op: "transcribe", inputs: { video: ref.url }, params: { ...(ref.seconds && { duration: ref.seconds, sourceDuration: ref.seconds }) } }));+ }+ return { steps, costUsd: engine === "open" ? 0 : Math.round(cost * 1000) / 1000, demo, ...(errors.length && !Object.keys(steps).length && { error: errors[0] }) };+}++function beginAnalysis(id: string, ref: SeriesReference, engine: Engine): SeriesAnalysis {+ const started = startSteps(ref, engine);+ if (started.error) {+ // Nothing can read the clip on this engine right now: the brief from its header, and why.+ return { engine, status: "ready", steps: {}, offline: true, note: `${started.error}. This brief comes from the clip's shape and length only — fix that and read it again.`, costUsd: 0 };+ }+ return { engine, status: "reading", steps: started.steps, stage: engine === "open" ? "Gemma 4 is watching the clip…" : "Reading the frames and the words…", costUsd: started.costUsd, demo: started.demo };+}++declare global {+ var __fuobeContentBriefs: Map<string, Promise<void>> | undefined;+}+const writing = () => (globalThis.__fuobeContentBriefs ??= new Map<string, Promise<void>>());++/** Wait for a series' brief to be written (tests). */+export const briefWritten = (id: string) => writing().get(id) ?? Promise.resolve();++const done = (g: Generation | null) => !g || g.status === "succeeded" || g.status === "failed" || g.status === "canceled";+const textOf = (g: Generation | null) => (g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "text") : undefined);+const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;++/** Up to `n` items spread evenly over a list (first and last kept). */+export function spread<T>(list: T[], n: number): T[] {+ if (list.length <= n) return list;+ if (n <= 1) return list.slice(0, 1);+ return Array.from({ length: n }, (_, i) => list[Math.round((i * (list.length - 1)) / (n - 1))]);+}++const IMAGE_TYPE = /^image\/(jpeg|png|gif|webp)$/;++async function framesOf(g: Generation | null): Promise<LlmImage[]> {+ if (g?.status !== "succeeded") return [];+ const outs = g.outputs.filter((o) => o.kind === "image" && !o.meta?.demo);+ const picked = spread(+ [...outs].sort((a, b) => Number(a.meta?.index ?? 0) - Number(b.meta?.index ?? 0)),+ MAX_BRIEF_FRAMES,+ );+ const images: LlmImage[] = [];+ for (const o of picked) {+ try {+ const f = await readRef(o.url);+ if (IMAGE_TYPE.test(f.contentType) && f.data.length <= 4.5 * 1024 * 1024) images.push({ data: f.data, contentType: f.contentType });+ } catch {+ // A frame that can't be read is left out.+ }+ }+ return images;+}++async function writeBrief(id: string): Promise<void> {+ const r = seriesRow(id);+ if (!r) return;+ const d = dataOf(r);+ const a = d.analysis;+ const ref = d.reference;+ if (!a || a.status !== "reading" || !ref) return;+ const base = offlineBrief({ seconds: ref.seconds, width: ref.width, height: ref.height, title: ref.title });+ const header = ref.width && ref.height ? { aspect: base.aspect } : {};+ let brief: StyleBrief = base;+ let note: string | undefined;+ let offline = false;++ if (a.engine === "open") {+ const g = getGeneration(a.steps.brief ?? "", { includeDeleted: true });+ const out = textOf(g);+ const parsed = out && !out.meta?.demo ? parseBrief(out.text ?? "", base) : null;+ if (parsed) brief = { ...parsed.brief, ...header };+ else {+ offline = true;+ note = out?.meta?.demo+ ? "Demo brief — start ComfyUI (with Gemma 4 E4B) to read the clip for real. This one comes from the clip's shape and length."+ : g?.status === "failed"+ ? `Gemma 4 couldn't read the clip (${g.error ?? "it failed"}). This brief comes from the clip's shape and length — read it again to retry.`+ : "Gemma 4's answer wasn't a brief. This one comes from the clip's shape and length — read it again to retry.";+ }+ } else {+ const framesGen = getGeneration(a.steps.frames ?? "", { includeDeleted: true });+ const wordsGen = getGeneration(a.steps.transcript ?? "", { includeDeleted: true });+ const words = textOf(wordsGen);+ const cues = words && !words.meta?.demo && Array.isArray(words.meta?.cues) ? (words.meta.cues as TimedText[]) : [];+ const frames = await framesOf(framesGen);+ const fallback = offlineBrief({ seconds: ref.seconds, width: ref.width, height: ref.height, cues, title: ref.title });+ brief = fallback;+ const demo = (framesGen?.outputs.some((o) => o.meta?.demo) ?? false) || !!words?.meta?.demo;+ if (!frames.length && !cues.length) {+ offline = true;+ note = demo+ ? "Demo brief — connect fal and Claude in Settings to read the clip for real. This one comes from the clip's shape and length."+ : `The clip couldn't be read (${framesGen?.error ?? wordsGen?.error ?? "no frames or words came back"}). This brief comes from its shape and length — read it again to retry.`;+ } else if (!llmTextBackend()) {+ offline = true;+ note = "No LLM is connected (Settings → AI helper), so this brief comes from the clip's shape, length and narration pace.";+ } else {+ const transcript = cues.map((c) => `[${mmss(c.start)}] ${c.text.trim()}`).join("\n");+ const user = briefRequest({ seconds: ref.seconds, width: ref.width, height: ref.height, frames: frames.length, transcript, title: ref.title });+ // A text-only Ollama model can't take pictures: it answers from the words then.+ const answer = (await llmText(BRIEF_SYSTEM, user, frames)) ?? (frames.length && llmTextBackend() === "ollama" ? await llmText(BRIEF_SYSTEM, user) : null);+ const parsed = answer ? parseBrief(answer, fallback) : null;+ if (parsed) brief = { ...parsed.brief, ...header };+ else {+ offline = true;+ note = "The LLM didn't answer with a brief, so this one comes from the clip's shape, length and narration pace — read it again to retry.";+ }+ }+ }+ patch(id, (cur) => {+ // Read again (or deleted) meanwhile: that read wins.+ if (cur.analysis?.status !== "reading" || JSON.stringify(cur.analysis.steps) !== JSON.stringify(a.steps)) return;+ cur.brief = brief;+ cur.analysis = { ...cur.analysis, status: "ready", stage: undefined, offline: offline || undefined, note };+ });+}++/** Moves a reading series on: the steps' progress, then the brief once they're all done. */+function advance(id: string, d: SeriesData): SeriesData {+ const a = d.analysis;+ if (!a || a.status !== "reading") return d;+ const gens = Object.values(a.steps).map((g) => getGeneration(g, { includeDeleted: true }));+ if (!gens.every(done)) {+ const running = gens.find((g) => g && !done(g));+ return { ...d, analysis: { ...a, stage: running?.status === "queued" ? "Waiting for its turn…" : a.stage } };+ }+ if (!writing().has(id)) {+ const job = writeBrief(id)+ .catch((e: Error) => {+ patch(id, (cur) => {+ if (cur.analysis?.status === "reading") cur.analysis = { ...cur.analysis, status: "failed", stage: undefined, error: e.message || "Couldn't write the brief" };+ });+ })+ .finally(() => writing().delete(id));+ writing().set(id, job);+ }+ return { ...d, analysis: { ...a, stage: a.engine === "open" ? "Writing the brief…" : "Claude is writing the brief…" } };+}++// ---------------------------------------------------------------------------+// Series++/** Episode 1 first: the series' own in plan order, then any made in Faceless Studio's channel page, oldest first. */+function inOrder<T extends { id: string; createdAt: number }>(cards: T[], ids: string[]): T[] {+ const at = new Map(ids.map((id, i) => [id, i]));+ const rank = (c: T) => at.get(c.id) ?? ids.length;+ return [...cards].sort((a, b) => rank(a) - rank(b) || a.createdAt - b.createdAt);+}++function toView(r: SeriesRow, d: SeriesData): SeriesView {+ const channel = r.channel_id ? getChannel(r.channel_id) : null;+ return {+ id: r.id,+ name: d.name ?? channel?.name ?? null,+ prompt: d.prompt,+ reference: d.reference,+ analysis: d.analysis,+ brief: d.brief,+ settings: d.settings,+ plan: d.plan,+ channel,+ episodes: channel ? inOrder(listEpisodes({ channelId: channel.id, limit: 200 }), d.episodeIds ?? []) : [],+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ };+}++export function seriesView(id: string): SeriesView {+ const r = mustRow(id);+ return toView(r, advance(id, dataOf(r)));+}++/** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */+export async function createSeries(input: { reference: ReferenceInput | null; engine: Engine; prompt?: string }): Promise<SeriesView> {+ checkEngine(input.engine);+ const reference = input.reference ? await resolveReference(input.reference) : null;+ const id = nanoid(10);+ const now = Date.now();+ const preset = reference?.kind === "preset" ? getPreset(reference.presetId) : undefined;+ const data: SeriesData = { name: null, prompt: input.prompt?.trim().slice(0, MAX_PROMPT) ?? "", reference, analysis: null, brief: preset ? preset.brief : null, settings: null, plan: [] };+ if (preset) data.analysis = { engine: input.engine, status: "ready", steps: {}, costUsd: 0 };+ db().prepare("INSERT INTO content_series (id, channel_id, data_json, created_at, updated_at) VALUES (?, NULL, ?, ?, ?)").run(id, JSON.stringify(data), now, now);+ if (reference?.url) {+ data.analysis = beginAnalysis(id, reference, input.engine);+ if (data.analysis.status === "ready") data.brief = offlineBrief({ seconds: reference.seconds, width: reference.width, height: reference.height, title: reference.title });+ save(id, data);+ }+ return seriesView(id);+}++/** Read the reference again (after an offline brief, a failure, or on the other engine). */+export async function rereadSeries(id: string, engine: Engine): Promise<SeriesView> {+ checkEngine(engine);+ const r = mustRow(id);+ const d = dataOf(r);+ if (!d.reference?.url) throw new FacelessError("This series has no clip to read — add one first");+ for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});+ d.analysis = beginAnalysis(id, d.reference, engine);+ if (d.analysis.status === "ready") d.brief = offlineBrief({ seconds: d.reference.seconds, width: d.reference.width, height: d.reference.height, title: d.reference.title });+ save(id, d);+ return seriesView(id);+}++export const BriefSchema = z.object({+ format: z.string().max(400),+ hook: z.string().max(400),+ shotSeconds: z.number().min(1).max(30),+ pacing: z.string().max(400),+ shots: z.array(z.string().max(120)).max(12),+ look: z.string().max(600),+ styleId: z.string().max(60),+ animation: z.enum(["fully-animated", "seamless", "scene-by-scene", "frame-by-frame"]),+ voice: z.object({ tone: z.string().max(200), wordsPerMinute: z.number().min(60).max(300).optional(), language: z.string().max(40).optional() }),+ music: z.object({ mood: z.string().max(300), energy: z.enum(["low", "medium", "high"]).optional() }),+ captions: z.object({ style: z.string().max(200), position: z.enum(["top", "center", "bottom"]), words: z.number().int().min(1).max(8) }),+ aspect: z.enum(["9:16", "16:9"]),+ topics: z.array(z.string().max(200)).max(12),+});++/** Edit the brief by hand, or rename the series. */+export function updateSeries(id: string, p: { brief?: StyleBrief; name?: string }): SeriesView {+ const r = mustRow(id);+ const d = dataOf(r);+ if (p.brief) {+ if (d.analysis?.status === "reading") throw new FacelessError("Wait for the brief to be read first", 409);+ d.brief = p.brief;+ }+ if (p.name !== undefined) d.name = p.name.trim().slice(0, 60) || null;+ save(id, d);+ return seriesView(id);+}++export async function deleteSeries(id: string): Promise<void> {+ const r = mustRow(id);+ const d = dataOf(r);+ for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});+ if (r.channel_id && getChannel(r.channel_id)) await deleteChannel(r.channel_id);+ db().prepare("DELETE FROM content_series WHERE id = ?").run(id);+}++/** Series that have been made (drafts that never ran stay out of the list). */+export function listSeries(): SeriesCard[] {+ const rows = db().prepare("SELECT * FROM content_series WHERE channel_id IS NOT NULL ORDER BY updated_at DESC LIMIT 100").all() as SeriesRow[];+ return rows.flatMap((r) => {+ const channel = getChannel(r.channel_id!);+ if (!channel) return [];+ const d = dataOf(r);+ const eps = inOrder(listEpisodes({ channelId: channel.id, limit: 200 }), d.episodeIds ?? []);+ const first = eps.find((e) => e.still) ?? eps[0];+ return [+ {+ id: r.id,+ name: d.name ?? channel.name,+ prompt: d.prompt,+ channelId: channel.id,+ episodes: eps.length,+ done: eps.filter((e) => e.status === "done").length,+ rendering: eps.filter((e) => e.status === "rendering" || e.status === "writing").length,+ poster: first?.still ?? null,+ thumbnail: d.reference?.thumbnail ?? null,+ styleId: channel.settings.styleId,+ aspect: channel.settings.aspect,+ updatedAt: r.updated_at,+ },+ ];+ });+}++// ---------------------------------------------------------------------------+// Settings, prices and the plan++export interface SeriesInput {+ prompt: string;+ settings: SeriesSettings;+ /** The narrator: null on the open engine until a sample is added; left out, one is picked for the brief's tone. */+ voice?: NarratorVoice | null;+ subtitles?: boolean;+ music?: boolean;+}++function briefFor(o: { seriesId?: string; presetId?: string; brief?: StyleBrief }): StyleBrief {+ if (o.brief) return o.brief;+ if (o.seriesId) {+ const d = dataOf(mustRow(o.seriesId));+ if (d.brief) return d.brief;+ if (d.analysis?.status === "reading") throw new FacelessError("The reference is still being read — a moment", 409);+ }+ const p = o.presetId ? getPreset(o.presetId) : undefined;+ if (p) return p.brief;+ throw new FacelessError("Add a reference or pick a preset style first");+}++const voices = () => pickerData(getModel).voices;++export function episodeSettings(input: SeriesInput, brief: StyleBrief): EpisodeSettings {+ const s = input.settings;+ if (!CF_LENGTH_VALUES.includes(s.length)) throw new FacelessError("Choose one of the offered lengths (30 sec to 5 min)");+ return seriesSettings({+ engine: s.engine,+ length: s.length,+ animation: s.animation,+ aspect: s.aspect,+ brief,+ genre: genreInfo(s.genre),+ ...(input.voice !== undefined && { voice: input.voice }),+ voices: voices(),+ subtitles: input.subtitles,+ music: input.music,+ });+}++/** What reading a minute of reference costs here (fal frames + Scribe v2 + Claude; nothing on the open engine or as a demo). */+function analysisPerMinute(engine: Engine): number {+ if (engine === "open") return 0;+ try {+ const frames = previewGeneration({ feature: "content-factory", modelId: "extract-frames", op: "extract-frames", inputs: { video: "/api/files/estimate.mp4" }, params: { frameInterval: 90 } });+ const words = previewGeneration({ feature: "content-factory", modelId: "scribe-v2", op: "transcribe", inputs: { video: "/api/files/estimate.mp4" }, params: { duration: 60, sourceDuration: 60 } });+ if (frames.demo && words.demo) return 0;+ return briefCostUsd({ seconds: 60, framesUsd: frames.costUsd ?? 0, transcribePerMinute: words.costUsd ?? 0, claude: llmTextBackend() === "claude" });+ } catch {+ return 0;+ }+}++/** The whole series' price before anything runs: one episode at the brief's pace, times the episodes. */+export function estimateSeries(input: SeriesInput & { seriesId?: string; presetId?: string; brief?: StyleBrief }): SeriesEstimate {+ const s = input.settings;+ const perMinute = analysisPerMinute(s.engine);+ let brief: StyleBrief;+ try {+ brief = briefFor(input);+ } catch {+ // No reference yet: price the default look, so the composer always shows a price.+ brief = getPreset("what-if")!.brief;+ }+ const settings = episodeSettings(input, brief);+ const est = estimateEpisode({ kind: "faceless", settings, genre: s.genre });+ return {+ price: seriesPrice(est.estimate, s.episodes),+ demo: est.demo,+ seconds: est.seconds,+ scenes: est.blocks,+ ...(est.error && { error: est.error }),+ ...(est.notes && { notes: est.notes }),+ analysisPerMinute: perMinute,+ };+}++const PLAN_TIMEOUT_MS = 25_000;++/** Episode titles: the engine's LLM when it answers in time, else the genre's beats around the prompt. */+async function planEpisodes(o: { prompt: string; settings: SeriesSettings; brief: StyleBrief; count: number; previous: string[]; next?: string }): Promise<{ name: string | null; episodes: SeriesEpisodePlan[] }> {+ const genre = genreInfo(o.settings.genre);+ if (o.count === 1 && !o.previous.length && !o.next?.trim()) return { name: null, episodes: offlineSeries(o.prompt, genre.id, 1) };+ const answer = await askLlm(o.settings.engine, SERIES_SYSTEM, seriesBrief({ prompt: o.prompt, genre, count: o.count, format: o.brief.format, previous: o.previous, next: o.next }), { timeoutMs: PLAN_TIMEOUT_MS });+ const parsed = answer ? parseSeries(answer) : null;+ const got = (parsed?.episodes ?? []).slice(0, o.count);+ const fill = offlineSeries(o.prompt, genre.id, o.count - got.length, o.previous.length + got.length);+ // Without the LLM, the next episode is what the user said happens in it.+ const episodes = [...got, ...fill].map((e, i) => (i === 0 && !got.length && o.next?.trim() ? { ...e, synopsis: o.next.trim().slice(0, 400) } : e));+ return { name: parsed?.name ?? null, episodes };+}++const COULDNT_PLAN = "Couldn't plan your episodes. You weren't charged, so it's safe to try again.";++function startEpisodes(o: { channelId: string; prompt: string; plan: SeriesEpisodePlan[]; earlier: string[]; settings: EpisodeSettings; review: boolean; series: boolean }): string[] {+ const titles = [...o.earlier];+ const ids: string[] = [];+ o.plan.forEach((ep) => {+ const topic = episodeTopic(o.prompt, ep, { number: titles.length + 1, earlier: titles, series: o.series });+ const made = createEpisode({ kind: "faceless", channelId: o.channelId, topic, settings: o.settings, autoRender: !o.review, saveLook: false, ...(o.series && { title: ep.title }) });+ ids.push(made.id);+ titles.push(ep.title);+ });+ return ids;+}++/** "Generate here": plan the episodes, make the series' channel, and start every episode (rendered straight after its script unless `review`). */+export async function generateSeries(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {+ const r = mustRow(id);+ if (r.channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);+ const d = dataOf(r);+ checkEngine(input.settings.engine);+ const prompt = input.prompt.trim();+ if (!prompt) throw new FacelessError("Say what the video is about");+ const brief = briefFor({ seriesId: id });+ const settings = episodeSettings(input, brief);+ const est = estimateEpisode({ kind: "faceless", settings, genre: input.settings.genre });+ if (est.error) throw new FacelessError(est.error);+ const count = Math.max(1, Math.min(MAX_EPISODES, Math.round(input.settings.episodes)));+ let plan: { name: string | null; episodes: SeriesEpisodePlan[] };+ let channelId: string;+ try {+ plan = await planEpisodes({ prompt, settings: input.settings, brief, count, previous: [] });+ const channelSettings: ChannelSettings = {+ engine: settings.engine,+ styleId: settings.styleId,+ styleRefs: [],+ voice: settings.voice,+ aspect: settings.aspect,+ subtitles: settings.subtitles,+ music: settings.music,+ animation: settings.animation,+ length: settings.length,+ ...(settings.brief && { brief: settings.brief }),+ };+ const channel = await createChannel({ idea: prompt, genre: input.settings.genre, engine: settings.engine, ...(plan.name && { name: plan.name }), avatar: false, settings: channelSettings });+ channelId = channel.id;+ } catch (e) {+ if (e instanceof FacelessError) throw e;+ throw new FacelessError(COULDNT_PLAN, 500);+ }+ // Seen as made from here on (a second click gets "This series is made").+ const next = { ...d, name: plan.name, prompt, settings: { ...input.settings, episodes: count }, plan: plan.episodes };+ save(id, next, channelId);+ const ids = startEpisodes({ channelId, prompt, plan: plan.episodes, earlier: [], settings, review: !!input.review, series: count > 1 });+ save(id, { ...next, episodeIds: ids });+ return seriesView(id);+}++/** "Next episode": plan more after the ones already made, the first one following what the user says happens in it. */+export async function addEpisodes(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {+ const r = mustRow(id);+ const d = dataOf(r);+ const channel = r.channel_id ? getChannel(r.channel_id) : null;+ if (!channel || !d.settings || !d.brief) throw new FacelessError("Make the series first", 409);+ checkEngine(channel.settings.engine);+ const count = Math.max(1, Math.min(MAX_EPISODES, Math.round(input.count)));+ const settings = episodeSettings({ prompt: d.prompt, settings: { ...d.settings, engine: channel.settings.engine }, voice: channel.settings.voice, subtitles: channel.settings.subtitles, music: channel.settings.music }, d.brief);+ const est = estimateEpisode({ kind: "faceless", settings, genre: d.settings.genre });+ if (est.error) throw new FacelessError(est.error);+ const previous = d.plan.map((e) => e.title);+ const more = await planEpisodes({ prompt: d.prompt, settings: d.settings, brief: d.brief, count, previous, next: input.next }).catch(() => {+ throw new FacelessError(COULDNT_PLAN, 500);+ });+ const ids = startEpisodes({ channelId: channel.id, prompt: d.prompt, plan: more.episodes, earlier: previous, settings, review: !!input.review, series: true });+ save(id, { ...d, plan: [...d.plan, ...more.episodes], settings: { ...d.settings, episodes: d.plan.length + more.episodes.length }, episodeIds: [...(d.episodeIds ?? []), ...ids] });+ return seriesView(id);+}++// ---------------------------------------------------------------------------+// "Generate in Claude"++export function claudePrompt(input: SeriesInput & { seriesId?: string; presetId?: string; voiceName?: string }): { message: string; bytes: number; needsToken: boolean } {+ const brief = briefFor(input);+ const s = input.settings;+ const d = input.seriesId ? dataOf(mustRow(input.seriesId)) : null;+ const ref = d?.reference;+ const reference = ref && ref.kind !== "preset" ? `${ref.title ? `“${ref.title}”` : "clip"}${ref.platform ? ` (${PLATFORM_LABEL[ref.platform as ReferencePlatform]})` : ""}` : null;+ const voice = input.voice?.kind === "preset" ? input.voice.id : null;+ const message = claudeMessage({ prompt: input.prompt, brief, length: s.length, episodes: s.episodes, animation: s.animation as AnimationStyleId, genre: genreInfo(s.genre), aspect: s.aspect, engine: s.engine, voice, reference });+ return { message, bytes: new TextEncoder().encode(message).length, needsToken: authEnabled() };+}++// ---------------------------------------------------------------------------+// Schemas and the API's error shape++export const SeriesSettingsSchema = z.object({+ engine: z.enum(["cloud", "open"]),+ length: z.number().int().min(15).max(600),+ episodes: z.number().int().min(1, "At least one episode").max(MAX_EPISODES, `Up to ${MAX_EPISODES} episodes at a time`),+ animation: z.enum(["fully-animated", "seamless", "scene-by-scene", "frame-by-frame"]),+ genre: z.enum(["education", "history", "kids", "storytelling"]),+ aspect: z.enum(["9:16", "16:9"]),+});++export const SeriesInputSchema = z.object({+ prompt: z.string().max(MAX_PROMPT, `Keep it under ${MAX_PROMPT} characters`),+ settings: SeriesSettingsSchema,+ voice: VoiceSchema.nullable().optional(),+ subtitles: z.boolean().optional(),+ music: z.boolean().optional(),+});++export const ReferenceSchema = z.union([+ z.object({ kind: z.literal("upload"), url: z.string().startsWith("/api/files/").max(500), title: z.string().max(200).optional() }),+ z.object({ kind: z.literal("link"), link: z.string().max(2000) }),+ z.object({ kind: z.literal("preset"), presetId: z.string().max(60) }),+]);++/** The faceless API's `{ error }` responses, plus `needsUpload` when a link gave no clip. */+export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {+ try {+ return await fn();+ } catch (e) {+ if (e instanceof NeedsUpload) return Response.json({ error: e.message, needsUpload: true }, { status: e.status });+ return facelessHandle(() => {+ throw e;+ });+ }+}diff --git a/src/server/db.ts b/src/server/db.tsindex c64ccf4d..9b116ebe 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -438,6 +438,16 @@ const MIGRATIONS: string[] = [sent_json TEXT);CREATE INDEX IF NOT EXISTS assist_thread_state_project ON assist_thread_state(project_id);`,+ // round 4 (r4/content-factory): Content Factory series — the reference clip, its style brief, the planned+ // episodes and the settings; the episodes themselves are Faceless episodes in the series' channel.+ `CREATE TABLE IF NOT EXISTS content_series (+ id TEXT PRIMARY KEY,+ channel_id TEXT,+ data_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS content_series_updated ON content_series(updated_at DESC);`,];declare global {diff --git a/src/server/enhance.ts b/src/server/enhance.tsindex 838cd29a..43d08d63 100644--- a/src/server/enhance.ts+++ b/src/server/enhance.ts@@ -28,16 +28,28 @@ function instruction(prompt: string, kind: MediaKind, op: Operation): string {return `Rewrite this as ${what}:\n\n${prompt}`;}-async function viaClaude(system: string, user: string): Promise<string | null> {+/** A picture for a model that can see (Content Factory's reference frames): JPEG, PNG, GIF or WebP. */+export interface LlmImage {+ data: Buffer;+ contentType: string;+}++async function viaClaude(system: string, user: string, images: LlmImage[] = []): Promise<string | null> {const client = new Anthropic({ apiKey: getSetting("anthropicKey") });+ const content = images.length+ ? [+ ...images.map((i) => ({ type: "image" as const, source: { type: "base64" as const, media_type: i.contentType as "image/jpeg", data: i.data.toString("base64") } })),+ { type: "text" as const, text: user },+ ]+ : user;const res = await client.beta.messages.create({model: "claude-opus-5-5",- max_tokens: 1024,+ max_tokens: images.length ? 4096 : 1024,output_config: { effort: "low" },betas: ["server-side-fallback-2026-07-01"],fallbacks: "default",system,- messages: [{ role: "user", content: user }],+ messages: [{ role: "user", content }],} as Parameters<typeof client.beta.messages.create>[0] & { fallbacks: string });if (!("content" in res) || res.stop_reason === "refusal") return null;const text = res.content@@ -48,7 +60,7 @@ async function viaClaude(system: string, user: string): Promise<string | null> {return text || null;}-async function viaOllama(system: string, user: string): Promise<string | null> {+async function viaOllama(system: string, user: string, images: LlmImage[] = []): Promise<string | null> {const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {method: "POST",headers: { "Content-Type": "application/json" },@@ -58,26 +70,34 @@ async function viaOllama(system: string, user: string): Promise<string | null> {think: false,messages: [{ role: "system", content: system },- { role: "user", content: user },+ // A vision model (qwen3-vl, gemma3…) reads the pictures; a text-only one answers from the words.+ { role: "user", content: user, ...(images.length && { images: images.map((i) => i.data.toString("base64")) }) },],}),- signal: AbortSignal.timeout(60_000),+ signal: AbortSignal.timeout(images.length ? 180_000 : 60_000),});if (!res.ok) throw new Error(`ollama ${res.status}`);const j = (await res.json()) as { message?: { content?: string } };return j.message?.content?.replace(/<think>[\s\S]*?<\/think>/g, "").trim() || null;}+/** Which LLM llmText would ask right now (Claude is the one that costs money). */+export function llmTextBackend(): "claude" | "ollama" | null {+ const choice = getSetting("enhanceProvider");+ if (choice === "none") return null;+ if (choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"))) return "claude";+ return choice === "ollama" || choice === "auto" ? "ollama" : null;+}+/*** One-shot text from whichever LLM this install allows: Claude (when a key is set, and never* on "open source only" installs unless picked explicitly), else a local Ollama. Null when none.+ * `images` go along for a model that can see them (Content Factory's reference frames).*/-export async function llmText(system: string, user: string): Promise<string | null> {- const choice = getSetting("enhanceProvider");- if (choice === "none") return null;- const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));- if (useClaude) return viaClaude(system, user).catch(() => null);- if (choice === "ollama" || choice === "auto") return viaOllama(system, user).catch(() => null);+export async function llmText(system: string, user: string, images: LlmImage[] = []): Promise<string | null> {+ const backend = llmTextBackend();+ if (backend === "claude") return viaClaude(system, user, images).catch(() => null);+ if (backend === "ollama") return viaOllama(system, user, images).catch(() => null);return null;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 39c7cc60..d0e642da 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -224,6 +224,8 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [// Faceless / Explainer: a channel's avatar, style references and voice samples, episode sources.{ table: "faceless_channels", cols: ["avatar_url", "reference_json", "settings_json"] },{ table: "faceless_episodes", cols: ["settings_json", "sources_json"] },+ // Content Factory: a series' reference clip and its thumbnail.+ { table: "content_series", cols: ["data_json"] },];/** Whether anything still refers to this stored file (see ASSET_REFS). */diff --git a/tests/content-factory-api.test.ts b/tests/content-factory-api.test.tsnew file mode 100644index 00000000..ad063fdf--- /dev/null+++ b/tests/content-factory-api.test.ts@@ -0,0 +1,230 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import type { SeriesEstimate, SeriesView } from "@/lib/catalog/content-factory";++// Content Factory's server (r4/content-factory): references (an upload, a link through the guard and the+// SSRF-safe fetch, a preset), reading them into a brief on both engines (demo mode here), prices, "Generate+// here" (a channel and Faceless episodes that carry the brief), "Next episode", and the message for Claude.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-content-factory-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: cloud and open models run on the demo provider, and there's no LLM (the 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 { saveFile } = await import("@/server/storage");+const { getGeneration } = await import("@/server/generations");+const faceless = await import("@/server/faceless");+const cf = await import("@/server/content-factory");+const seriesRoute = await import("@/app/api/content-factory/series/route");+const oneRoute = await import("@/app/api/content-factory/series/[id]/route");+const generateRoute = await import("@/app/api/content-factory/series/[id]/generate/route");+const episodesRoute = await import("@/app/api/content-factory/series/[id]/episodes/route");+const readRoute = await import("@/app/api/content-factory/series/[id]/read/route");+const estimateRoute = await import("@/app/api/content-factory/estimate/route");+const claudeRoute = await import("@/app/api/content-factory/claude/route");++beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++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 params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+const view = (id: string): SeriesView => JSON.parse(JSON.stringify(cf.seriesView(id)));++async function readied(id: string, ms = 60_000): Promise<SeriesView> {+ const end = Date.now() + ms;+ for (;;) {+ const v = view(id);+ if (v.analysis?.status !== "reading") {+ await cf.briefWritten(id);+ return view(id);+ }+ if (Date.now() > end) throw new Error(`still reading: ${v.analysis.stage}`);+ await sleep(300);+ }+}++const clip = () => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-portrait.mp4")), contentType: "video/mp4", name: "reference.mp4", source: "upload" }).url;+const settings = { engine: "cloud" as const, length: 30, episodes: 3, animation: "scene-by-scene" as const, genre: "history" as const, aspect: "9:16" as const };++describe("the reference", () => {+ it("refuses bad links before fetching anything, and asks for an upload where a platform keeps its video", async () => {+ const local = await seriesRoute.POST(json("POST", { reference: { kind: "link", link: "http://localhost:3000/clip.mp4" }, engine: "cloud" }));+ expect(local.status).toBe(400);+ expect((await local.json()).error).toMatch(/public link/);+ const profile = await seriesRoute.POST(json("POST", { reference: { kind: "link", link: "https://www.tiktok.com/@someone" }, engine: "cloud" }));+ expect(profile.status).toBe(400);+ const yt = await seriesRoute.POST(json("POST", { reference: { kind: "link", link: "https://youtu.be/dQw4w9WgXcQ" }, engine: "cloud" }));+ expect(yt.status).toBe(422);+ expect(await yt.json()).toMatchObject({ needsUpload: true, error: expect.stringMatching(/upload it here/) });+ });++ it("fetches a link only through the SSRF-safe fetch: a private address is refused", async () => {+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "link", link: "http://10.1.2.3/reference.mp4" }, engine: "cloud" }));+ expect(res.status).toBe(422);+ expect(await res.json()).toMatchObject({ needsUpload: true, error: expect.stringMatching(/private network/) });+ });++ it("refuses an upload that isn't a video", async () => {+ const img = saveFile({ data: Buffer.from("GIF89a"), contentType: "image/gif", name: "x.gif", source: "upload" }).url;+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "upload", url: img }, engine: "cloud" }));+ expect(res.status).toBe(400);+ });++ it("a preset's brief is ready straight away, for nothing", async () => {+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "dark-history" }, engine: "cloud" }));+ expect(res.status).toBe(201);+ const v: SeriesView = await res.json();+ expect(v.analysis).toMatchObject({ status: "ready", costUsd: 0 });+ expect(v.brief?.styleId).toBeTruthy();+ expect(v.reference).toMatchObject({ kind: "preset", presetId: "dark-history" });+ });+});++describe("reading a clip into a brief", () => {+ it("cloud: frames and a transcript as generations, then the brief (offline in demo mode, and it says so)", async () => {+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "upload", url: clip(), title: "My reference" }, engine: "cloud" }));+ expect(res.status).toBe(201);+ const v: SeriesView = await res.json();+ expect(v.reference).toMatchObject({ kind: "upload", title: "My reference" });+ expect(v.reference?.seconds).toBeGreaterThan(0);+ expect(v.reference?.height).toBeGreaterThan(v.reference!.width!);+ expect(v.analysis).toMatchObject({ engine: "cloud", status: "reading", demo: true });+ const frames = getGeneration(v.analysis!.steps.frames!)!;+ const words = getGeneration(v.analysis!.steps.transcript!)!;+ expect(frames.request).toMatchObject({ feature: "content-factory", modelId: "extract-frames", op: "extract-frames" });+ expect(frames.request.params?.frameInterval).toBeGreaterThanOrEqual(1);+ expect(words.request).toMatchObject({ modelId: "scribe-v2", op: "transcribe" });+ const ready = await readied(v.id);+ expect(ready.analysis).toMatchObject({ status: "ready", offline: true, note: expect.stringMatching(/^Demo brief/) });+ // The clip's own shape wins: a portrait clip gives a 9:16 brief.+ expect(ready.brief).toMatchObject({ aspect: "9:16" });+ }, 90_000);++ it("open: one Gemma 4 generation (reference-brief-gemma4), its first 30 s", async () => {+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "upload", url: clip() }, engine: "open" }));+ const v: SeriesView = await res.json();+ expect(Object.keys(v.analysis!.steps)).toEqual(["brief"]);+ const g = getGeneration(v.analysis!.steps.brief!)!;+ expect(g.request).toMatchObject({ modelId: "oss-reference-brief", op: "write", inputs: { video: expect.stringMatching(/^\/api\/files\//) } });+ expect(g.request.params?.duration).toBeLessThanOrEqual(30);+ const ready = await readied(v.id);+ expect(ready.analysis).toMatchObject({ status: "ready", offline: true, note: expect.stringMatching(/start ComfyUI/) });+ // Read again on the other engine: a new read replaces the old one.+ const again = await readRoute.POST(json("POST", { engine: "cloud" }), params({ id: v.id }));+ expect(((await again.json()) as SeriesView).analysis).toMatchObject({ engine: "cloud", status: "reading" });+ await readied(v.id);+ }, 90_000);++ it("the frame interval asks for about a frame a second, at most 20 over the clip", () => {+ expect(cf.frameInterval(10, 30)).toBe(30);+ expect(cf.frameInterval(60, 30)).toBe(90);+ expect(cf.frameInterval(300, 60)).toBe(300);+ expect(cf.frameInterval(undefined, undefined)).toBe(45);+ expect(cf.spread([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4)).toEqual([1, 4, 7, 10]);+ expect(cf.spread([1, 2], 4)).toEqual([1, 2]);+ });+});++describe("prices, Generate here and Next episode", () => {+ let series: SeriesView;++ it("prices the series before anything runs: one episode at the brief's pace × the episodes", async () => {+ const res = await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "dark-history" }, engine: "cloud" }));+ series = await res.json();+ const est: SeriesEstimate = await (await estimateRoute.POST(json("POST", { prompt: "The lost city of Ys", settings, seriesId: series.id }))).json();+ expect(est.price.episodes).toBe(3);+ expect(est.price.total).toBeCloseTo(est.price.perEpisode * 3, 1);+ expect(est.scenes).toBeGreaterThan(3);+ expect(est.demo).toBe(true);+ const one: SeriesEstimate = await (await estimateRoute.POST(json("POST", { prompt: "x", settings: { ...settings, episodes: 1 }, seriesId: series.id }))).json();+ expect(one.price.total).toBeCloseTo(one.price.perEpisode, 2);+ // The open engine needs a narrator's voice sample first (in demo mode the demo narrator stands in).+ expect(((await (await estimateRoute.POST(json("POST", { prompt: "x", settings: { ...settings, engine: "open" }, seriesId: series.id, voice: null }))).json()) as SeriesEstimate).demo).toBe(true);+ setSetting("demoMode", "off");+ try {+ const open: SeriesEstimate = await (await estimateRoute.POST(json("POST", { prompt: "x", settings: { ...settings, engine: "open" }, seriesId: series.id, voice: null }))).json();+ expect(open.error).toMatch(/narrator's voice/);+ expect(open.analysisPerMinute).toBe(0);+ } finally {+ setSetting("demoMode", "auto");+ }+ // A length outside 30 s – 5 min is refused.+ expect((await estimateRoute.POST(json("POST", { prompt: "x", settings: { ...settings, length: 45 }, seriesId: series.id }))).status).toBe(400);+ });++ it("makes the channel and one Faceless episode per planned title, each carrying the brief", async () => {+ const res = await generateRoute.POST(json("POST", { prompt: "The lost city of Ys", settings }), params({ id: series.id }));+ expect(res.status).toBe(200);+ const v: SeriesView = await res.json();+ expect(v.channel).toBeTruthy();+ expect(v.channel!.settings.brief?.script.join(" ")).toMatch(/Format:/);+ expect(v.plan).toHaveLength(3);+ expect(v.episodes.map((e) => e.title)).toEqual(v.plan.map((p) => p.title));+ const ep = faceless.episodeView(v.episodes[0].id).episode;+ expect(ep.settings).toMatchObject({ length: 30, animation: "frames", aspect: "9:16", brief: { sceneSeconds: expect.any(Number) } });+ expect(ep.topic).toMatch(/^Episode 1 of the series “The lost city of Ys”/);+ expect(faceless.episodeView(v.episodes[2].id).episode.topic).toMatch(/Earlier episodes: .+; .+\./);+ // A second click doesn't make it twice.+ expect((await generateRoute.POST(json("POST", { prompt: "The lost city of Ys", settings }), params({ id: series.id }))).status).toBe(409);+ // GET handlers start with connection(), which needs a request scope: read through the server module.+ const list = cf.listSeries();+ expect(list).toEqual(expect.arrayContaining([expect.objectContaining({ id: series.id, episodes: 3, channelId: v.channel!.id })]));+ });++ it("plans the next episodes after the ones already made", async () => {+ const res = await episodesRoute.POST(json("POST", { count: 2, next: "The bells under the sea ring again" }), params({ id: series.id }));+ const v: SeriesView = await res.json();+ expect(v.plan).toHaveLength(5);+ expect(v.episodes).toHaveLength(5);+ expect(v.plan[3].synopsis).toBe("The bells under the sea ring again");+ const ep = faceless.episodeView(v.episodes[3].id).episode;+ expect(ep.topic).toMatch(/^Episode 4 of the series/);+ expect(ep.settings.brief).toBeTruthy();+ });++ it("a one-video series lets the script writer name it, and a draft without a brief can't run", async () => {+ const one: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();+ const v: SeriesView = await (await generateRoute.POST(json("POST", { prompt: "What if the Moon had a city", settings: { ...settings, episodes: 1, animation: "fully-animated" } }), params({ id: one.id }))).json();+ expect(v.episodes).toHaveLength(1);+ expect(faceless.episodeView(v.episodes[0].id).episode.settings.animation).toBe("animated");+ const empty: SeriesView = await (await seriesRoute.POST(json("POST", { reference: null, engine: "cloud" }))).json();+ const res = await generateRoute.POST(json("POST", { prompt: "x", settings }), params({ id: empty.id }));+ expect(res.status).toBe(400);+ expect((await res.json()).error).toMatch(/reference or pick a preset/);+ });++ it("deletes the series with its channel", async () => {+ const channelId = view(series.id).channel!.id;+ expect((await oneRoute.DELETE(json("DELETE"), params({ id: series.id }))).status).toBe(204);+ expect(faceless.getChannel(channelId)).toBeNull();+ expect(() => cf.seriesView(series.id)).toThrow(/not found/);+ });+});++describe("Generate in Claude", () => {+ it("composes the message from the brief, with nothing sent anywhere", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();+ const res = await claudeRoute.POST(json("POST", { prompt: "What if cats ruled the world", settings, seriesId: s.id, voice: { kind: "preset", id: "JBFqnCBsd6RMkjVDRZzb" } }));+ const out = await res.json();+ expect(out.needsToken).toBe(false);+ expect(out.bytes).toBeLessThanOrEqual(64 * 1024);+ expect(out.message).toContain("series of 3 episodes");+ expect(out.message).toContain('voice "JBFqnCBsd6RMkjVDRZzb"');+ expect(out.message).toContain("faceless_episode");+ expect((await claudeRoute.POST(json("POST", { prompt: " ", settings, seriesId: s.id }))).status).toBe(400);+ });++ it("edits the brief by hand", async () => {+ const s: SeriesView = await (await seriesRoute.POST(json("POST", { reference: { kind: "preset", presetId: "what-if" }, engine: "cloud" }))).json();+ const res = await oneRoute.PATCH(json("PATCH", { brief: { ...s.brief!, hook: "Start on the punchline" } }), params({ id: s.id }));+ expect(((await res.json()) as SeriesView).brief?.hook).toBe("Start on the punchline");+ });+});diff --git a/tests/content-factory.test.ts b/tests/content-factory.test.tsindex ca4e6fed..afdfcf1d 100644--- a/tests/content-factory.test.ts+++ b/tests/content-factory.test.ts@@ -351,13 +351,22 @@ describe("Generate in Claude", () => {expect(m).toContain("Make a video about: What if cars could fly");expect(m).toContain('load_skill "faceless-video"');expect(m).toContain("estimate_job");- expect(m).toMatch(/Run faceless_episode once per episode with style ".+", aspect_ratio "9:16" and voice "JBFqnCBsd6RMkjVDRZzb"/);+ expect(m).toMatch(/Run faceless_episode once per episode with style_id "colorful-3d", style ".+", aspect_ratio "9:16" and voice "JBFqnCBsd6RMkjVDRZzb"/);expect(m).toContain("never the reference's people");expect(m).not.toContain("voice_sample");expect(m).not.toMatch(/\n\n\n/);expect(claudeMessage({ ...base, episodes: 1, engine: "open" })).toMatch(/^Make a faceless short-video episode[\s\S]*voice_sample/);});+ it("splits a long episode into parts of at most 8 scenes (the tool's limit)", () => {+ // 1 min fits in 8 scenes of 7–8 s; 3 min needs 18 scenes of 10 s: 3 parts of 6.+ expect(claudeMessage({ ...base, length: 60 })).toMatch(/write 8 scenes: narration of at most \d+ words each \(about 8 s spoken\)/);+ const m = claudeMessage({ ...base, length: 180, episodes: 1 });+ expect(m).toMatch(/as 3 parts of about 6 scenes/);+ expect(m).toContain("Run faceless_episode once per part");+ expect(claudeMessage({ ...base, length: 30 })).not.toContain("parts of");+ });+it("stays within 64 KB however long the prompt is", () => {const m = claudeMessage({ ...base, prompt: "flying cars ".repeat(20_000) });expect(new TextEncoder().encode(m).length).toBeLessThanOrEqual(MAX_CLAUDE_MESSAGE);