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
Skills: a skill never runs another skill, and run_skill takes every value as text
Claudecb0d51cb4b70
diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex a5cb4cdc..42fdf920 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -93,10 +93,28 @@ const GenerateStepSchema = z.object({chain: z.array(ChainSlotSchema).max(RECIPE_LIMITS.steps).optional(),request: RequestSchema,});+/** Why a step can't be a saved skill (run_skill): a skill runs its own steps, never another skill or itself. */+export const NESTED_SKILL = "a skill can't run another skill: put that skill's steps in this one instead";+/** Tools a recipe's step never calls. */+const NOT_A_STEP = new Set(["run_skill"]);++/** Whether a recipe.json's text has a step that runs a skill (checked before its shape, so an upload is refused by name). */+export function runsASkill(text: string): boolean {+ try {+ const json = JSON.parse(text.replace(/^\uFEFF/, "")) as { steps?: unknown };+ return Array.isArray(json?.steps) && json.steps.some((s) => !!s && typeof s === "object" && NOT_A_STEP.has(String((s as { tool?: unknown }).tool)));+ } catch {+ return false;+ }+}+const ToolStepSchema = z.object({...StepBase,kind: z.literal("tool"),- tool: z.string().regex(/^[a-z][a-z0-9_]{1,40}$/, "an Assist tool's name, e.g. dub_video"),+ tool: z+ .string()+ .regex(/^[a-z][a-z0-9_]{1,40}$/, "an Assist tool's name, e.g. dub_video")+ .refine((t) => !NOT_A_STEP.has(t), NESTED_SKILL),input: z.record(z.string(), z.unknown()),});const StepSchema = z.discriminatedUnion("kind", [GenerateStepSchema, ToolStepSchema]);diff --git a/src/server/assist/skill-tools.ts b/src/server/assist/skill-tools.tsindex 6fef8201..77c5c87f 100644--- a/src/server/assist/skill-tools.ts+++ b/src/server/assist/skill-tools.ts@@ -1,12 +1,13 @@import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";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 { NESTED_SKILL, 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";+import { defineTool, type ToolContext, type ToolOutcome } from "./define";/*** run_skill (package W3): a saved skill whose files hold a recipe runs by itself with values for its inputs — the@@ -14,9 +15,20 @@ import { defineTool, type ToolContext } from "./define";* 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()]);+// Every value is words to the model (a number too, "5"): one JSON type, no type arrays, for every provider's schema rules.+// A number a model sends anyway is taken as its digits; the recipe reads numbers from text as a form does.+const Value = z.preprocess((v) => (typeof v === "number" && Number.isFinite(v) ? String(v) : v), z.string());const Values = z.record(z.string(), Value);+/**+ * Inside a skill's own pricing or run: a recipe never has a run_skill step (its schema refuses one), and this guard+ * stops one written before that rule, or anything else, from pricing or running a skill inside a skill (no recursion).+ */+const inSkill = new AsyncLocalStorage<string>();+/** Work done for a skill (its pricing, its run): a run_skill call inside it is refused. */+export const insideSkill = <T>(name: string, fn: () => T): T => inSkill.run(name, fn);+const nested = () => (inSkill.getStore() ? `${NESTED_SKILL.charAt(0).toUpperCase()}${NESTED_SKILL.slice(1)} (/${inSkill.getStore()} is running)` : null);+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."),@@ -40,6 +52,8 @@ export function inputList(recipe: Pick<Recipe, "params">, only?: (id: string) =>/** 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 loop = nested();+ if (loop) return { error: loop };const n = name.replace(/^\//, "").trim();const projectId = ctx.thread?.projectId ?? null;const runnable = () =>@@ -80,7 +94,7 @@ function plan(input: RunSkill, ctx: ToolContext): PlannedJob[] {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 est = insideSkill(found.name, () => 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)))];@@ -109,7 +123,7 @@ const runSkill = defineTool({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 ?? {};+ return insideSkill(found.name, () => estimateRecipe(found.name, { values: input.rows?.[0] ?? input.values ?? {} }, engineOf(input, found.recipe, ctx))).place ?? {};} catch {return {};}@@ -117,31 +131,35 @@ const runSkill = defineTool({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,- };+ return insideSkill(found.name, () => runFound(input, ctx, found));},});+async function runFound(input: RunSkill, ctx: ToolContext, found: { recipe: Recipe; title: string; name: string }): Promise<ToolOutcome> {+ 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/recipes.ts b/src/server/recipes.tsindex 6ee3f105..22f521fa 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -87,7 +87,7 @@ export function getRecipe(name: string): { skill: Skill; recipe: Recipe } {}/** Tools a recipe may call: the gated ones that make something (not remember, which changes what Assist knows). */-const runnableTool = (name: string) => !!getTool(name)?.gated && name !== "remember";+const runnableTool = (name: string) => !!getTool(name)?.gated && name !== "remember" && name !== "run_skill";/*** Problems only the server can see: a model the catalog doesn't have (after REPLACED_BY), a tool a recipe can't call,diff --git a/src/server/skills.ts b/src/server/skills.tsindex 090586b4..78f36a51 100644--- a/src/server/skills.ts+++ b/src/server/skills.ts@@ -2,7 +2,7 @@ import "server-only";import fs from "node:fs";import path from "node:path";import { parseSkillMd, SKILL_LIMITS, SKILL_NAME_RE, toSkillMd, type Skill, type SkillMeta, type SkillSummary } from "@/lib/assist";-import { parseRecipe, RECIPE_FILE, stripChecks, stripExamples, type Recipe } from "@/lib/recipe";+import { NESTED_SKILL, parseRecipe, RECIPE_FILE, runsASkill, stripChecks, stripExamples, type Recipe } from "@/lib/recipe";import { unzip, ZipError } from "./assist/unzip";import { db } from "./db";import { zip } from "./zip";@@ -196,6 +196,7 @@ export function setSkillFile(name: string, file: string, content: string | null)if (!cur) throw new SkillError("No such skill", 404);if (cur.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then change your copy", 403);if (!safeFilePath(file)) throw new SkillError(`“${file}” isn't a file name a skill can carry (a text file such as notes.md or recipe.json)`);+ if (file === RECIPE_FILE && content !== null && runsASkill(content)) throw new SkillError(`Check recipe.json: ${NESTED_SKILL}`, 422);const r = db().prepare("SELECT files_json FROM skills WHERE name = ?").get(name) as { files_json: string };const files = (JSON.parse(r.files_json) as StoredFile[]).filter((f) => f.path !== file);if (content !== null) files.push({ path: file, content });@@ -400,6 +401,7 @@ export function importSkill(file: { name: string; data: Buffer }, opts: { replaccontinue;}bytes += e.data.length;+ if (rel === RECIPE_FILE && runsASkill(e.data.toString("utf8"))) throw new SkillError(`Check recipe.json and try again: ${NESTED_SKILL}.`);files.push({ path: rel, content: rel === RECIPE_FILE ? unverified(e.data.toString("utf8")) : e.data.toString("utf8") });}} else {