The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Assist: Save as skill turns a chat that ran into a skill, and run_skill runs saved skills on one priced card
Claudefaeb15c41045
diff --git a/src/app/api/assist/skills/draft/name/route.ts b/src/app/api/assist/skills/draft/name/route.tsindex 3881b2ab..5eab4601 100644--- a/src/app/api/assist/skills/draft/name/route.ts+++ b/src/app/api/assist/skills/draft/name/route.ts@@ -1,19 +1,17 @@-import { z } from "zod";-import { badBody, recipeFailure } from "@/server/recipe-routes";-import { draftFromGenerations, nameDraft } from "@/server/recipe-builder";--const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });+import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";+import { draftFromGenerations, draftFromThread, nameDraft } from "@/server/recipe-builder";/*** The optional naming pass for a draft (Claude or Ollama, whichever this install allows): names for its inputs, slots in- * its prompts, a title, a description and a SKILL.md body. `naming` is null when there's no LLM or its answer was malformed.+ * its prompts, a title, a description and a SKILL.md body. A chat's draft also gives it what the person asked for.+ * `naming` is null when there's no LLM or its answer was malformed.*/export async function POST(request: Request) {- const parsed = Body.safeParse(await request.json().catch(() => ({})));+ const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {- const { draft } = draftFromGenerations(parsed.data.generations);- return Response.json({ naming: draft ? await nameDraft(draft) : null });+ const { draft, words } = "thread" in parsed.data ? draftFromThread(parsed.data.thread) : { ...draftFromGenerations(parsed.data.generations), words: [] };+ return Response.json({ naming: draft ? await nameDraft(draft, words) : null });} catch (e) {return recipeFailure(e);}diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.tsindex 85db57d6..d4025910 100644--- a/src/app/api/assist/skills/draft/route.ts+++ b/src/app/api/assist/skills/draft/route.ts@@ -1,17 +1,19 @@-import { z } from "zod";-import { badBody, recipeFailure } from "@/server/recipe-routes";-import { draftFromGenerations } from "@/server/recipe-builder";--const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });+import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";+import { draftFromGenerations, draftFromThread } from "@/server/recipe-builder";/**- * A skill drafted from results in the Library (W2): the steps behind them rebuilt from their requests, every input- * Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks couldn't be used and why.+ * A skill drafted from results in the Library (W2) or from an Assist chat (W3): the steps behind them rebuilt from+ * their requests, every input Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks+ * (or which of the chat's steps) couldn't be used and why.*/export async function POST(request: Request) {- const parsed = Body.safeParse(await request.json().catch(() => ({})));+ const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {+ if ("thread" in parsed.data) {+ const { draft, refusals } = draftFromThread(parsed.data.thread);+ return Response.json({ draft, refusals });+ }return Response.json(draftFromGenerations(parsed.data.generations));} catch (e) {return recipeFailure(e);diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxindex b6cc897b..6a962a20 100644--- a/src/components/assist-view.tsx+++ b/src/components/assist-view.tsx@@ -1,6 +1,6 @@"use client";-import { Bot, CalendarClock, Cpu, Loader2, MessageSquarePlus } from "lucide-react";+import { BookmarkPlus, Bot, CalendarClock, Cpu, Loader2, MessageSquarePlus } from "lucide-react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useMemo, useRef, useState } from "react";@@ -21,6 +21,7 @@ import { ProjectDot, RailButton } from "@/components/assist/shell";import { SkillIcon } from "@/components/assist/skill-icon";import { Transcript } from "@/components/assist/transcript";import { AssistVisitorNote } from "@/components/assist/visitor-note";+import { useSkillBuilder } from "@/components/skills/skill-builder-provider";import { useAssistActions, useAssistThread, useEngine } from "@/lib/api";import { ASSIST_SUGGESTIONS, assistDraft, modeLabel, threadModeChoice, type AssistAvailability, type AssistModeChoice, type AssistProject, type AssistThread, type SkillSummary } from "@/lib/assist";import type { Generation } from "@/lib/catalog/types";@@ -106,6 +107,7 @@ export function AssistView() {const projects = useProjects();const end = useRef<HTMLDivElement>(null);const [scheduling, setScheduling] = useState(false);+ const builder = useSkillBuilder();const go = (next: string | null) => router.replace(next ? `/assist?c=${next}` : "/assist", { scroll: false });const thread = view.data?.thread;@@ -174,6 +176,16 @@ export function AssistView() {<TooltipContent>Run this chat's request again on a schedule</TooltipContent></Tooltip>)}+ {thread && builder && thread.items.some((i) => i.role === "generations" && i.ids.length > 0) && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="sm" onClick={() => builder.openChat(thread.id)} aria-label="Save as skill">+ <BookmarkPlus /> <span className="hidden lg:inline">Save as skill</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>Turn what ran in this chat into a skill you can run again with new inputs</TooltipContent>+ </Tooltip>+ )}{id && (<Button variant="ghost" size="sm" onClick={() => go(null)} aria-label="New chat"><MessageSquarePlus /> <span className="hidden sm:inline">New chat</span>diff --git a/src/components/assist/chat-menu.tsx b/src/components/assist/chat-menu.tsxindex 8db55828..27509e70 100644--- a/src/components/assist/chat-menu.tsx+++ b/src/components/assist/chat-menu.tsx@@ -1,6 +1,6 @@"use client";-import { Check, FolderInput, MoreHorizontal, Pencil, Trash2 } from "lucide-react";+import { BookmarkPlus, Check, FolderInput, MoreHorizontal, Pencil, Trash2 } from "lucide-react";import { useId, useState } from "react";import { toast } from "sonner";import {@@ -30,12 +30,13 @@ import { Label } from "@/components/ui/label";import type { AssistThreadSummary } from "@/lib/assist";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { useSkillBuilder } from "@/components/skills/skill-builder-provider";import { useChatActions, useProjects } from "./hooks";import { ProjectDot } from "./project-dot";/*** A chat's menu (the rail row and the chat header): rename it, move it into a project or out of- * one, delete it. While a reply is running the server refuses a move, and says so in a toast.+ * one, save what ran in it as a skill, delete it. While a reply is running the server refuses a move, and says so in a toast.*/export function ChatMenu({chat,@@ -52,6 +53,7 @@ export function ChatMenu({const actions = useChatActions();const [renaming, setRenaming] = useState(false);const [deleting, setDeleting] = useState(false);+ const builder = useSkillBuilder();const move = async (projectId: string | null) => {if ((chat.projectId ?? null) === projectId) return;try {@@ -103,6 +105,11 @@ export function ChatMenu({))}</DropdownMenuSubContent></DropdownMenuSub>+ {builder && (+ <DropdownMenuItem onSelect={() => builder.openChat(chat.id)}>+ <BookmarkPlus /> Save as skill…+ </DropdownMenuItem>+ )}<DropdownMenuSeparator /><DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}><Trash2 /> Delete…diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex 3450eccb..dfac1cac 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -243,17 +243,22 @@ export interface DraftCheckResult {why?: string;}-/** The draft of a skill from picked results: its steps rebuilt, every input Fixed, and the picks it couldn't use. */-export function useSkillDraft(ids: string[]) {+/** What a skill is drafted from: results picked in the Library (W2), or an Assist chat whose plans ran (W3). */+export type DraftSource = { generations: string[] } | { thread: string };++const sourceKey = (s: DraftSource) => ("thread" in s ? `chat:${s.thread}` : s.generations.join(","));++/** The draft of a skill from picked results or a chat: its steps rebuilt, every input Fixed, and what it couldn't use. */+export function useSkillDraft(source: DraftSource) {return useQuery({- queryKey: ["skill-draft", ids.join(",")],- enabled: ids.length > 0,+ queryKey: ["skill-draft", sourceKey(source)],+ enabled: "thread" in source || source.generations.length > 0,retry: false,// Read once while the review is open, and dropped when it closes: opened again, it is drafted again (a name saved// since is taken, a result trashed since is gone).staleTime: Infinity,gcTime: 0,- queryFn: () => recipeCall<{ draft: SkillDraft | null; refusals: DraftRefusal[] }>("/api/assist/skills/draft", { generations: ids }),+ queryFn: () => recipeCall<{ draft: SkillDraft | null; refusals: DraftRefusal[] }>("/api/assist/skills/draft", source),});}@@ -263,7 +268,7 @@ export function useDraftActions() {/** Price it on each engine (`plan`), or add the free dry run (`demo`). */check: (recipe: unknown, level: "plan" | "demo", title?: string) => recipeCall<DraftCheckResult>("/api/assist/skills/draft/check", { recipe, level, title }),/** The optional naming pass (null: no LLM, or its answer didn't fit). */- name: async (ids: string[]) => (await recipeCall<{ naming: Naming | null }>("/api/assist/skills/draft/name", { generations: ids })).naming,+ name: async (source: DraftSource) => (await recipeCall<{ naming: Naming | null }>("/api/assist/skills/draft/name", source)).naming,save: async (body: { name: string; title: string; description: string; whenToUse?: string; body: string; recipe: unknown }) => {const view = await recipeCall<RecipeView>("/api/assist/skills/draft/save", body);qc.setQueryData(["assist-recipe", view.name], view);diff --git a/src/components/skills/skill-builder-provider.tsx b/src/components/skills/skill-builder-provider.tsxindex 7cecb011..36937499 100644--- a/src/components/skills/skill-builder-provider.tsx+++ b/src/components/skills/skill-builder-provider.tsx@@ -2,6 +2,7 @@import dynamic from "next/dynamic";import { createContext, useCallback, useContext, useMemo, useState } from "react";+import type { DraftSource } from "@/components/assist/hooks";/*** "Make a skill" from anywhere under the studio layout (the result ⋯ menu in the Library, the feeds and the viewer; the@@ -10,6 +11,8 @@ import { createContext, useCallback, useContext, useMemo, useState } from "reactinterface SkillBuilderApi {/** Draft a skill from these results (Library ids). */open: (ids: string[]) => void;+ /** Draft a skill from an Assist chat: the plans that ran in it (W3, "Save as skill"). */+ openChat: (thread: string) => void;}const Ctx = createContext<SkillBuilderApi | null>(null);@@ -20,14 +23,15 @@ export const useSkillBuilder = () => useContext(Ctx);const SkillBuilder = dynamic(() => import("./skill-builder").then((m) => m.SkillBuilder), { ssr: false });export function SkillBuilderProvider({ children }: { children: React.ReactNode }) {- const [ids, setIds] = useState<string[] | null>(null);+ const [source, setSource] = useState<DraftSource | null>(null);// After a menu has closed and handed focus back, so the dialog keeps it.- const open = useCallback((list: string[]) => void setTimeout(() => list.length && setIds([...new Set(list)]), 0), []);- const api = useMemo(() => ({ open }), [open]);+ const open = useCallback((list: string[]) => void setTimeout(() => list.length && setSource({ generations: [...new Set(list)] }), 0), []);+ const openChat = useCallback((thread: string) => void setTimeout(() => setSource({ thread }), 0), []);+ const api = useMemo(() => ({ open, openChat }), [open, openChat]);return (<Ctx.Provider value={api}>{children}- {ids && <SkillBuilder key={ids.join(",")} ids={ids} onClose={() => setIds(null)} />}+ {source && <SkillBuilder key={"thread" in source ? `chat:${source.thread}` : source.generations.join(",")} source={source} onClose={() => setSource(null)} />}</Ctx.Provider>);}diff --git a/src/components/skills/skill-builder.tsx b/src/components/skills/skill-builder.tsxindex f0f8114f..46b0ad08 100644--- a/src/components/skills/skill-builder.tsx+++ b/src/components/skills/skill-builder.tsx@@ -4,7 +4,7 @@ import { AlertTriangle, ArrowRight, AudioLines, Box, Check, ChevronDown, Cloud,import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { RunSkillDialog } from "@/components/assist/run-skill-dialog";-import { useDraftActions, useSkillDraft, type DraftCheckResult } from "@/components/assist/hooks";+import { useDraftActions, useSkillDraft, type DraftCheckResult, type DraftSource } from "@/components/assist/hooks";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";@@ -26,13 +26,13 @@ import { cn } from "@/lib/utils";* the demo provider); then Save, which opens the Run form with the inputs it was made from ("Try it with new inputs").* A tall dialog on a desktop, the whole screen on a phone.*/-export function SkillBuilder({ ids, onClose }: { ids: string[]; onClose: () => void }) {+export function SkillBuilder({ source, onClose }: { source: DraftSource; onClose: () => void }) {const [saved, setSaved] = useState<string | null>(null);return (<><Dialog open={!saved} onOpenChange={(o) => !o && !saved && onClose()}><DialogContent className="flex h-[min(94svh,960px)] flex-col gap-0 overflow-hidden p-0 max-sm:h-svh max-sm:max-h-svh max-sm:max-w-full max-sm:rounded-none max-sm:ring-0 sm:max-w-[1120px]">- <Loader ids={ids} onClose={onClose} onSaved={setSaved} />+ <Loader source={source} onClose={onClose} onSaved={setSaved} /></DialogContent></Dialog>{saved && <RunSkillDialog name={saved} examples intro="Try it with new inputs: the form starts with the ones it was made from." onClose={onClose} />}@@ -40,17 +40,21 @@ export function SkillBuilder({ ids, onClose }: { ids: string[]; onClose: () => v);}-function Loader({ ids, onClose, onSaved }: { ids: string[]; onClose: () => void; onSaved: (name: string) => void }) {- const q = useSkillDraft(ids);+function Loader({ source, onClose, onSaved }: { source: DraftSource; onClose: () => void; onSaved: (name: string) => void }) {+ const q = useSkillDraft(source);+ const chat = "thread" in source;+ const count = chat ? 0 : source.generations.length;const header = (<DialogHeader className="border-b px-5 pt-5 pb-4 text-left">- <DialogTitle className="font-heading text-[24px] leading-tight font-normal">Make a skill</DialogTitle>+ <DialogTitle className="font-heading text-[24px] leading-tight font-normal">{chat ? "Save as skill" : "Make a skill"}</DialogTitle><DialogDescription>- From {ids.length === 1 ? "this result" : `${ids.length} results`}: Fuobe rebuilds the steps from what you made, so nothing has to be recorded.+ {chat+ ? "From this chat: Fuobe rebuilds the steps from the plans that ran, so next time it runs them again with new inputs."+ : `From ${count === 1 ? "this result" : `${count} results`}: Fuobe rebuilds the steps from what you made, so nothing has to be recorded.`}</DialogDescription></DialogHeader>);- if (q.data?.draft) return <Review draft={q.data.draft} refusals={q.data.refusals} ids={ids} onClose={onClose} onSaved={onSaved} header={header} />;+ if (q.data?.draft) return <Review draft={q.data.draft} refusals={q.data.refusals} source={source} onClose={onClose} onSaved={onSaved} header={header} />;return (<>{header}@@ -61,7 +65,7 @@ function Loader({ ids, onClose, onSaved }: { ids: string[]; onClose: () => void;</p>) : q.data ? (<>- <p className="text-[14px]">{q.data.refusals.length === 1 ? "This result can't become a skill yet:" : "None of these results can become a skill yet:"}</p>+ <p className="text-[14px]">{chat ? "This chat can't become a skill yet:" : q.data.refusals.length === 1 ? "This result can't become a skill yet:" : "None of these results can become a skill yet:"}</p><Refusals list={q.data.refusals} open /></>) : (@@ -93,7 +97,7 @@ interface CheckState {const ENGINE_WORD = { cloud: "Cloud", open: "your GPU" } as const;-function Review({ draft, refusals, ids, onClose, onSaved, header }: { draft: SkillDraft; refusals: DraftRefusal[]; ids: string[]; onClose: () => void; onSaved: (name: string) => void; header: React.ReactNode }) {+function Review({ draft, refusals, source, onClose, onSaved, header }: { draft: SkillDraft; refusals: DraftRefusal[]; source: DraftSource; onClose: () => void; onSaved: (name: string) => void; header: React.ReactNode }) {const actions = useDraftActions();const [varies, setVaries] = useState<Record<string, boolean>>({});const [labels, setLabels] = useState<Record<string, string>>({});@@ -171,7 +175,7 @@ function Review({ draft, refusals, ids, onClose, onSaved, header }: { draft: Skiconst suggest = async () => {setNaming("asking");try {- const n = await actions.name(ids);+ const n = await actions.name(source);setNaming(n ?? "none");} catch {setNaming("none");diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 1547a381..40cb3cad 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -460,6 +460,13 @@ export function skillSlug(title: string): string {);}+/**+ * The generation ids a tool result started, in order: every id of each `"started": [...]` list (on+ * the open engine 4 takes are 4 generations of one job) and each `"id": "..."`.+ */+export const startedIds = (body: string): string[] =>+ [...body.matchAll(/"started":\s*\[([^\]]*)\]|"(?:started|id)":\s*"([\w-]+)"/g)].flatMap((m) => (m[2] ? [m[2]] : [...m[1].matchAll(/"([\w-]+)"/g)].map((x) => x[1])));+/*** Leading `/name` tokens of a message: "/product-photoshoot /thumbnail-generation a coffee ad"* → skills [product-photoshoot, thumbnail-generation], text "a coffee ad". Unknown names stay in the text.diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.tsindex 6533bc46..d4ba1e7c 100644--- a/src/lib/recipe-builder.ts+++ b/src/lib/recipe-builder.ts@@ -155,6 +155,12 @@ export function studioOf(feature: string): StudioInfo | undefined {return { name: HELPER_STUDIOS[base] ?? "another studio" };}+/** The studio an Assist tool makes its work in ("dub_video" → "Translate & dub"; a storyboard is the Storyboard's). */+export function studioForTool(tool: string): string | undefined {+ if (tool === "create_storyboard") return "Storyboard";+ return STUDIOS.find(([, s]) => s.tool === tool)?.[1].name;+}+export const notSupported = (studio: string) => `Made in ${studio}: making a skill from it isn't supported yet`;/**diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex cb60c725..8a6473b6 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -15,6 +15,7 @@ import {normalizeAgent,renderContext,slashSkills,+ startedIds,threadTitle,type AssistAgent,type AssistAvailability,@@ -31,6 +32,7 @@ import {import { freePick, manualGroups, smartPick, toOption, choices, type Choice, type ConnectedProvider, type World } from "@/lib/assist-models";import { getLlmModel, getLlmProvider, LLM_REGISTRY_CHECKED } from "@/lib/catalog/llm-providers";import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";+import { isMediaType, RECIPE_LIMITS, type Recipe } from "@/lib/recipe";import { db } from "../db";import { getGeneration } from "../generations";import { activeLocal, aiHelper, chatLocal, emptyReply, localLabel, localProblem, localSoon, pinnedKind, toChatMessages, type Ready } from "../llm";@@ -40,7 +42,7 @@ import { toHostedMessages } from "../llm/hosted-messages";import type { Replay } from "../llm/types";import { offeredDefault } from "../model-access";import { engineMode, getSetting } from "../settings";-import { getSkill } from "../skills";+import { getSkill, skillRecipe } from "../skills";import { readRef } from "../storage";import { spendOf, withinCap } from "@/lib/assist-schedule";import { activeConnectors, connectorName, MCP_BETA, mcpParams, withoutMissingServers, type Connector } from "./connectors";@@ -707,6 +709,7 @@ How you work: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".+- A skill marked "runs by itself" is a saved recipe: when one fits the request, call run_skill with its name and values for its inputs (files from the user's attachments, words from their message) instead of planning the steps again. Ask only for a required input you can't fill.- 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.`;@@ -870,6 +873,17 @@ export const offline: ModelCall = async ({ messages, ctx, skills }) => {if (stills.length) return reply([text(`Pick a number from 1 to ${stills.length}.`)], "end_turn");// No stills in this chat: read it as a new request.}+ // A loaded skill that runs by itself (the last one loaded): its inputs filled from the message, one run_skill card.+ for (const s of [...(skills ?? [])].reverse()) {+ const recipe = (s as { recipe?: boolean }).recipe ? skillRecipe(s.name) : null;+ if (!recipe) continue;+ const r = offlineSkillRun(said, s.name, s.title, recipe);+ if (!("tool" in r)) return reply([text(r.say)], "end_turn");+ return reply(+ [text(r.say), { type: "tool_use", id: `toolu_offline_${nanoid(10)}`, name: r.tool, input: r.input, caller: { type: "direct" } } as unknown as Anthropic.Beta.BetaToolUseBlock],+ "tool_use",+ );+ }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");@@ -880,6 +894,57 @@ export const offline: ModelCall = async ({ messages, ctx, skills }) => {);};+const TYPE_NAMES: Record<string, string> = { image: "an image", video: "a video", audio: "an audio file", text: "words", number: "a number", choice: "a choice", element: "an element" };++/**+ * A saved skill that runs by itself, from a message (no LLM): its media inputs from the attached files by kind and+ * order, its first text input from the words, the rest from their defaults or the values it was made with. A required+ * input still empty (a file that wasn't attached) is asked for by name instead.+ */+export function offlineSkillRun(message: string, name: string, title: string, recipe: Recipe): { tool: "run_skill"; input: Record<string, unknown>; say: string } | { say: string } {+ const [body, attached = ""] = message.split(/\n\nAttached files[^\n]*\n/);+ const files = [...attached.matchAll(/^- (image|video|audio|text|model3d) \d+: (\S+)$/gm)].map((m) => ({ kind: m[1], url: m[2] }));+ // A lone "/name" (with files) gets words written for it: those aren't the person's.+ const words = /^Use the .+ skills?(?: with the attached files)?\.$/.test(body.trim()) ? "" : body.trim();+ const values: Record<string, string | number> = {};+ const taken = new Set<number>();+ let wordsUsed = false;+ const filled: string[] = [];+ for (const p of recipe.params) {+ if (isMediaType(p.type)) {+ const i = files.findIndex((f, k) => !taken.has(k) && f.kind === p.type);+ if (i >= 0) {+ taken.add(i);+ values[p.id] = files[i].url;+ filled.push(`your ${p.type}`);+ continue;+ }+ // A file the person didn't attach is theirs to give: only a default stands in, never the one it was made with.+ if (p.default !== undefined && p.default !== "") values[p.id] = p.default;+ continue;+ }+ if (p.type === "text" && !wordsUsed && words) {+ wordsUsed = true;+ values[p.id] = words.slice(0, p.max ?? RECIPE_LIMITS.text);+ filled.push(`“${words.length > 60 ? `${words.slice(0, 59).trimEnd()}…` : words}”`);+ continue;+ }+ const v = p.default ?? p.example;+ if (v !== undefined && v !== null && v !== "") values[p.id] = v;+ }+ const missing = recipe.params.filter((p) => p.required && values[p.id] === undefined);+ if (missing.length) {+ const need = missing.map((p) => `${p.label} (${TYPE_NAMES[p.type] ?? p.type})`);+ const media = missing.some((p) => isMediaType(p.type));+ return { say: `${title} needs ${need.length > 1 ? `${need.slice(0, -1).join(", ")} and ${need.at(-1)}` : need[0]}. ${media ? "Attach it and send /" + name + " again." : `Send /${name} with it.`}` };+ }+ return {+ tool: "run_skill",+ input: { name, values },+ say: `I'll run your ${title} skill${filled.length ? ` with ${filled.join(" and ")}` : ""}: the same steps it was saved with, priced below.`,+ };+}+/** Under every offline plan: the rule-based planner is a fallback, not the assistant. */export const OFFLINE_NOTE = "Offline planner — connect a model in Settings → AI helper (Anthropic, OpenAI, Google, OpenRouter… or a local model) for better plans.";@@ -892,13 +957,6 @@ const FOLLOW_UP: Record<MediaKind, string> = {model3d: "Want another take, or a model from a different photo?",};-/**- * The generation ids a tool result started, in order: every id of each `"started": [...]` list (on- * the open engine 4 takes are 4 generations of one job) and each `"id": "..."`.- */-const startedIds = (body: string) =>- [...body.matchAll(/"started":\s*\[([^\]]*)\]|"(?:started|id)":\s*"([\w-]+)"/g)].flatMap((m) => (m[2] ? [m[2]] : [...m[1].matchAll(/"([\w-]+)"/g)].map((x) => x[1])));-/** The kind of the last generation a tool result started (the end of a chain), image when unknown. */function startedKind(body: string): MediaKind {for (const id of startedIds(body).reverse()) {@@ -1370,7 +1428,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {}if (ask) {// Malformed arguments (common from small local models) go straight back as an error the model can fix, not onto an approval card.- const invalid = validateInput(u.name, u.input);+ const invalid = validateInput(u.name, u.input, ctx);if (invalid) {results.push({ type: "tool_result", tool_use_id: u.id, is_error: true, content: invalid });continue;diff --git a/src/server/assist/context-tools.ts b/src/server/assist/context-tools.tsindex cd6247a6..1dd26165 100644--- a/src/server/assist/context-tools.ts+++ b/src/server/assist/context-tools.ts@@ -26,7 +26,20 @@ const listSkills = defineTool({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 }))),+ content: JSON.stringify(+ list.map((s) => {+ // A recipe skill runs by itself with run_skill: its inputs by id and type.+ const recipe = s.recipe ? skillRecipe(s.name) : null;+ return {+ name: s.name,+ title: s.title,+ description: s.description,+ whenToUse: s.whenToUse || undefined,+ loaded: ctx.thread?.skills.includes(s.name) || undefined,+ ...(recipe && { runsByItself: { tool: "run_skill", inputs: recipe.params.map((p) => ({ id: p.id, type: p.type, label: p.label, ...(p.required && p.default === undefined && { required: true }) })) } }),+ };+ }),+ ),items: [{ id: "", role: "tool", text: `Looked through ${list.length} skill${list.length === 1 ? "" : "s"}` }],};},diff --git a/src/server/assist/context.ts b/src/server/assist/context.tsindex dca4648f..51ddfbe6 100644--- a/src/server/assist/context.ts+++ b/src/server/assist/context.ts@@ -92,6 +92,14 @@ export function skillsFor(projectId: string | null): Skill[] {return own.length ? own : enabledSkills();}+/** " (runs by itself: run_skill with product, name)": how a recipe skill is marked in the skills list. */+export function runsByItself(name: string): string {+ const recipe = skillRecipe(name);+ if (!recipe) return "";+ const ids = recipe.params.map((p) => p.id);+ return ` (runs by itself: run_skill${ids.length ? ` with ${ids.join(", ")}` : ""})`;+}+export function canUseSkill(name: string, projectId: string | null): boolean {return skillsFor(projectId).some((s) => s.name === name);}@@ -145,7 +153,9 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {}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) });+ // A skill with a recipe runs by itself: said first, so a long description can't cut it off.+ const runs = s.recipe ? runsByItself(s.name) : "";+ facts.push({ section: "skills", key: s.name, text: clip(`- /${s.name} — ${s.title}${runs}: ${s.description}${s.whenToUse ? ` Use when: ${s.whenToUse}` : ""}`, 520) });}for (const name of c.skills) {const s = getSkill(name);diff --git a/src/server/assist/define.ts b/src/server/assist/define.tsindex f1513631..0765ffd3 100644--- a/src/server/assist/define.ts+++ b/src/server/assist/define.ts@@ -42,6 +42,8 @@ export interface ToolDef<S extends z.ZodType> {gated?: boolean;strict?: boolean;run: (input: z.infer<S>, ctx: ToolContext) => Promise<ToolOutcome>;+ /** For gated tools: what the arguments need beyond their shape (a skill's inputs), checked before a card is shown. */+ check?: (input: z.infer<S>, ctx: ToolContext) => string | null;/** 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). */diff --git a/src/server/assist/skill-tools.ts b/src/server/assist/skill-tools.tsnew file mode 100644index 00000000..6fef8201--- /dev/null+++ b/src/server/assist/skill-tools.ts@@ -0,0 +1,147 @@+import "server-only";+import { z } from "zod";+import type { PlannedJob } from "@/lib/assist";+import type { Engine } from "@/lib/catalog/types";+import { RECIPE_LIMITS, type ParamType, type Recipe } from "@/lib/recipe";+import { estimateRecipe, getRecipe, recipeEngines, runRecipe, verifyRecipe } from "../recipes";+import { getSkill, skillRecipe } from "../skills";+import { canUseSkill, skillsFor } from "./context";+import { defineTool, type ToolContext } from "./define";++/**+ * run_skill (package W3): a saved skill whose files hold a recipe runs by itself with values for its inputs — the+ * same steps, priced first, no planning. Gated like generate, so Assist shows one priced card (an atomic pipeline,+ * or a studio's tool call that opens in its studio), MCP lists it and estimate_job prices it.+ */++const Value = z.union([z.string(), z.number()]);+const Values = z.record(z.string(), Value);++const RunSkillInput = z.object({+ name: z.string().describe("The skill's name, without the slash (e.g. lamp-turntable). Only skills marked “runs by itself” have a recipe."),+ values: Values.optional().describe("A value for each of the skill's inputs, by input id: file URLs (/api/files/… from the chat) for image, video and audio inputs, words for text, a number, one of a choice's options, an @handle for an element. Inputs left out take their default."),+ rows: z+ .array(Values)+ .max(RECIPE_LIMITS.rows)+ .optional()+ .describe(`Several runs at once (up to ${RECIPE_LIMITS.rows}), each with its own values, instead of values.`),+ engine: z.enum(["cloud", "open"]).optional().describe("Where to run it: cloud (paid APIs) or open (the user's GPU). Leave it out to use the chat's engine when the skill runs there."),+});+type RunSkill = z.infer<typeof RunSkillInput>;++const ENGINE_WORDS: Record<Engine, string> = { cloud: "the cloud", open: "your GPU" };+const TYPE_WORDS: Record<ParamType, string> = { image: "image", video: "video", audio: "audio", text: "text", number: "number", choice: "choice", element: "@element" };++/** "product (image) and name (text)": what a skill's inputs are, for an error the model can fix. */+export function inputList(recipe: Pick<Recipe, "params">, only?: (id: string) => boolean): string {+ const list = recipe.params.filter((p) => !only || only(p.id)).map((p) => `${p.id} (${p.type === "choice" ? (p.options ?? []).join(" | ") : TYPE_WORDS[p.type]})`);+ return list.length > 1 ? `${list.slice(0, -1).join(", ")} and ${list.at(-1)}` : (list[0] ?? "nothing");+}++/** The skill to run, when this chat (or MCP, which has every enabled skill) may use it; else why not, with the ones that run. */+function find(name: string, ctx: ToolContext): { recipe: Recipe; title: string; name: string } | { error: string } {+ const n = name.replace(/^\//, "").trim();+ const projectId = ctx.thread?.projectId ?? null;+ const runnable = () =>+ skillsFor(projectId)+ .filter((s) => s.recipe)+ .map((s) => s.name);+ const s = getSkill(n);+ if (!s || !canUseSkill(n, projectId)) return { error: `No skill called “${n}” is available here. Skills that run by themselves: ${runnable().join(", ") || "none yet"}.` };+ const recipe = s.recipe ? skillRecipe(n) : null;+ if (!recipe) return { error: `/${n} has no recipe, so it doesn't run by itself: load it with load_skill and follow it instead. Skills that run by themselves: ${runnable().join(", ") || "none yet"}.` };+ return { recipe, title: s.title, name: n };+}++/** The engine to ask for: the call's, else the chat's when the skill runs there (else the skill picks). */+function engineOf(input: RunSkill, recipe: Recipe, ctx: ToolContext): Engine | undefined {+ if (input.engine) return input.engine;+ return recipeEngines(recipe).includes(ctx.engine) ? ctx.engine : undefined;+}++/** What's wrong with the values, naming the inputs: "needs product (image) and name (text)". */+function valueErrors(input: RunSkill, recipe: Recipe, name: string): string | null {+ const rows = input.rows ?? [input.values ?? {}];+ const known = new Set(recipe.params.map((p) => p.id));+ const unknown = [...new Set(rows.flatMap((r) => Object.keys(r).filter((k) => !known.has(k))))];+ if (unknown.length) return `/${name} has no input ${unknown.map((k) => `“${k}”`).join(", ")}: it takes ${inputList(recipe)}`;+ const missing = recipe.params.filter((p) => p.required && p.default === undefined && rows.some((r) => r[p.id] === undefined || (typeof r[p.id] === "string" && !String(r[p.id]).trim())));+ if (missing.length) return `/${name} needs ${inputList(recipe, (id) => missing.some((p) => p.id === id))}`;+ return null;+}++/** The skill's price as the card shows it: every job of every run, atomic when it's a pipeline. */+function plan(input: RunSkill, ctx: ToolContext): PlannedJob[] {+ const found = find(input.name, ctx);+ const failed = (error: string): PlannedJob[] => [+ { tool: "run_skill", modelId: "skill", modelName: "title" in found ? found.title : input.name, kind: "image", op: "t2i", note: "Run a skill", prompt: "", count: 1, costUsd: null, demo: false, error },+ ];+ if ("error" in found) return failed(found.error);+ const bad = valueErrors(input, found.recipe, found.name);+ if (bad) return failed(bad);+ try {+ const est = estimateRecipe(found.name, { ...(input.rows ? { rows: input.rows } : { values: input.values ?? {} }) }, engineOf(input, found.recipe, ctx));+ const pipeline = found.recipe.steps.every((s) => s.kind === "generate");+ const jobs = est.runs.flatMap((r) => r.jobs.map((j) => ({ ...j, tool: "run_skill", ...(pipeline && { atomic: true }) })));+ const errors = [...est.errors, ...est.runs.flatMap((r) => r.errors.map((e) => (est.runs.length > 1 ? `Row ${r.line}: ${e}` : e)))];+ if (!jobs.length) return failed(errors[0] ?? "Nothing to run");+ // What stops it is said once, on the first job (a job's own error stays on it).+ return errors.length && !jobs.some((j) => j.error) ? [{ ...jobs[0], error: errors.join("; ") }, ...jobs.slice(1)] : jobs;+ } catch (e) {+ return failed((e as Error).message);+ }+}++const runSkill = defineTool({+ name: "run_skill",+ description:+ "Run a saved skill that runs by itself (the skills list marks them “runs by itself” and names their inputs): the same steps it was saved with, with new values for its inputs — no planning needed. When a skill like that fits the request, call this with values from the user's message and attachments instead of planning the steps again. Gated by the same approval card as generate.",+ schema: RunSkillInput,+ gated: true,+ // Values that don't fit go back to the model as an error naming the inputs, not onto an approval card.+ check: (input, ctx) => {+ const found = find(input.name, ctx);+ return "error" in found ? found.error : valueErrors(input, found.recipe, found.name);+ },+ plan,+ title: (input) => getSkill(input.name.replace(/^\//, "").trim())?.title ?? input.name,+ place: (input, ctx) => {+ const found = find(input.name, ctx);+ if ("error" in found || found.recipe.steps.every((s) => s.kind === "generate")) return {};+ try {+ return estimateRecipe(found.name, { values: input.rows?.[0] ?? input.values ?? {} }, engineOf(input, found.recipe, ctx)).place ?? {};+ } catch {+ return {};+ }+ },+ async run(input, ctx) {+ const found = find(input.name, ctx);+ if ("error" in found) return { content: JSON.stringify({ error: found.error }), isError: true };+ const bad = valueErrors(input, found.recipe, found.name);+ if (bad) return { content: JSON.stringify({ error: bad }), isError: true };+ const asked = engineOf(input, found.recipe, ctx);+ const body = input.rows ? { rows: input.rows } : { values: input.values ?? {} };+ // A recipe not yet priced on this engine gets its free plan check first (a saved draft has had it already).+ const { recipe, skill } = getRecipe(found.name);+ const engine = asked ?? recipeEngines(recipe)[0];+ if (engine && !recipe.verified?.[engine]?.plan && skill.source === "user") {+ const check = await verifyRecipe(found.name, "plan", engine).catch((e: Error) => ({ ok: false, why: e.message }));+ if (!check.ok) return { content: JSON.stringify({ error: `/${found.name} doesn't run on ${ENGINE_WORDS[engine]} as it is: check it on the Skills page` }), isError: true };+ }+ const out = await runRecipe(found.name, body, asked);+ const ids = out.runs.flatMap((r) => r.ids);+ const href = out.runs.find((r) => r.href && r.href !== "/library")?.href;+ return {+ content: JSON.stringify({+ skill: found.name,+ engine: out.engine,+ runs: out.runs.map((r) => ({ started: r.ids, ...(r.batchId && { batch: r.batchId }), ...(r.href && { href: r.href }), ...(r.error && { error: r.error }) })),+ ...(out.demo && { demo: true }),+ note: href ? "The skill's studio job opens at href; its results appear there and in the Library." : "Each run's steps start by themselves as the ones they wait for finish; results appear in the Library.",+ }),+ items: ids.length ? [{ id: "", role: "generations", ids }] : undefined,+ };+ },+});++export const SKILL_TOOLS = [runSkill];diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsindex 89e2153d..14c1bc62 100644--- a/src/server/assist/tools.ts+++ b/src/server/assist/tools.ts@@ -25,6 +25,7 @@ import { CONTEXT_TOOLS } from "./context-tools";import { defineTool, type JobPlace, type ResultContent, type ToolContext, type ToolDef, type ToolOutcome } from "./define";// Fills STUDIO_ROUTES with the studio modules (Layers, Shorts, dub, Faceless, Ads, Captions).import "./studio-routes";+import { SKILL_TOOLS } from "./skill-tools";import { STUDIO_TOOLS } from "./studio-tools";export type { ToolContext, ToolOutcome };@@ -546,8 +547,9 @@ const storyboard = defineTool({export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecent, checkGenerations, generate, storyboard, defineTool(katanaTool)];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);+// Skills, memory and project sources; then whole studios (layers, restyle, dub, faceless, ads, captions); then saved+// skills that run by themselves (run_skill).+TOOLS.push(...CONTEXT_TOOLS, ...STUDIO_TOOLS, ...SKILL_TOOLS);/** The approval card's heading for one gated call. */export function cardTitle(name: string, input: unknown): string {@@ -567,10 +569,11 @@ export function apiSchema(schema: z.ZodType): Anthropic.Beta.BetaTool.InputSchemif (!node || typeof node !== "object") return node;const out: Record<string, unknown> = {};for (const [k, v] of Object.entries(node)) {- if (["$schema", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "maxItems", "minItems", "multipleOf"].includes(k)) continue;+ if (["$schema", "propertyNames", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "maxItems", "minItems", "multipleOf"].includes(k)) continue;out[k] = k === "properties" ? Object.fromEntries(Object.entries(v as object).map(([p, s]) => [p, walk(s)])) : walk(v);}- if (out.type === "object") out.additionalProperties = false;+ // A map (a skill's values by input id) says what its values are; every other object is closed.+ if (out.type === "object" && (out.additionalProperties === undefined || out.additionalProperties === true || out.properties)) out.additionalProperties = false;return out;};return walk(json) as Anthropic.Beta.BetaTool.InputSchema;@@ -587,12 +590,13 @@ export function apiTools(): Anthropic.Beta.BetaTool[] {const describeIssues = (issues: { path: PropertyKey[]; message: string }[]) => `Invalid input: ${issues.map((i) => `${i.path.map(String).join(".")} ${i.message}`).join("; ")}`;-/** The error a tool call's arguments would get, or null when they're valid. */-export function validateInput(name: string, input: unknown): string | null {+/** The error a tool call's arguments would get, or null when they're valid (with a chat's context, its own check too). */+export function validateInput(name: string, input: unknown, ctx?: ToolContext): string | null {const tool = getTool(name);if (!tool) return `Unknown tool ${name}`;const parsed = tool.schema.safeParse(input);- return parsed.success ? null : describeIssues(parsed.error.issues);+ if (!parsed.success) return describeIssues(parsed.error.issues);+ return ctx && tool.check ? tool.check(parsed.data, ctx) : null;}/**diff --git a/src/server/mcp.ts b/src/server/mcp.tsindex 7f837030..8965f88c 100644--- a/src/server/mcp.ts+++ b/src/server/mcp.ts@@ -16,7 +16,7 @@ import { enabledSkills, getSkill, skillRecipe } from "./skills";*/const PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];-const SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.2.0" };+const SERVER_INFO = { name: "fuobe", title: "Fuobe studio", version: "1.3.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. " +@@ -24,6 +24,7 @@ const INSTRUCTIONS ="Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, restore_video, and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " +"Each studio job opens in that Fuobe studio (a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor, Katana): the result's href is its page on this Fuobe server, so give the user that link; a call the studio can't take runs as plain steps and says why. " +"Skills are playbooks for kinds of jobs (product photos, UGC videos, thumbnails…): list_skills, then load_skill to read one — they're also offered as prompts. " ++ "A skill that runs by itself (list_skills marks it and names its inputs) runs with run_skill and values for those inputs, the same steps every time: price it with estimate_job first. " +"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 {diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.tsindex 468bc6f0..55c48448 100644--- a/src/server/recipe-builder.ts+++ b/src/server/recipe-builder.ts@@ -17,6 +17,7 @@ import {skillBody,slugify,STEPS_REFUSAL,+ studioForTool,studioOf,type DraftCandidate,type DraftRefusal,@@ -29,7 +30,9 @@ import { db } from "./db";import { llmText, llmTextBackend, type LlmImage } from "./enhance";import { listElements } from "./elements";import { currentRequest, getGeneration, unfilledRequest } from "./generations";-import { getSkill } from "./skills";+import { startedIds } from "@/lib/assist";+import { cardTitle, getTool, planFor } from "./assist/tools";+import { getSkill, SkillError } from "./skills";import { absolutePath, readRef } from "./storage";/**@@ -710,10 +713,38 @@ export interface DraftResult {* runs now, chain-filled inputs taken out, server fields dropped), or a studio's result as its tool step, and propose* the inputs that could vary (all Fixed) and the checks. A pick that can't be used is a refusal with the reason.*/-export function draftFromGenerations(ids: string[]): DraftResult {- const refusals: DraftRefusal[] = [];+export const draftFromGenerations = (ids: string[]): DraftResult => buildDraft(ids);++/** Where a draft comes from besides picked results: an Assist chat, its studio calls as they ran, and what it left out. */+interface Origin {+ thread?: string;+ /** Studio calls of the chat: each the tool's exact input, and the result that stands for it. */+ calls?: { lifted: Lifted; pick: Generation }[];+ refusals?: DraftRefusal[];+ notes?: string[];+ /** Every generation the kept calls started (the recipe's source). */+ generations?: string[];+}++/** A studio's work as one tool step (W2's lifts and W3's chat calls). */+function toolNode(walk: Walk, lifted: Lifted, g: Generation): Node {+ const key = walk.key(lifted.tool.replace(/_/g, "-"));+ return {+ key,+ gen: g,+ rows: [g.id],+ step: { key, kind: "tool", label: lifted.studio, tool: lifted.tool, input: lifted.input },+ label: lifted.studio,+ modelName: lifted.studio,+ notes: [`Runs ${lifted.studio} again with the same settings`],+ tool: { studio: lifted.studio, record: lifted.record, inputs: lifted.inputs, texts: lifted.texts },+ };+}++function buildDraft(ids: string[], o: Origin = {}): DraftResult {+ const refusals: DraftRefusal[] = [...(o.refusals ?? [])];const walk = new Walk();- const tools: { node: Node; pick: Generation }[] = [];+ const tools: { node: Node; pick: Generation }[] = (o.calls ?? []).map((c) => ({ node: toolNode(walk, c.lifted, c.pick), pick: c.pick }));const generated: Generation[] = [];const unique = [...new Set(ids)].slice(0, 200);for (const id of unique) {@@ -739,18 +770,7 @@ export function draftFromGenerations(ids: string[]): DraftResult {continue;}if (tools.some((t) => t.node.tool?.record === lifted.record)) continue;- const key = walk.key(lifted.tool.replace(/_/g, "-"));- const node: Node = {- key,- gen: g,- rows: [g.id],- step: { key, kind: "tool", label: lifted.studio, tool: lifted.tool, input: lifted.input },- label: lifted.studio,- modelName: lifted.studio,- notes: [`Runs ${lifted.studio} again with the same settings`],- tool: { studio: lifted.studio, record: lifted.record, inputs: lifted.inputs, texts: lifted.texts },- };- tools.push({ node, pick: g });+ tools.push({ node: toolNode(walk, lifted, g), pick: g });continue;}// A plain result: its graph, all or nothing (a refused step refuses the result that needs it).@@ -793,7 +813,8 @@ export function draftFromGenerations(ids: string[]): DraftResult {if (Object.keys(checks).length) recipe.checks = checks;const all = nodes.flatMap((n) => n.rows.map((id) => getGeneration(id, { includeDeleted: true }))).filter((g): g is Generation => !!g);const demo = all.length > 0 && all.every((g) => g.provider === "mock");- recipe.source = { from: "library", generations: unique.filter((id) => !refusals.some((r) => r.id === id)), at: today(), ...(demo && { demo: true }) };+ const used = o.generations ?? unique.filter((id) => !refusals.some((r) => r.id === id));+ recipe.source = { from: o.thread ? "assist" : "library", ...(o.thread && { thread: o.thread }), generations: used.slice(0, 200), at: today(), ...(demo && { demo: true }) };const labelOf = new Map(nodes.map((n) => [n.key, n.label]));const draftSteps: DraftStep[] = nodes.map((n) => {@@ -817,8 +838,9 @@ export function draftFromGenerations(ids: string[]): DraftResult {const flow = nodes.map((n) => n.label).join(" → ");const models = [...new Set(nodes.map((n) => n.modelName))];const kinds = [...new Set(nodes.filter((n) => leaves.has(n.key)).map((n) => n.gen.kind))];- const description = cut(`${nodes.length === 1 ? flow : `${nodes.length} steps: ${flow}`}, with ${models.join(", ")}. Made from results in the Library and run again with new inputs.`, 1000);- const whenToUse = cut(`When you want another ${kinds.join(" and ")} made the way “${title}” was (${dayOf(lead.gen.createdAt)}), with new inputs.`, 1000);+ const made = o.thread ? "Made in an Assist chat" : "Made from results in the Library";+ const description = cut(`${nodes.length === 1 ? flow : `${nodes.length} steps: ${flow}`}, with ${models.join(", ")}. ${made} and run again with new inputs.`, 1000);+ const whenToUse = cut(`When you want another ${kinds.join(" and ")} made the way “${title}” was${o.thread ? " in Assist" : ""} (${dayOf(lead.gen.createdAt)}), with new inputs.`, 1000);const draft: SkillDraft = {recipe,steps: draftSteps,@@ -828,12 +850,218 @@ export function draftFromGenerations(ids: string[]): DraftResult {description,whenToUse,demo,- notes: [...(demo ? [DEMO_NOTE] : []), ...walk.notes],+ notes: [...(demo ? [DEMO_NOTE] : []), ...(o.notes ?? []), ...walk.notes],llm: llmTextBackend(),};return { draft, refusals };}+// ---------------------------------------------------------------------------+// A skill from an Assist chat (W3)++/** Why a chat's step can't join the others: a studio step's result feeding another step, or the other way round (W7). */+export const STUDIO_WAIT = "Skills can't wait for a studio step yet: make a skill from each step on its own";++/** Tools whose started generations are drafted as plain results (a run_skill pipeline is one too). */+const GENERATE_TOOLS = new Set(["generate", "run_skill"]);+const TERMINAL = new Set(["succeeded", "failed", "canceled"]);++interface ChatCall {+ order: number;+ name: string;+ input: Record<string, unknown>;+ gens: Generation[];+ /** File links in its input, and the outputs it made. */+ inputs: Set<string>;+ outputs: Set<string>;+ /** What it makes: the kind of its last result (a generate call), or the tool itself (a studio call). */+ makes: string;+ studio: boolean;+}++type Block = { type: string; id?: string; name?: string; input?: unknown; tool_use_id?: string; is_error?: boolean; content?: unknown; text?: string };++const textOf = (c: unknown): string =>+ typeof c === "string" ? c : Array.isArray(c) ? c.map((b: Block) => (b?.type === "text" && typeof b.text === "string" ? b.text : "")).join("\n") : "";++/** Every file link (a Fuobe file or an http(s) link) in a value, with its path. */+function mediaIn(v: unknown, path: (string | number)[] = [], out: { path: (string | number)[]; url: string }[] = []) {+ if (typeof v === "string") {+ if (isMediaRef(v)) out.push({ path, url: v });+ } else if (Array.isArray(v)) v.forEach((x, i) => mediaIn(x, [...path, i], out));+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) mediaIn(x, [...path, k], out);+ return out;+}++/** Words in a value (a story, instructions, a scene: three words or more), with their paths. */+function wordsIn(v: unknown, path: (string | number)[] = [], out: { path: (string | number)[]; text: string }[] = []) {+ if (typeof v === "string") {+ if (!isMediaRef(v) && v.trim().split(/\s+/).length >= 3) out.push({ path, text: v });+ } else if (Array.isArray(v)) v.forEach((x, i) => wordsIn(x, [...path, i], out));+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) wordsIn(x, [...path, k], out);+ return out;+}++const VIDEO_FILE = /\.(mp4|webm|mov|mkv)(\?|$)/i;+const AUDIO_FILE = /\.(mp3|wav|ogg|m4a|flac|aac)(\?|$)/i;+const FIELD_LABELS: Record<string, string> = {+ video: "Video",+ footage: "Footage",+ reference: "Reference edit",+ references: "Reference image",+ photos: "Subject photo",+ images: "Image",+ image: "Image",+ audio: "Audio",+ product: "Product photo",+ logo: "Logo",+ story: "Story",+ scenes: "Scene",+ instructions: "What to keep in mind",+ style: "Look",+};++/** A form label for a field of a tool's input ("photos", 1 of 2 → "Subject photo 2"). */+function fieldLabel(path: (string | number)[], several: boolean): string {+ const key = [...path].reverse().find((p): p is string => typeof p === "string") ?? "input";+ const index = [...path].reverse().find((p): p is number => typeof p === "number");+ const base = FIELD_LABELS[key] ?? capital(key.replace(/_/g, " ").replace(/([^s])s$/, "$1"));+ return several && index !== undefined ? `${base} ${index + 1}` : base;+}++const fileType = (url: string, path: (string | number)[]): "image" | "video" | "audio" => {+ if (VIDEO_FILE.test(url)) return "video";+ if (AUDIO_FILE.test(url)) return "audio";+ const key = path.filter((p): p is string => typeof p === "string").join(" ");+ return /\.(png|jpe?g|webp|gif|avif)(\?|$)/i.test(url) ? "image" : /video|clip|footage|reference$/.test(key) ? "video" : /audio|voice|music|sound/.test(key) ? "audio" : "image";+};++/** A chat's studio call as a tool step: its exact input, its files and words as candidates. */+function chatLift(c: ChatCall, useId: string): Lifted {+ const files = mediaIn(c.input);+ const count = (p: (string | number)[]) => files.filter((f) => f.path.length === p.length && f.path.slice(0, -1).join("/") === p.slice(0, -1).join("/")).length;+ const words = wordsIn(c.input);+ const wordCount = (p: (string | number)[]) => words.filter((w) => w.path.slice(0, -1).join("/") === p.slice(0, -1).join("/")).length;+ let studio: string | undefined = studioForTool(c.name);+ if (!studio) {+ try {+ studio = planFor(c.name, c.input, { engine: c.gens[0]?.engine ?? "cloud" }).studio;+ } catch {+ studio = undefined;+ }+ }+ return {+ tool: c.name,+ studio: studio ?? cardTitle(c.name, c.input),+ record: `chat:${useId}`,+ input: JSON.parse(JSON.stringify(c.input)) as Record<string, unknown>,+ inputs: files.map((f) => ({ path: f.path, type: fileType(f.url, f.path), label: fieldLabel(f.path, count(f.path) > 1) })),+ texts: words.map((w) => ({ path: w.path, label: fieldLabel(w.path, typeof w.path.at(-1) === "number" && wordCount(w.path) > 1) })),+ };+}++/** The words a user typed (the files they attached are listed after them), unless Fuobe wrote them for a lone /skill. */+function userWords(text: string): { words: string; files: string[] } {+ const [body, attached = ""] = text.split(/\n\nAttached files[^\n]*\n/);+ const files = [...attached.matchAll(/^- \w+ \d+: (\S+)$/gm)].map((m) => m[1]);+ const words = /^Use the .+ skills?(?: with the attached files)?\.$/.test(body.trim()) ? "" : body.trim();+ return { words, files };+}++export interface ThreadDraft extends DraftResult {+ /** What the person asked for in the chat, for the naming pass. */+ words: string[];+}++/**+ * The draft of a skill from an Assist chat (W3): each assistant tool call paired with its result, keeping the gated+ * calls that ran — approved on a card or started by auto-run, which has no card — and started something that didn't+ * all fail. Declined calls and errors are left out; of calls that make the same thing again, the last is kept (a+ * heuristic: a later try replaces an earlier one unless it used its result). Generate calls are drafted from the+ * results they made, so a result passed on by hand to a later call becomes a step reference (linkByFile); a studio+ * call is one tool step with the exact input it ran with, and a reference into or out of one is refused (W7).+ */+export function draftFromThread(threadId: string): ThreadDraft {+ const r = db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(threadId) as { messages_json: string } | undefined;+ if (!r) throw new SkillError("No such chat", 404);+ const messages = JSON.parse(r.messages_json) as { role: string; content: unknown }[];+ const uses: { id: string; name: string; input: Record<string, unknown> }[] = [];+ const results = new Map<string, { error: boolean; text: string }>();+ const words: string[] = [];+ for (const m of messages) {+ if (!Array.isArray(m.content)) continue;+ for (const b of m.content as Block[]) {+ if (m.role === "assistant" && b.type === "tool_use" && b.id && b.name) uses.push({ id: b.id, name: b.name, input: (b.input ?? {}) as Record<string, unknown> });+ else if (m.role === "user" && b.type === "tool_result" && b.tool_use_id) results.set(b.tool_use_id, { error: !!b.is_error, text: textOf(b.content) });+ else if (m.role === "user" && b.type === "text" && typeof b.text === "string") {+ const u = userWords(b.text);+ if (u.words) words.push(u.words);+ }+ }+ }+ let declined = 0;+ let failed = 0;+ const refusals: DraftRefusal[] = [];+ const calls: (ChatCall & { use: string })[] = [];+ uses.forEach((u, order) => {+ const tool = getTool(u.name);+ if (!tool?.gated || u.name === "remember") return;+ const res = results.get(u.id);+ if (!res) return;+ if (res.error) {+ if (/declined|instead of approving/i.test(res.text)) declined++;+ else failed++;+ return;+ }+ const gens = [...new Set(startedIds(res.text))].map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);+ const live = gens.filter((g) => g.status !== "failed" && g.status !== "canceled");+ if (!live.length) {+ if (gens.length) failed++;+ return;+ }+ const outputs = new Set(live.flatMap((g) => g.outputs.map((o) => o.url)));+ const studio = !GENERATE_TOOLS.has(u.name);+ calls.push({ use: u.id, order, name: u.name, input: u.input, gens: live, inputs: new Set(mediaIn(u.input).map((f) => f.url)), outputs, makes: studio ? u.name : `${u.name}:${live.at(-1)!.kind}`, studio });+ });+ // The same tool making the same kind of thing again: the last try, unless a later call used an earlier one's result.+ const usedLater = (c: ChatCall) => calls.some((d) => d.order > c.order && [...c.outputs].some((u) => d.inputs.has(u)));+ const kept = calls.filter((c) => usedLater(c) || !calls.some((d) => d.order > c.order && d.makes === c.makes));+ const replaced = calls.length - kept.length;+ // A studio step's result feeding a later step, or a step's result feeding a studio step: refused (W7).+ const joined: typeof kept = [];+ for (const c of kept) {+ const from = joined.filter((d) => [...d.outputs].some((u) => c.inputs.has(u)));+ if (from.length && (c.studio || from.some((d) => d.studio))) {+ refusals.push({ id: c.gens[0].id, title: cut(cardTitle(c.name, c.input), 80), reason: STUDIO_WAIT });+ continue;+ }+ joined.push(c);+ }+ const notes: string[] = [];+ if (replaced) notes.push(replaced === 1 ? "An earlier try of a step was left out: the skill keeps the last one" : `${replaced} earlier tries of steps were left out: the skill keeps the last of each`);+ if (declined || failed) notes.push(`Left out: ${[declined && `${declined} plan${declined === 1 ? "" : "s"} you declined`, failed && `${failed} that didn't run`].filter(Boolean).join(" and ")}`);+ if (!joined.length) {+ const reason = calls.length || declined || failed ? "Nothing it made can be repeated yet" : "Nothing in it has run yet: run a plan, then save the chat as a skill";+ return { draft: null, refusals: refusals.length ? refusals : [{ id: threadId, title: "This chat", reason }], words };+ }+ const studioCalls: Origin["calls"] = [];+ const ids: string[] = [];+ for (const c of joined) {+ if (!c.studio) {+ ids.push(...c.gens.map((g) => g.id));+ continue;+ }+ if (c.gens.some((g) => !TERMINAL.has(g.status))) {+ refusals.push({ id: c.gens[0].id, title: cut(cardTitle(c.name, c.input), 80), reason: "It's still running: make the skill once it's done" });+ continue;+ }+ const pick = c.gens.findLast((g) => g.status === "succeeded");+ if (pick) studioCalls.push({ lifted: chatLift(c, c.use), pick });+ }+ const result = buildDraft(ids, { thread: threadId, calls: studioCalls, refusals, notes, generations: joined.flatMap((c) => c.gens.map((g) => g.id)) });+ return { ...result, words };+}+/** The deterministic SKILL.md body of a draft as it stands (every input Fixed). */export const draftBody = (draft: SkillDraft) => skillBody(draft.recipe, draft, { title: draft.title, description: draft.description, name: draft.name });@@ -851,6 +1079,7 @@ Rules:- Generalise a value only when the next run would really change it, and never lose counts, order, relationships between steps or selection rules. If the same words appear in several prompts, they are one input.- Suggest a slot only for words that appear verbatim in a step's prompt. Prefer few inputs: a skill with fewer inputs is easier to run.- Keep observable completion checks only (what kind of result, how many, its shape, length, sound). Never invent a success condition the record doesn't show.+- "asked", when present, is what the person typed in the chat the steps came from: use it to name the skill and its inputs, never as a step of its own.- Prefer Fuobe's own tools in the body (run_skill, generate, the studio tools) over describing other software.Answer with one JSON object and nothing else:{"name": "kebab-case-name", "title": "Short Title", "description": "One sentence on what it makes and from what.", "when_to_use": "When to pick it.", "inputs": [{"candidate": "<candidate id>", "id": "snake_case_id", "label": "Form label"}], "slots": [{"step": "<step key>", "text": "exact words from that step's prompt", "id": "snake_case_id", "label": "Form label"}], "body": "A SKILL.md body in Markdown: a # title, what it makes, ## Inputs, ## Steps, ## Using Fuobe from an agent."}`;@@ -876,7 +1105,7 @@ async function leafStills(draft: SkillDraft): Promise<LlmImage[]> {* The optional naming pass: Claude or Ollama (whichever this install allows; none, no pass) names the inputs, suggests* slots in the prompts, a title, a description, when to use it and a SKILL.md body. Malformed output is ignored (null).*/-export async function nameDraft(draft: SkillDraft): Promise<Naming | null> {+export async function nameDraft(draft: SkillDraft, asked: string[] = []): Promise<Naming | null> {if (!llmTextBackend()) return null;const record = {steps: draft.recipe.steps.map((s) => {@@ -888,6 +1117,8 @@ export async function nameDraft(draft: SkillDraft): Promise<Naming | null> {candidates: draft.candidates.filter((c) => !c.locked).map((c) => ({ candidate: c.id, kind: c.kind, type: c.type, label: c.label, example: typeof c.example === "string" && c.kind === "media" ? `(a ${c.type} file)` : c.example })),checks: draft.recipe.checks ?? {},current: { name: draft.name, title: draft.title, description: draft.description },+ // What the person asked for in the chat the steps came from (W3): words to name things by, never a step.+ ...(asked.length && { asked: asked.slice(-6).map((w) => cut(w, 600)) }),};const images = await leafStills(draft);const text = await llmText(NAMING_SYSTEM, `${images.length ? "The pictures are the results the person kept.\n" : ""}The record:\n${JSON.stringify(record, null, 2)}`, images);diff --git a/src/server/recipe-routes.ts b/src/server/recipe-routes.tsindex 2008a30d..1d924d4f 100644--- a/src/server/recipe-routes.ts+++ b/src/server/recipe-routes.ts@@ -18,3 +18,9 @@ export function recipeFailure(e: unknown): Response {}export const badBody = (issues: z.core.$ZodIssue[]) => Response.json({ error: issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; ") }, { status: 400 });++/** What a skill is drafted from: results picked in the Library (W2), or an Assist chat whose plans ran (W3). */+export const DraftSource = z.union([+ z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) }),+ z.object({ thread: z.string().min(1).max(40) }),+]);diff --git a/tests/assist-skill-tools.test.ts b/tests/assist-skill-tools.test.tsnew file mode 100644index 00000000..90483c87--- /dev/null+++ b/tests/assist-skill-tools.test.ts@@ -0,0 +1,333 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import type Anthropic from "@anthropic-ai/sdk";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++// Route handlers call connection() (no request scope in a test).+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 120_000 });++/**+ * Skills W3: a chat that ran becomes a skill (draftFromThread), and a saved skill with a recipe runs from Assist, MCP+ * and the offline planner through run_skill, priced on one card.+ */++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-skill-tools-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: open models run on the demo provider, and there's no LLM.+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const agent = await import("@/server/assist/agent");+const tools = await import("@/server/assist/tools");+const { chatFacts } = await import("@/server/assist/context");+const builder = await import("@/server/recipe-builder");+const recipes = await import("@/server/recipes");+const skills = await import("@/server/skills");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const { saveFile } = await import("@/server/storage");+const { encodePng } = await import("@/server/png");+const draftRoute = await import("@/app/api/assist/skills/draft/route");+const nameRoute = await import("@/app/api/assist/skills/draft/name/route");++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++let photo = "";+let clip = "";+beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+ photo = saveFile({ data: encodePng({ width: 64, height: 48, data: Buffer.alloc(64 * 48 * 4, 180) }), contentType: "image/png", source: "upload", name: "lamp.png" }).url;+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "talk.mp4" }).url;+});++type Block = Anthropic.Beta.BetaContentBlock;+type Msg = Anthropic.Beta.BetaMessage;+const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;+const toolUse = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Block;+const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason) => ({ content, stop_reason: stop, stop_details: null }) as Msg;++/** A model that answers from a script. */+const scripted = (...turns: Msg[]): import("@/server/assist/agent").ModelCall => async () => {+ const next = turns.shift();+ if (!next) throw new Error("script ran out");+ return next;+};++async function settle(ids: string[], ms = 60_000) {+ const until = Date.now() + ms;+ for (;;) {+ const all = ids.map((id) => gens.getGeneration(id, { includeDeleted: true })!);+ if (all.every((g) => ["succeeded", "failed", "canceled"].includes(g.status))) return all;+ if (Date.now() > until) throw new Error(`timed out: ${all.map((g) => `${g.id} ${g.status} ${g.message}`).join(", ")}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++const threadIds = (id: string) => agent.getThread(id)!.thread.items.flatMap((i) => (i.role === "generations" ? i.ids : []));+const json = (body: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });++/** A stored chat whose messages are written as the agent stores them (tool calls and their results). */+function storedChat(calls: { id: string; name: string; input: unknown; result: unknown; error?: boolean }[], said = "Make my lamp turn on a plinth") {+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ const messages: Anthropic.Beta.BetaMessageParam[] = [{ role: "user", content: [{ type: "text", text: `${said}\n\nAttached files (pass these URLs as inputs):\n- image 1: ${photo}` }] }];+ for (const c of calls) {+ messages.push({ role: "assistant", content: [toolUse(c.id, c.name, c.input)] as never });+ messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: c.id, content: typeof c.result === "string" ? c.result : JSON.stringify(c.result), ...(c.error && { is_error: true }) }] });+ }+ db().prepare("UPDATE assist_threads SET messages_json = ? WHERE id = ?").run(JSON.stringify(messages), t.id);+ return t.id;+}++/** A finished row written straight into the table (a studio's result): only what the builder reads. */+function row(o: { id: string; request: Record<string, unknown>; feature: string; op: string; kind: string; outputs: { url: string; kind: string }[] }) {+ const now = Date.now();+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, provider_input_json, external_id, external_meta_json, outputs_json, error, cost_usd, favorite, created_at, updated_at, completed_at, depends_on)+ VALUES (@id, NULL, @feature, NULL, @model, 'cloud', 'mock', @op, @kind, 'succeeded', NULL, NULL, NULL, @request, NULL, NULL, NULL, @outputs, NULL, 0, 0, @now, @now, @now, NULL)`,+ )+ .run({ id: o.id, feature: o.feature, model: o.request.modelId as string, op: o.op, kind: o.kind, request: JSON.stringify(o.request), outputs: JSON.stringify(o.outputs), now });+ return o.id;+}++describe("draftFromThread", () => {+ it("keeps an approved generate chain and an auto-run call; leaves out a declined call and one whose results all failed", async () => {+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ // 1. Asked first, approved: a still of the lamp, then animated (one generate call, chained with after).+ agent.addMessage(t.id, "Put my lamp on a travertine plinth, then make it turn", [photo]);+ await agent.run(+ t.id,+ scripted(+ reply(+ [+ toolUse("toolu_chain", "generate", {+ summary: "Lamp on a plinth, then a turntable",+ jobs: [+ { model_id: "nano-banana-pro", op: "edit", prompt: "a matte black desk lamp on a travertine plinth, soft window light", images: [photo], aspect_ratio: "1:1" },+ { model_id: "kling-3", op: "i2v", prompt: "slow turntable of the desk lamp", after: 0, duration: 5 },+ ],+ }),+ ],+ "tool_use",+ ),+ ),+ );+ expect(agent.getThread(t.id)!.thread.status).toBe("waiting");+ await agent.answerApproval(t.id, true);+ await agent.run(t.id, scripted(reply([text("Here it comes.")], "end_turn")));+ // 2. Declined on its card.+ agent.addMessage(t.id, "Also a poster of it");+ await agent.run(t.id, scripted(reply([toolUse("toolu_declined", "generate", { summary: "Poster", jobs: [{ model_id: "nano-banana-pro", prompt: "a poster of a desk lamp" }] })], "tool_use")));+ await agent.answerApproval(t.id, false);+ await agent.run(t.id, scripted(reply([text("Okay.")], "end_turn")));+ // 3. Auto-run (no card): a voice-over. 4. Auto-run too, but every result failed.+ await agent.updateThread(t.id, { autoApprove: true });+ agent.addMessage(t.id, "Add a voice-over, and a jingle");+ await agent.run(+ t.id,+ scripted(+ reply([toolUse("toolu_auto", "generate", { summary: "Voice-over", jobs: [{ model_id: "elevenlabs-v4", op: "tts", prompt: "Meet Lumen, the lamp that follows the sun." }] })], "tool_use"),+ reply([toolUse("toolu_failed", "generate", { summary: "Jingle", jobs: [{ model_id: "nano-banana-pro", prompt: "a jingle cover" }] })], "tool_use"),+ reply([text("Done.")], "end_turn"),+ ),+ );+ const items = agent.getThread(t.id)!.thread.items;+ // The auto-run calls started without a card.+ expect(items.filter((i) => i.role === "approval")).toHaveLength(2);+ const all = threadIds(t.id);+ await settle(all);+ // The jingle's results all failed.+ const history = JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(t.id) as { messages_json: string }).messages_json) as { content: unknown }[];+ const failedResult = history.flatMap((m) => (Array.isArray(m.content) ? m.content : [])).find((b: { tool_use_id?: string }) => b.tool_use_id === "toolu_failed") as { content: string };+ const failedIds = [...failedResult.content.matchAll(/"started":\s*\["([\w-]+)"/g)].map((m) => m[1]);+ expect(failedIds.length).toBeGreaterThan(0);+ db().prepare(`UPDATE generations SET status = 'failed' WHERE id IN (${failedIds.map(() => "?").join(",")})`).run(...failedIds);++ const { draft, refusals, words } = builder.draftFromThread(t.id);+ expect(refusals).toEqual([]);+ expect(draft).not.toBeNull();+ const steps = draft!.recipe.steps.filter((s) => s.kind === "generate");+ expect(steps.map((s) => s.request.modelId)).toEqual(["nano-banana-pro", "kling-3", "elevenlabs-v4"]);+ // The chain stays a chain: the clip waits for the still and takes it as its start frame.+ expect(steps[1].after).toBe(steps[0].key);+ expect(steps[1].chain).toMatchObject([{ slot: "images" }]);+ expect(steps[2].after).toBeUndefined();+ // The lamp photo the person attached is a media candidate (Fixed, as every candidate starts).+ expect(draft!.candidates.find((c) => c.kind === "media")).toMatchObject({ type: "image", example: photo });+ expect(draft!.recipe.params).toEqual([]);+ expect(draft!.recipe.source).toMatchObject({ from: "assist", thread: t.id });+ expect(draft!.description).toMatch(/Made in an Assist chat/);+ expect(draft!.notes.join(" ")).toMatch(/1 plan you declined and 1 that didn't run/);+ expect(words).toEqual(["Put my lamp on a travertine plinth, then make it turn", "Also a poster of it", "Add a voice-over, and a jingle"]);++ // The route answers the same (the words stay on the server, for the naming pass).+ const res = await draftRoute.POST(json({ thread: t.id }));+ expect(res.status).toBe(200);+ const body = (await res.json()) as { draft: { recipe: unknown }; refusals: unknown[]; words?: unknown };+ expect(body.draft.recipe).toEqual(draft!.recipe);+ expect(body.words).toBeUndefined();+ // No LLM here: the naming pass has nothing to say.+ expect(await (await nameRoute.POST(json({ thread: t.id }))).json()).toEqual({ naming: null });+ });++ it("merges a result passed on by hand into a later generate call as a step reference", async () => {+ const still = gens.createGenerations({ feature: "assist", modelId: "nano-banana-pro", op: "edit", prompt: "the lamp on a plinth", inputs: { images: [photo] } });+ await settle(still.map((g) => g.id));+ const out = gens.getGeneration(still[0].id)!.outputs[0].url;+ const clipGen = gens.createGenerations({ feature: "assist", modelId: "kling-3", op: "flf2v", prompt: "the lamp turns", inputs: { images: [photo], endImage: out }, params: { duration: 5 } });+ await settle(clipGen.map((g) => g.id));+ // An earlier try of the still with other words: replaced by the later one.+ const early = gens.createGenerations({ feature: "assist", modelId: "nano-banana-pro", op: "edit", prompt: "the lamp, first try", inputs: { images: [photo] } });+ await settle(early.map((g) => g.id));+ const id = storedChat([+ { id: "toolu_early", name: "generate", input: { summary: "First try", jobs: [{ model_id: "nano-banana-pro", prompt: "the lamp, first try", images: [photo] }] }, result: [{ model: "nano-banana-pro", started: early.map((g) => g.id) }] },+ { id: "toolu_still", name: "generate", input: { summary: "Still", jobs: [{ model_id: "nano-banana-pro", prompt: "the lamp on a plinth", images: [photo] }] }, result: [{ model: "nano-banana-pro", started: still.map((g) => g.id) }] },+ { id: "toolu_clip", name: "generate", input: { summary: "Clip", jobs: [{ model_id: "kling-3", prompt: "the lamp turns", images: [photo], end_image: out }] }, result: [{ model: "kling-3", started: clipGen.map((g) => g.id) }] },+ ]);+ const { draft, refusals } = builder.draftFromThread(id);+ expect(refusals).toEqual([]);+ const steps = draft!.recipe.steps as Extract<(typeof draft & object)["recipe"]["steps"][number], { kind: "generate" }>[];+ expect(steps.map((s) => s.request.prompt)).toEqual(["the lamp on a plinth", "the lamp turns"]);+ // end_image (endImage on the request) → the endImage chain slot; the photo stays a file of its own.+ expect(steps[1].after).toBe(steps[0].key);+ expect(steps[1].chain).toEqual([{ slot: "endImage" }]);+ expect(steps[1].request.inputs).toEqual({ images: [photo] });+ expect(draft!.notes.join(" ")).toMatch(/An earlier try of a step was left out/);+ });++ it("makes a studio call one tool step with the input it ran with, and refuses a reference into it", async () => {+ const video = gens.createGenerations({ feature: "assist", modelId: "kling-3", op: "i2v", prompt: "the lamp turns", inputs: { images: [photo] }, params: { duration: 5 } });+ await settle(video.map((g) => g.id));+ const made = gens.getGeneration(video[0].id)!.outputs[0].url;+ const captioned = row({ id: "cap-from-gen", feature: "captions", op: "captions", kind: "video", request: { feature: "captions", modelId: "veed-captions", op: "captions", inputs: { video: made } }, outputs: [{ url: clip, kind: "video" }] });+ const id = storedChat([+ { id: "toolu_video", name: "generate", input: { summary: "Clip", jobs: [{ model_id: "kling-3", prompt: "the lamp turns", images: [photo] }] }, result: [{ model: "kling-3", started: video.map((g) => g.id) }] },+ { id: "toolu_caps", name: "add_captions", input: { video: made, translate_to: "Spanish" }, result: { started: [captioned], href: "/video-tools/captions" } },+ ]);+ const { draft, refusals } = builder.draftFromThread(id);+ expect(refusals).toEqual([{ id: captioned, title: expect.any(String), reason: builder.STUDIO_WAIT }]);+ expect(draft!.recipe.steps.map((s) => s.kind)).toEqual(["generate"]);++ // On its own, the studio call is the skill: its exact input, its file a candidate.+ const solo = row({ id: "cap-solo", feature: "captions", op: "captions", kind: "video", request: { feature: "captions", modelId: "veed-captions", op: "captions", inputs: { video: clip } }, outputs: [{ url: clip, kind: "video" }] });+ const alone = builder.draftFromThread(storedChat([{ id: "toolu_solo", name: "add_captions", input: { video: clip, translate_to: "German" }, result: { started: [solo] } }]));+ expect(alone.refusals).toEqual([]);+ expect(alone.draft!.recipe.steps).toEqual([{ key: expect.any(String), kind: "tool", label: "Captions", tool: "add_captions", input: { video: clip, translate_to: "German" } }]);+ expect(alone.draft!.candidates).toEqual([expect.objectContaining({ kind: "media", type: "video", example: clip, at: [{ step: alone.draft!.recipe.steps[0].key, path: ["video"] }] })]);+ });++ it("says when nothing in a chat ran, and 404s an unknown chat", async () => {+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ expect(builder.draftFromThread(t.id)).toMatchObject({ draft: null, refusals: [{ id: t.id, reason: expect.stringMatching(/Nothing in it has run yet/) }] });+ expect((await draftRoute.POST(json({ thread: "nope" }))).status).toBe(404);+ expect((await draftRoute.POST(json({ thread: "" }))).status).toBe(400);+ });+});++/** The research's turntable as a saved skill: a product photo and its name, cut out, staged, turned. */+function lampSkill(name = "lamp-turntable") {+ if (skills.getSkill(name)) return name;+ skills.createSkill({ name, title: "Lamp turntable", description: "A product turntable from a photo.", body: "# Turntable\n\n1. Cut out, stage, spin." });+ recipes.saveRecipe(name, {+ fuobeRecipe: 1,+ params: [+ { id: "product", label: "Product photo", type: "image", required: true, example: photo },+ { id: "name", label: "Product name", type: "text", required: true, example: "Lumen desk lamp", max: 200 },+ { id: "aspect", label: "Shape", type: "choice", options: ["1:1", "9:16", "16:9"], default: "1:1" },+ ],+ steps: [+ { key: "cutout", kind: "generate", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{product}}"] } } },+ { key: "scene", kind: "generate", after: ["cutout"], chain: [{ slot: "images", position: "first" }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}} on a travertine plinth", params: { aspectRatio: "{{aspect}}" } } },+ { key: "spin", kind: "generate", after: ["scene"], chain: [{ slot: "images" }], request: { feature: "skill", modelId: "kling-3", op: "i2v", prompt: "slow turntable of the {{name}}", params: { duration: 5 } } },+ ],+ });+ return name;+}++describe("run_skill", () => {+ it("prices a pipeline as one atomic plan titled by the skill, and runs it in demo mode", async () => {+ const name = lampSkill();+ const input = { name, values: { product: photo, name: "Halo floor lamp" } };+ const plan = tools.planFor("run_skill", input, { engine: "cloud" });+ expect(plan.error).toBeUndefined();+ expect(plan.jobs.map((j) => j.modelId)).toEqual(["birefnet-cloud", "nano-banana-pro", "kling-3"]);+ expect(plan.jobs.every((j) => j.atomic && j.demo && !j.error && j.tool === "run_skill")).toBe(true);+ expect(tools.cardTitle("run_skill", input)).toBe("Lamp turntable");+ const out = await tools.executeTool("run_skill", input, { engine: "cloud" });+ expect(out.isError).toBeFalsy();+ const body = JSON.parse(out.content as string) as { skill: string; engine: string; demo: boolean; runs: { started: string[]; batch: string }[] };+ expect(body).toMatchObject({ skill: name, engine: "cloud", demo: true });+ const ids = body.runs[0].started;+ expect(out.items).toEqual([{ id: "", role: "generations", ids }]);+ const done = await settle(ids);+ expect(done.every((g) => g.status === "succeeded" && g.provider === "mock")).toBe(true);+ expect(done[1].request.prompt).toBe("Halo floor lamp on a travertine plinth");+ // The skill's own stamp, so its runs are its runs.+ expect(done[0].request.skill).toMatchObject({ name });+ });++ it("sends bad values back as an error naming the inputs, before any card", async () => {+ const name = lampSkill();+ const ctx = { engine: "cloud" as const };+ expect(tools.validateInput("run_skill", { name, values: {} }, ctx)).toBe(`/${name} needs product (image) and name (text)`);+ expect(tools.validateInput("run_skill", { name, values: { product: photo, name: "x", colour: "red" } }, ctx)).toMatch(/has no input “colour”: it takes product \(image\), name \(text\) and aspect \(1:1 \| 9:16 \| 16:9\)/);+ expect(tools.validateInput("run_skill", { name: "product-photoshoot" }, ctx)).toMatch(/doesn't run by itself.*lamp-turntable/);+ expect(tools.validateInput("run_skill", { name: "nope" }, ctx)).toMatch(/No skill called “nope”/);+ // Through the agent: the call goes back to the model as an error, and no card is shown.+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ agent.addMessage(t.id, "Run my lamp skill");+ await agent.run(t.id, scripted(reply([toolUse("toolu_bad", "run_skill", { name, values: { name: "Halo" } })], "tool_use"), reply([text("Which photo?")], "end_turn")));+ expect(agent.getThread(t.id)!.thread.items.some((i) => i.role === "approval")).toBe(false);+ // A value of the wrong kind is priced as an error the card shows.+ const bad = tools.planFor("run_skill", { name, values: { product: "not a file", name: "Halo" } }, ctx);+ expect(bad.jobs[0].error).toMatch(/Product photo/);+ });++ it("is marked in the skills index and the system prompt says to use it", () => {+ const name = lampSkill();+ const facts = chatFacts({ engine: "cloud", autoApprove: false, projectId: null, skills: [] });+ expect(facts.find((f) => f.section === "skills" && f.key === name)?.text).toMatch(/^- \/lamp-turntable — Lamp turntable \(runs by itself: run_skill with product, name, aspect\):/);+ });+});++describe("the offline planner", () => {+ it("turns /lamp-turntable plus an attachment into one run_skill card, and runs it", async () => {+ const name = lampSkill();+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ agent.addMessage(t.id, `/${name}`, [photo]);+ await agent.run(t.id, agent.offline);+ const view = agent.getThread(t.id)!.thread;+ expect(view.status).toBe("waiting");+ const card = view.items.find((i) => i.role === "approval");+ expect(card).toMatchObject({ summary: "Lamp turntable", status: "pending" });+ expect(card?.role === "approval" && card.jobs.map((j) => j.modelId)).toEqual(["birefnet-cloud", "nano-banana-pro", "kling-3"]);+ const history = JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(t.id) as { messages_json: string }).messages_json) as { role: string; content: Block[] }[];+ const call = history.at(-1)!.content.find((b) => b.type === "tool_use") as { name: string; input: unknown };+ // The photo from the attachment; the name from the values it was made with (no words were typed); the shape's default.+ expect(call).toMatchObject({ name: "run_skill", input: { name, values: { product: photo, name: "Lumen desk lamp", aspect: "1:1" } } });+ await agent.answerApproval(t.id, true);+ await agent.run(t.id, agent.offline);+ const ids = threadIds(t.id);+ expect(ids).toHaveLength(3);+ expect((await settle(ids)).every((g) => g.status === "succeeded")).toBe(true);+ expect(agent.getThread(t.id)!.thread.items.some((i) => i.role === "assistant" && /On it/.test(i.text))).toBe(true);+ });++ it("takes the words for the first text input, and asks for a file that wasn't attached", async () => {+ const name = lampSkill();+ expect(agent.offlineSkillRun(`Halo floor lamp\n\nAttached files (pass these URLs as inputs):\n- image 1: ${photo}`, name, "Lamp turntable", recipes.getRecipe(name).recipe)).toMatchObject({+ tool: "run_skill",+ input: { name, values: { product: photo, name: "Halo floor lamp", aspect: "1:1" } },+ });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });+ agent.addMessage(t.id, `/${name} Halo floor lamp`);+ await agent.run(t.id, agent.offline);+ const items = agent.getThread(t.id)!.thread.items;+ expect(items.some((i) => i.role === "approval")).toBe(false);+ expect(items.findLast((i) => i.role === "assistant")).toMatchObject({ text: `Lamp turntable needs Product photo (an image). Attach it and send /${name} again.` });+ });+});diff --git a/tests/assist.test.ts b/tests/assist.test.tsindex bfadc448..8d2b7749 100644--- a/tests/assist.test.ts+++ b/tests/assist.test.ts@@ -54,7 +54,10 @@ describe("assist tools", () => {}};tools.forEach((t) => walk(t.input_schema));- expect(objects.every((o) => o.additionalProperties === false)).toBe(true);+ // Closed, but for a map that says what its values are (run_skill's values by input id).+ expect(objects.every((o) => o.additionalProperties === false || (!o.properties && typeof o.additionalProperties === "object"))).toBe(true);+ expect(objects.some((o) => typeof o.additionalProperties === "object")).toBe(true);+ expect(json).not.toMatch(/"propertyNames"/);// generate has more optional fields than strict mode allows per request (zod validates it instead).expect(tools.find((t) => t.name === "generate")?.strict).toBeUndefined();expect(tools.find((t) => t.name === "create_storyboard")?.strict).toBe(true);diff --git a/tests/mcp.test.ts b/tests/mcp.test.tsindex 0727728d..b52592f8 100644--- a/tests/mcp.test.ts+++ b/tests/mcp.test.ts@@ -51,6 +51,24 @@ describe("MCP server", () => {expect(await rpc("tools/call", { name: "rm_rf" })).toMatchObject({ error: { code: -32602 } });});+ it("serves run_skill (W3): listed, priced by estimate_job, and named in the instructions of version 1.3.0", async () => {+ const init = (await rpc("initialize", { protocolVersion: "2025-06-18" })) as { result: { serverInfo: { version: string }; instructions: string } };+ expect(init.result.serverInfo.version).toBe("1.3.0");+ expect(init.result.instructions).toMatch(/run_skill/);+ const r = (await rpc("tools/list")) as { result: { tools: { name: string; description: string; inputSchema: { properties: Record<string, { enum?: string[] } & Record<string, unknown>> }; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] } };+ const run = r.result.tools.find((t) => t.name === "run_skill")!;+ expect(run).toBeDefined();+ expect(run.annotations).toEqual({ readOnlyHint: false, openWorldHint: true });+ expect(run.description).toMatch(/estimate_job/);+ expect(Object.keys(run.inputSchema.properties)).toEqual(["name", "values", "rows", "engine"]);+ const estimate = r.result.tools.find((t) => t.name === "estimate_job")!;+ expect(estimate.inputSchema.properties.tool.enum).toContain("run_skill");+ // A skill without a recipe is a tool error that names the skills that run by themselves.+ const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "run_skill", arguments: { name: "product-photoshoot" } } })) as { result: { isError: boolean; content: { text: string }[] } };+ expect(est.result.isError).toBe(true);+ expect(est.result.content[0].text).toMatch(/doesn't run by itself/);+ });+it("runs a tool and returns MCP content", async () => {const r = (await rpc("tools/call", { name: "search_models", arguments: { kind: "video", query: "kling" } })) as { result: { content: { type: string; text: string }[] } };const body = JSON.parse(r.result.content[0].text) as { models: { id: string }[] };diff --git a/tests/public-signup-visitors.test.ts b/tests/public-signup-visitors.test.tsindex 3bb4e47d..1e853a36 100644--- a/tests/public-signup-visitors.test.ts+++ b/tests/public-signup-visitors.test.ts@@ -98,6 +98,8 @@ describe("Assist is the owner's", () => {["POST", "/api/assist/skills"],["POST", "/api/assist/skills/upload"],["POST", "/api/assist/skills/draft"],+ // Save as skill from a chat (W3) drafts and names through these two.+ ["POST", "/api/assist/skills/draft/name"],["PATCH", "/api/assist/skills/ad-multiplier"],["POST", "/api/assist/skills/product-photoshoot/run"],["POST", "/api/assist/memory"],