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 agent: frozen per-chat context, modes, skill/memory/project tools, studio tools, MCP prompts

Claude614a2af7aa63
diff --git a/src/app/api/assist/[id]/route.ts b/src/app/api/assist/[id]/route.ts
index e3593a4e..72490fca 100644
--- a/src/app/api/assist/[id]/route.ts
+++ b/src/app/api/assist/[id]/route.ts
@@ -1,8 +1,14 @@
import { connection } from "next/server";
import { z } from "zod";
-import { deleteThread, getThread, updateThread } from "@/server/assist/agent";
+import { AssistBusyError, deleteThread, getThread, updateThread } from "@/server/assist/agent";
+import { ModeChoice } from "@/server/assist/schemas";
-const Patch = z.object({ autoApprove: z.boolean().optional(), title: z.string().trim().min(1).max(80).optional() });
+const Patch = z.object({
+ autoApprove: z.boolean().optional(),
+ title: z.string().trim().min(1).max(80).optional(),
+ projectId: z.string().max(40).nullable().optional(),
+ mode: ModeChoice.optional(),
+});
export async function GET(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {
await connection();
@@ -10,11 +16,16 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/assist/[id]">)
return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });
}
+/** Ask-first, rename, move into or out of a project, or switch the mode (Free / Smart / Manual). */
export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/[id]">) {
const parsed = Patch.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });
- const t = updateThread((await ctx.params).id, parsed.data);
- return t ? Response.json(t) : Response.json({ error: "Not found" }, { status: 404 });
+ try {
+ const t = await updateThread((await ctx.params).id, parsed.data);
+ return t ? Response.json(t) : Response.json({ error: "Not found" }, { status: 404 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 400 });
+ }
}
export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {
diff --git a/src/app/api/assist/route.ts b/src/app/api/assist/route.ts
index 8b5bf8b1..d06ca60b 100644
--- a/src/app/api/assist/route.ts
+++ b/src/app/api/assist/route.ts
@@ -1,24 +1,40 @@
import { after, connection } from "next/server";
import { z } from "zod";
-import { addMessage, createThread, listThreads, resolveAgent, run } from "@/server/assist/agent";
-import { AssistMessage } from "@/server/assist/schemas";
+import { addMessage, availability, createThread, listThreads, resolveAgent, resolveMode, run } from "@/server/assist/agent";
+import { AssistMessage, ModeChoice } from "@/server/assist/schemas";
-const Create = AssistMessage.extend({ engine: z.enum(["cloud", "open"]), autoApprove: z.boolean().optional() });
+const Create = AssistMessage.extend({
+ engine: z.enum(["cloud", "open"]),
+ autoApprove: z.boolean().optional(),
+ projectId: z.string().max(40).nullish(),
+ mode: ModeChoice.optional(),
+});
-export async function GET() {
+/** Chats (all, `?project=<id>`, or `?project=none` for chats outside projects; `?q=` searches), with what can run. */
+export async function GET(request: Request) {
await connection();
- return Response.json({ threads: listThreads(), agent: await resolveAgent() });
+ const sp = new URL(request.url).searchParams;
+ const project = sp.get("project");
+ const threads = listThreads({ project: project === "none" ? null : (project ?? undefined), q: sp.get("q") ?? undefined });
+ const [agent, can] = await Promise.all([resolveAgent(), availability()]);
+ return Response.json({ threads, agent, availability: can });
}
/** Start a chat with its first message; the agent replies in the background (poll the thread). */
export async function POST(request: Request) {
const parsed = Create.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });
- const { text, attachments, engine, autoApprove } = parsed.data;
- const thread = createThread({ engine, autoApprove, agent: await resolveAgent() });
+ const { text, attachments, engine, autoApprove, projectId, mode } = parsed.data;
+ const r = await resolveMode(mode);
+ let thread;
+ try {
+ thread = createThread({ engine, autoApprove, agent: r.agent, projectId: projectId ?? null, mode: r.mode, model: r.model, effort: r.effort });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 404 });
+ }
const updated = addMessage(thread.id, text, attachments);
// Claimed now (not in after()) so a poll that lands first doesn't see a stale "running" thread.
const reply = run(thread.id);
after(() => reply);
- return Response.json(updated, { status: 201 });
+ return Response.json({ ...updated, ...(r.note && { note: r.note }) }, { status: 201 });
}
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 9c767189..8ae46b1f 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -2,18 +2,48 @@ import "server-only";
import Anthropic from "@anthropic-ai/sdk";
import { nanoid } from "nanoid";
import { AUDIO_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, MUSIC_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
-import { type AssistItem, type AssistThread, type AssistThreadSummary, type AssistThreadView, threadTitle } from "@/lib/assist";
+import {
+ ASSIST_EFFORTS,
+ CLAUDE_MODELS,
+ contextUpdate,
+ DEFAULT_CLAUDE_MODEL,
+ DEFAULT_EFFORT,
+ factMap,
+ guessCategory,
+ renderContext,
+ slashSkills,
+ threadTitle,
+ type AssistAgent,
+ type AssistAvailability,
+ type AssistEffort,
+ type AssistItem,
+ type AssistMode,
+ type AssistModeChoice,
+ type AssistThread,
+ type AssistThreadSummary,
+ type AssistThreadView,
+ type SkillMeta,
+} from "@/lib/assist";
import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
import { engineMode, getSetting } from "../settings";
+import { getSkill } from "../skills";
import { readRef } from "../storage";
-import { apiTools, executeTool, getTool, planFor, validateInput, type ToolContext } from "./tools";
+import { canUseSkill, chatFacts } from "./context";
+import { getProject, touchProject } from "./projects";
+import { apiTools, cardTitle, executeTool, getTool, planFor, validateInput, type ToolContext } from "./tools";
/**
* The Assist agent loop. History is kept exactly as the API returned it (append-only, thinking
* included) so later turns stay valid; generations that cost money stop the loop with an approval
* card, and the user's answer resumes it with the matching tool results.
+ *
+ * Each chat's system prompt is frozen when it starts: the fixed instructions plus the chat's
+ * context (date, engine, approval mode, project, memory, skills). What changes later — a memory
+ * saved, a skill loaded, auto-run switched on — reaches the model as an appended
+ * `role: "system"` "Context update" message, never by rewriting earlier text, so the prompt cache
+ * and earlier thinking blocks stay valid.
*/
type MessageParam = Anthropic.Beta.BetaMessageParam;
@@ -21,10 +51,15 @@ type ToolResult = Anthropic.Beta.BetaToolResultBlockParam;
type UserBlock = Exclude<MessageParam["content"], string>[number];
export interface ModelRequest {
+ /** stable: the fixed instructions; turn: this chat's frozen context. */
system: { stable: string; turn: string };
messages: MessageParam[];
tools: Anthropic.Beta.BetaTool[];
ctx: ToolContext;
+ /** The chat's model choice (Manual mode): a Claude model id or an Ollama model name, and the effort. */
+ settings?: { model?: string | null; effort?: AssistEffort | null };
+ /** Skills loaded in the chat (the offline planner uses their hints). */
+ skills?: SkillMeta[];
}
export type ModelCall = (req: ModelRequest) => Promise<Anthropic.Beta.BetaMessage>;
@@ -58,10 +93,35 @@ interface Row {
updated_at: number;
}
+interface StateRow {
+ thread_id: string;
+ project_id: string | null;
+ mode: AssistMode | null;
+ model: string | null;
+ effort: AssistEffort | null;
+ skills_json: string;
+ context: string | null;
+ sent_json: string | null;
+}
+
+/** Per-chat state beside the transcript (assist_thread_state). */
+interface Ext {
+ projectId: string | null;
+ mode: AssistMode | null;
+ model: string | null;
+ effort: AssistEffort | null;
+ skills: string[];
+ /** The chat's frozen context block (null until the first model call). */
+ context: string | null;
+ /** The facts the model has seen, to send only what changed. */
+ sent: Record<string, string> | null;
+}
+
interface State {
thread: AssistThread;
messages: MessageParam[];
pending: Pending | null;
+ ext: Ext;
}
declare global {
@@ -69,23 +129,45 @@ declare global {
}
const runs = (globalThis.__fuobeAssistRuns ??= new Set());
+function loadExt(id: string): Ext {
+ const r = db().prepare("SELECT * FROM assist_thread_state WHERE thread_id = ?").get(id) as StateRow | undefined;
+ return {
+ projectId: r?.project_id ?? null,
+ mode: r?.mode ?? null,
+ model: r?.model ?? null,
+ effort: r?.effort ?? null,
+ skills: r ? (JSON.parse(r.skills_json) as string[]) : [],
+ context: r?.context ?? null,
+ sent: r?.sent_json ? (JSON.parse(r.sent_json) as Record<string, string>) : null,
+ };
+}
+
+function withExt(t: AssistThread, e: Ext): AssistThread {
+ return { ...t, projectId: e.projectId, mode: e.mode ?? (t.agent === "claude" ? "smart" : "free"), model: e.model, effort: e.effort, skills: e.skills };
+}
+
function load(id: string): State | null {
const r = db().prepare("SELECT * FROM assist_threads WHERE id = ?").get(id) as Row | undefined;
if (!r) return null;
+ const ext = loadExt(id);
const s: State = {
- thread: {
- id: r.id,
- title: r.title,
- status: r.status,
- agent: r.agent,
- engine: r.engine,
- autoApprove: !!r.auto_approve,
- items: JSON.parse(r.items_json) as AssistItem[],
- createdAt: r.created_at,
- updatedAt: r.updated_at,
- },
+ thread: withExt(
+ {
+ id: r.id,
+ title: r.title,
+ status: r.status,
+ agent: r.agent,
+ engine: r.engine,
+ autoApprove: !!r.auto_approve,
+ items: JSON.parse(r.items_json) as AssistItem[],
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ },
+ ext,
+ ),
messages: JSON.parse(r.messages_json) as MessageParam[],
pending: r.pending_json ? (JSON.parse(r.pending_json) as Pending) : null,
+ ext,
};
// A run that died with the server (restart, crash) leaves the thread "running": reopen it.
if (s.thread.status === "running" && !runs.has(id)) {
@@ -98,26 +180,46 @@ function load(id: string): State | null {
function save(s: State): void {
s.thread.updatedAt = Date.now();
- db()
- .prepare(
- `INSERT INTO assist_threads (id, title, status, agent, engine, auto_approve, messages_json, items_json, pending_json, created_at, updated_at)
- VALUES (@id, @title, @status, @agent, @engine, @auto_approve, @messages_json, @items_json, @pending_json, @created_at, @updated_at)
- ON CONFLICT(id) DO UPDATE SET title = @title, status = @status, auto_approve = @auto_approve, messages_json = @messages_json,
- items_json = @items_json, pending_json = @pending_json, updated_at = @updated_at`,
- )
- .run({
- id: s.thread.id,
- title: s.thread.title,
- status: s.thread.status,
- agent: s.thread.agent,
- engine: s.thread.engine,
- auto_approve: s.thread.autoApprove ? 1 : 0,
- messages_json: JSON.stringify(s.messages),
- items_json: JSON.stringify(s.thread.items),
- pending_json: s.pending ? JSON.stringify(s.pending) : null,
- created_at: s.thread.createdAt,
- updated_at: s.thread.updatedAt,
- });
+ Object.assign(s.thread, withExt(s.thread, s.ext));
+ db().transaction(() => {
+ db()
+ .prepare(
+ `INSERT INTO assist_threads (id, title, status, agent, engine, auto_approve, messages_json, items_json, pending_json, created_at, updated_at)
+ VALUES (@id, @title, @status, @agent, @engine, @auto_approve, @messages_json, @items_json, @pending_json, @created_at, @updated_at)
+ ON CONFLICT(id) DO UPDATE SET title = @title, status = @status, agent = @agent, auto_approve = @auto_approve, messages_json = @messages_json,
+ items_json = @items_json, pending_json = @pending_json, updated_at = @updated_at`,
+ )
+ .run({
+ id: s.thread.id,
+ title: s.thread.title,
+ status: s.thread.status,
+ agent: s.thread.agent,
+ engine: s.thread.engine,
+ auto_approve: s.thread.autoApprove ? 1 : 0,
+ messages_json: JSON.stringify(s.messages),
+ items_json: JSON.stringify(s.thread.items),
+ pending_json: s.pending ? JSON.stringify(s.pending) : null,
+ created_at: s.thread.createdAt,
+ updated_at: s.thread.updatedAt,
+ });
+ db()
+ .prepare(
+ `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, skills_json, context, sent_json)
+ VALUES (@thread_id, @project_id, @mode, @model, @effort, @skills_json, @context, @sent_json)
+ ON CONFLICT(thread_id) DO UPDATE SET project_id = @project_id, mode = @mode, model = @model, effort = @effort,
+ skills_json = @skills_json, context = @context, sent_json = @sent_json`,
+ )
+ .run({
+ thread_id: s.thread.id,
+ project_id: s.ext.projectId,
+ mode: s.ext.mode,
+ model: s.ext.model,
+ effort: s.ext.effort,
+ skills_json: JSON.stringify(s.ext.skills),
+ context: s.ext.context,
+ sent_json: s.ext.sent ? JSON.stringify(s.ext.sent) : null,
+ });
+ })();
}
type NewItem = AssistItem extends infer T ? (T extends AssistItem ? Omit<T, "id"> : never) : never;
@@ -127,12 +229,28 @@ function push(s: State, item: NewItem | AssistItem): AssistItem {
return full;
}
-export function listThreads(): AssistThreadSummary[] {
- return (db().prepare("SELECT id, title, status, updated_at FROM assist_threads ORDER BY updated_at DESC LIMIT 100").all() as Row[]).map((r) => ({
+/** Chats, newest first. `project`: one project's chats; null: chats outside projects; omitted: all. `q` searches titles and messages. */
+export function listThreads(f: { project?: string | null; q?: string } = {}): AssistThreadSummary[] {
+ const where: string[] = [];
+ const args: unknown[] = [];
+ if (f.project === null) where.push("s.project_id IS NULL");
+ else if (f.project) {
+ where.push("s.project_id = ?");
+ args.push(f.project);
+ }
+ if (f.q?.trim()) {
+ const like = `%${f.q.trim().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
+ where.push("(t.title LIKE ? ESCAPE '\\' OR t.items_json LIKE ? ESCAPE '\\')");
+ args.push(like, like);
+ }
+ const sql = `SELECT t.id, t.title, t.status, t.updated_at, s.project_id FROM assist_threads t LEFT JOIN assist_thread_state s ON s.thread_id = t.id
+ ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY t.updated_at DESC LIMIT 100`;
+ return (db().prepare(sql).all(...args) as (Pick<Row, "id" | "title" | "status" | "updated_at"> & { project_id: string | null })[]).map((r) => ({
id: r.id,
title: r.title,
status: r.status,
updatedAt: r.updated_at,
+ projectId: r.project_id,
}));
}
@@ -145,31 +263,64 @@ export function getThread(id: string): AssistThreadView | null {
}
export function deleteThread(id: string): void {
- db().prepare("DELETE FROM assist_threads WHERE id = ?").run(id);
+ db().transaction(() => {
+ db().prepare("DELETE FROM assist_threads WHERE id = ?").run(id);
+ db().prepare("DELETE FROM assist_thread_state WHERE thread_id = ?").run(id);
+ })();
}
-export function updateThread(id: string, patch: { autoApprove?: boolean; title?: string }): AssistThread | null {
+export class AssistBusyError extends Error {}
+
+export interface ThreadPatch {
+ autoApprove?: boolean;
+ title?: string;
+ /** Move the chat into a project (or out, with null). */
+ projectId?: string | null;
+ mode?: AssistModeChoice;
+}
+
+export async function updateThread(id: string, patch: ThreadPatch): Promise<AssistThread | null> {
const s = load(id);
if (!s) return null;
if (patch.autoApprove !== undefined) s.thread.autoApprove = patch.autoApprove;
if (patch.title) s.thread.title = patch.title;
+ if (patch.projectId !== undefined) {
+ if (s.thread.status === "running" || runs.has(id)) throw new AssistBusyError("Wait for this reply to finish, then move the chat");
+ if (patch.projectId && !getProject(patch.projectId)) throw new Error("That project doesn't exist anymore");
+ s.ext.projectId = patch.projectId;
+ // Skills the new project doesn't offer are unloaded.
+ s.ext.skills = s.ext.skills.filter((n) => canUseSkill(n, s.ext.projectId));
+ }
+ if (patch.mode) {
+ if (s.thread.status === "running" || runs.has(id)) throw new AssistBusyError("Wait for this reply to finish, then switch");
+ const r = await resolveMode(patch.mode);
+ s.thread.agent = r.agent;
+ s.ext.mode = r.mode;
+ s.ext.model = r.model;
+ s.ext.effort = r.effort;
+ if (r.note) push(s, { role: "notice", tone: "info", text: r.note });
+ }
save(s);
return s.thread;
}
-let ollamaProbe: { at: number; url: string; ok: boolean } | null = null;
-async function ollamaReachable(): Promise<boolean> {
+// ---------------------------------------------------------------------------
+// Which LLM runs a chat: modes
+
+let ollamaProbe: { at: number; url: string; ok: boolean; models: string[] } | null = null;
+async function probeOllama(): Promise<{ ok: boolean; models: string[] }> {
const url = getSetting("ollamaUrl").replace(/\/+$/, "");
- if (ollamaProbe && ollamaProbe.url === url && Date.now() - ollamaProbe.at < 30_000) return ollamaProbe.ok;
- const ok = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(800) })
- .then((r) => r.ok)
- .catch(() => false);
- ollamaProbe = { at: Date.now(), url, ok };
- return ok;
+ if (ollamaProbe && ollamaProbe.url === url && Date.now() - ollamaProbe.at < 30_000) return ollamaProbe;
+ const res = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(800) })
+ .then(async (r) => (r.ok ? ((await r.json().catch(() => ({}))) as { models?: { name?: string }[] }) : null))
+ .catch(() => null);
+ ollamaProbe = { at: Date.now(), url, ok: !!res, models: (res?.models ?? []).map((m) => m.name ?? "").filter(Boolean).slice(0, 50) };
+ return ollamaProbe;
}
+const ollamaReachable = async () => (await probeOllama()).ok;
/**
- * Which LLM drives new chats: Claude when a key is set (on open-source-only installs only when
+ * Which LLM drives new chats by default: Claude when a key is set (on open-source-only installs only when
* picked explicitly), else a reachable local Ollama, else the offline planner.
*/
export async function resolveAgent(): Promise<AssistThread["agent"]> {
@@ -182,14 +333,86 @@ export async function resolveAgent(): Promise<AssistThread["agent"]> {
return (await ollamaReachable()) ? "ollama" : "offline";
}
-export function createThread(opts: { engine: Engine; agent: AssistThread["agent"]; autoApprove?: boolean; title?: string }): AssistThread {
+const claudeAllowed = () => !!getSetting("anthropicKey") && (engineMode() !== "open" || getSetting("enhanceProvider") === "anthropic");
+
+export async function availability(): Promise<AssistAvailability> {
+ const o = await probeOllama();
+ const aiOff = getSetting("enhanceProvider") === "none";
+ const claude = claudeAllowed();
+ return {
+ claude,
+ ollama: o.ok,
+ ollamaModels: o.models,
+ ollamaModel: getSetting("ollamaModel"),
+ aiOff,
+ defaultMode: !aiOff && claude && getSetting("enhanceProvider") !== "ollama" ? "smart" : "free",
+ };
+}
+
+export interface ResolvedMode {
+ mode: AssistMode;
+ agent: AssistAgent;
+ model: string | null;
+ effort: AssistEffort | null;
+ /** Why the chat didn't get what was asked (no key, AI helper off…). */
+ note?: string;
+}
+
+const OLLAMA_NAME = /^[\w.:/-]{1,100}$/;
+
+/**
+ * Supercomputer's modes on Fuobe's agents: Smart = Claude Opus 5.5; Free = a local model through
+ * Ollama (or the offline planner when none answers); Manual = the model and effort you pick.
+ * Without a choice, the default from Settings (resolveAgent).
+ */
+export async function resolveMode(choice?: Partial<AssistModeChoice>): Promise<ResolvedMode> {
+ const free = async (note?: string): Promise<ResolvedMode> =>
+ (await ollamaReachable()) ? { mode: "free", agent: "ollama", model: null, effort: null, note } : { mode: "free", agent: "offline", model: null, effort: null, note };
+ if (getSetting("enhanceProvider") === "none") {
+ return { mode: choice?.mode ?? "free", agent: "offline", model: null, effort: null, ...(choice?.mode && choice.mode !== "free" && { note: "The AI helper is off in Settings, so this chat uses the offline planner." }) };
+ }
+ if (!choice?.mode) {
+ const agent = await resolveAgent();
+ return { mode: agent === "claude" ? "smart" : "free", agent, model: null, effort: null };
+ }
+ const noKey = "Smart and Claude need an Anthropic API key (Settings → API keys) — using Free instead.";
+ if (choice.mode === "smart") return claudeAllowed() ? { mode: "smart", agent: "claude", model: DEFAULT_CLAUDE_MODEL, effort: DEFAULT_EFFORT } : free(noKey);
+ if (choice.mode === "free") return free();
+ // Manual
+ const agent = choice.agent ?? "claude";
+ if (agent === "claude") {
+ if (!getSetting("anthropicKey")) return free(noKey);
+ const model = CLAUDE_MODELS.some((m) => m.id === choice.model) ? choice.model! : DEFAULT_CLAUDE_MODEL;
+ const effort = ASSIST_EFFORTS.some((e) => e.id === choice.effort) ? choice.effort! : DEFAULT_EFFORT;
+ return { mode: "manual", agent: "claude", model, effort };
+ }
+ if (agent === "ollama") {
+ const model = choice.model && OLLAMA_NAME.test(choice.model) ? choice.model : null;
+ return { mode: "manual", agent: "ollama", model, effort: null, ...(!(await ollamaReachable()) && { note: `Ollama isn't answering at ${getSetting("ollamaUrl")} — start it, or pick another mode.` }) };
+ }
+ return { mode: "manual", agent: "offline", model: null, effort: null };
+}
+
+export function createThread(opts: {
+ engine: Engine;
+ agent: AssistThread["agent"];
+ autoApprove?: boolean;
+ title?: string;
+ projectId?: string | null;
+ mode?: AssistMode | null;
+ model?: string | null;
+ effort?: AssistEffort | null;
+}): AssistThread {
const now = Date.now();
+ if (opts.projectId && !getProject(opts.projectId)) throw new Error("That project doesn't exist anymore");
const s: State = {
thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: opts.agent, engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },
messages: [],
pending: null,
+ ext: { projectId: opts.projectId ?? null, mode: opts.mode ?? null, model: opts.model ?? null, effort: opts.effort ?? null, skills: [], context: null, sent: null },
};
save(s);
+ if (opts.projectId) touchProject(opts.projectId);
return s.thread;
}
@@ -271,39 +494,41 @@ How you work:
- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.
- For multi-step work (an image, then animate it; transcribe, translate, then voice it), put the steps in one generate call and set "after" on each later job: it starts by itself when the earlier job finishes and gets its result as input. When you need to judge a result before deciding the next step, wait with check_generations instead (look=true to see images) and pass the output URL into the next call.
- Besides images, video and audio, models can transcribe speech, translate or write text (scripts, captions, ad copy), split images into layers, separate voice from background, trim, caption or re-sound clips, and turn an image into a 3D model: search_models with kind "text" or "model3d" finds the text and 3D ones.
+- Whole studio jobs have their own tools — split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions: use them instead of chaining those steps by hand.
- 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.`;
+- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.
-function turnSystem(t: AssistThread): string {
- const mode = engineMode();
- const engine =
- mode === "open"
- ? "This install runs open-source models only (ComfyUI on the user's GPU)."
- : mode === "cloud"
- ? "This install runs paid cloud APIs only."
- : t.engine === "open"
- ? "The user prefers open-source models (ComfyUI, free on their GPU); use paid ones only when no open model can do the job, and say so."
- : "The user prefers paid cloud models (best quality); open-source models are available too.";
- const approval = t.autoApprove ? "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for." : "Ask-first is on: each generate call shows an approval card.";
- return `Today is ${new Date().toISOString().slice(0, 10)}. ${engine} ${approval}`;
-}
+Skills, memory and projects (your context below lists them):
+- Skills are playbooks for whole kinds of jobs. When the request matches one under "Skills you can load", call load_skill with its name before planning, then follow it. A message that starts with /name has already loaded that skill. Follow every skill under "Skills in use".
+- Memory is what you know about the user. Follow it without mentioning it. When the user states something lasting — a preference, their style, a convention, their setup, a fix that worked — save it with remember: one short sentence, no secrets, nothing about only the current job. Correct an outdated memory with remember and its id as "replaces".
+- In a project, follow its instructions. Its sources are listed with ids: read one in full with read_source when it matters; image, video and audio sources are inputs by URL.
+- "Context update" messages from the system later in the chat replace the matching parts of your context.`;
// ---------------------------------------------------------------------------
// Models
-export const claude: ModelCall = async ({ system, messages, tools }) => {
+/** Models that take server-side fallbacks on a refusal ("default" routing). */
+const FALLBACK_MODELS = new Set(["claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1"]);
+
+export const claude: ModelCall = async ({ system, messages, tools, settings }) => {
const client = new Anthropic({ apiKey: getSetting("anthropicKey") });
+ const model = settings?.model && CLAUDE_MODELS.some((m) => m.id === settings.model) ? settings.model : DEFAULT_CLAUDE_MODEL;
+ const fallback = FALLBACK_MODELS.has(model);
return client.beta.messages.create({
- model: "claude-opus-5-5",
+ model,
max_tokens: 16000,
- thinking: { type: "adaptive" },
- output_config: { effort: "medium" },
- betas: ["server-side-fallback-2026-07-01"],
- fallbacks: "default",
+ // drop_block: a thinking block the API can't replay (a chat that switched models, or one from
+ // before contexts were frozen) is dropped instead of failing the request.
+ thinking: { type: "adaptive", block_binding: { prefix_mismatch_behavior: "drop_block" } },
+ output_config: { effort: settings?.effort ?? DEFAULT_EFFORT },
+ betas: [...(fallback ? (["server-side-fallback-2026-07-01"] as const) : []), "thinking-binding-controls-2026-08-01"],
+ ...(fallback && { fallbacks: "default" as const }),
+ // The fixed instructions and the chat's frozen context are cached; so is the conversation so far.
+ cache_control: { type: "ephemeral" },
system: [
{ type: "text", text: system.stable, cache_control: { type: "ephemeral" } },
- { type: "text", text: system.turn },
+ { type: "text", text: system.turn, cache_control: { type: "ephemeral" } },
],
tools,
messages: await hydrate(messages),
@@ -324,6 +549,10 @@ export function toOllamaMessages(system: ModelRequest["system"], messages: Messa
out.push({ role: m.role, content: m.content });
continue;
}
+ if (m.role === "system") {
+ out.push({ role: "system", content: m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n") });
+ continue;
+ }
if (m.role === "assistant") {
const text = m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
const calls = m.content.flatMap((b) => {
@@ -342,12 +571,13 @@ export function toOllamaMessages(system: ModelRequest["system"], messages: Messa
}
/** A local model through Ollama's tool calling (qwen3, llama3.x, mistral…), answering in the same shape as Claude. */
-export const ollama: ModelCall = async ({ system, messages, tools }) => {
+export const ollama: ModelCall = async ({ system, messages, tools, settings }) => {
+ const model = settings?.model || getSetting("ollamaModel");
const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- model: getSetting("ollamaModel"),
+ model,
stream: false,
messages: toOllamaMessages(system, messages),
tools: tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema } })),
@@ -375,12 +605,13 @@ export const ollama: ModelCall = async ({ system, messages, tools }) => {
}
const stop: Anthropic.Beta.BetaStopReason = j.message?.tool_calls?.length ? "tool_use" : j.done_reason === "length" ? "max_tokens" : "end_turn";
if (!content.length) content.push({ type: "text", text: "…", citations: null } as Anthropic.Beta.BetaTextBlock);
- return { id: `msg_ollama_${nanoid(8)}`, type: "message", role: "assistant", model: getSetting("ollamaModel"), content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
+ return { id: `msg_ollama_${nanoid(8)}`, type: "message", role: "assistant", model, content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
};
/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */
-export const offline: ModelCall = async ({ messages, ctx }) => {
- const last = messages.at(-1);
+export const offline: ModelCall = async ({ messages, ctx, skills }) => {
+ // Context updates (system messages) aren't the user's words.
+ const last = messages.findLast((m) => m.role !== "system");
const blocks = last && typeof last.content !== "string" ? last.content : [];
const reply = (content: Anthropic.Beta.BetaContentBlock[], stop: Anthropic.Beta.BetaStopReason): Anthropic.Beta.BetaMessage =>
({ id: `msg_offline_${nanoid(8)}`, type: "message", role: "assistant", model: "offline", content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null }) as unknown as Anthropic.Beta.BetaMessage;
@@ -391,9 +622,11 @@ export const offline: ModelCall = async ({ messages, ctx }) => {
if (results.length && !said.trim()) {
const body = results.map((r) => (typeof r.content === "string" ? r.content : "")).join(" ");
if (results.some((r) => r.is_error)) return reply([text(/declined/i.test(body) ? "Okay, I won't run that. Tell me what to change." : `That didn't start: ${body.replace(/^.*"error":"([^"]+)".*$/, "$1")}`)], "end_turn");
+ if (/"saved":/.test(body)) return reply([text("Saved to memory — every chat will follow it from now on.")], "end_turn");
return reply([text(`On it — the results will appear here as they finish. ${FOLLOW_UP[startedKind(body)]}`)], "end_turn");
}
- const plan = offlinePlan(said, ctx.engine);
+ const hint = skills?.find((s) => s.offline)?.offline;
+ const plan = offlinePlan(said, ctx.engine, hint);
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");
// step() adds OFFLINE_NOTE as a quiet line under the plan card.
return reply(
@@ -431,9 +664,10 @@ const num = (s: string) => NUMBER_WORDS[s] ?? Number(s);
/**
* 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.
+ * storyboards, music and voice-overs, translations and scripts, and "remember that …".
+ * A loaded skill's offline hints (its kind, format, count and style) fill in what the words leave open.
*/
-export function offlinePlan(message: string, preferred: Engine): { tool: string; input: Record<string, unknown>; say: string } | null {
+export function offlinePlan(message: string, preferred: Engine, hint?: SkillMeta["offline"]): { 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;
@@ -442,20 +676,30 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
const t = text.toLowerCase();
const mode = engineMode();
const engine: Engine = mode === "both" ? preferred : mode;
+
+ // "Remember that I always want 9:16" → a memory (approved like a plan in ask-first mode).
+ const memory = /^(?:please\s+)?(?:remember|note|keep in mind)(?:\s+that)?[:,]?\s+(.{4,})$/is.exec(text);
+ if (memory) {
+ const what = memory[1].trim().replace(/\.$/, "");
+ const sentence = `${what.charAt(0).toUpperCase()}${what.slice(1)}.`;
+ return { tool: "remember", input: { text: sentence, category: guessCategory(what) }, say: "I'll remember that for every chat." };
+ }
+
const count = (() => {
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;
+ return m ? num(m[1]) : hint?.outputs;
})();
// "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 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" : hint?.aspect;
const pick = (d: { cloud: string; open: string }) => (engine === "open" && d.open ? d.open : d.cloud);
const textModel = engine === "open" ? "oss-text-llm" : "text-llm";
+ const styled = (p: string) => (hint?.style ? `${p}. ${hint.style}` : p);
// "… 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);
@@ -466,7 +710,7 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
.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 still = { model_id: pick(images.length ? EDIT_STUDIO.defaultModels : IMAGE_STUDIO.defaultModels), prompt: styled(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.`,
@@ -485,7 +729,7 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
const frames = Math.max(1, Math.min(8, count ?? 4));
return {
tool: "create_storyboard",
- input: { story: text, frames, ...(images.length && { references: images.slice(0, 4) }), ...(aspect && { aspect_ratio: aspect }) },
+ input: { story: text, frames, ...(images.length && { references: images.slice(0, 4) }), ...(aspect && { aspect_ratio: aspect }), ...(hint?.style && { style: hint.style }) },
say: `I'll split that into ${frames} frames with the same characters and look, each made from the one before.`,
};
}
@@ -502,7 +746,10 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
};
}
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);
+ 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)) ||
+ (hint?.kind === "text" && !files.length));
if (isWriting) {
return {
tool: "generate",
@@ -510,8 +757,9 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
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") || !!shots || /\b(videos?|clips?|animate|animation|motion|films?|footage|movies?|trailers?|commercials?|ads?)\b/.test(t));
+ const isSpeech = !isMusic && (/\b(voice ?over|narrat\w*|read (this|it|out)|say|speak|text to speech|tts)\b/.test(t) || hint?.kind === "audio");
+ 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) || hint?.kind === "video");
if (isMusic || isSpeech) {
const quoted = /["“]([^"”]+)["”]/.exec(text)?.[1] ?? text.replace(/^.*?:\s*/, "");
return {
@@ -525,7 +773,7 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
const multi = isVideo && shots ? shots : undefined;
const job = {
model_id: pick(studio.defaultModels),
- prompt: text,
+ prompt: styled(text),
...(images.length && { images: images.slice(0, isVideo ? 1 : 4) }),
...(aspect && { aspect_ratio: aspect }),
...(n > 1 && { outputs: n }),
@@ -542,6 +790,22 @@ export function offlinePlan(message: string, preferred: Engine): { tool: string;
// ---------------------------------------------------------------------------
// The loop
+function toolCtx(s: State): ToolContext {
+ return {
+ engine: s.thread.engine,
+ thread: {
+ id: s.thread.id,
+ projectId: s.ext.projectId,
+ get skills() {
+ return s.ext.skills;
+ },
+ loadSkill: (name) => {
+ if (!s.ext.skills.includes(name)) s.ext.skills = [...s.ext.skills, name];
+ },
+ },
+ };
+}
+
async function runTool(name: string, input: unknown, ctx: ToolContext): Promise<{ result: Omit<ToolResult, "tool_use_id">; items: AssistItem[] }> {
const out = await executeTool(name, input, ctx);
return { result: { type: "tool_result", content: out.content, ...(out.isError && { is_error: true }) }, items: out.items ?? [] };
@@ -551,9 +815,35 @@ function ordered(results: ToolResult[], order: string[]): ToolResult[] {
return [...results].sort((a, b) => order.indexOf(a.tool_use_id) - order.indexOf(b.tool_use_id));
}
+/**
+ * The chat's system prompt and, when something changed since the model last looked, the
+ * "Context update" message to append. The first call freezes the context into the system prompt.
+ */
+function contextFor(s: State): { system: ModelRequest["system"]; update: MessageParam | null; sent: Record<string, string> } {
+ const facts = chatFacts({ engine: s.thread.engine, autoApprove: s.thread.autoApprove, projectId: s.ext.projectId, skills: s.ext.skills });
+ const sent = factMap(facts);
+ if (!s.ext.context) {
+ s.ext.context = renderContext(facts);
+ s.ext.sent = sent;
+ return { system: { stable: STABLE_SYSTEM, turn: s.ext.context }, update: null, sent };
+ }
+ // A system message must follow a user turn (the user's words or tool results).
+ const text = s.messages.at(-1)?.role === "user" ? contextUpdate(s.ext.sent ?? {}, facts) : null;
+ return { system: { stable: STABLE_SYSTEM, turn: s.ext.context }, update: text ? { role: "system", content: text } : null, sent };
+}
+
async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
- const ctx: ToolContext = { engine: s.thread.engine };
- const res = await model({ system: { stable: STABLE_SYSTEM, turn: turnSystem(s.thread) }, messages: s.messages, tools: apiTools(), ctx });
+ const ctx = toolCtx(s);
+ const { system, update, sent } = contextFor(s);
+ const active = s.ext.skills.map((n) => getSkill(n)).filter((x): x is NonNullable<typeof x> => !!x);
+ const res = await model({
+ system,
+ messages: update ? [...s.messages, update] : s.messages,
+ tools: apiTools(),
+ ctx,
+ settings: { model: s.ext.model, effort: s.ext.effort },
+ skills: active,
+ });
if (res.stop_reason === "refusal") {
// Nothing is appended: the user's turn stays last and their next message joins it.
@@ -564,6 +854,11 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
push(s, { role: "notice", tone: "error", text: "This chat is too long to continue. Start a new one." });
return "stop";
}
+ // The update is now part of the conversation the model answered.
+ if (update) {
+ s.messages.push(update);
+ s.ext.sent = sent;
+ }
s.messages.push({ role: "assistant", content: res.content });
const text = res.content
.filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")
@@ -610,9 +905,9 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
if (gated.length) {
const plans = gated.map((g) => planFor(g.name, g.input, ctx));
const jobs = plans.flatMap((p) => p.jobs);
- const summaries = gated.map((g) => (g.input as { summary?: string }).summary).filter(Boolean);
const total = plans.some((p) => p.total === null) ? null : plans.reduce((n, p) => n + (p.total ?? 0), 0);
- const item = push(s, { role: "approval", summary: summaries.join(" · ") || (gated[0].name === "create_storyboard" ? "Storyboard" : "Generate"), jobs, totalUsd: total, status: "pending" });
+ const summary = [...new Set(gated.map((g) => cardTitle(g.name, g.input)))].join(" · ");
+ const item = push(s, { role: "approval", summary, jobs, totalUsd: total, status: "pending" });
offlineNote();
s.pending = { approvalItemId: item.id, results, gated, order };
s.thread.status = "waiting";
@@ -647,16 +942,26 @@ export async function run(id: string, model?: ModelCall): Promise<void> {
next = "stop";
}
if (next === "stop") break;
+ refreshFlags(s);
save(s);
if (i === MAX_STEPS - 1) push(s, { role: "notice", tone: "info", text: "Paused after many steps. Send a message to keep going." });
}
if (s.thread.status === "running") s.thread.status = "idle";
+ refreshFlags(s);
save(s);
} finally {
runs.delete(id);
}
}
+/** Keep what the user changed while the agent worked (the Ask-first switch, a rename). */
+function refreshFlags(s: State): void {
+ const r = db().prepare("SELECT title, auto_approve FROM assist_threads WHERE id = ?").get(s.thread.id) as { title: string; auto_approve: number } | undefined;
+ if (!r) return;
+ s.thread.autoApprove = r.auto_approve === 1;
+ s.thread.title = r.title;
+}
+
function errorText(e: unknown): string {
if (e instanceof Anthropic.AuthenticationError) return "Your Anthropic API key was rejected. Check it in Settings → API keys.";
if (e instanceof Anthropic.RateLimitError) return "Claude is rate-limited right now. Try again in a minute.";
@@ -665,21 +970,28 @@ function errorText(e: unknown): string {
return (e as Error).message || "Something went wrong";
}
-export class AssistBusyError extends Error {}
-
-/** Add the user's message; a pending plan they didn't approve is declined with their message as feedback. */
+/**
+ * Add the user's message; a pending plan they didn't approve is declined with their message as feedback.
+ * Leading `/name` tokens load those skills into the chat first.
+ */
export function addMessage(id: string, text: string, attachments: string[] = []): AssistThread {
const s = load(id);
if (!s) throw new Error("Not found");
if (s.thread.status === "running" || runs.has(id)) throw new AssistBusyError("Still working on the last message");
- if (!s.thread.items.some((i) => i.role === "user")) s.thread.title = threadTitle(text);
+ const slash = slashSkills(text, (n) => canUseSkill(n, s.ext.projectId));
+ for (const n of slash.skills) if (!s.ext.skills.includes(n)) s.ext.skills = [...s.ext.skills, n];
+ const titles = slash.skills.map((n) => getSkill(n)?.title ?? n);
+ // With only "/katana" (and files), the model still needs words to act on.
+ const words = slash.text || (slash.skills.length ? `Use the ${titles.join(" and ")} skill${titles.length > 1 ? "s" : ""}${attachments.length ? " with the attached files" : ""}.` : text);
+ if (!s.thread.items.some((i) => i.role === "user")) s.thread.title = threadTitle(slash.text || titles.join(", ") || text);
// Tool results first: they answer the assistant's last turn.
const results = s.pending ? decline(s, "The user replied with new instructions instead of approving; follow them.") : [];
if (!results.length) closeDanglingToolUses(s.messages);
- appendUser(s.messages, [...results, ...userBlocks(text, attachments)]);
- push(s, { role: "user", text, ...(attachments.length && { attachments }) });
+ appendUser(s.messages, [...results, ...userBlocks(words, attachments)]);
+ push(s, { role: "user", text: slash.skills.length ? slash.text : text, ...(attachments.length && { attachments }), ...(slash.skills.length && { skills: slash.skills }) });
s.thread.status = "running";
save(s);
+ if (s.ext.projectId) touchProject(s.ext.projectId);
return s.thread;
}
@@ -698,8 +1010,9 @@ function decline(s: State, why = "The user declined this plan. Ask what they'd l
async function runApproved(s: State, p: Pending): Promise<ToolResult[]> {
const results = [...p.results];
+ const ctx = toolCtx(s);
for (const g of p.gated) {
- const { result, items } = await runTool(g.name, g.input, { engine: s.thread.engine });
+ const { result, items } = await runTool(g.name, g.input, ctx);
results.push({ ...result, tool_use_id: g.id });
for (const it of items) push(s, it);
}
diff --git a/src/server/assist/context-tools.ts b/src/server/assist/context-tools.ts
new file mode 100644
index 00000000..93bddc56
--- /dev/null
+++ b/src/server/assist/context-tools.ts
@@ -0,0 +1,115 @@
+import "server-only";
+import { z } from "zod";
+import { guessCategory, MEMORY_CATEGORIES, MEMORY_MAX_CHARS, toCategory, type MemoryCategory } from "@/lib/assist";
+import { getSkill, skillFile } from "../skills";
+import { canUseSkill, skillsFor } from "./context";
+import { defineTool } from "./define";
+import { addMemory, deleteMemory } from "./memory";
+import { getProject, sourceText } from "./projects";
+
+/** Tools for Skills, Memory and Projects (Supercomputer's "load skill", "use and update memory", "project assets"). */
+
+const listSkills = defineTool({
+ name: "list_skills",
+ description:
+ "List the skills you can load: playbooks for whole kinds of jobs (product photos, UGC videos, thumbnails, faceless videos, dubbing…) with what each does and when to use it. The context already lists them briefly; call this for the full descriptions or to search by words.",
+ schema: z.object({
+ query: z.string().optional().describe("Words to match in a skill's name, title or description."),
+ }),
+ async run({ query }, ctx) {
+ const projectId = ctx.thread?.projectId ?? null;
+ let list = skillsFor(projectId);
+ if (query?.trim()) {
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
+ const scored = list.map((s) => ({ s, n: words.filter((w) => `${s.name} ${s.title} ${s.description} ${s.whenToUse}`.toLowerCase().includes(w)).length }));
+ if (scored.some((x) => x.n)) list = scored.filter((x) => x.n).sort((a, b) => b.n - a.n).map((x) => x.s);
+ }
+ return {
+ content: JSON.stringify(list.map((s) => ({ name: s.name, title: s.title, description: s.description, whenToUse: s.whenToUse || undefined, loaded: ctx.thread?.skills.includes(s.name) || undefined }))),
+ items: [{ id: "", role: "tool", text: `Looked through ${list.length} skill${list.length === 1 ? "" : "s"}` }],
+ };
+ },
+});
+
+const loadSkill = defineTool({
+ name: "load_skill",
+ description:
+ "Load a skill by name before you plan a job it covers; its instructions then guide this chat. Load one whenever the user's request matches a listed skill — once per chat is enough. With `file`, read one of the extra files a skill comes with.",
+ schema: z.object({
+ name: z.string().describe("The skill's name, e.g. product-photoshoot (without the slash)."),
+ file: z.string().optional().describe("A file bundled with the skill, as listed under it."),
+ }),
+ async run({ name, file }, ctx) {
+ const n = name.replace(/^\//, "").trim();
+ const s = getSkill(n);
+ const projectId = ctx.thread?.projectId ?? null;
+ if (!s || !canUseSkill(n, projectId)) {
+ const names = skillsFor(projectId).map((x) => x.name);
+ return { content: `No skill called “${n}” is available here. Available: ${names.join(", ") || "none"}.`, isError: true };
+ }
+ if (file) {
+ const text = skillFile(n, file);
+ if (text === null) return { content: `/${n} has no file “${file}”. Its files: ${s.files.map((f) => f.path).join(", ") || "none"}.`, isError: true };
+ return { content: text.length > 40_000 ? `${text.slice(0, 40_000)}\n… (cut at 40,000 characters)` : text, items: [{ id: "", role: "tool", text: `Read ${file} from ${s.title}` }] };
+ }
+ const item = { id: "", role: "tool" as const, text: `Using the ${s.title} skill`, href: `/assist/skills?skill=${s.name}` };
+ if (ctx.thread) {
+ if (ctx.thread.skills.includes(n)) return { content: `/${n} is already loaded — its instructions are in your context. Follow them.` };
+ ctx.thread.loadSkill(n);
+ return { content: `Loaded /${n} (${s.title}). Its instructions are added to your context right after this result — read them, then follow them for this job.`, items: [item] };
+ }
+ // Over MCP there's no chat context to add to: the instructions come back as the result.
+ return { content: `# ${s.title} (/${s.name})\n\n${s.body}`, items: [item] };
+ },
+});
+
+const remember = defineTool({
+ name: "remember",
+ description:
+ "Save a lasting fact about the user to memory so every future chat follows it: a preference (\"always vertical 9:16\"), their style, how they like replies, a naming or brand convention, their setup, a fix that worked. One short sentence per call, in the third person or as an instruction. Don't save one-off details of the current job, guesses, or secrets (keys, passwords). To correct a memory, pass its id as `replaces`. In ask-first mode the user approves each memory.",
+ schema: z.object({
+ text: z.string().describe(`The memory, one sentence (under ${MEMORY_MAX_CHARS} characters).`),
+ category: z.string().optional().describe(`One of: ${MEMORY_CATEGORIES.join(", ")}.`),
+ scope: z.enum(["personal", "project"]).optional().describe("project = only this project's chats (default inside a project); personal = every chat."),
+ replaces: z.string().optional().describe("The id of a memory this one corrects or replaces."),
+ }),
+ gated: true,
+ title: () => "Remember this?",
+ plan: ({ text, category, scope }, ctx) => {
+ const cat: MemoryCategory = toCategory(category) ?? guessCategory(text);
+ const where = (scope ?? (ctx.thread?.projectId ? "project" : "personal")) === "project" ? "This project" : "All chats";
+ return [{ tool: "remember", modelId: "memory", modelName: `Memory · ${cat}`, kind: "text", op: "memory", prompt: text.trim(), count: 0, costUsd: 0, demo: false, note: where, ...(text.trim().length > MEMORY_MAX_CHARS && { error: `Too long — keep it under ${MEMORY_MAX_CHARS} characters` }) }];
+ },
+ async run({ text, category, scope, replaces }, ctx) {
+ const projectId = ctx.thread?.projectId ?? null;
+ const sc = scope ?? (projectId ? "project" : "personal");
+ const cat: MemoryCategory = toCategory(category) ?? guessCategory(text);
+ const m = addMemory({ text, category: cat, scope: sc, projectId: sc === "project" ? projectId : null, source: "agent" });
+ if (replaces && replaces !== m.id) deleteMemory(replaces);
+ return {
+ content: JSON.stringify({ saved: m.id, category: m.category, scope: m.scope }),
+ items: [{ id: "", role: "tool", text: `Remembered: ${m.text}`, href: "/assist/memory" }],
+ };
+ },
+});
+
+const readSource = defineTool({
+ name: "read_source",
+ description: "Read the full text of one of this project's sources (a page, a document, a note) by the id shown in the project's source list. Only works inside a project.",
+ schema: z.object({
+ id: z.string().describe("The source id from the context, e.g. Ab3dE9xK1q."),
+ }),
+ async run({ id }, ctx) {
+ const projectId = ctx.thread?.projectId;
+ if (!projectId || !getProject(projectId)) return { content: "This chat isn't in a project, so it has no sources.", isError: true };
+ const s = sourceText(projectId, id.replace(/^\[|\]$/g, ""));
+ if (!s) return { content: `No source ${id} in this project.`, isError: true };
+ if (!s.text) return { content: JSON.stringify({ title: s.source.title, kind: s.source.kind, url: s.source.url, note: s.source.error ?? "This source has no text: pass its URL as an input instead." }) };
+ return {
+ content: `# ${s.source.title}${s.source.url ? `\n${s.source.url}` : ""}\n\n${s.text}`,
+ items: [{ id: "", role: "tool", text: `Read ${s.source.title}` }],
+ };
+ },
+});
+
+export const CONTEXT_TOOLS = [listSkills, loadSkill, remember, readSource];
diff --git a/src/server/assist/context.ts b/src/server/assist/context.ts
new file mode 100644
index 00000000..a1066049
--- /dev/null
+++ b/src/server/assist/context.ts
@@ -0,0 +1,113 @@
+import "server-only";
+import type { AssistMemory, ContextFact, Skill } from "@/lib/assist";
+import type { Engine } from "@/lib/catalog/types";
+import { engineMode } from "../settings";
+import { enabledSkills, getSkill } from "../skills";
+import { memoriesFor } from "./memory";
+import { getProject } from "./projects";
+
+/**
+ * What the agent knows about this chat beyond the fixed instructions: the date, engine and
+ * approval mode, the project (instructions and sources), memory, the skills it can load and the
+ * ones loaded. Rendered as the chat's second system block when it starts; later changes reach the
+ * model as appended "Context update" messages (see contextUpdate in lib/assist.ts).
+ */
+
+const MEMORY_ITEMS = 80;
+const MEMORY_CHARS = 8000;
+const SKILL_INDEX = 60;
+const SKILL_BODY = 30_000;
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).replace(/\s+\S*$/, "")}…` : s);
+
+export interface ChatInfo {
+ engine: Engine;
+ autoApprove: boolean;
+ projectId: string | null;
+ /** Loaded skills. */
+ skills: string[];
+}
+
+export function engineLine(engine: Engine): string {
+ const mode = engineMode();
+ return mode === "open"
+ ? "This install runs open-source models only (ComfyUI on the user's GPU)."
+ : mode === "cloud"
+ ? "This install runs paid cloud APIs only."
+ : engine === "open"
+ ? "The user prefers open-source models (ComfyUI, free on their GPU); use paid ones only when no open model can do the job, and say so."
+ : "The user prefers paid cloud models (best quality); open-source models are available too.";
+}
+
+export const approvalLine = (autoApprove: boolean) =>
+ autoApprove
+ ? "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for. Memories you save are kept straight away."
+ : "Ask-first is on: each generate call (and each memory you save) shows an approval card.";
+
+/** The skills a chat can use: a project's own list when it has one, else every enabled skill. */
+export function skillsFor(projectId: string | null): Skill[] {
+ const project = projectId ? getProject(projectId) : null;
+ if (project?.skills.length) return project.skills.map((n) => getSkill(n)).filter((s): s is Skill => !!s);
+ return enabledSkills();
+}
+
+export function canUseSkill(name: string, projectId: string | null): boolean {
+ return skillsFor(projectId).some((s) => s.name === name);
+}
+
+export function memoryLine(m: AssistMemory): string {
+ return `- (${m.id}) [${m.category}] ${m.text}${m.scope === "project" ? " (project)" : ""}`;
+}
+
+export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {
+ const facts: ContextFact[] = [
+ { section: "now", key: "date", text: `Today is ${now.toISOString().slice(0, 10)}.` },
+ { section: "now", key: "engine", text: engineLine(c.engine) },
+ { section: "now", key: "approval", text: approvalLine(c.autoApprove) },
+ ];
+ const project = c.projectId ? getProject(c.projectId) : null;
+ if (project) {
+ facts.push({
+ section: "project",
+ key: "about",
+ text: [
+ `This chat is in the project “${project.name}”.`,
+ project.instructions ? `The project's instructions — follow them:\n${project.instructions}` : "It has no extra instructions.",
+ project.skills.length ? `Only the project's skills are available here.` : "",
+ ]
+ .filter(Boolean)
+ .join("\n"),
+ });
+ for (const s of project.sources) {
+ const where = s.kind === "element" ? ` — ${s.excerpt?.split("\n")[0] ?? ""}` : s.url ? ` — ${s.url}` : "";
+ const body =
+ s.status === "error"
+ ? ` (couldn't be read: ${clip(s.error ?? "", 120)})`
+ : s.chars
+ ? ` — ${s.chars.toLocaleString("en")} characters, starts: “${clip((s.excerpt ?? "").replace(/\s+/g, " "), 160)}” (read_source for the full text)`
+ : s.kind === "image" || s.kind === "video" || s.kind === "audio"
+ ? " (pass the URL as an input)"
+ : "";
+ facts.push({ section: "sources", key: s.id, text: `- [${s.id}] ${s.kind}: ${s.title}${where}${body}` });
+ }
+ }
+ const memories = memoriesFor(project?.id ?? null, project?.usePersonalMemory ?? true);
+ let chars = 0;
+ for (const m of memories.slice(0, MEMORY_ITEMS)) {
+ const line = memoryLine(m);
+ chars += line.length;
+ if (chars > MEMORY_CHARS) break;
+ facts.push({ section: "memory", key: m.id, text: line });
+ }
+ const available = skillsFor(project?.id ?? null);
+ for (const s of available.slice(0, SKILL_INDEX)) {
+ facts.push({ section: "skills", key: s.name, text: clip(`- /${s.name} — ${s.title}: ${s.description}${s.whenToUse ? ` Use when: ${s.whenToUse}` : ""}`, 520) });
+ }
+ for (const name of c.skills) {
+ const s = getSkill(name);
+ if (!s) continue;
+ const files = s.files.length ? `\n\n(Files with this skill, readable with load_skill and file: ${s.files.map((f) => f.path).join(", ")})` : "";
+ facts.push({ section: "active", key: s.name, text: `### /${s.name} — ${s.title}\n${clip(s.body, SKILL_BODY)}${files}` });
+ }
+ return facts;
+}
diff --git a/src/server/assist/define.ts b/src/server/assist/define.ts
new file mode 100644
index 00000000..fedf3732
--- /dev/null
+++ b/src/server/assist/define.ts
@@ -0,0 +1,44 @@
+import "server-only";
+import type Anthropic from "@anthropic-ai/sdk";
+import type { z } from "zod";
+import type { AssistItem, PlannedJob } from "@/lib/assist";
+
+/** Shared shape of Assist's tools (also served over MCP). */
+
+export type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];
+
+export interface ToolContext {
+ engine: "cloud" | "open";
+ /** The Assist chat running the tool; absent over MCP. */
+ thread?: {
+ id: string;
+ projectId: string | null;
+ /** Skills already loaded in this chat. */
+ skills: string[];
+ /** Load a skill into this chat: its instructions join the context on the next model call. */
+ loadSkill: (name: string) => void;
+ };
+}
+
+export interface ToolOutcome {
+ content: ResultContent;
+ isError?: boolean;
+ /** Cards to show in the chat (generations started, a short "looked up models" line…). */
+ items?: AssistItem[];
+}
+
+export interface ToolDef<S extends z.ZodType> {
+ name: string;
+ description: string;
+ schema: S;
+ /** Spends money or GPU time (or, for remember, changes what Assist knows): waits for the user's approval unless auto-approve is on. */
+ gated?: boolean;
+ strict?: boolean;
+ run: (input: z.infer<S>, ctx: ToolContext) => Promise<ToolOutcome>;
+ /** For gated tools: what the run would do, priced. */
+ plan?: (input: z.infer<S>, ctx: ToolContext) => PlannedJob[];
+ /** The approval card's heading for this call (default: its summary field, else the tool's name). */
+ title?: (input: z.infer<S>) => string;
+}
+
+export const defineTool = <S extends z.ZodType>(def: ToolDef<S>) => def;
diff --git a/src/server/assist/studio-tools.ts b/src/server/assist/studio-tools.ts
new file mode 100644
index 00000000..7fe6a3db
--- /dev/null
+++ b/src/server/assist/studio-tools.ts
@@ -0,0 +1,438 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import type { PlannedJob } from "@/lib/assist";
+import { getModel } from "@/lib/catalog";
+import type { ChainSlot, Engine, GenerationRequest } from "@/lib/catalog/types";
+import { createPipeline, type PipelineStep } from "../chains";
+import { createGenerations, outputKind, previewChained } from "../generations";
+import { engineMode } from "../settings";
+import { defineTool, type ToolContext, type ToolOutcome } from "./define";
+
+/**
+ * Agent access to whole studios: split an image into layers, restyle footage, dub a video, make a
+ * faceless episode, a batch of ads, captions. Each tool runs the studio's own module when one is
+ * wired into STUDIO_ROUTES (so the job shows up in that studio), and otherwise builds the same job
+ * from catalog models with createPipeline — the studios that aren't in this build still work
+ * from Assist and MCP, just without their own page.
+ */
+
+// ---------------------------------------------------------------------------
+// Wiring for the studio modules (set at merge; see the report for each adapter)
+
+/** What a studio module returns when it takes a job: the generations to show and its page. */
+export interface StudioRun {
+ /** Generation ids to show in the chat (the finished results first). */
+ ids: string[];
+ /** The studio page for this job, e.g. /layers/<id>. */
+ href?: string;
+ /** Extra facts for the agent (session id, segments, steps). */
+ info?: Record<string, unknown>;
+}
+
+export interface StudioRoute<I> {
+ /** Price the job; the built-in plan is used when absent. */
+ plan?: (input: I, ctx: ToolContext) => PlannedJob[];
+ run: (input: I, ctx: ToolContext) => Promise<StudioRun>;
+}
+
+const ref = z.string().describe("A file URL from the chat: an attachment, a project source or an earlier output (/api/files/…).");
+
+const LayersInput = z.object({
+ image: ref.describe("The image to split."),
+ layers: z.number().int().optional().describe("How many layers (2–8, default 4)."),
+ focus: z.string().optional().describe("What to separate, e.g. 'the person, the product, the headline text, the background'."),
+ model_id: z.string().optional().describe("A layers model from search_models (task layers); default: the engine's best."),
+});
+const RestyleInput = z.object({
+ video: ref.describe("The footage to restyle."),
+ style: z.string().describe("The new look, e.g. 'claymation, warm studio light' or 'anime, cel shading'."),
+ references: z.array(ref).optional().describe("Up to 4 style reference images."),
+ model_id: z.string().optional().describe("A video-to-video model from search_models (task v2v)."),
+});
+const DubInput = z.object({
+ video: ref.describe("The video to dub."),
+ languages: z.array(z.string()).describe("1–4 languages to dub into, e.g. ['Spanish', 'German']."),
+ lipsync: z.boolean().optional().describe("Re-sync the lips to the new speech (default true)."),
+ source_language: z.string().optional().describe("The language spoken in the video, if known."),
+});
+const FacelessInput = z.object({
+ title: z.string().optional().describe("The episode title."),
+ scenes: z
+ .array(
+ z.object({
+ narration: z.string().describe("What the narrator says over this scene (about 8–10 seconds of speech)."),
+ visual: z.string().describe("What the scene shows, in the episode's style."),
+ }),
+ )
+ .describe("2–8 scenes in order."),
+ style: z.string().describe("The visual style for every scene, e.g. 'flat 2D illustration, muted palette'."),
+ aspect_ratio: z.string().optional().describe("9:16 (default), 16:9 or 1:1."),
+ voice: z.string().optional().describe("A voice id for the narrator (search_models kind audio lists them)."),
+});
+const AdsInput = z.object({
+ brief: z.string().describe("What the ads sell and to whom, with the offer or angle."),
+ product_image: ref.optional().describe("The product photo (keeps the real product in every ad)."),
+ count: z.number().int().optional().describe("How many different ads (1–8, default 4)."),
+ aspect_ratios: z.array(z.string()).optional().describe("Formats for each ad: 1:1, 4:5 (default), 9:16, 16:9."),
+ headline: z.string().optional().describe("A headline to use exactly; otherwise each ad gets its own."),
+ cta: z.string().optional().describe("Call to action, e.g. 'Shop now'."),
+ brand_id: z.string().optional().describe("A brand kit id from the Ads studio, when the user has one."),
+ product_id: z.string().optional().describe("A product id from the Ads studio, when the user has one."),
+});
+const CaptionsInput = z.object({
+ video: ref.describe("The video to caption."),
+ spoken_language: z.string().optional().describe("The language spoken in the video (auto-detected when left out on most models)."),
+ translate_to: z.string().optional().describe("Caption in this language instead (translated subtitles)."),
+});
+
+export type LayersToolInput = z.infer<typeof LayersInput>;
+export type RestyleToolInput = z.infer<typeof RestyleInput>;
+export type DubToolInput = z.infer<typeof DubInput>;
+export type FacelessToolInput = z.infer<typeof FacelessInput>;
+export type AdsToolInput = z.infer<typeof AdsInput>;
+export type CaptionsToolInput = z.infer<typeof CaptionsInput>;
+
+/** Studio modules plug in here; a tool falls back to its catalog-model pipeline when its entry is empty. */
+export const STUDIO_ROUTES: {
+ split_layers?: StudioRoute<LayersToolInput>;
+ restyle_footage?: StudioRoute<RestyleToolInput>;
+ dub_video?: StudioRoute<DubToolInput>;
+ faceless_episode?: StudioRoute<FacelessToolInput>;
+ create_ads?: StudioRoute<AdsToolInput>;
+ add_captions?: StudioRoute<CaptionsToolInput>;
+} = {};
+
+// ---------------------------------------------------------------------------
+// Fallback: pipelines of catalog models
+
+const engineOf = (ctx: ToolContext): Engine => (engineMode() === "both" ? ctx.engine : (engineMode() as Engine));
+const pick = (ctx: ToolContext, cloud: string, open: string, override?: string) => override || (engineOf(ctx) === "open" ? open : cloud);
+const asList = <T,>(a: T | T[] | undefined): T[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);
+const req = (r: Omit<GenerationRequest, "feature">): GenerationRequest => ({ feature: "assist", ...r });
+
+/** Price each step of a pipeline the way createPipeline validates it, without creating anything. */
+export function planSteps(tool: string, steps: PipelineStep[]): PlannedJob[] {
+ const jobs = steps.map((s, i): PlannedJob => {
+ const chain = s.chain ?? s.request.chain;
+ const r: GenerationRequest = { ...s.request, ...(chain && { chain }) };
+ const label = s.request.step?.label ?? `Step ${i + 1} of ${steps.length}`;
+ try {
+ const p = previewChained(r, asList(s.after).length);
+ return { tool, modelId: p.model.id, modelName: p.model.name, kind: outputKind(p.op, p.model), op: p.op, prompt: s.request.prompt?.trim() || label, count: p.outputs, costUsd: p.costUsd, demo: p.demo, note: label };
+ } catch (e) {
+ const m = getModel(s.request.modelId);
+ return { tool, modelId: s.request.modelId, modelName: m?.name ?? s.request.modelId, kind: m?.kind ?? "video", op: s.request.op ?? "t2i", prompt: s.request.prompt?.trim() || label, count: 0, costUsd: 0, demo: false, note: label, error: (e as Error).message };
+ }
+ });
+ // createPipeline refuses a mix of demo and real steps: say so on the card already.
+ if (jobs.some((j) => j.demo && !j.error) && jobs.some((j) => !j.demo && !j.error)) {
+ const d = jobs.find((j) => j.demo && !j.error)!;
+ d.error = `${d.modelName} would run as a demo while the other steps run for real — connect it in Settings, or turn on demo mode`;
+ }
+ return jobs;
+}
+
+/** Steps labelled for the Library ("Voice · Spanish"), keeping createPipeline's order index. */
+function labelled(steps: (PipelineStep & { label: string })[]): PipelineStep[] {
+ return steps.map(({ label, ...s }, i) => ({ ...s, request: { ...s.request, step: { label, index: i, of: steps.length } } }));
+}
+
+function layerSteps(i: LayersToolInput, ctx: ToolContext): PipelineStep[] {
+ const n = Math.max(2, Math.min(8, i.layers ?? 4));
+ return labelled([
+ {
+ key: "layers",
+ label: "Layers",
+ request: req({ modelId: pick(ctx, "seedream-5-layers", "oss-qwen-layered", i.model_id), op: "layers", prompt: i.focus?.trim() || "Split the image into clean layers", inputs: { images: [i.image] }, params: { numLayers: n } }),
+ },
+ ]);
+}
+
+function restyleSteps(i: RestyleToolInput, ctx: ToolContext): PipelineStep[] {
+ const refs = (i.references ?? []).slice(0, 4);
+ return labelled([
+ {
+ key: "restyle",
+ label: "Restyled video",
+ request: req({ modelId: pick(ctx, "kling-o3", "oss-mixed-media", i.model_id), op: "v2v", prompt: i.style, inputs: { video: i.video, ...(refs.length && { images: refs }) } }),
+ },
+ ]);
+}
+
+function dubSteps(i: DubToolInput, ctx: ToolContext): PipelineStep[] {
+ const langs = [...new Set(i.languages.map((l) => l.trim()).filter(Boolean))].slice(0, 4);
+ if (!langs.length) throw new Error("Name the language to dub into");
+ const lipsync = i.lipsync !== false;
+ if (engineOf(ctx) === "cloud") {
+ // HeyGen translates, re-voices, lip-syncs and keeps the background in one job.
+ return labelled(langs.map((l, k) => ({ key: `dub${k}`, label: `Dub · ${l}`, request: req({ modelId: "heygen-translate", op: "dub", inputs: { video: i.video }, params: { targetLanguage: l, sourceLanguage: i.source_language } }) })));
+ }
+ const steps: (PipelineStep & { label: string })[] = [
+ { key: "stems", label: "Voice and background", request: req({ modelId: "oss-voice-separate", op: "separate-audio", inputs: { video: i.video } }) },
+ { key: "words", label: "Transcript", request: req({ modelId: "oss-qwen3-asr", op: "transcribe", params: { sourceLanguage: i.source_language } }), after: "stems", chain: [{ slot: "audio", stem: "voice" }] },
+ ];
+ langs.forEach((l, k) => {
+ steps.push(
+ { key: `tr${k}`, label: `Translation · ${l}`, request: req({ modelId: "oss-text-llm", op: "translate", params: { targetLanguage: l } }), after: "words", chain: [{ slot: "prompt" }] },
+ {
+ key: `voice${k}`,
+ label: `Voice · ${l}`,
+ request: req({ modelId: "oss-chatterbox", op: "tts" }),
+ after: [`tr${k}`, "stems"],
+ chain: [{ slot: "prompt" }, { slot: "voiceAudio", stem: "voice" }],
+ },
+ );
+ if (lipsync) steps.push({ key: `lips${k}`, label: `Lip sync · ${l}`, request: req({ modelId: "oss-infinitetalk-v2v", op: "lipsync", inputs: { video: i.video } }), after: `voice${k}`, chain: [{ slot: "audio" }] });
+ const background: ChainSlot = { slot: "audio2", stem: "background" };
+ steps.push(
+ lipsync
+ ? { key: `film${k}`, label: `Dubbed video · ${l}`, request: req({ modelId: "oss-mux", op: "mux" }), after: [`lips${k}`, `voice${k}`, "stems"], chain: [{ slot: "video" }, { slot: "audio" }, background] }
+ : { key: `film${k}`, label: `Dubbed video · ${l}`, request: req({ modelId: "oss-mux", op: "mux", inputs: { video: i.video } }), after: [`voice${k}`, "stems"], chain: [{ slot: "audio" }, background] },
+ );
+ });
+ return labelled(steps);
+}
+
+function facelessSteps(i: FacelessToolInput, ctx: ToolContext): PipelineStep[] {
+ const scenes = i.scenes.filter((s) => s.visual.trim() || s.narration.trim()).slice(0, 8);
+ if (scenes.length < 2) throw new Error("Give at least 2 scenes");
+ const open = engineOf(ctx) === "open";
+ const aspect = ["9:16", "16:9", "1:1"].includes(i.aspect_ratio ?? "") ? i.aspect_ratio! : "9:16";
+ const stillModel = open ? "oss-z-image-turbo" : "nano-banana-pro";
+ // Higgsfield's Faceless runs Gemini Omni Flash per block (16:9 / 9:16 only); square goes to Seedance.
+ const clipModel = open ? "oss-wan22-14b-fast" : aspect === "1:1" ? "seedance-2-5" : "gemini-omni-flash";
+ const steps: (PipelineStep & { label: string })[] = [];
+ scenes.forEach((s, k) => {
+ steps.push(
+ { key: `still${k}`, label: `Scene ${k + 1} · still`, request: req({ modelId: stillModel, op: "t2i", prompt: `${s.visual.trim()}. Style: ${i.style.trim()}. No text.`, params: { aspectRatio: aspect } }) },
+ {
+ key: `clip${k}`,
+ label: `Scene ${k + 1} · clip`,
+ request: req({ modelId: clipModel, op: "i2v", prompt: `${s.visual.trim()}. Gentle, slow camera push-in; subtle natural motion; same style.`, params: { aspectRatio: aspect, ...(clipModel === "seedance-2-5" && { duration: 5 }) } }),
+ after: `still${k}`,
+ chain: [{ slot: "images", position: "first" }],
+ },
+ );
+ });
+ // Joins: the open join takes up to 4 clips a step, so longer episodes join in groups first.
+ const join = open ? "oss-join-clips" : "join-clips";
+ const clips = scenes.map((_, k) => `clip${k}`);
+ let film: string;
+ if (clips.length <= (open ? 4 : 24)) {
+ steps.push({ key: "film", label: "Joined scenes", request: req({ modelId: join, op: "concat", prompt: i.title?.trim() || "Episode" }), after: clips, chain: clips.map(() => ({ slot: "videos" as const })) });
+ film = "film";
+ } else {
+ const groups: string[] = [];
+ for (let g = 0; g * 4 < clips.length; g++) {
+ const part = clips.slice(g * 4, g * 4 + 4);
+ steps.push({ key: `part${g}`, label: `Scenes ${g * 4 + 1}–${g * 4 + part.length} joined`, request: req({ modelId: join, op: "concat", prompt: i.title?.trim() || "Episode" }), after: part, chain: part.map(() => ({ slot: "videos" as const })) });
+ groups.push(`part${g}`);
+ }
+ steps.push({ key: "film", label: "Joined scenes", request: req({ modelId: join, op: "concat", prompt: i.title?.trim() || "Episode" }), after: groups, chain: groups.map(() => ({ slot: "videos" as const })) });
+ film = "film";
+ }
+ steps.push(
+ { key: "voice", label: "Narration", request: req({ modelId: open ? "oss-chatterbox" : "elevenlabs-v4", op: "tts", prompt: scenes.map((s) => s.narration.trim()).filter(Boolean).join("\n\n"), params: { voice: i.voice } }) },
+ { key: "episode", label: "Episode", request: req({ modelId: open ? "oss-mux" : "merge-audio-video", op: "mux", prompt: i.title?.trim() || "Episode" }), after: [film, "voice"], chain: [{ slot: "video" }, { slot: "audio" }] },
+ );
+ return labelled(steps);
+}
+
+function captionSteps(i: CaptionsToolInput, ctx: ToolContext): PipelineStep[] {
+ if (engineOf(ctx) === "cloud") {
+ const model = i.translate_to ? "veed-subtitles" : "auto-subtitle";
+ return labelled([{ key: "captions", label: "Captioned video", request: req({ modelId: model, op: "captions", inputs: { video: i.video }, params: { sourceLanguage: i.spoken_language, targetLanguage: i.translate_to } }) }]);
+ }
+ const steps: (PipelineStep & { label: string })[] = [{ key: "words", label: "Transcript", request: req({ modelId: "oss-qwen3-asr", op: "transcribe", inputs: { video: i.video }, params: { sourceLanguage: i.spoken_language } }) }];
+ let last = "words";
+ if (i.translate_to) {
+ steps.push({ key: "tr", label: `Translation · ${i.translate_to}`, request: req({ modelId: "oss-text-llm", op: "translate", params: { targetLanguage: i.translate_to } }), after: "words", chain: [{ slot: "prompt" }] });
+ last = "tr";
+ }
+ steps.push({ key: "captions", label: "Captioned video", request: req({ modelId: "oss-captions-burnin", op: "captions", inputs: { video: i.video } }), after: last, chain: [{ slot: "prompt" }] });
+ return labelled(steps);
+}
+
+const AD_ANGLES = [
+ "Hero layout: the product large in the centre, headline above, call-to-action button below, bold brand colour backdrop",
+ "Lifestyle scene: the product in use in a real setting, headline on a clean band across the top",
+ "Offer burst: a large badge with the offer, the product to one side, high-contrast colours",
+ "Minimal split layout: the product on one half, the headline and a short line on the other, lots of whitespace",
+ "Social proof card: a short customer quote with five stars beside the product",
+ "Benefit callouts: the product with three short labelled benefits and simple icons",
+ "Close-up detail: a dramatic macro of the product with the headline in large type",
+ "Problem / solution: the problem on the left, the product as the answer on the right",
+];
+
+function adRequests(i: AdsToolInput, ctx: ToolContext): GenerationRequest[] {
+ const n = Math.max(1, Math.min(8, i.count ?? 4));
+ const ratios = (i.aspect_ratios?.length ? i.aspect_ratios : ["4:5"]).slice(0, 4);
+ const open = engineOf(ctx) === "open";
+ const model = i.product_image ? (open ? "oss-qwen-edit" : "nano-banana-pro") : open ? "oss-qwen-image" : "nano-banana-pro";
+ const out: GenerationRequest[] = [];
+ for (let k = 0; k < n && out.length < 12; k++) {
+ for (const ratio of ratios) {
+ if (out.length >= 12) break;
+ const text = [
+ `Advertising creative: ${i.brief.trim()}.`,
+ `${AD_ANGLES[k % AD_ANGLES.length]}.`,
+ i.headline ? `Headline exactly: “${i.headline.trim()}”.` : "A short, punchy headline of 2–6 words.",
+ i.cta ? `Call-to-action button: “${i.cta.trim()}”.` : "",
+ i.product_image ? "Keep the product exactly as in the photo: same shape, colours, label and logo." : "",
+ "Clean modern layout, crisp legible typography, no other text, no watermark.",
+ ]
+ .filter(Boolean)
+ .join(" ");
+ out.push(req({ modelId: model, op: i.product_image ? "edit" : "t2i", prompt: text, ...(i.product_image && { inputs: { images: [i.product_image] } }), params: { aspectRatio: ratio } }));
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// The tools
+
+function startPipeline(tool: string, steps: PipelineStep[], title: string, show: "last" | "all" = "last"): ToolOutcome {
+ const p = createPipeline(steps.map((s) => ({ ...s, request: { ...s.request, batchTitle: title.slice(0, 200) } })));
+ const final = p.items.at(-1)!;
+ const finals = steps.filter((s) => !steps.some((t) => asList(t.after).includes(s.key))).map((s) => p.byKey[s.key].id);
+ const ids = show === "all" ? p.items.map((g) => g.id) : finals;
+ return {
+ content: JSON.stringify({
+ steps: steps.map((s) => ({ step: s.request.step?.label, id: p.byKey[s.key].id, waitsFor: asList(s.after).map((a) => p.byKey[a].id) })),
+ results: finals,
+ demo: final.provider === "mock" || undefined,
+ note: `${steps.length} step${steps.length === 1 ? "" : "s"}; each starts by itself when the ones it waits for finish. The finished result${finals.length > 1 ? "s appear" : " appears"} in the chat.`,
+ }),
+ items: [
+ { id: "", role: "tool", text: `${tool}: started ${steps.length} step${steps.length === 1 ? "" : "s"}`, href: "/library" },
+ { id: "", role: "generations", ids },
+ ],
+ };
+}
+
+async function viaStudio<I>(route: StudioRoute<I> | undefined, input: I, ctx: ToolContext, label: string): Promise<ToolOutcome | null> {
+ if (!route) return null;
+ const r = await route.run(input, ctx);
+ return {
+ content: JSON.stringify({ results: r.ids, ...(r.href && { open: r.href }), ...r.info }),
+ items: [{ id: "", role: "tool", text: label, ...(r.href && { href: r.href }) }, ...(r.ids.length ? [{ id: "", role: "generations" as const, ids: r.ids }] : [])],
+ };
+}
+
+const splitLayers = defineTool({
+ name: "split_layers",
+ description:
+ "Split an image into separate transparent layers (person, product, text, background…) for editing — Fuobe's Layers studio. Use it for 'separate the layers', 'make this editable', 'cut everything out into layers'. Gated by the same approval card as generate.",
+ schema: LayersInput,
+ gated: true,
+ title: () => "Split into layers",
+ plan: (i, ctx) => STUDIO_ROUTES.split_layers?.plan?.(i, ctx) ?? planSteps("split_layers", layerSteps(i, ctx)),
+ async run(i, ctx) {
+ return (await viaStudio(STUDIO_ROUTES.split_layers, i, ctx, "Opened a Layers project")) ?? startPipeline("Layers", layerSteps(i, ctx), "Layers", "all");
+ },
+});
+
+const restyleFootage = defineTool({
+ name: "restyle_footage",
+ description:
+ "Restyle the user's own footage into a new look (anime, claymation, oil paint, a reference image's style) while keeping its motion — Fuobe's Shorts / Mixed Media studio. Use it for 'turn my clip into…', 'restyle this video'. Gated by the same approval card as generate.",
+ schema: RestyleInput,
+ gated: true,
+ title: (i) => `Restyle: ${i.style.slice(0, 60)}`,
+ plan: (i, ctx) => STUDIO_ROUTES.restyle_footage?.plan?.(i, ctx) ?? planSteps("restyle_footage", restyleSteps(i, ctx)),
+ async run(i, ctx) {
+ return (await viaStudio(STUDIO_ROUTES.restyle_footage, i, ctx, "Started a Shorts restyle")) ?? startPipeline("Restyle", restyleSteps(i, ctx), `Restyle: ${i.style}`);
+ },
+});
+
+const dubVideo = defineTool({
+ name: "dub_video",
+ description:
+ "Dub a video into 1–4 other languages in the speaker's own voice, optionally lip-synced, keeping the background sound — Fuobe's Translate & dub studio. One approval runs every step (voice separation, transcript, translation, voice, lip sync, mix). Gated by the same approval card as generate.",
+ schema: DubInput,
+ gated: true,
+ title: (i) => `Dub into ${i.languages.join(", ")}`,
+ plan: (i, ctx) => {
+ if (STUDIO_ROUTES.dub_video?.plan) return STUDIO_ROUTES.dub_video.plan(i, ctx);
+ try {
+ return planSteps("dub_video", dubSteps(i, ctx));
+ } catch (e) {
+ return [{ tool: "dub_video", modelId: "dub", modelName: "Translate & dub", kind: "video", op: "dub", prompt: i.languages.join(", "), count: 0, costUsd: 0, demo: false, error: (e as Error).message }];
+ }
+ },
+ async run(i, ctx) {
+ return (await viaStudio(STUDIO_ROUTES.dub_video, i, ctx, "Started a dub")) ?? startPipeline("Dub", dubSteps(i, ctx), `Dub into ${i.languages.join(", ")}`);
+ },
+});
+
+const facelessEpisode = defineTool({
+ name: "faceless_episode",
+ description:
+ "Make a narrated faceless video from scenes you wrote: a still and an animated clip per scene in one style, the narration, joined into one episode — Fuobe's Faceless studio. Write the narration and visuals first (load the faceless-video skill), then call this once. Gated by the same approval card as generate.",
+ schema: FacelessInput,
+ gated: true,
+ title: (i) => i.title?.trim() || "Faceless episode",
+ plan: (i, ctx) => {
+ if (STUDIO_ROUTES.faceless_episode?.plan) return STUDIO_ROUTES.faceless_episode.plan(i, ctx);
+ try {
+ return planSteps("faceless_episode", facelessSteps(i, ctx));
+ } catch (e) {
+ return [{ tool: "faceless_episode", modelId: "faceless", modelName: "Faceless episode", kind: "video", op: "concat", prompt: i.title ?? "Episode", count: 0, costUsd: 0, demo: false, error: (e as Error).message }];
+ }
+ },
+ async run(i, ctx) {
+ return (await viaStudio(STUDIO_ROUTES.faceless_episode, i, ctx, "Started a faceless episode")) ?? startPipeline("Faceless episode", facelessSteps(i, ctx), i.title?.trim() || "Faceless episode");
+ },
+});
+
+const createAds = defineTool({
+ name: "create_ads",
+ description:
+ "Make a batch of different ad creatives (1–8 concepts × up to 4 formats) for a product: varied layouts and angles, headline, call to action, the real product from its photo — Fuobe's Ads studio. Use it for 'ads for my product', 'a set of Meta ads', 'creatives to test'. Gated by the same approval card as generate.",
+ schema: AdsInput,
+ gated: true,
+ title: (i) => `${Math.max(1, Math.min(8, i.count ?? 4))} ads: ${i.brief.slice(0, 50)}`,
+ plan: (i, ctx) => {
+ if (STUDIO_ROUTES.create_ads?.plan) return STUDIO_ROUTES.create_ads.plan(i, ctx);
+ return planSteps(
+ "create_ads",
+ adRequests(i, ctx).map((r, k) => ({ key: `ad${k}`, request: { ...r, step: { label: `Ad ${k + 1} · ${r.params?.aspectRatio}`, index: k, of: 0 } } })),
+ );
+ },
+ async run(i, ctx) {
+ const studio = await viaStudio(STUDIO_ROUTES.create_ads, i, ctx, "Started an ads batch");
+ if (studio) return studio;
+ const batchId = nanoid(10);
+ const ids: string[] = [];
+ const errors: string[] = [];
+ for (const r of adRequests(i, ctx)) {
+ try {
+ ids.push(...createGenerations({ ...r, batchTitle: `Ads: ${i.brief.slice(0, 120)}` }, { batchId }).map((g) => g.id));
+ } catch (e) {
+ errors.push((e as Error).message);
+ }
+ }
+ if (!ids.length) return { content: JSON.stringify({ error: errors[0] ?? "Nothing could start" }), isError: true };
+ return { content: JSON.stringify({ started: ids, ...(errors.length && { errors }) }), items: [{ id: "", role: "generations", ids }] };
+ },
+});
+
+const addCaptions = defineTool({
+ name: "add_captions",
+ description:
+ "Burn captions into a video from its speech, optionally translated into another language — Fuobe's Captions tool. Gated by the same approval card as generate.",
+ schema: CaptionsInput,
+ gated: true,
+ title: (i) => (i.translate_to ? `Captions in ${i.translate_to}` : "Captions"),
+ plan: (i, ctx) => STUDIO_ROUTES.add_captions?.plan?.(i, ctx) ?? planSteps("add_captions", captionSteps(i, ctx)),
+ async run(i, ctx) {
+ return (await viaStudio(STUDIO_ROUTES.add_captions, i, ctx, "Started captions")) ?? startPipeline("Captions", captionSteps(i, ctx), i.translate_to ? `Captions in ${i.translate_to}` : "Captions");
+ },
+});
+
+export const STUDIO_TOOLS = [splitLayers, restyleFootage, dubVideo, facelessEpisode, createAds, addCaptions];
+
+/** For tests: the fallback pipelines, as they would be created. */
+export const fallbackSteps = { layers: layerSteps, restyle: restyleSteps, dub: dubSteps, faceless: facelessSteps, captions: captionSteps, ads: adRequests };
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index 95dbaac0..ba9f4674 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -4,7 +4,7 @@ import { nanoid } from "nanoid";
import { z } from "zod";
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 { type PlannedJob, totalCost } from "@/lib/assist";
import { STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
import { createPipeline } from "../chains";
import { listElements } from "../elements";
@@ -14,33 +14,11 @@ import { llmBackends } from "../providers/llm";
import { engineMode } from "../settings";
import { readRef } from "../storage";
import { createStoryboard } from "../storyboard";
+import { CONTEXT_TOOLS } from "./context-tools";
+import { defineTool, type ResultContent, type ToolContext, type ToolDef, type ToolOutcome } from "./define";
+import { STUDIO_TOOLS } from "./studio-tools";
-type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];
-
-export interface ToolContext {
- engine: "cloud" | "open";
-}
-
-export interface ToolOutcome {
- content: ResultContent;
- isError?: boolean;
- /** Cards to show in the chat (generations started, a short "looked up models" line…). */
- items?: AssistItem[];
-}
-
-interface ToolDef<S extends z.ZodType> {
- name: string;
- description: string;
- schema: S;
- /** Spends money or GPU time: waits for the user's approval unless auto-approve is on. */
- gated?: boolean;
- strict?: boolean;
- run: (input: z.infer<S>, ctx: ToolContext) => Promise<ToolOutcome>;
- /** For gated tools: what the run would do, priced. */
- plan?: (input: z.infer<S>, ctx: ToolContext) => PlannedJob[];
-}
-
-const defineTool = <S extends z.ZodType>(def: ToolDef<S>) => def;
+export type { ToolContext, ToolOutcome };
const ref = z.string().describe("A file URL from the chat: an attachment or an earlier output (/api/files/…).");
@@ -502,6 +480,19 @@ const storyboard = defineTool({
export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecent, checkGenerations, generate, storyboard];
export const getTool = (name: string) => TOOLS.find((t) => t.name === name);
+// Skills, memory and project sources; then whole studios (layers, restyle, dub, faceless, ads, captions).
+TOOLS.push(...CONTEXT_TOOLS, ...STUDIO_TOOLS);
+
+/** The approval card's heading for one gated call. */
+export function cardTitle(name: string, input: unknown): string {
+ const t = getTool(name);
+ const parsed = t?.schema.safeParse(input);
+ if (t?.title && parsed?.success) return t.title(parsed.data);
+ const summary = (input as { summary?: unknown } | null)?.summary;
+ if (typeof summary === "string" && summary.trim()) return summary.trim();
+ return name === "create_storyboard" ? "Storyboard" : "Generate";
+}
+
/** JSON Schema for the API: every object closed, constraints the API doesn't take removed (zod still checks them). */
export function apiSchema(schema: z.ZodType): Anthropic.Beta.BetaTool.InputSchema {
const json = z.toJSONSchema(schema) as Record<string, unknown>;
diff --git a/src/server/mcp.ts b/src/server/mcp.ts
index 0d6bf9cd..46c44d8d 100644
--- a/src/server/mcp.ts
+++ b/src/server/mcp.ts
@@ -2,20 +2,24 @@ import "server-only";
import { z } from "zod";
import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";
import { engineMode } from "./settings";
+import { enabledSkills, getSkill } from "./skills";
/**
* Fuobe as an MCP server (Model Context Protocol, streamable HTTP transport, stateless):
* other agents — Claude Desktop, Claude Code, any MCP client — can look up models, price a
* plan, start generations and fetch results. Same tools as Assist; the client's own approval
- * prompt replaces Assist's plan card, so `estimate_cost` is offered for asking first.
+ * prompt replaces Assist's plan card, so `estimate_cost` / `estimate_job` are offered for asking
+ * first. Assist's skills are served as MCP prompts (and through list_skills / load_skill).
*/
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 SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.1.0" };
const INSTRUCTIONS =
"Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows); it also transcribes, translates and writes text and turns images into 3D models. " +
"Look up models with search_models (kinds image, video, audio, text, model3d), price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " +
'Chain steps in one generate call with "after" (a still, then animate it). ' +
+ "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions): price them with estimate_job first. " +
+ "Skills are playbooks for kinds of jobs (product photos, UGC videos, thumbnails…): list_skills, then load_skill to read one — they're also offered as prompts. " +
"Generations run in the background: poll check_generations (wait_seconds up to 120) for output URLs; text results come back inline. Output URLs are paths on this Fuobe server.";
interface JsonRpcRequest {
@@ -32,16 +36,27 @@ const fail = (id: JsonRpcRequest["id"], code: number, message: string): JsonRpcR
const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud" });
-const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost"]);
+const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost", "estimate_job", "list_skills", "load_skill", "read_source"]);
+
+/** Gated tools other than generate and create_storyboard (priced with estimate_job). */
+const jobTools = () => TOOLS.filter((t) => t.gated && t.plan && !["generate", "create_storyboard", "remember"].includes(t.name)).map((t) => t.name);
+
+function describe(t: (typeof TOOLS)[number]): string {
+ // Assist's approval card doesn't exist here: say what the call costs instead.
+ const base = t.description.replace(/The app shows the user the plan[^.]*\.( so call this directly instead of asking for confirmation in text\.)?/, "").replace(/\s*Gated by the same approval card as generate\.|\s*In ask-first mode the user approves each memory\./, "").trim();
+ if (!t.gated) return t.description;
+ if (t.name === "remember") return `${base} Changes what Fuobe Assist remembers about the user in every chat: confirm with the user first.`;
+ const how = t.name === "generate" || t.name === "create_storyboard" ? "price it with estimate_cost" : "price it with estimate_job";
+ return `${base} Spends money on paid models (or GPU time on open ones): ${how} and confirm with the user first.`;
+}
function toolList() {
- const tools = TOOLS.map((t) => ({
+ const tools: { name: string; title: string; description: string; inputSchema: unknown; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] = TOOLS.map((t) => ({
name: t.name,
title: t.name.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()),
- // Assist's approval card doesn't exist here: say what the call costs instead.
- description: t.gated ? `${t.description.replace(/The app shows the user the plan[^.]*\.( so call this directly instead of asking for confirmation in text\.)?/, "").trim()} Spends money on paid models (or GPU time on open ones): price it with estimate_cost and confirm with the user first.` : t.description,
+ description: describe(t),
inputSchema: apiSchema(t.schema),
- annotations: { readOnlyHint: READ_ONLY.has(t.name), openWorldHint: !!t.gated },
+ annotations: { readOnlyHint: READ_ONLY.has(t.name), openWorldHint: !!t.gated && t.name !== "remember" },
}));
const gen = getTool("generate")!;
tools.push({
@@ -51,6 +66,22 @@ function toolList() {
inputSchema: apiSchema(gen.schema),
annotations: { readOnlyHint: true, openWorldHint: false },
});
+ const jobs = jobTools();
+ tools.push({
+ name: "estimate_job",
+ title: "Estimate a studio job",
+ description: `Price a studio tool call (${jobs.join(", ")}) without running it: every step with its model and estimated USD, and whether it would run as a demo. Pass the tool's name and the arguments you'd give it.`,
+ inputSchema: {
+ type: "object",
+ properties: {
+ tool: { type: "string", enum: jobs, description: "The studio tool to price." },
+ arguments: { type: "object", description: "The arguments you'd pass to that tool." },
+ },
+ required: ["tool", "arguments"],
+ additionalProperties: false,
+ },
+ annotations: { readOnlyHint: true, openWorldHint: false },
+ });
return tools;
}
@@ -68,6 +99,7 @@ function toContent(content: unknown): Content[] {
}
const CallParams = z.object({ name: z.string(), arguments: z.record(z.string(), z.unknown()).optional() });
+const JobParams = z.object({ tool: z.string(), arguments: z.record(z.string(), z.unknown()) });
async function call(params: unknown) {
const p = CallParams.safeParse(params);
@@ -77,11 +109,50 @@ async function call(params: unknown) {
const plan = planFor("generate", getTool("generate")!.schema.parse(args), ctx());
return { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError: plan.jobs.every((j) => j.error) };
}
+ if (name === "estimate_job") {
+ const j = JobParams.safeParse(args);
+ if (!j.success || !jobTools().includes(j.data.tool)) return { content: [{ type: "text", text: `Pass tool (one of ${jobTools().join(", ")}) and its arguments.` }], isError: true };
+ const plan = planFor(j.data.tool, j.data.arguments, ctx());
+ const isError = !!plan.error || plan.jobs.every((x) => x.error);
+ return { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError };
+ }
if (!getTool(name)) return undefined;
const out = await executeTool(name, args, ctx());
return { content: toContent(out.content), isError: !!out.isError };
}
+// ---------------------------------------------------------------------------
+// Prompts: Assist's skills
+
+function promptList() {
+ return enabledSkills().map((s) => ({
+ name: s.name,
+ title: s.title,
+ description: s.whenToUse ? `${s.description} Use when: ${s.whenToUse}` : s.description,
+ arguments: [{ name: "request", description: "What to make (optional): the job the skill should guide.", required: false }],
+ }));
+}
+
+function promptGet(params: unknown) {
+ const p = z.object({ name: z.string(), arguments: z.record(z.string(), z.string()).optional() }).safeParse(params);
+ if (!p.success) return null;
+ const s = getSkill(p.data.name);
+ if (!s || !s.enabled) return undefined;
+ const request = p.data.arguments?.request?.trim();
+ return {
+ description: s.description,
+ messages: [
+ {
+ role: "user",
+ content: {
+ type: "text",
+ text: `Follow the “${s.title}” skill from Fuobe for this job, using Fuobe's tools (search_models, generate and the studio tools).\n\n${s.body}${request ? `\n\n---\n\nThe job: ${request}` : ""}`,
+ },
+ },
+ ],
+ };
+}
+
/** Handle one JSON-RPC message; null for notifications (no response). */
export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {
const m = msg as JsonRpcRequest;
@@ -93,7 +164,7 @@ export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {
const asked = String(m.params?.protocolVersion ?? "");
return ok(m.id, {
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
- capabilities: { tools: { listChanged: false } },
+ capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
serverInfo: SERVER_INFO,
instructions: INSTRUCTIONS,
});
@@ -116,7 +187,13 @@ export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {
case "resources/list":
return ok(m.id, { resources: [] });
case "prompts/list":
- return ok(m.id, { prompts: [] });
+ return ok(m.id, { prompts: promptList() });
+ case "prompts/get": {
+ const r = promptGet(m.params);
+ if (r === null) return fail(m.id, -32602, "prompts/get needs a name");
+ if (r === undefined) return fail(m.id, -32602, `Unknown prompt ${String(m.params?.name)}`);
+ return ok(m.id, r);
+ }
default:
return fail(m.id, -32601, `Method not found: ${m.method}`);
}