Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Evaluation: pnpm eval:from-skill writes a saved skill's examples and checks as a suite the harness runs through the skill's own routes

Claude2ce0493e4272
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjs
index f18ea7ca..fcaa2d27 100644
--- a/bin/lib/commands.mjs
+++ b/bin/lib/commands.mjs
@@ -1163,7 +1163,7 @@ export const COMMANDS = {
},
eval: {
summary: "Measure Fuobe Originals: run a suite, score, review blind, compare runs",
- usage: "fuobe eval <run|report|review|compare|promote|covers|history|validate|setup|trash> [options] (from a Fuobe checkout)",
+ usage: "fuobe eval <run|report|review|compare|promote|covers|history|validate|setup|trash|from-skill> [options] (from a Fuobe checkout)",
examples: ["fuobe eval run --suite selftest --engine demo", "fuobe eval run --suite soul --engine open --looks v1-general --variants recipe,prompt-only", "fuobe eval compare latest~1 latest --fail-on clip --threshold 1"],
passthrough: true,
run: evalHarness,
diff --git a/docs/cli.md b/docs/cli.md
index d7c161a6..6a88dcde 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -274,6 +274,7 @@ fuobe eval run --suite selftest --engine demo # a free self-test of the h
fuobe eval run --suite soul --engine open --looks v1-general --variants recipe,prompt-only
fuobe eval compare latest~1 latest --fail-on clip --threshold 1 # exit 1 on a regression
fuobe eval trash latest # the run's generations to that Fuobe's Trash
+fuobe eval from-skill lamp-turntable # a saved skill as a suite: then run --suite skill-lamp-turntable
```
See [`scripts/eval/README.md`](../scripts/eval/README.md) for the suites, metrics, blind review and
diff --git a/package.json b/package.json
index 63c8692b..35f723d1 100644
--- a/package.json
+++ b/package.json
@@ -28,7 +28,8 @@
"eval:validate": "node scripts/eval/eval.mjs validate",
"eval:setup": "node scripts/eval/eval.mjs setup",
"eval:trash": "node scripts/eval/eval.mjs trash",
- "eval:covers": "node scripts/eval/eval.mjs covers"
+ "eval:covers": "node scripts/eval/eval.mjs covers",
+ "eval:from-skill": "node scripts/eval/eval.mjs from-skill"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.135.0",
diff --git a/scripts/eval/README.md b/scripts/eval/README.md
index 7162f945..d1463379 100644
--- a/scripts/eval/README.md
+++ b/scripts/eval/README.md
@@ -79,6 +79,7 @@ harness measures what a user gets.
| `pnpm eval:validate` | Checks every case file, and that the generated suites match the research |
| `pnpm eval:setup` | Creates the metrics venv with uv (`--identity`, `--download`, `--dinov2`, `--torch-backend`) |
| `pnpm eval:trash <runId>` | Moves the run's generations to the Trash of the Fuobe it ran on (`--dry-run` counts them). The run's folder here keeps its outputs and scores |
+| `pnpm eval:from-skill <name>` | Writes a suite that runs a saved skill with the examples it was made from, one case per engine it runs on, to `local/cases/skill-<name>.json` ([Skills](#saved-skills)) |
Every command takes `--json`. Runs are named by id, by path, or as `latest`, `latest~1` (the run
before) and so on. `pnpm eval:<command> --help` lists each command's options.
@@ -237,6 +238,29 @@ mode On) is skipped with its case, so a "trained" result is always a trained LoR
the trained style as the board's own look (`"presetId": "own-style"`), as a trained moodboard does in
the app.
+## Saved skills
+
+A skill saved with a recipe (Skills → Make a skill, or Save as skill in Assist) can be regression-tested like an
+Original. `pnpm eval:from-skill <name>` reads the skill's recipe from the Fuobe it talks to and writes
+`scripts/eval/local/cases/skill-<name>.json` (git-ignored, since it names your own files):
+
+- one case per engine the skill runs on. Each sends the skill's run route (`POST /api/assist/skills/<name>/run`)
+ that engine and the recipe's examples, and is priced first by the skill's estimate route, so `--max-usd` caps a
+ cloud run as it does any other;
+- a media input with no example, and every media input of a `--engine demo` run, takes a fixture instead;
+- the recipe's checks (kind, takes, shape, length, sound, look) go into the case's note, and the result is scored
+ by its kind (`aesthetic` for a picture, `temporal` for a clip).
+
+```bash
+pnpm eval:from-skill lamp-turntable
+pnpm eval:run --suite skill-lamp-turntable --engine demo # free
+pnpm eval:run --suite skill-lamp-turntable --engine cloud --max-usd 2
+pnpm eval:compare latest~1 latest --fail-on aesthetic # after a model change
+```
+
+A skill that runs a studio tool (Translate & dub, Katana, Captions) isn't measured yet: its steps run inside the
+studio. Write the suite again after you change the skill.
+
## The case format
A suite file follows `cases/case.schema.json`, which editors use for completion. The schema is
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjs
index a63fad76..b061c5db 100644
--- a/scripts/eval/eval.mjs
+++ b/scripts/eval/eval.mjs
@@ -7,7 +7,7 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
-import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
+import { loadSuite, readSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
import { compareRuns, compareText, promote, promoteText, researchRecords } from "./lib/compare.mjs";
import { coversFromMasters, makeCovers, versionCovers } from "./lib/covers.mjs";
import { templateCoversFromMasters, versionTemplateCovers } from "./lib/template-covers.mjs";
@@ -16,6 +16,7 @@ import { METRICS_DIR, REPO_DIR, resultsDir } from "./lib/paths.mjs";
import { RECIPES_FILE } from "./lib/recipes.mjs";
import { writeReport } from "./lib/report.mjs";
import { serveReview, writeReview } from "./lib/review.mjs";
+import { suiteFromSkill, suitePath } from "./lib/from-skill.mjs";
import { DEFAULT_CLOUD_CAP, money, runEval } from "./lib/run.mjs";
import { connect } from "./lib/server.mjs";
import { listRuns, readJsonl, resolveRun } from "./lib/store.mjs";
@@ -98,6 +99,11 @@ pnpm eval:covers --versions [--dry-run] [--public-dir public] [--manifest …]
that presets' manifest). It encodes only a still's small copy that's missing or older than its still (one copied
in by hand), first; --dry-run lists those and fails until they're made.`,
history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
+ "from-skill": `pnpm eval:from-skill <name> [--out <file>] [--url …] [--token …]
+
+ Writes a suite that runs the saved skill <name> with the examples it was made from (its recipe's inputs), one case
+ per engine it runs on, with its checks as the case's note. It goes to scripts/eval/local/cases/skill-<name>.json
+ (git-ignored: it names your own files). Then: pnpm eval:run --suite skill-<name> --engine demo|open|cloud`,
validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
trash: "pnpm eval:trash <runId> [--dry-run] moves the run's generations to that Fuobe's Trash (its results here stay)",
setup: "pnpm eval:setup [--identity] [--asr] [--download [--dinov2] [--scrfd]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv); --asr adds Whisper for the separation suite's word error rate",
@@ -129,7 +135,7 @@ export async function main(argv, io = {}) {
print(rest[0] && HELP[rest[0]] ? HELP[rest[0]] : usage());
return 0;
}
- const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup, trash, covers };
+ const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup, trash, covers, "from-skill": fromSkill };
if (!commands[command]) {
note(`Unknown command “${command}”.\n${usage()}`);
return 2;
@@ -579,3 +585,25 @@ async function setup(args, ctx) {
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exitCode = await main(process.argv.slice(2));
}
+
+/** pnpm eval:from-skill <name>: a saved skill's recipe as a suite (scripts/eval/lib/from-skill.mjs). */
+async function fromSkill(args, ctx) {
+ const { values: v, positionals } = parse(args, {}, { positionals: true });
+ if (v.help) return ctx.print(HELP["from-skill"]), 0;
+ const name = positionals[0]?.replace(/^\//, "");
+ if (!name) throw new Usage("Name the skill: pnpm eval:from-skill <name>");
+ const { client, target } = connect({ url: v.url, token: v.token }, { env: ctx.env, home: ctx.io.home, fetch: ctx.io.fetch });
+ const view = await client.request("GET", `/api/assist/skills/${encodeURIComponent(name)}/recipe`);
+ const suite = suiteFromSkill(view);
+ const file = path.resolve(v.out ?? suitePath(name));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ // Written next to cases/case.schema.json's copy in the repo, so an editor completes it.
+ fs.writeFileSync(file, `${JSON.stringify({ $schema: path.relative(path.dirname(file), path.join(REPO_DIR, "scripts/eval/cases/case.schema.json")), ...suite }, null, 2)}\n`);
+ readSuite(file);
+ if (v.json) ctx.print(JSON.stringify({ file, suite: suite.suite, cases: suite.cases.map((c) => c.id), server: target.url }));
+ else {
+ ctx.print(`Wrote ${path.relative(process.cwd(), file) || file}: ${suite.cases.length} case${suite.cases.length === 1 ? "" : "s"} (${suite.cases.map((c) => c.id).join(", ")})`);
+ ctx.print(`Run it: pnpm eval:run --suite ${v.out ? file : suite.suite} --engine demo (free; then --engine ${view.engines.join(" or ")})`);
+ }
+ return 0;
+}
diff --git a/scripts/eval/lib/from-skill.mjs b/scripts/eval/lib/from-skill.mjs
new file mode 100644
index 00000000..03b25eb9
--- /dev/null
+++ b/scripts/eval/lib/from-skill.mjs
@@ -0,0 +1,95 @@
+// pnpm eval:from-skill <name>: a saved skill's recipe (src/lib/recipe.ts) as an evaluation suite, so the harness can
+// regression-test the skill on the GPU or the cloud under its spend cap. The case runs the skill through its own route
+// (POST /api/assist/skills/<name>/run, priced first by …/estimate) with the recipe's examples as its inputs; the
+// recipe's checks become the case's note and its metrics. Pure: eval.mjs fetches the recipe and writes the file.
+import path from "node:path";
+import { LOCAL_DIR } from "./paths.mjs";
+
+/** A file the harness ships, per input type: a demo run's input, and the input of one that has no example. */
+const FIXTURE = { image: "fixtures/start-frame.png", video: "fixtures/walk-6s.mp4", audio: "fixtures/voice.wav" };
+/** The case's input list per type (cases' `inputs`), and the body's token for its n-th file. */
+const SLOT = { image: "images", video: "videos", audio: "audios" };
+/** What a kind of result is measured by (no reference or prompt of its own: the words vary per skill). */
+const METRICS_FOR = { image: ["aesthetic"], video: ["temporal"], audio: [] };
+
+const slug = (s) =>
+ String(s)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 60) || "skill";
+
+/** Where the suite goes: the git-ignored local cases folder (it holds links to your own files), as skill-<name>.json. */
+export const suitePath = (name) => path.join(LOCAL_DIR, "cases", `skill-${slug(name)}.json`);
+
+/** The steps no other step waits for: what a run ends with. */
+function leaves(steps) {
+ const waited = new Set(steps.flatMap((s) => (s.after === undefined ? [] : Array.isArray(s.after) ? s.after : [s.after])));
+ return steps.filter((s) => !waited.has(s.key));
+}
+
+/** A check's words: "video · 1 · 9:16 · 4.5–5.5 s · no sound · looks like …". */
+function checkWords(key, c) {
+ const parts = [c.kind, c.count !== undefined && `${c.count} take${Number(c.count) === 1 ? "" : "s"}`, c.aspect, Array.isArray(c.seconds) ? `${c.seconds[0]}–${c.seconds[1]} s` : c.seconds !== undefined && `${c.seconds} s`, c.sound === true ? "with sound" : c.sound === false ? "no sound" : null, c.look && `looks like “${c.look}”`];
+ return `${key}: ${parts.filter(Boolean).join(" · ")}`;
+}
+
+/**
+ * The suite for a skill, from what GET /api/assist/skills/<name>/recipe answers (a RecipeView). One case per engine the
+ * skill runs on (each sends that engine to the run route), and one for --engine demo. Throws when the harness can't
+ * measure it: a skill that runs a studio tool (its steps run inside the studio) or one that runs nowhere here.
+ */
+export function suiteFromSkill(view) {
+ const recipe = view?.recipe;
+ if (!recipe || !Array.isArray(recipe.steps)) throw new Error("That skill has no recipe to measure");
+ if (recipe.steps.some((s) => s.kind !== "generate")) throw new Error(`/${view.name} runs a studio tool: the harness measures skills made of generate steps`);
+ if (!view.engines?.length) throw new Error(`/${view.name} doesn't run on this Fuobe${view.why ? `: ${view.why}` : ""}`);
+ const ends = leaves(recipe.steps);
+ const end = ends.at(-1);
+ const checks = recipe.checks ?? {};
+ const kind = ["image", "video", "audio"].includes(checks[end.key]?.kind) ? checks[end.key].kind : (Object.values(checks).find((c) => ["image", "video", "audio"].includes(c?.kind))?.kind ?? "image");
+ // Inputs: each media input's example (a file on that Fuobe, or a link), else a fixture; the demo case uses fixtures.
+ const inputs = {};
+ const demoInputs = {};
+ const values = {};
+ const missing = [];
+ for (const p of recipe.params) {
+ if (SLOT[p.type]) {
+ const slot = SLOT[p.type];
+ const example = typeof p.example === "string" && p.example ? p.example : null;
+ if (!example) missing.push(p.label);
+ (inputs[slot] ??= []).push(example ?? FIXTURE[p.type]);
+ (demoInputs[slot] ??= []).push(FIXTURE[p.type]);
+ values[p.id] = `{{inputs.${slot}.${inputs[slot].length - 1}}}`;
+ } else if (p.example !== undefined) values[p.id] = p.example;
+ else if (p.default !== undefined) values[p.id] = p.default;
+ }
+ const notes = [
+ `Runs the skill /${view.name} through its run route with the examples it was made from.`,
+ ...(Object.keys(checks).length ? [`Its checks: ${Object.entries(checks).map(([k, c]) => checkWords(k, c)).join("; ")}.`] : []),
+ ...(missing.length ? [`No example for ${missing.join(", ")}: a fixture stands in.`] : []),
+ ];
+ const route = `/api/assist/skills/${view.name}/run`;
+ const estimate = `/api/assist/skills/${view.name}/estimate`;
+ const engines = view.engines;
+ const targets = Object.fromEntries([...engines, "demo"].map((e) => [e, { models: [end.request.modelId] }]));
+ const caseFor = (engine) => ({
+ id: `skill-${slug(view.name)}/${engine}`,
+ title: `${view.title} (${engine === "open" ? "your GPU" : "the cloud"})`,
+ ...(Object.keys(inputs).length && { inputs, demoInputs }),
+ submit: { route, estimate, body: { values, engine }, result: "final" },
+ engines: engine === engines[0] ? [engine, "demo"] : [engine],
+ metrics: METRICS_FOR[kind],
+ note: notes.join(" "),
+ });
+ return {
+ suite: `skill-${slug(view.name)}`,
+ title: `Skill: ${view.title}`,
+ description: `Regression test of the saved skill /${view.name}: ${recipe.steps.length} step${recipe.steps.length === 1 ? "" : "s"} (${recipe.steps.map((s) => s.request.modelId).join(" → ")}), written by pnpm eval:from-skill. Write it again after you change the skill.`,
+ original: `skill:${view.name}`,
+ kind,
+ targets,
+ defaults: { seeds: [1001], metrics: METRICS_FOR[kind], timeoutSeconds: 1800 },
+ cases: engines.map(caseFor),
+ };
+}
diff --git a/scripts/eval/lib/run.mjs b/scripts/eval/lib/run.mjs
index 42edba18..21c1f377 100644
--- a/scripts/eval/lib/run.mjs
+++ b/scripts/eval/lib/run.mjs
@@ -93,7 +93,9 @@ async function pool(items, n, fn) {
*/
export const routeResult = (answer, how) => {
const stitch = Array.isArray(answer?.stitches) ? answer.stitches.at(-1) : undefined;
- const items = answer?.items ?? (stitch ? (answer.segments ?? []).flatMap((s) => (s.takes ?? []).map((t) => ({ id: t.look }))) : []);
+ // A saved skill's run (POST /api/assist/skills/<name>/run): its rows in step order, the last one a step nothing waits for.
+ const skillRows = Array.isArray(answer?.runs) ? answer.runs.flatMap((r) => (r.ids ?? []).map((id) => ({ id }))) : null;
+ const items = answer?.items ?? skillRows ?? (stitch ? (answer.segments ?? []).flatMap((s) => (s.takes ?? []).map((t) => ({ id: t.look }))) : []);
const final = answer?.final ?? (stitch?.final ? { id: stitch.final } : items.at(-1));
if (how === "all") return items.length ? items : [final].filter(Boolean);
if (how === "last") return [items.at(-1) ?? final].filter(Boolean);
@@ -457,7 +459,10 @@ async function price(client, job, inputs, ctx) {
const route = job.submit.estimate === false ? null : (job.submit.estimate ?? `${job.submit.route}/estimate`);
if (!route) return { studio: true, costUsd: null, demo: ctx.engine === "demo", modelId: job.model.id };
const e = await client.request("POST", route, { json: body });
- return { studio: true, costUsd: e.costUsd ?? e.totalUsd ?? null, demo: e.demo ?? ctx.engine === "demo", modelId: e.modelId ?? job.model.id, ...(e.modelName && { modelName: e.modelName }), ...(Array.isArray(e.providers) && { providers: e.providers }), notes: e.notes };
+ // A saved skill's estimate (RecipeEstimate): its total, or why it can't run.
+ if (Array.isArray(e.runs) && e.runnable === false) throw new Error([...(e.errors ?? []), ...e.runs.flatMap((r) => r.errors ?? [])][0] ?? "it can't run");
+ const skillTotal = Array.isArray(e.runs) ? e.total : undefined;
+ return { studio: true, costUsd: e.costUsd ?? e.totalUsd ?? skillTotal ?? null, demo: e.demo ?? ctx.engine === "demo", modelId: e.modelId ?? job.model.id, ...(e.modelName && { modelName: e.modelName }), ...(Array.isArray(e.providers) && { providers: e.providers }), notes: e.notes };
}
const p = await client.request("POST", "/api/generations", { json: { ...job.request, inputs }, query: { preview: 1 } });
return { ...p, ...(p.model?.id && { modelId: p.model.id, modelName: p.model.name }) };
diff --git a/tests/eval-from-skill.test.ts b/tests/eval-from-skill.test.ts
new file mode 100644
index 00000000..7bf2b846
--- /dev/null
+++ b/tests/eval-from-skill.test.ts
@@ -0,0 +1,155 @@
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { Writable } from "node:stream";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+/**
+ * Skills W6: `pnpm eval:from-skill <name>` writes a suite from a saved skill's recipe (its examples and checks), and the
+ * harness runs it through the skill's own routes, served over HTTP as a running Fuobe serves them, on the demo provider.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-skill-"));
+const results = path.join(dir, "results");
+process.env.FUOBE_DATA_DIR = path.join(dir, "data");
+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 skills = await import("@/server/skills");
+const recipes = await import("@/server/recipes");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const status = await import("@/app/api/status/route");
+const models = await import("@/app/api/models/route");
+const generations = await import("@/app/api/generations/route");
+const generation = await import("@/app/api/generations/[id]/route");
+const uploads = await import("@/app/api/uploads/route");
+const files = await import("@/app/api/files/[...path]/route");
+const recipeRoute = await import("@/app/api/assist/skills/[name]/recipe/route");
+const estimateRoute = await import("@/app/api/assist/skills/[name]/estimate/route");
+const runRoute = await import("@/app/api/assist/skills/[name]/run/route");
+
+const evalCli = (await import("../scripts/eval/eval.mjs")) as { main: (argv: string[], io?: object) => Promise<number> };
+const fromSkill = (await import("../scripts/eval/lib/from-skill.mjs")) as { suiteFromSkill: (view: unknown) => Record<string, unknown> & { cases: Record<string, unknown>[] } };
+const runner = (await import("../scripts/eval/lib/run.mjs")) as { routeResult: (answer: unknown, how?: string) => { id: string }[] };
+const store = (await import("../scripts/eval/lib/store.mjs")) as { latestJobs: (d: string) => (Record<string, unknown> & { status: string; caseId: string })[] };
+
+const ctx = (params: Record<string, unknown>) => ({ params: Promise.resolve(params) }) as never;
+const ROUTES: [string, RegExp, (req: Request, m: RegExpExecArray) => Promise<Response>][] = [
+ ["GET", /^\/api\/status$/, () => status.GET()],
+ ["GET", /^\/api\/models$/, (r) => models.GET(r)],
+ ["POST", /^\/api\/generations$/, (r) => generations.POST(r)],
+ ["GET", /^\/api\/generations\/([^/]+)$/, (r, m) => generation.GET(r, ctx({ id: m[1] }))],
+ ["POST", /^\/api\/uploads$/, (r) => uploads.POST(r)],
+ ["GET", /^\/api\/files\/(.+)$/, (r, m) => files.GET(r, ctx({ path: m[1].split("/").map(decodeURIComponent) }))],
+ ["GET", /^\/api\/assist\/skills\/([^/]+)\/recipe$/, (r, m) => recipeRoute.GET(r, ctx({ name: m[1] }))],
+ ["POST", /^\/api\/assist\/skills\/([^/]+)\/estimate$/, (r, m) => estimateRoute.POST(r, ctx({ name: m[1] }))],
+ ["POST", /^\/api\/assist\/skills\/([^/]+)\/run$/, (r, m) => runRoute.POST(r, ctx({ name: m[1] }))],
+];
+
+let server: http.Server;
+let base = "";
+let photo = "";
+
+beforeAll(async () => {
+ setSetting("demoMode", "on");
+ 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;
+ server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://fuobe.test");
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ const route = ROUTES.find(([method, re]) => method === req.method && re.test(url.pathname));
+ if (!route) {
+ res.writeHead(404, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ error: "Not found" }));
+ }
+ const body = chunks.length && req.method !== "GET" ? Buffer.concat(chunks) : undefined;
+ const request = new Request(`http://localhost${url.pathname}${url.search}`, { method: req.method, headers: req.headers as Record<string, string>, body });
+ try {
+ const answer = await route[2](request, route[1].exec(url.pathname)!);
+ res.writeHead(answer.status, Object.fromEntries(answer.headers));
+ res.end(Buffer.from(await answer.arrayBuffer()));
+ } catch (e) {
+ res.writeHead(500, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise((r) => server.close(r));
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+async function cli(argv: string[]) {
+ let out = "";
+ let err = "";
+ const sink = (put: (s: string) => void) => new Writable({ write: (c, _e, done) => (put(c.toString()), done()) });
+ const code = await evalCli.main(argv, { stdout: sink((s) => (out += s)), stderr: sink((s) => (err += s)), env: { ...process.env, FUOBE_EVAL_RESULTS: results, FUOBE_URL: base, FUOBE_CONFIG: path.join(dir, "no-config.json"), FUOBE_EVAL_PYTHON: "/nonexistent/python" } });
+ return { code, stdout: out, stderr: err };
+}
+
+const lamp = () => ({
+ 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"], 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 plinth", params: { aspectRatio: "{{aspect}}" } } },
+ ],
+ checks: { scene: { kind: "image", count: 1, aspect: "{{aspect}}", look: "a lamp on a plinth" } },
+});
+
+describe("pnpm eval:from-skill", () => {
+ it("writes a suite from the recipe's examples and checks, and the harness runs it through the skill's routes", async () => {
+ skills.createSkill({ name: "lamp-scene", title: "Lamp scene", description: "A product on a plinth.", body: "x" });
+ recipes.saveRecipe("lamp-scene", lamp());
+ expect((await recipes.verifyRecipe("lamp-scene", "plan")).ok).toBe(true);
+ const out = path.join(dir, "suites", "skill-lamp-scene.json");
+ const w = await cli(["from-skill", "lamp-scene", "--out", out]);
+ expect(w.code, w.stderr).toBe(0);
+ const suite = JSON.parse(fs.readFileSync(out, "utf8"));
+ expect(suite).toMatchObject({ suite: "skill-lamp-scene", kind: "image", targets: { cloud: { models: ["nano-banana-pro"] }, demo: { models: ["nano-banana-pro"] } } });
+ expect(suite.cases).toHaveLength(1);
+ expect(suite.cases[0]).toMatchObject({
+ id: "skill-lamp-scene/cloud",
+ engines: ["cloud", "demo"],
+ inputs: { images: [photo] },
+ demoInputs: { images: ["fixtures/start-frame.png"] },
+ submit: { route: "/api/assist/skills/lamp-scene/run", estimate: "/api/assist/skills/lamp-scene/estimate", body: { engine: "cloud", values: { product: "{{inputs.images.0}}", name: "Lumen desk lamp", aspect: "1:1" } } },
+ });
+ expect(suite.cases[0].note).toMatch(/Its checks: scene: image · 1 take · \{\{aspect\}\} · looks like “a lamp on a plinth”/);
+
+ const r = await cli(["run", "--suite", out, "--engine", "demo", "--no-metrics"]);
+ expect(r.code, r.stderr).toBe(0);
+ const runId = /Run (\S+):/.exec(r.stderr)?.[1] ?? "";
+ const rows = store.latestJobs(path.join(results, runId));
+ expect(rows.map((x) => [x.caseId, x.status])).toEqual([["skill-lamp-scene/cloud", "succeeded"]]);
+ // Its runs carry the skill's stamp, so they're in its History.
+ expect(recipes.skillHistory("lamp-scene").runs).toBe(1);
+ });
+
+ it("reads a skill run's answer: its rows, the last one the result", () => {
+ const answer = { engine: "cloud", demo: true, runs: [{ batchId: "b1", ids: ["g1", "g2", "g3"], href: "/library" }] };
+ expect(runner.routeResult(answer)).toEqual([{ id: "g3" }]);
+ expect(runner.routeResult(answer, "all").map((g) => g.id)).toEqual(["g1", "g2", "g3"]);
+ });
+
+ it("refuses a skill that runs a studio tool, or runs nowhere here", () => {
+ const view = { name: "caps", title: "Caps", engines: ["cloud"], recipe: { params: [], steps: [{ key: "c", kind: "tool", tool: "add_captions", input: {} }] } };
+ expect(() => fromSkill.suiteFromSkill(view)).toThrow(/runs a studio tool/);
+ expect(() => fromSkill.suiteFromSkill({ ...view, engines: [], why: "It runs on cloud models, which aren't available here", recipe: lamp() })).toThrow(/doesn't run on this Fuobe: It runs on cloud models/);
+ });
+});