Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Assist: chained plans, offline planner patterns, new kinds and ops for agents

Claude93ec45635fb3
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index af8856b7..38a6bc5d 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -8,7 +8,7 @@ import { db } from "../db";
import { getGeneration } from "../generations";
import { engineMode, getSetting } from "../settings";
import { readRef } from "../storage";
-import { apiTools, executeTool, getTool, planFor, type ToolContext } from "./tools";
+import { apiTools, executeTool, getTool, planFor, validateInput, type ToolContext } from "./tools";
/**
* The Assist agent loop. History is kept exactly as the API returned it (append-only, thinking
@@ -217,7 +217,8 @@ function closeDanglingToolUses(messages: MessageParam[]): void {
}
}
-const FILE_KIND = (url: string) => (/\.(mp4|webm|mov|mkv)$/i.test(url) ? "video" : /\.(mp3|wav|ogg|m4a|flac|aac)$/i.test(url) ? "audio" : "image");
+const FILE_KIND = (url: string) =>
+ /\.(mp4|webm|mov|mkv)$/i.test(url) ? "video" : /\.(mp3|wav|ogg|m4a|flac|aac)$/i.test(url) ? "audio" : /\.(txt|srt|vtt|json)$/i.test(url) ? "text" : /\.(glb|gltf)$/i.test(url) ? "model3d" : "image";
function userBlocks(text: string, attachments: string[]): UserBlock[] {
const blocks: UserBlock[] = [];
@@ -268,7 +269,8 @@ How you work:
- Look up models with search_models before you generate, and pick the model that best fits the job, the user's engine preference and their budget. Prefer connected models. Mention the model you picked and why in one line.
- Write rich, specific prompts: subject, setting, light, lens and composition; for video, the motion and camera move in time order. Keep any text the user wants rendered exactly.
- 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; a hero shot, then variations), wait for the first results with check_generations and pass its output URL into the next generate call. Use look=true when judging the results matters.
+- 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.
- 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.`;
@@ -394,28 +396,70 @@ export const offline: ModelCall = async ({ messages, ctx }) => {
const plan = offlinePlan(said, ctx.engine);
if (!plan) return reply([text("Tell me what to make — an image, a video, a voice-over or a storyboard — and attach any photos to use.")], "end_turn");
return reply(
- [text(plan.say), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: plan.tool, input: plan.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],
+ [text(`${plan.say}\n\n${OFFLINE_NOTE}`), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: plan.tool, input: plan.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],
"tool_use",
);
};
+/** Under every offline plan: the rule-based planner is a fallback, not the assistant. */
+export const OFFLINE_NOTE = "Offline planner — connect Claude or Ollama in Settings for better plans.";
+
const NUMBER_WORDS: Record<string, number> = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8 };
+const NUM = "(\\d|one|two|three|four|five|six|seven|eight)";
+const num = (s: string) => NUMBER_WORDS[s] ?? Number(s);
-/** Read a request like "3 vertical videos of a fox, animate this" into one tool call. */
+/**
+ * Read a request into one tool call: counts ("3 vertical videos", "4 portraits"), formats,
+ * attachments, multi-shot ("a 3-shot ad"), a still that is then animated (two chained jobs),
+ * storyboards, music and voice-overs, translations and scripts.
+ */
export function offlinePlan(message: string, preferred: Engine): { tool: string; input: Record<string, unknown>; say: string } | null {
const [body, attached = ""] = message.split(/\n\nAttached files[^\n]*\n/);
const text = body.trim();
if (!text) return null;
- const files = [...attached.matchAll(/^- (image|video|audio) \d+: (\S+)$/gm)].map((m) => ({ kind: m[1], url: m[2] }));
+ const files = [...attached.matchAll(/^- (image|video|audio|text|model3d) \d+: (\S+)$/gm)].map((m) => ({ kind: m[1], url: m[2] }));
const images = files.filter((f) => f.kind === "image").map((f) => f.url);
const t = text.toLowerCase();
const mode = engineMode();
const engine: Engine = mode === "both" ? preferred : mode;
const count = (() => {
- const m = /\b(\d|one|two|three|four|five|six|seven|eight)\s+(?:\w+\s+)?(images?|pictures?|photos?|versions?|takes?|variations?|options?|videos?|clips?|frames?|panels?|scenes?|shots?)\b/.exec(t);
- return m ? (NUMBER_WORDS[m[1]] ?? Number(m[1])) : undefined;
+ const m = new RegExp(
+ `\\b${NUM}\\s+(?:[\\w-]+\\s+)?(images?|pictures?|photos?|portraits?|headshots?|avatars?|stills?|posters?|thumbnails?|logos?|icons?|looks?|renders?|versions?|takes?|variations?|options?|videos?|clips?|frames?|panels?|scenes?)\\b`,
+ ).exec(t);
+ return m ? num(m[1]) : undefined;
+ })();
+ // "a 3-shot ad", "in 4 shots": one clip cut into shots, not several clips.
+ const shots = (() => {
+ const m = new RegExp(`\\b${NUM}[- ]shots?\\b`).exec(t) ?? new RegExp(`\\bin\\s+${NUM}\\s+shots\\b`).exec(t);
+ return m ? Math.max(2, Math.min(6, num(m[1]))) : undefined;
})();
const aspect = /\b(vertical|portrait|9:16|reels?|tiktok|stories|story format)\b/.test(t) ? "9:16" : /\b(square|1:1)\b/.test(t) ? "1:1" : /\b(wide|landscape|16:9|widescreen)\b/.test(t) ? "16:9" : undefined;
+ const pick = (d: { cloud: string; open: string }) => (engine === "open" && d.open ? d.open : d.cloud);
+ const textModel = engine === "open" ? "oss-text-llm" : "text-llm";
+
+ // "… hero still, then animate it": the image first, then a video made from it (one plan, two chained jobs).
+ const thenAnimate = /\bthen\b[^.?!]*\b(animate|animated|animation|bring (it|them) to life|make (it|them) move|turn (it|them) into an? (video|clip))\b/.test(t);
+ const [beforeThen] = text.split(/[,;]?\s*\bthen\b/i);
+ if (thenAnimate && /\b(still|photo|picture|image|portrait|poster|frame|shot|render|key ?visual)\b/i.test(beforeThen)) {
+ const subject = beforeThen
+ .replace(new RegExp(`\\b${NUM}[- ]shots?\\s*`, "i"), "")
+ .replace(/\s{2,}/g, " ")
+ .replace(/[\s,;:—–-]+$/, "")
+ .trim();
+ const still = { model_id: pick(images.length ? EDIT_STUDIO.defaultModels : IMAGE_STUDIO.defaultModels), prompt: subject, ...(images.length && { images: images.slice(0, 4) }), ...(aspect && { aspect_ratio: aspect }) };
+ const clip = {
+ model_id: pick(VIDEO_STUDIO.defaultModels),
+ prompt: `${subject}. The still comes to life: smooth, cinematic camera motion, natural movement.`,
+ after: 0,
+ ...(shots && { shots }),
+ ...(aspect && { aspect_ratio: aspect }),
+ };
+ return {
+ tool: "generate",
+ input: { summary: `Still, then animated: ${subject.slice(0, 70)}`, jobs: [still, clip] },
+ say: `I'll make the still first, then animate it${shots ? ` as a ${shots}-shot clip` : ""} — the video starts by itself as soon as the still is ready.`,
+ };
+ }
if (/\b(storyboard|comic|panels|shot list)\b/.test(t) || (count && /\b(frames|scenes|panels)\b/.test(t))) {
const frames = Math.max(1, Math.min(8, count ?? 4));
@@ -425,10 +469,29 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
say: `I'll split that into ${frames} frames with the same characters and look, each made from the one before.`,
};
}
- const pick = (d: { cloud: string; open: string }) => (engine === "open" && d.open ? d.open : d.cloud);
+
+ // Text steps: translations and scripts run on the LLM (demo text when none is connected).
+ const lang = /\btranslat\w*\b[^:]*?\b(?:into|to)\s+([a-z]+(?:\s\([^)]*\))?)/i.exec(text)?.[1];
+ if (lang && /\btranslat/.test(t)) {
+ const language = lang.charAt(0).toUpperCase() + lang.slice(1);
+ const source = /["“]([^"”]+)["”]/.exec(text)?.[1] ?? (text.includes(":") ? text.slice(text.indexOf(":") + 1).trim() : text);
+ return {
+ tool: "generate",
+ input: { summary: `Translate into ${language}`, jobs: [{ model_id: textModel, op: "translate", prompt: source, target_language: language }] },
+ say: `I'll translate that into ${language}.`,
+ };
+ }
const isMusic = /\b(music|song|soundtrack|beat|jingle)\b/.test(t);
+ const isWriting = !isMusic && /^(please\s+)?(write|draft|come up with|give me)\b/.test(t) && /\b(script|scripts|copy|captions?|taglines?|slogans?|hooks?|outline|story|poem|email|description|post|blog|headlines?|lines)\b/.test(t);
+ if (isWriting) {
+ return {
+ tool: "generate",
+ input: { summary: `Write: ${text.slice(0, 80)}`, jobs: [{ model_id: textModel, op: "write", prompt: text }] },
+ say: "I'll write that for you.",
+ };
+ }
const isSpeech = !isMusic && /\b(voice ?over|narrat\w*|read (this|it|out)|say|speak|text to speech|tts)\b/.test(t);
- const isVideo = !isMusic && !isSpeech && (files.some((f) => f.kind === "video") || /\b(videos?|clips?|animate|animation|motion|films?|footage|movies?|trailers?|commercials?)\b/.test(t));
+ const isVideo = !isMusic && !isSpeech && (files.some((f) => f.kind === "video") || !!shots || /\b(videos?|clips?|animate|animation|motion|films?|footage|movies?|trailers?|commercials?|ads?)\b/.test(t));
if (isMusic || isSpeech) {
const quoted = /["“]([^"”]+)["”]/.exec(text)?.[1] ?? text.replace(/^.*?:\s*/, "");
return {
@@ -439,8 +502,20 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
}
const studio = isVideo ? VIDEO_STUDIO : images.length ? EDIT_STUDIO : IMAGE_STUDIO;
const n = Math.max(1, Math.min(4, count ?? (isVideo ? 1 : 2)));
- const job = { model_id: pick(studio.defaultModels), prompt: text, ...(images.length && { images: images.slice(0, isVideo ? 1 : 4) }), ...(aspect && { aspect_ratio: aspect }), ...(n > 1 && { outputs: n }) };
- const what = isVideo ? (images.length ? "animate your image" : "make the video") : images.length ? "edit your image" : `make ${n} take${n === 1 ? "" : "s"}`;
+ const multi = isVideo && shots ? shots : undefined;
+ const job = {
+ model_id: pick(studio.defaultModels),
+ prompt: text,
+ ...(images.length && { images: images.slice(0, isVideo ? 1 : 4) }),
+ ...(aspect && { aspect_ratio: aspect }),
+ ...(n > 1 && { outputs: n }),
+ ...(multi && { shots: multi }),
+ };
+ const what = isVideo
+ ? `${images.length ? "animate your image" : "make the video"}${multi ? ` as ${multi} shots` : ""}`
+ : images.length
+ ? "edit your image"
+ : `make ${n} take${n === 1 ? "" : "s"}`;
return { tool: "generate", input: { summary: `${isVideo ? "Video" : images.length ? "Edit" : "Image"}: ${text.slice(0, 80)}`, jobs: [job] }, say: `I'll ${what} with the default ${isVideo ? "video" : "image"} model.` };
}
@@ -494,6 +569,12 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
const gated: Pending["gated"] = [];
for (const u of uses) {
if (getTool(u.name)?.gated && !s.thread.autoApprove) {
+ // Malformed arguments (common from small local models) go straight back as an error the model can fix, not onto an approval card.
+ const invalid = validateInput(u.name, u.input);
+ if (invalid) {
+ results.push({ type: "tool_result", tool_use_id: u.id, is_error: true, content: invalid });
+ continue;
+ }
gated.push({ id: u.id, name: u.name, input: u.input });
continue;
}
@@ -589,8 +670,7 @@ function decline(s: State, why = "The user declined this plan. Ask what they'd l
return ordered([...p.results, ...p.gated.map((g) => ({ type: "tool_result" as const, tool_use_id: g.id, is_error: true, content: why }))], p.order);
}
-async function approve(s: State): Promise<ToolResult[]> {
- const p = settle(s, true);
+async function runApproved(s: State, p: Pending): Promise<ToolResult[]> {
const results = [...p.results];
for (const g of p.gated) {
const { result, items } = await runTool(g.name, g.input, { engine: s.thread.engine });
@@ -604,10 +684,27 @@ async function approve(s: State): Promise<ToolResult[]> {
export async function answerApproval(id: string, ok: boolean): Promise<AssistThread> {
const s = load(id);
if (!s) throw new Error("Not found");
- if (!s.pending || s.thread.status !== "waiting") throw new AssistBusyError("Nothing is waiting for approval");
- const results = ok ? await approve(s) : decline(s);
- s.messages.push({ role: "user", content: results });
- s.thread.status = "running";
- save(s);
+ if (!s.pending || s.thread.status !== "waiting" || runs.has(id)) throw new AssistBusyError("Nothing is waiting for approval");
+ if (!ok) {
+ s.messages.push({ role: "user", content: decline(s) });
+ s.thread.status = "running";
+ save(s);
+ return s.thread;
+ }
+ // Claim the thread before the first await: a second approval (another tab, a retry) or a new
+ // message now finds it busy instead of running the same paid plan twice or being overwritten.
+ runs.add(id);
+ try {
+ const p = settle(s, true);
+ s.thread.status = "running";
+ save(s);
+ const results = await runApproved(s, p);
+ s.messages.push({ role: "user", content: results });
+ // Keep a toggle the user flipped meanwhile.
+ s.thread.autoApprove = (db().prepare("SELECT auto_approve FROM assist_threads WHERE id = ?").get(id) as { auto_approve: number } | undefined)?.auto_approve === 1;
+ save(s);
+ } finally {
+ runs.delete(id);
+ }
return s.thread;
}
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index c894e695..23cb5af9 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -1,13 +1,15 @@
import "server-only";
import type Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
-import { modelsFor } from "@/lib/catalog";
-import { OPERATION_LABELS, type GenerationRequest, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";
+import { getModel, modelsFor } from "@/lib/catalog";
+import { OPERATION_LABELS, type ChainSlot, type GenerationRequest, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";
import { type AssistItem, type PlannedJob, totalCost } from "@/lib/assist";
import { STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
+import { createPipeline } from "../chains";
import { listElements } from "../elements";
-import { createGenerations, getGeneration, listGenerations, previewGeneration } from "../generations";
+import { createGenerations, getGeneration, listGenerations, outputKind, previewChained, previewGeneration } from "../generations";
import { provider } from "../providers";
+import { llmBackends } from "../providers/llm";
import { engineMode } from "../settings";
import { readRef } from "../storage";
import { createStoryboard } from "../storyboard";
@@ -44,19 +46,21 @@ const ref = z.string().describe("A file URL from the chat: an attachment or an e
// ---------------------------------------------------------------------------
// search_models
-const KINDS = ["image", "video", "audio"] as const;
+/** Output kinds: "text" = transcripts, translations and scripts; "model3d" = 3D models (.glb). */
+const KINDS = ["image", "video", "audio", "text", "model3d"] as const;
function summarize(m: ModelDef) {
const o = m.options;
- const configured = m.routes.some((r) => provider(r.provider).isConfigured());
+ const local = m.routes.some((r) => r.provider === "llm");
+ const configured = m.routes.some((r) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured()));
return {
id: m.id,
name: m.name,
vendor: m.vendor,
- engine: m.engine === "open" ? "open source (ComfyUI)" : "paid cloud API",
+ engine: m.engine === "open" ? (local ? "open source (Ollama, on this machine)" : "open source (ComfyUI)") : local ? "Claude (or Ollama when no key is set)" : "paid cloud API",
about: m.tagline,
does: [...new Set(m.routes.map((r) => r.op))].map((op) => `${op} (${OPERATION_LABELS[op]})`),
- price: m.engine === "open" ? "free (your GPU)" : m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}` : "unknown",
+ price: m.engine === "open" ? (local ? "free (your machine)" : "free (your GPU)") : m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}` : "unknown",
connected: configured,
...(o.aspectRatios && { aspectRatios: o.aspectRatios }),
...(o.resolutions && { resolutions: o.resolutions }),
@@ -68,6 +72,7 @@ function summarize(m: ModelDef) {
...(o.multiShot && { multiShot: `up to ${o.multiShot.maxShots} shots` }),
...(o.voices?.length && { voices: o.voices.slice(0, 12).map((v) => v.id) }),
...(o.voiceClone && { voiceClone: true }),
+ ...(o.languages?.length && { languages: o.languages.length > 12 ? `${o.languages.slice(0, 12).join(", ")}…` : o.languages.join(", ") }),
...(o.presets && { needs: o.presets.required ? `a ${o.presets.label} (pick in the studio)` : undefined }),
};
}
@@ -77,8 +82,13 @@ const searchModels = defineTool({
description:
"Look up the models this studio can run for a kind of output. Call it before generate whenever you haven't already looked up models for this kind of job in this chat, and whenever the user names a model, asks what's best or cheapest, or wants a capability (audio, end frame, multi-shot, a voice). Returns ids, what each does, price, options and whether a provider is connected.",
schema: z.object({
- kind: z.enum(KINDS).describe("Output kind."),
- task: z.string().optional().describe("Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image."),
+ kind: z.enum(KINDS).describe("Output kind: image, video, audio, text (transcripts, translations, scripts) or model3d (3D models)."),
+ task: z
+ .string()
+ .optional()
+ .describe(
+ "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d.",
+ ),
query: z.string().optional().describe("Words to match in the model name, vendor or description, e.g. 'kling', 'cheap', 'photoreal'."),
}),
async run({ kind, task, query }, ctx) {
@@ -144,10 +154,26 @@ function genSummary(id: string) {
...(g.progress !== null && g.status === "running" && { progress: g.progress }),
...(g.error && { error: g.error }),
...(g.provider === "mock" && { demo: true }),
- outputs: g.outputs.map((o) => ({ url: o.url, kind: o.kind, ...(o.draftId && { draftId: o.draftId }) })),
+ outputs: g.outputs.map((o) => ({
+ url: o.url,
+ kind: o.kind,
+ ...(o.draftId && { draftId: o.draftId }),
+ // Text results are read, not opened: a transcript, translation or script comes back inline.
+ ...(o.text !== undefined && { text: o.text.length > 6000 ? `${o.text.slice(0, 6000)}… (${o.text.length} characters; the full text is at the URL)` : o.text }),
+ ...(o.meta && outputMeta(o.meta)),
+ })),
};
}
+/** The structured extras worth telling a model about (layer names and boxes, stems, cue counts). */
+function outputMeta(meta: Record<string, unknown>) {
+ const out: Record<string, unknown> = {};
+ for (const k of ["name", "z", "bbox", "stem", "language", "turntable", "demo"]) if (meta[k] !== undefined) out[k] = meta[k];
+ if (Array.isArray(meta.cues)) out.cues = meta.cues.length;
+ if (Array.isArray(meta.textBlocks)) out.textBlocks = meta.textBlocks;
+ return Object.keys(out).length ? { meta: out } : {};
+}
+
const listRecent = defineTool({
name: "list_recent",
description:
@@ -208,29 +234,67 @@ const checkGenerations = defineTool({
const Job = z.object({
model_id: z.string().describe("Model id from search_models."),
- prompt: z.string().describe("The full prompt. Put @handles here to use saved elements."),
- op: z.string().optional().describe("Operation id (t2i, edit, t2v, i2v, flf2v, ref2v, extend, tts…). Usually inferred from the inputs; set it when ambiguous."),
+ prompt: z.string().describe("The full prompt (for translate: the text to translate; for write: the brief). Put @handles here to use saved elements."),
+ op: z
+ .string()
+ .optional()
+ .describe(
+ "Operation id (t2i, edit, t2v, i2v, flf2v, ref2v, extend, tts, layers, transcribe, translate, write, trim, captions, mux, separate-audio, image-to-3d…). Usually inferred from the inputs; set it when ambiguous.",
+ ),
images: z.array(ref).optional().describe("Input images: the image to edit, the start frame, or references, in order."),
end_image: ref.optional().describe("End frame (first-and-last-frame video)."),
- video: ref.optional().describe("Input video (extend, edit, lipsync, upscale…)."),
- audio: ref.optional().describe("Input audio (lipsync, avatar)."),
+ video: ref.optional().describe("Input video (extend, edit, lipsync, upscale, trim, captions, transcribe…)."),
+ audio: ref.optional().describe("Input audio (lipsync, avatar, transcribe, separate-audio, mux)."),
+ voice_audio: ref.optional().describe("A recording of the voice to speak with (voice-cloning text to speech)."),
aspect_ratio: z.string().optional().describe("e.g. 16:9, 9:16, 1:1 — one the model lists."),
resolution: z.string().optional().describe("e.g. 1080p, 2K — one the model lists."),
duration: z.number().optional().describe("Seconds, for video and music — one the model lists."),
outputs: z.number().int().optional().describe("How many takes (1–4)."),
+ shots: z.number().int().optional().describe("Multi-shot video: cut the clip into this many shots (2–6), for models that list multi-shot."),
generate_audio: z.boolean().optional().describe("Native audio on/off, for video models that offer it."),
voice: z.string().optional().describe("Voice id for text to speech."),
+ target_language: z.string().optional().describe("Language to translate or dub into, e.g. Spanish."),
+ source_language: z.string().optional().describe("Language of the source speech or text, if known."),
+ start_time: z.number().optional().describe("Trim: where the kept part starts, in seconds."),
+ end_time: z.number().optional().describe("Trim: where the kept part ends, in seconds."),
+ num_layers: z.number().int().optional().describe("Layers: how many layers to split the image into."),
+ system: z.string().optional().describe("Write: extra instructions for the writer (tone, format, length)."),
+ after: z
+ .number()
+ .int()
+ .optional()
+ .describe(
+ "Index (0-based) of an earlier job in this same call whose result this job uses: it starts by itself when that job finishes. An image becomes the start frame or the image to edit, a video the input video, audio the soundtrack (or the voice to clone, for tts), text the prompt.",
+ ),
negative_prompt: z.string().optional(),
});
type JobInput = z.infer<typeof Job>;
+const SHOT_TYPES = ["Wide establishing shot", "Medium shot", "Close-up", "Detail shot", "Low-angle hero shot", "Slow push-in to the final frame"];
+
+/** n shots that fit the model: per-shot clips for joined (open) models, one total length for the others. */
+function shotList(model: ModelDef | undefined, n: number): { prompt: string; duration: number }[] | undefined {
+ const ms = model?.options.multiShot;
+ if (!ms) return undefined;
+ const count = Math.max(2, Math.min(ms.maxShots, n));
+ const durations = model.options.durations ?? [];
+ let each = model.defaults?.duration ?? 5;
+ if (ms.mode !== "concat") {
+ const total = [...durations].sort((a, b) => a - b).find((d) => d % count === 0 && d / count >= 3) ?? Math.max(...durations, count * 3);
+ each = total / count;
+ }
+ return Array.from({ length: count }, (_, i) => ({ prompt: SHOT_TYPES[i % SHOT_TYPES.length], duration: each }));
+}
+
function toRequest(j: JobInput): GenerationRequest {
const inputs = {
...(j.images?.length && { images: j.images }),
...(j.end_image && { endImage: j.end_image }),
...(j.video && { video: j.video }),
...(j.audio && { audio: j.audio }),
+ ...(j.voice_audio && { voiceAudio: j.voice_audio }),
};
+ const shots = j.shots && j.shots > 1 ? shotList(getModel(j.model_id), j.shots) : undefined;
return {
feature: "assist",
modelId: j.model_id,
@@ -241,41 +305,115 @@ function toRequest(j: JobInput): GenerationRequest {
params: {
aspectRatio: j.aspect_ratio,
resolution: j.resolution,
- duration: j.duration,
+ duration: shots ? undefined : j.duration,
numOutputs: j.outputs ? Math.max(1, Math.min(4, j.outputs)) : undefined,
generateAudio: j.generate_audio,
voice: j.voice,
+ targetLanguage: j.target_language,
+ sourceLanguage: j.source_language,
+ startTime: j.start_time,
+ endTime: j.end_time,
+ numLayers: j.num_layers,
+ ...(shots && { shots }),
+ ...(j.system && { extra: { system: j.system } }),
},
};
}
-function planJob(j: JobInput): PlannedJob {
- const req = toRequest(j);
- try {
- const p = previewGeneration(req);
- return { tool: "generate", modelId: p.model.id, modelName: p.model.name, kind: p.model.kind, op: p.op, prompt: j.prompt, count: p.outputs, costUsd: p.costUsd, demo: p.demo };
- } catch (e) {
- return { tool: "generate", modelId: j.model_id, modelName: j.model_id, kind: "image", op: (j.op as Operation) ?? "t2i", prompt: j.prompt, count: 0, costUsd: 0, demo: false, error: (e as Error).message };
+/** Where an earlier job's result goes in a later one, by what it is and what the later job does. */
+function slotFor(kind: MediaKind, op: Operation | undefined): ChainSlot {
+ if (kind === "text") return { slot: "prompt" };
+ if (kind === "video") return { slot: op === "concat" ? "videos" : "video" };
+ if (kind === "audio") return { slot: op === "tts" || op === "voice-change" ? "voiceAudio" : "audio" };
+ return { slot: "images", position: "first" };
+}
+
+interface ChainedJob {
+ job: JobInput;
+ req: GenerationRequest;
+ /** Index of the job this one waits for. */
+ after?: number;
+ preview?: ReturnType<typeof previewChained>;
+ error?: string;
+}
+
+/** Validate and price the jobs of one generate call, wiring `after` into chain slots. Never throws. */
+function chainJobs(jobs: JobInput[]): ChainedJob[] {
+ const out: ChainedJob[] = [];
+ jobs.forEach((job, i) => {
+ const req = toRequest(job);
+ const after = job.after;
+ if (after === undefined) {
+ try {
+ out.push({ job, req, preview: previewChained(req, 0) });
+ } catch (e) {
+ out.push({ job, req, error: (e as Error).message });
+ }
+ return;
+ }
+ const dep = out[after];
+ if (!Number.isInteger(after) || after < 0 || after >= i || !dep) {
+ out.push({ job, req, after, error: `"after" must point at an earlier job in this call (0–${i - 1})` });
+ return;
+ }
+ if (!dep.preview) {
+ out.push({ job, req, after, error: `Job ${after} can't run, so this one can't either` });
+ return;
+ }
+ const chained: GenerationRequest = { ...req, chain: [slotFor(outputKind(dep.preview.op, dep.preview.model), req.op)] };
+ try {
+ out.push({ job, req: chained, after, preview: previewChained(chained, 1) });
+ } catch (e) {
+ out.push({ job, req: chained, after, error: (e as Error).message });
+ }
+ });
+ return out;
+}
+
+function plannedJob(c: ChainedJob): PlannedJob {
+ if (c.preview) {
+ const p = c.preview;
+ return { tool: "generate", modelId: p.model.id, modelName: p.model.name, kind: outputKind(p.op, p.model), op: p.op, prompt: c.job.prompt, count: p.outputs, costUsd: p.costUsd, demo: p.demo };
}
+ const m = getModel(c.job.model_id);
+ return { tool: "generate", modelId: c.job.model_id, modelName: m?.name ?? c.job.model_id, kind: m?.kind ?? "image", op: (c.job.op as Operation) ?? "t2i", prompt: c.job.prompt, count: 0, costUsd: 0, demo: false, error: c.error };
}
const GenerateInput = z.object({
summary: z.string().describe("One short sentence describing the plan, shown on the approval card."),
- jobs: z.array(Job).describe("1–6 jobs. Jobs in one call run in parallel; to use one job's output in another, call generate again after check_generations."),
+ jobs: z
+ .array(Job)
+ .describe("1–6 jobs. Jobs run in parallel, except a job with \"after\", which waits for that earlier job and uses its result (a still, then animate it; transcribe, then translate, then voice it)."),
});
const generate = defineTool({
name: "generate",
description:
- "Start image, video or audio generations. The app shows the user the plan with its cost and runs it once they approve, so call this directly instead of asking for confirmation in text. Returns generation ids; their results appear in the chat by themselves.",
+ "Start image, video, audio, text (transcribe, translate, write) or 3D generations, alone or chained with \"after\". The app shows the user the plan with its cost and runs it once they approve, so call this directly instead of asking for confirmation in text. Returns generation ids; their results appear in the chat by themselves.",
schema: GenerateInput,
gated: true,
strict: true,
- plan: ({ jobs }) => jobs.slice(0, 6).map(planJob),
+ plan: ({ jobs }) => chainJobs(jobs.slice(0, 6)).map(plannedJob),
async run({ jobs }) {
+ const list = jobs.slice(0, 6);
+ if (list.some((j) => j.after !== undefined)) {
+ // Chained jobs: one pipeline, created only if every step is valid.
+ const chained = chainJobs(list);
+ const bad = chained.findIndex((c) => c.error);
+ if (bad >= 0) return { content: JSON.stringify({ error: `Job ${bad}: ${chained[bad].error}` }), isError: true };
+ const p = createPipeline(chained.map((c, i) => ({ key: `job${i}`, request: c.req, ...(c.after !== undefined && { after: `job${c.after}` }) })));
+ const results = chained.map((c, i) => {
+ const g = p.byKey[`job${i}`];
+ return { model: c.job.model_id, started: [g.id], ...(c.after !== undefined && { waitsFor: p.byKey[`job${c.after}`].id }), demo: g.provider === "mock" || undefined, costUsd: g.costUsd || undefined };
+ });
+ return {
+ content: JSON.stringify({ results, note: "Chained jobs start by themselves when the job they wait for finishes." }),
+ items: [{ id: "", role: "generations", ids: p.items.map((g) => g.id) }],
+ };
+ }
const ids: string[] = [];
const results: unknown[] = [];
- for (const j of jobs.slice(0, 6)) {
+ for (const j of list) {
try {
const gens = createGenerations(toRequest(j));
ids.push(...gens.map((g) => g.id));
@@ -381,9 +519,23 @@ export function apiTools(): Anthropic.Beta.BetaTool[] {
}));
}
-export function planFor(name: string, input: unknown, ctx: ToolContext): { jobs: PlannedJob[]; total: number | null } {
+const describeIssues = (issues: { path: PropertyKey[]; message: string }[]) => `Invalid input: ${issues.map((i) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}`;
+
+/** The error a tool call's arguments would get, or null when they're valid. */
+export function validateInput(name: string, input: unknown): string | null {
+ const tool = getTool(name);
+ if (!tool) return `Unknown tool ${name}`;
+ const parsed = tool.schema.safeParse(input);
+ 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 } {
const t = getTool(name);
- const jobs = t?.plan?.(input, ctx) ?? [];
+ 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) };
}
@@ -392,7 +544,7 @@ export async function executeTool(name: string, input: unknown, ctx: ToolContext
const tool = getTool(name);
if (!tool) return { content: `Unknown tool ${name}`, isError: true };
const parsed = tool.schema.safeParse(input);
- if (!parsed.success) return { content: `Invalid input: ${parsed.error.issues.map((i: { path: PropertyKey[]; message: string }) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}`, isError: true };
+ if (!parsed.success) return { content: describeIssues(parsed.error.issues), isError: true };
try {
return await tool.run(parsed.data, ctx);
} catch (e) {
diff --git a/src/server/mcp.ts b/src/server/mcp.ts
index 4fe1cbf8..0d6bf9cd 100644
--- a/src/server/mcp.ts
+++ b/src/server/mcp.ts
@@ -13,9 +13,10 @@ import { engineMode } from "./settings";
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.0.0" };
const INSTRUCTIONS =
- "Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows). " +
- "Look up models with search_models, price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " +
- "Generations run in the background: poll check_generations (wait_seconds up to 120) for output URLs. Output URLs are paths on this Fuobe server.";
+ "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). ' +
+ "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.";
interface JsonRpcRequest {
jsonrpc: "2.0";
diff --git a/tests/assist-runtime.test.ts b/tests/assist-runtime.test.ts
new file mode 100644
index 00000000..e3ec1ac5
--- /dev/null
+++ b/tests/assist-runtime.test.ts
@@ -0,0 +1,195 @@
+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 { z } from "zod";
+import type Anthropic from "@anthropic-ai/sdk";
+
+vi.setConfig({ testTimeout: 60_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-rt-"));
+process.env.FUOBE_DATA_DIR = dir;
+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 agent = await import("@/server/assist/agent");
+const tools = await import("@/server/assist/tools");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+
+type Msg = Anthropic.Beta.BetaMessage;
+type Block = Anthropic.Beta.BetaContentBlock;
+const toolUse = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Block;
+const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;
+const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason) => ({ content, stop_reason: stop, stop_details: null }) as Msg;
+
+function scripted(...turns: Msg[]) {
+ const seen: Anthropic.Beta.BetaMessageParam[][] = [];
+ const call: import("@/server/assist/agent").ModelCall = async ({ messages }) => {
+ seen.push(structuredClone(messages));
+ const next = turns.shift();
+ if (!next) throw new Error("script ran out");
+ return next;
+ };
+ return { call, seen };
+}
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const dependsOn = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;
+
+describe("offline planner (U18)", () => {
+ it("makes a still, then animates it, for 'hero still, then animate it' — with the shots it asked for", () => {
+ const p = agent.offlinePlan("A 3-shot product ad for a matte black perfume bottle — hero still, then animate it", "cloud")!;
+ expect(p.tool).toBe("generate");
+ const jobs = (p.input as { jobs: Record<string, unknown>[] }).jobs;
+ expect(jobs).toHaveLength(2);
+ expect(jobs[0]).toMatchObject({ model_id: "nano-banana-pro", prompt: "A product ad for a matte black perfume bottle — hero still" });
+ expect(jobs[0].after).toBeUndefined();
+ expect(jobs[1]).toMatchObject({ model_id: "seedance-2-5", after: 0, shots: 3 });
+ expect(p.say).toMatch(/still first, then animate it as a 3-shot clip/);
+ // The open engine picks the open defaults.
+ expect((agent.offlinePlan("A photo of a lighthouse, then animate it", "open")!.input as { jobs: { model_id: string }[] }).jobs.map((j) => j.model_id)).toEqual(["oss-z-image-turbo", "oss-wan22-14b-fast"]);
+ });
+
+ it("reads 'N portraits' as N takes and 'N-shot' video as one multi-shot clip", () => {
+ expect(agent.offlinePlan("4 portraits of a jazz singer in a smoky club", "cloud")).toMatchObject({ input: { jobs: [{ model_id: "nano-banana-pro", outputs: 4 }] } });
+ const shot = agent.offlinePlan("a 3-shot video of a fox running through snow", "cloud")!;
+ expect(shot.input).toMatchObject({ jobs: [{ model_id: "seedance-2-5", shots: 3 }] });
+ expect((shot.input as { jobs: { outputs?: number }[] }).jobs[0].outputs).toBeUndefined();
+ // Still a storyboard when it asks for frames.
+ expect(agent.offlinePlan("6 frames of a heist in Paris", "cloud")).toMatchObject({ tool: "create_storyboard", input: { frames: 6 } });
+ });
+
+ it("sends translations and scripts to the text model", () => {
+ expect(agent.offlinePlan("Translate into Spanish: Welcome to our studio", "cloud")).toMatchObject({
+ input: { jobs: [{ model_id: "text-llm", op: "translate", prompt: "Welcome to our studio", target_language: "Spanish" }] },
+ });
+ expect(agent.offlinePlan("Write a 30-second voice-over script about cold brew", "open")).toMatchObject({ input: { jobs: [{ model_id: "oss-text-llm", op: "write" }] } });
+ // Songs are still music.
+ expect(agent.offlinePlan("Write a lo-fi song for studying", "open")).toMatchObject({ input: { jobs: [{ model_id: "oss-ace-step" }] } });
+ });
+
+ it("says it's the offline planner under its plan, then runs the chained plan end to end", async () => {
+ const t = agent.createThread({ agent: "offline", engine: "cloud" });
+ agent.addMessage(t.id, "A 3-shot product ad for a matte black perfume bottle — hero still, then animate it");
+ await agent.run(t.id, agent.offline);
+ let v = agent.getThread(t.id)!;
+ expect(v.thread.status).toBe("waiting");
+ const said = v.thread.items.find((i) => i.role === "assistant") as { text: string };
+ expect(said.text).toContain(agent.OFFLINE_NOTE);
+ expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect Claude or Ollama in Settings for better plans.");
+ const card = v.thread.items.find((i) => i.role === "approval") as { jobs: { kind: string; op: string; error?: string }[] };
+ expect(card.jobs.map((j) => [j.kind, j.op, j.error])).toEqual([
+ ["image", "t2i", undefined],
+ ["video", "i2v", undefined],
+ ]);
+ await agent.answerApproval(t.id, true);
+ await agent.run(t.id, agent.offline);
+ v = agent.getThread(t.id)!;
+ expect(v.generations).toHaveLength(2);
+ const [still, clip] = v.generations;
+ expect(dependsOn(clip.id)).toBe(still.id);
+ expect(clip.request.chain).toEqual([{ slot: "images", position: "first" }]);
+ expect(clip.request.params?.shots).toHaveLength(3);
+ });
+});
+
+describe("approval races (S11)", () => {
+ it("claims the thread before running the approved plan", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ let runs = 0;
+ tools.TOOLS.push({
+ name: "slow_paid_tool",
+ description: "test",
+ schema: z.object({}),
+ gated: true,
+ plan: () => [],
+ run: async () => {
+ runs++;
+ await gate;
+ return { content: "done" };
+ },
+ });
+ try {
+ const t = agent.createThread({ agent: "offline", engine: "cloud" });
+ agent.addMessage(t.id, "go");
+ await agent.run(t.id, scripted(reply([toolUse("toolu_slow", "slow_paid_tool", {})], "tool_use")).call);
+ expect(agent.getThread(t.id)!.thread.status).toBe("waiting");
+ const first = agent.answerApproval(t.id, true);
+ await expect(agent.answerApproval(t.id, true)).rejects.toThrow(/Nothing is waiting/);
+ expect(() => agent.addMessage(t.id, "and another thing")).toThrow(/Still working/);
+ // Polling the thread meanwhile doesn't mistake it for a crashed run.
+ expect(agent.getThread(t.id)!.thread.items.some((i) => i.role === "notice")).toBe(false);
+ release();
+ await first;
+ expect(runs).toBe(1);
+ await agent.run(t.id, scripted(reply([text("Done.")], "end_turn")).call);
+ expect(agent.getThread(t.id)!.thread.status).toBe("idle");
+ } finally {
+ tools.TOOLS.splice(tools.TOOLS.findIndex((x) => x.name === "slow_paid_tool"), 1);
+ }
+ });
+});
+
+describe("malformed gated calls (S12)", () => {
+ it("go back to the model as an error instead of crashing the turn or showing a card", async () => {
+ const t = agent.createThread({ agent: "ollama", engine: "open" });
+ agent.addMessage(t.id, "make a fox");
+ const m = scripted(reply([toolUse("toolu_bad", "generate", { INVALID_JSON: "{jobs: [" })], "tool_use"), reply([text("Let me fix that.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ const v = agent.getThread(t.id)!;
+ expect(v.thread.items.some((i) => i.role === "approval" || i.role === "notice")).toBe(false);
+ const result = (m.seen[1].at(-1)!.content as Anthropic.Beta.BetaToolResultBlockParam[])[0];
+ expect(result).toMatchObject({ tool_use_id: "toolu_bad", is_error: true, content: expect.stringMatching(/^Invalid input: .*jobs/) });
+ expect(tools.planFor("generate", { summary: "x" }, { engine: "cloud" })).toMatchObject({ jobs: [], error: expect.stringMatching(/jobs/) });
+ });
+});
+
+describe("new kinds and operations in the tools", () => {
+ it("finds text models and runs chained jobs, returning text inline", async () => {
+ const found = await tools.executeTool("search_models", { kind: "text", task: "translate" }, { engine: "open" });
+ const models = JSON.parse(found.content as string).models as { id: string; engine: string }[];
+ expect(models[0]).toMatchObject({ id: "oss-text-llm", engine: "open source (Ollama, on this machine)" });
+ expect(models.map((m) => m.id)).toContain("text-llm");
+
+ const out = await tools.executeTool(
+ "generate",
+ {
+ summary: "Script, then a voice-over",
+ jobs: [
+ { model_id: "text-llm", op: "write", prompt: "A 2-line hook for a coffee ad" },
+ { model_id: "elevenlabs-v4", prompt: "{text}", after: 0 },
+ ],
+ },
+ { engine: "cloud" },
+ );
+ expect(out.isError).toBeFalsy();
+ const { results } = JSON.parse(out.content as string) as { results: { started: string[]; waitsFor?: string }[] };
+ const voice = gens.getGeneration(results[1].started[0])!;
+ expect(voice.request.chain).toEqual([{ slot: "prompt" }]);
+ expect(dependsOn(voice.id)).toBe(results[0].started[0]);
+ const end = Date.now() + 30_000;
+ while (gens.getGeneration(voice.id)!.status !== "succeeded" && Date.now() < end) await new Promise((r) => setTimeout(r, 250));
+ expect(gens.getGeneration(voice.id)!.request.prompt).toMatch(/Demo text for|Demo script for/);
+ const checked = await tools.executeTool("check_generations", { ids: [results[0].started[0]] }, { engine: "cloud" });
+ const summary = JSON.parse((checked.content as { text: string }[])[0].text) as { outputs: { kind: string; text?: string; meta?: { demo?: boolean } }[] }[];
+ expect(summary[0].outputs[0]).toMatchObject({ kind: "text", text: expect.stringMatching(/Demo/), meta: { demo: true } });
+ });
+
+ it("prices a chained plan and points out a bad 'after'", () => {
+ const plan = tools.planFor(
+ "generate",
+ { summary: "x", jobs: [{ model_id: "nano-banana-pro", prompt: "a fox" }, { model_id: "kling-3", prompt: "it runs", after: 0 }, { model_id: "kling-3", prompt: "nope", after: 5 }] },
+ { engine: "cloud" },
+ );
+ expect(plan.jobs.map((j) => [j.kind, j.op])).toEqual([
+ ["image", "t2i"],
+ ["video", "i2v"],
+ ["video", "t2i"],
+ ]);
+ expect(plan.jobs[2].error).toMatch(/earlier job/);
+ });
+});