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 keeps studio and Katana calls, and the offline planner runs only the skill a message names
Claude79698c2783b2
diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 40cb3cad..30d08484 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -46,7 +46,8 @@ export type AssistItem =| { id: string; role: "tool"; text: string; href?: string; studio?: string; connector?: string; failed?: boolean }/** `opens`: the studios the plan's jobs open in; `notes`: why a studio job runs in the Library instead. */| { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined"; opens?: string[]; notes?: string[] }- | { id: string; role: "generations"; ids: string[]; storyboard?: boolean }+ /** `use`: the tool call that started them (its tool_use id), so a chat's calls are matched to what they made. */+ | { id: string; role: "generations"; ids: string[]; storyboard?: boolean; use?: string }| { id: string; role: "notice"; text: string; tone: "info" | "error" };export type AssistStatus = "idle" | "running" | "waiting";@@ -460,12 +461,11 @@ 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])));+/** The tool result a plan gets when the person declines its card, or answers it with a new message instead. */+export const DECLINED = "The user declined this plan. Ask what they'd like to change.";+export const REPLIED_INSTEAD = "The user replied with new instructions instead of approving; follow them.";+/** Whether a tool result is the chat's own word that the person didn't approve the plan (not a provider's error). */+export const declinedByUser = (result: string): boolean => result === DECLINED || result === REPLIED_INSTEAD;/*** Leading `/name` tokens of a message: "/product-photoshoot /thumbnail-generation a coffee ad"diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 8a6473b6..c9ce2dbb 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -8,14 +8,15 @@ import {ASSIST_EFFORTS,CLAUDE_MODELS,contextUpdate,+ DECLINED,DEFAULT_CLAUDE_MODEL,DEFAULT_EFFORT,factMap,guessCategory,normalizeAgent,renderContext,+ REPLIED_INSTEAD,slashSkills,- startedIds,threadTitle,type AssistAgent,type AssistAvailability,@@ -78,6 +79,8 @@ export interface ModelRequest {threadId?: string;/** Skills loaded in the chat (the offline planner uses their hints). */skills?: SkillMeta[];+ /** The skills the person's latest message named (/name): the offline planner runs one of those, never an earlier one. */+ named?: string[];/** Custom MCP connectors (Settings → Assist): Claude gets them through the MCP connector; other agents can't use them. */connectors?: Connector[];}@@ -832,7 +835,7 @@ export const local: ModelCall = async ({ system, messages, tools, settings }) =>};/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */-export const offline: ModelCall = async ({ messages, ctx, skills }) => {+export const offline: ModelCall = async ({ messages, ctx, skills, named }) => {// Context updates (system messages) aren't the user's words.const last = messages.findLast((m) => m.role !== "system");const blocks = last && typeof last.content !== "string" ? last.content : [];@@ -873,8 +876,9 @@ 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()) {+ // A skill this message named that runs by itself (the last one named): its inputs filled from the message, one+ // run_skill card. A skill loaded earlier in the chat stays a hint, so a new request isn't read as its inputs.+ for (const s of (skills ?? []).filter((k) => named?.includes(k.name)).reverse()) {const recipe = (s as { recipe?: boolean }).recipe ? skillRecipe(s.name) : null;if (!recipe) continue;const r = offlineSkillRun(said, s.name, s.title, recipe);@@ -957,6 +961,13 @@ 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()) {@@ -1303,6 +1314,9 @@ function toolCtx(s: State): ToolContext {};}+/** A call's generations remember the call (Save as skill matches each call to what it made, whatever its result says). */+const madeBy = (it: AssistItem, use: string): AssistItem => (it.role === "generations" ? { ...it, use } : it);+async function runTool(name: string, input: unknown, ctx: ToolContext): Promise<{ result: Omit<ToolResult, "tool_use_id">; items: AssistItem[] }> {const out = await executeTool(name, input, ctx);return { result: { type: "tool_result", content: out.content, ...(out.isError && { is_error: true }) }, items: out.items ?? [] };@@ -1356,6 +1370,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const connectors = chatConnectors(s);const { system, update, sent } = contextFor(s, connectors);const active = s.ext.skills.map((n) => getSkill(n)).filter((x): x is NonNullable<typeof x> => !!x);+ const latest = s.thread.items.findLast((i) => i.role === "user");const res = await model({system,messages: update ? [...s.messages, update] : s.messages,@@ -1364,6 +1379,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {settings: { model: s.ext.model, effort: s.ext.effort, provider: s.ext.provider },threadId: s.thread.id,skills: active,+ named: latest?.role === "user" ? (latest.skills ?? []) : [],...(connectors.length && { connectors }),});@@ -1440,7 +1456,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const { result, items } = await runTool(u.name, u.input, ctx);results.push({ ...result, tool_use_id: u.id });if (price && !result.is_error) s.ext.spentUsd = Math.round((s.ext.spentUsd + price) * 1000) / 1000;- for (const it of items) push(s, it);+ for (const it of items) push(s, madeBy(it, u.id));}const order = uses.map((u) => u.id);if (gated.length) {@@ -1558,7 +1574,7 @@ export function addMessage(id: string, text: string, attachments: string[] = [])// The first message names the chat, unless it was started with a name (a scheduled run's).if (!s.thread.items.some((i) => i.role === "user") && s.thread.title === "New chat") s.thread.title = threadTitle(slash.text || titles.join(", ") || text);// Tool results first: they answer the assistant's last turn.- const results = s.pending ? decline(s, "The user replied with new instructions instead of approving; follow them.") : [];+ const results = s.pending ? decline(s, REPLIED_INSTEAD) : [];if (!results.length) closeDanglingToolUses(s.messages);appendUser(s.messages, [...results, ...userBlocks(words, attachments)]);push(s, { role: "user", text: slash.skills.length ? slash.text : text, ...(attachments.length && { attachments }), ...(slash.skills.length && { skills: slash.skills }) });@@ -1576,7 +1592,7 @@ function settle(s: State, approved: boolean): Pending {return p;}-function decline(s: State, why = "The user declined this plan. Ask what they'd like to change."): ToolResult[] {+function decline(s: State, why = DECLINED): ToolResult[] {const p = settle(s, false);return ordered([...p.results, ...p.gated.map((g) => ({ type: "tool_result" as const, tool_use_id: g.id, is_error: true, content: why }))], p.order);}@@ -1587,7 +1603,7 @@ async function runApproved(s: State, p: Pending): Promise<ToolResult[]> {for (const g of p.gated) {const { result, items } = await runTool(g.name, g.input, ctx);results.push({ ...result, tool_use_id: g.id });- for (const it of items) push(s, it);+ for (const it of items) push(s, madeBy(it, g.id));}return ordered(results, p.order);}diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.tsindex 55c48448..411121be 100644--- a/src/server/recipe-builder.ts+++ b/src/server/recipe-builder.ts@@ -30,7 +30,7 @@ import { db } from "./db";import { llmText, llmTextBackend, type LlmImage } from "./enhance";import { listElements } from "./elements";import { currentRequest, getGeneration, unfilledRequest } from "./generations";-import { startedIds } from "@/lib/assist";+import { declinedByUser, type AssistItem } from "@/lib/assist";import { cardTitle, getTool, planFor } from "./assist/tools";import { getSkill, SkillError } from "./skills";import { absolutePath, readRef } from "./storage";@@ -961,11 +961,32 @@ function chatLift(c: ChatCall, useId: string): Lifted {}/** 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 };+function userWords(text: string): string {+ const [body] = text.split(/\n\nAttached files[^\n]*\n/);+ return /^Use the .+ skills?(?: with the attached files)?\.$/.test(body.trim()) ? "" : body.trim();+}++/**+ * The generation ids a tool result names, for a chat saved before its generations items said which call made them:+ * each `started`, `results` and `final` (a generate call, a studio that opened, Katana), and each `id` (a pipeline's+ * steps, a storyboard's frames). Ids that aren't generations are dropped by the caller.+ */+function idsInResult(text: string): string[] {+ let json: unknown;+ try {+ json = JSON.parse(text);+ } catch {+ return [];+ }+ const out: string[] = [];+ const walk = (v: unknown, key?: string) => {+ if (typeof v === "string") {+ if (key && ["started", "results", "final", "id"].includes(key) && /^[\w-]{4,40}$/.test(v)) out.push(v);+ } else if (Array.isArray(v)) v.forEach((x) => walk(x, key));+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) walk(x, k);+ };+ walk(json);+ return out;}export interface ThreadDraft extends DraftResult {@@ -982,9 +1003,12 @@ export interface ThreadDraft extends DraftResult {* 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;+ const r = db().prepare("SELECT messages_json, items_json FROM assist_threads WHERE id = ?").get(threadId) as { messages_json: string; items_json: string } | undefined;if (!r) throw new SkillError("No such chat", 404);const messages = JSON.parse(r.messages_json) as { role: string; content: unknown }[];+ // The generations each call started, as the chat shows them (every tool's own list, whatever its result says).+ const madeBy = new Map<string, string[]>();+ for (const i of JSON.parse(r.items_json) as AssistItem[]) if (i.role === "generations" && i.use) madeBy.set(i.use, [...(madeBy.get(i.use) ?? []), ...i.ids]);const uses: { id: string; name: string; input: Record<string, unknown> }[] = [];const results = new Map<string, { error: boolean; text: string }>();const words: string[] = [];@@ -994,8 +1018,8 @@ export function draftFromThread(threadId: string): ThreadDraft {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);+ const said = userWords(b.text);+ if (said) words.push(said);}}}@@ -1009,11 +1033,11 @@ export function draftFromThread(threadId: string): ThreadDraft {const res = results.get(u.id);if (!res) return;if (res.error) {- if (/declined|instead of approving/i.test(res.text)) declined++;+ if (declinedByUser(res.text.trim())) declined++;else failed++;return;}- const gens = [...new Set(startedIds(res.text))].map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);+ const gens = [...new Set(madeBy.get(u.id) ?? idsInResult(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++;@@ -1023,9 +1047,15 @@ export function draftFromThread(threadId: string): ThreadDraft {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));+ // The same tool making the same kind of thing again: the last try, unless a later call that is kept used an earlier+ // one's result. Walked from the end, so a call is kept only for a kept call (A, B from A, A', B' from A' keeps A', B').+ const keptSet = new Set<ChatCall>();+ for (const c of [...calls].reverse()) {+ const last = !calls.some((d) => d.order > c.order && d.makes === c.makes);+ const used = [...keptSet].some((d) => [...c.outputs].some((u) => d.inputs.has(u)));+ if (last || used) keptSet.add(c);+ }+ const kept = calls.filter((c) => keptSet.has(c));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 = [];diff --git a/tests/assist-skill-tools.test.ts b/tests/assist-skill-tools.test.tsindex 90483c87..544da9c0 100644--- a/tests/assist-skill-tools.test.ts+++ b/tests/assist-skill-tools.test.ts@@ -32,6 +32,10 @@ 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");+const { insideSkill } = await import("@/server/assist/skill-tools");+const { zip } = await import("@/server/zip");+const { NESTED_SKILL } = await import("@/lib/recipe");+const { DECLINED } = await import("@/lib/assist");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -82,16 +86,25 @@ function storedChat(calls: { id: string; name: string; input: unknown; result: ureturn 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;+/** The text of a call's tool result, as the chat stored it. */+function toolResult(thread: string, use: string): string {+ const history = JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(thread) as { messages_json: string }).messages_json) as { content: unknown }[];+ const b = history.flatMap((m) => (Array.isArray(m.content) ? m.content : [])).find((x: { tool_use_id?: string }) => x.tool_use_id === use) as { content: string };+ return b.content;+}++/** Calls run in a chat through the real agent, one message each, every one approved on its card. */+async function chatRun(engine: "cloud" | "open", calls: { id: string; name: string; input: unknown }[], thread?: string, said = "Make my lamp turn on a plinth") {+ const id = thread ?? agent.createThread({ agent: "offline", engine }).id;+ for (const c of calls) {+ agent.addMessage(id, said, [photo]);+ await agent.run(id, scripted(reply([toolUse(c.id, c.name, c.input)], "tool_use")));+ expect(agent.getThread(id)!.thread.status).toBe("waiting");+ await agent.answerApproval(id, true);+ await agent.run(id, scripted(reply([text("Started.")], "end_turn")));+ expect(toolResult(id, c.id)).not.toMatch(/^\{"error"/);+ }+ return id;}describe("draftFromThread", () => {@@ -199,25 +212,43 @@ describe("draftFromThread", () => {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" } },+ it("refuses a generate result passed into a studio call, as the studio call really answered", async () => {+ // A clip made in the chat, then captioned in the chat: both calls run through the agent, approved on their cards.+ const t = await chatRun("open", [+ { id: "toolu_clip", name: "generate", input: { summary: "Clip", jobs: [{ model_id: "kling-3", op: "i2v", prompt: "the lamp turns", images: [photo], duration: 5 }] } },]);- const { draft, refusals } = builder.draftFromThread(id);- expect(refusals).toEqual([{ id: captioned, title: expect.any(String), reason: builder.STUDIO_WAIT }]);+ const [made] = await settle(threadIds(t));+ await chatRun("open", [{ id: "toolu_caps", name: "add_captions", input: { video: made.outputs[0].url, translate_to: "Spanish" } }], t);+ await settle(threadIds(t));+ const { draft, refusals } = builder.draftFromThread(t);+ expect(refusals).toEqual([{ id: expect.any(String), title: "Captions in Spanish", 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"] }] })]);+ /** Each studio tool as it really answers (a studio that opened, Katana's final cut), run through the agent in demo mode. */+ it.each([+ ["split_layers", "Layers", () => ({ image: photo, focus: "the lamp and the background" }), "results"],+ ["add_captions", "Captions", () => ({ video: clip, translate_to: "German" }), "results"],+ ["katana", "Katana", () => ({ reference: clip, photos: [photo], instructions: "keep the warm light" }), "final"],+ ])("makes a %s call that opened in %s one tool step with the input it ran with", async (tool, studio, input, field) => {+ const t = await chatRun("open", [{ id: `toolu_${tool}`, name: tool, input: input() }]);+ // The real result: the studio's own shape, with no "started" list.+ const result = toolResult(t, `toolu_${tool}`);+ expect(result).not.toMatch(/"started"/);+ expect(JSON.parse(result)).toHaveProperty(field);+ await settle(threadIds(t), 110_000);+ const check = (id: string) => {+ const { draft, refusals } = builder.draftFromThread(id);+ expect(refusals).toEqual([]);+ expect(draft!.recipe.steps).toEqual([{ key: expect.any(String), kind: "tool", label: studio, tool, input: input() }]);+ expect(draft!.recipe.source).toMatchObject({ from: "assist", thread: t, generations: threadIds(t) });+ expect(draft!.candidates.filter((c) => c.kind === "media").map((c) => c.example)).toEqual(Object.values(input()).flat().filter((v) => typeof v === "string" && v.startsWith("/api/files/")));+ };+ check(t);+ // A chat saved before its generations said which call made them: read from the result itself.+ const items = agent.getThread(t)!.thread.items.map((i) => (i.role === "generations" ? { ...i, use: undefined } : i));+ db().prepare("UPDATE assist_threads SET items_json = ? WHERE id = ?").run(JSON.stringify(items), t);+ check(t);});it("says when nothing in a chat ran, and 404s an unknown chat", async () => {@@ -228,6 +259,42 @@ describe("draftFromThread", () => {});});+describe("draftFromThread: tries and errors", () => {+ it("keeps the last tries when retries interleave (A, B from A, A', B' from A'), with nothing left over", async () => {+ const t = agent.createThread({ agent: "offline", engine: "cloud" }).id;+ const still = (id: string, prompt: string) => ({ id, name: "generate", input: { summary: prompt, jobs: [{ model_id: "nano-banana-pro", op: "edit", prompt, images: [photo] }] } });+ const turn = (id: string, prompt: string, from: string) => ({ id, name: "generate", input: { summary: prompt, jobs: [{ model_id: "kling-3", op: "i2v", prompt, images: [from], duration: 5 }] } });+ const outputOf = async (use: string) => {+ const ids = agent.getThread(t)!.thread.items.flatMap((i) => (i.role === "generations" && i.use === use ? i.ids : []));+ return (await settle(ids)).at(-1)!.outputs[0].url;+ };+ await chatRun("cloud", [still("toolu_a", "lamp first try")], t);+ await chatRun("cloud", [turn("toolu_b", "turn the first try", await outputOf("toolu_a"))], t);+ await chatRun("cloud", [still("toolu_a2", "lamp second try")], t);+ await chatRun("cloud", [turn("toolu_b2", "turn the second try", await outputOf("toolu_a2"))], t);+ await settle(threadIds(t));+ const { draft, refusals } = builder.draftFromThread(t);+ expect(refusals).toEqual([]);+ const steps = draft!.recipe.steps.filter((s) => s.kind === "generate");+ expect(steps.map((s) => s.request.prompt)).toEqual(["lamp second try", "turn the second try"]);+ expect(steps[1].after).toBe(steps[0].key);+ expect(draft!.notes.join(" ")).toMatch(/2 earlier tries of steps were left out/);+ });++ it("counts only the chat's own decline as declined: an error that says declined is a call that didn't run", async () => {+ const failed = { id: "toolu_refused", name: "generate", input: { summary: "Poster", jobs: [{ model_id: "nano-banana-pro", prompt: "a poster" }] }, result: [{ model: "nano-banana-pro", error: "The request was declined by the provider's safety system" }], error: true };+ const declined = { id: "toolu_no", name: "generate", input: { summary: "Poster", jobs: [{ model_id: "nano-banana-pro", prompt: "a poster" }] }, result: DECLINED, error: true };+ expect(builder.draftFromThread(storedChat([failed])).draft).toBeNull();+ const id = storedChat([failed, declined]);+ expect(builder.draftFromThread(id)).toMatchObject({ draft: null, refusals: [{ reason: "Nothing it made can be repeated yet" }] });+ // Both kinds side by side, under a call that ran: the notes say which was which.+ const ran = gens.createGenerations({ feature: "assist", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp" });+ await settle(ran.map((g) => g.id));+ const both = storedChat([failed, declined, { id: "toolu_ran", name: "generate", input: { summary: "Lamp", jobs: [{ model_id: "nano-banana-pro", prompt: "a lamp" }] }, result: [{ model: "nano-banana-pro", started: ran.map((g) => g.id) }] }]);+ expect(builder.draftFromThread(both).draft!.notes.join(" ")).toMatch(/Left out: 1 plan you declined and 1 that didn't run/);+ });+});+/** 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;@@ -294,6 +361,58 @@ describe("run_skill", () => {});});+describe("a skill inside a skill", () => {+ const nestedRecipe = (name: string) => ({+ fuobeRecipe: 1,+ params: [{ id: "product", label: "Product photo", type: "image", required: true, example: photo }],+ steps: [{ key: "again", kind: "tool", tool: "run_skill", input: { name, values: { product: "{{product}}" } } }],+ });++ it("is refused when a recipe is saved, written as a file or uploaded", () => {+ skills.createSkill({ name: "loop-self", title: "Loop", description: "Runs itself.", body: "# Loop" });+ expect(() => recipes.saveRecipe("loop-self", nestedRecipe("loop-self"))).toThrow(NESTED_SKILL);+ expect(() => recipes.saveRecipe("loop-self", nestedRecipe(lampSkill()))).toThrow(NESTED_SKILL);+ expect(() => skills.setSkillFile("loop-self", "recipe.json", JSON.stringify(nestedRecipe("loop-self")))).toThrow(NESTED_SKILL);+ expect(skills.getSkill("loop-self")!.recipe).toBeFalsy();+ const archive = zip([+ { name: "loop-up/SKILL.md", data: Buffer.from("---\nname: loop-up\ndescription: Runs itself.\n---\n# Loop\n") },+ { name: "loop-up/recipe.json", data: Buffer.from(JSON.stringify(nestedRecipe("loop-up"))) },+ ]);+ expect(() => skills.importSkill({ name: "loop-up.zip", data: archive })).toThrow(NESTED_SKILL);+ expect(skills.getSkill("loop-up")).toBeFalsy();+ });++ it("is priced and run as an error, never a loop, even from inside a skill's own work", async () => {+ const name = lampSkill();+ // A recipe.json stored before the rule (written straight into the table): it no longer reads as a recipe.+ skills.createSkill({ name: "loop-old", title: "Old loop", description: "Runs itself.", body: "# Loop" });+ db().prepare("UPDATE skills SET files_json = ? WHERE name = ?").run(JSON.stringify([{ path: "recipe.json", content: JSON.stringify(nestedRecipe("loop-old")) }]), "loop-old");+ const plan = tools.planFor("run_skill", { name: "loop-old", values: { product: photo } }, { engine: "cloud" });+ expect(plan.jobs).toEqual([expect.objectContaining({ error: expect.stringMatching(/doesn't run by itself/) })]);+ // The guard: run_skill inside a skill's pricing or run answers an error at once.+ const inner = { name, values: { product: photo, name: "Halo" } };+ expect(insideSkill("outer", () => tools.planFor("run_skill", inner, { engine: "cloud" })).jobs[0].error).toMatch(/can't run another skill/);+ expect(insideSkill("outer", () => tools.validateInput("run_skill", inner, { engine: "cloud" }))).toMatch(/can't run another skill/);+ const out = await insideSkill("outer", () => tools.executeTool("run_skill", inner, { engine: "cloud" }));+ expect(out).toMatchObject({ isError: true, content: expect.stringMatching(/can't run another skill/) });+ // Outside a skill it prices as before.+ expect(tools.planFor("run_skill", inner, { engine: "cloud" }).jobs.every((j) => !j.error)).toBe(true);+ });+});++describe("run_skill's values", () => {+ it("are words to every provider: one string type, numbers taken as their digits", () => {+ const name = lampSkill();+ const schema = tools.apiTools().find((t) => t.name === "run_skill")!.input_schema as { properties: Record<string, { additionalProperties?: unknown; items?: { additionalProperties?: unknown } }> };+ expect(JSON.stringify(schema)).not.toMatch(/"type":\[/);+ expect(schema.properties.values.additionalProperties).toEqual({ type: "string" });+ expect(schema.properties.rows.items!.additionalProperties).toEqual({ type: "string" });+ expect(tools.validateInput("run_skill", { name, values: { product: photo, name: 42 } }, { engine: "cloud" })).toBeNull();+ const plan = tools.planFor("run_skill", { name, values: { product: photo, name: 42 } }, { engine: "cloud" });+ expect(plan.jobs[1]).toMatchObject({ prompt: "42 on a travertine plinth" });+ });+});+describe("the offline planner", () => {it("turns /lamp-turntable plus an attachment into one run_skill card, and runs it", async () => {const name = lampSkill();@@ -330,4 +449,25 @@ describe("the offline planner", () => {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.` });});+ it("runs a skill only when the message names it: a new request later in the chat is planned as usual", 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);+ await agent.answerApproval(t.id, true);+ await agent.run(t.id, agent.offline);+ agent.addMessage(t.id, "now make a 5 second video of a cat surfing");+ await agent.run(t.id, agent.offline);+ 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: { jobs: { prompt: string }[] } };+ expect(call.name).toBe("generate");+ expect(call.input.jobs[0].prompt).toMatch(/cat surfing/);+ expect(agent.getThread(t.id)!.thread.items.some((i) => i.role === "assistant" && /needs Product photo/.test(i.text))).toBe(false);+ // Named again, it runs again.+ await agent.answerApproval(t.id, false);+ agent.addMessage(t.id, `/${name} Halo floor lamp`, [photo]);+ await agent.run(t.id, agent.offline);+ const again = 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[] }[];+ expect(again.at(-1)!.content.find((b) => b.type === "tool_use")).toMatchObject({ name: "run_skill", input: { name, values: { product: photo, name: "Halo floor lamp" } } });+ });});