@womp/spark-agent 17.7.2 → 17.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,264 @@
1
+ // Kakapo multiplexer: one WebSocket endpoint that many clients use as if each had its own Kakapo, backed by one
2
+ // engine. Each client works in a "space" with its own scene; the engine holds one space's scene at a time, and the
3
+ // proxy swaps scenes in before any call that reads or changes the engine's scene, so spaces never see each other.
4
+ //
5
+ // Bench tooling only: not part of the agent API, and not meant for user sessions (no auth, one engine-wide lock).
6
+ //
7
+ // Spaces: connections to ws://<host>:<port>/s/<name> share the named space, which lives until the proxy stops, so a
8
+ // later connection (a bench reading the finished scene) finds what an earlier one built. A connection to any other
9
+ // path gets a space of its own that ends with it. A new space starts with the template scene: the engine's scene
10
+ // when the proxy started, unless one is given.
11
+ //
12
+ // How it works:
13
+ // - A space's scene lives in the engine while the space is resident; when another space needs the engine, the
14
+ // proxy takes the resident scene back with scene_state_get and loads the next one with scene_state_set. The scene
15
+ // JSON carries the camera, so a space's camera comes back with its scene.
16
+ // - Calls run one at a time on the engine, in arrival order. A screenshot keeps the engine until its frame arrives,
17
+ // so no swap lands mid-render.
18
+ // - scene_state_get for a space that is not resident is answered from its stored copy, without a swap.
19
+ // - Calls that do not touch the scene (ping, font and node-type lists) go straight through.
20
+ // - Request ids are rewritten so clients' ids cannot collide; token results (screenshot frames, JSON with a
21
+ // `token`) go back to the connection that sent the token. Engine broadcasts (a method with no params) are
22
+ // dropped: they describe whichever space happened to be resident.
23
+ import { WebSocketServer, WebSocket } from "ws";
24
+ /** Calls that need no scene in the engine, forwarded without waiting for the engine lock. */
25
+ const SCENELESS = new Set(["ping", "get_fonts", "get_node_types", "get_procedural_nodes"]);
26
+ /** How long a screenshot (or other token call) may hold the engine waiting for its frame. */
27
+ const TOKEN_HOLD_MS = 180_000;
28
+ export class KakapoMux {
29
+ options;
30
+ stats = { connections: 0, swaps: 0, calls: 0, waitMs: 0, swapMs: 0 };
31
+ server;
32
+ engine;
33
+ nextUpstreamId = 1;
34
+ nextClientId = 1;
35
+ pending = new Map();
36
+ tokenOwner = new Map();
37
+ tokenWaiters = new Map();
38
+ clients = new Set();
39
+ spaces = new Map();
40
+ resident;
41
+ template = "";
42
+ lockTail = Promise.resolve();
43
+ log;
44
+ constructor(options) {
45
+ this.options = options;
46
+ this.log = options.log ?? (() => undefined);
47
+ }
48
+ get port() {
49
+ const address = this.server?.address();
50
+ return typeof address === "object" && address ? address.port : this.options.port;
51
+ }
52
+ /** Named spaces and their stored scenes; the resident one's copy is stale until it is taken out. */
53
+ get spaceNames() { return [...this.spaces.keys()]; }
54
+ async start() {
55
+ const engine = new WebSocket(this.options.upstream, { perMessageDeflate: false, maxPayload: 1 << 30 });
56
+ await new Promise((resolve, reject) => { engine.once("open", resolve); engine.once("error", reject); });
57
+ this.engine = engine;
58
+ engine.on("message", (data, isBinary) => this.fromEngine(data, isBinary));
59
+ engine.on("close", () => {
60
+ for (const p of this.pending.values())
61
+ p.reject(new Error("Kakapo closed the connection."));
62
+ this.pending.clear();
63
+ for (const client of this.clients)
64
+ client.socket.close(1011, "engine closed");
65
+ });
66
+ engine.on("error", () => undefined);
67
+ this.template = this.options.template ?? String(await this.engineCall("scene_state_get"));
68
+ this.server = new WebSocketServer({ port: this.options.port, host: this.options.host ?? "127.0.0.1", perMessageDeflate: false, maxPayload: 1 << 30 });
69
+ await new Promise((resolve, reject) => { this.server.once("listening", resolve); this.server.once("error", reject); });
70
+ this.server.on("connection", (socket, request) => this.accept(socket, request.url ?? "/"));
71
+ }
72
+ async stop() {
73
+ for (const client of this.clients)
74
+ client.socket.terminate();
75
+ await new Promise((resolve) => this.server ? this.server.close(() => resolve()) : resolve());
76
+ this.engine?.close();
77
+ }
78
+ accept(socket, url) {
79
+ const id = this.nextClientId++;
80
+ const match = /^\/s\/([^/?#]+)/.exec(url);
81
+ const name = match ? decodeURIComponent(match[1]) : undefined;
82
+ let space = name === undefined ? undefined : this.spaces.get(name);
83
+ if (!space) {
84
+ space = { name: name ?? `#${id}`, named: name !== undefined, scene: this.template, connections: 0 };
85
+ if (name !== undefined)
86
+ this.spaces.set(name, space);
87
+ }
88
+ space.connections++;
89
+ const client = { id, socket, space, tokens: new Set() };
90
+ this.clients.add(client);
91
+ this.stats.connections++;
92
+ this.log(`connection ${id} opened on ${space.name} (${this.clients.size} open)`);
93
+ socket.on("message", (data, isBinary) => {
94
+ if (isBinary)
95
+ return;
96
+ let message;
97
+ try {
98
+ message = JSON.parse(data.toString());
99
+ }
100
+ catch {
101
+ return;
102
+ }
103
+ this.handle(client, message).catch((error) => this.reply(client, message.id, undefined, error));
104
+ });
105
+ socket.on("close", () => {
106
+ this.clients.delete(client);
107
+ client.space.connections--;
108
+ for (const token of client.tokens)
109
+ this.tokenOwner.delete(token);
110
+ // A private space ends here; left resident, its scene simply stays in the engine until the next swap.
111
+ if (!client.space.named && this.resident === client.space)
112
+ this.resident = undefined;
113
+ this.log(`connection ${id} closed (${this.clients.size} open)`);
114
+ });
115
+ socket.on("error", () => undefined);
116
+ }
117
+ async handle(client, message) {
118
+ const { id, method, params = [] } = message;
119
+ if (typeof method !== "string")
120
+ return;
121
+ this.stats.calls++;
122
+ if (SCENELESS.has(method))
123
+ return this.forward(client, id, method, params);
124
+ if (method === "scene_state_get" && this.resident !== client.space) {
125
+ // Read the copy only once queued work has run: an earlier call may still change this space's scene.
126
+ return this.withEngine(client, false, async () => this.reply(client, id, this.resident === client.space ? await this.engineCall("scene_state_get") : client.space.scene));
127
+ }
128
+ const tokens = tokensOf(params);
129
+ return this.withEngine(client, true, async () => {
130
+ for (const token of tokens) {
131
+ this.tokenOwner.set(token, client);
132
+ client.tokens.add(token);
133
+ }
134
+ const frames = tokens.map((token) => new Promise((resolve) => {
135
+ const timer = setTimeout(() => { this.tokenWaiters.delete(token); resolve(); }, TOKEN_HOLD_MS);
136
+ this.tokenWaiters.set(token, () => { clearTimeout(timer); this.tokenWaiters.delete(token); resolve(); });
137
+ }));
138
+ try {
139
+ const t0 = Date.now();
140
+ this.log(`rpc start space=${client.space.name} method=${method} tokens=${tokens.length}`);
141
+ const reply = await this.engineSend(method, params);
142
+ this.send(client, { ...reply, id });
143
+ // A failed call delivers no frame; anything else keeps the engine until its frames are back.
144
+ if (!reply.error)
145
+ await Promise.all(frames);
146
+ this.log(`rpc done space=${client.space.name} method=${method} ms=${Date.now() - t0}${reply.error ? ` err=${JSON.stringify(reply.error).slice(0, 120)}` : ""}`);
147
+ }
148
+ finally {
149
+ for (const token of tokens)
150
+ this.tokenWaiters.get(token)?.();
151
+ }
152
+ });
153
+ }
154
+ /** Runs `work` with the engine to this client's space alone, swapping its scene in first when `swap` is set. */
155
+ withEngine(client, swap, work) {
156
+ const queued = Date.now();
157
+ const run = this.lockTail.then(async () => {
158
+ this.stats.waitMs += Date.now() - queued;
159
+ if (!this.clients.has(client))
160
+ return;
161
+ if (swap && this.resident !== client.space)
162
+ await this.swapIn(client.space);
163
+ await work();
164
+ });
165
+ this.lockTail = run.catch(() => undefined);
166
+ return run;
167
+ }
168
+ async swapIn(space) {
169
+ const started = Date.now();
170
+ const out = this.resident;
171
+ this.log(`swap start out=${out?.name ?? "none"} in=${space.name} inLen=${space.scene.length}`);
172
+ // A private space whose connections are gone has nothing to keep.
173
+ if (out && (out.named || out.connections > 0))
174
+ out.scene = String(await this.engineCall("scene_state_get"));
175
+ this.resident = undefined;
176
+ await this.engineCall("scene_state_set", [space.scene]);
177
+ this.resident = space;
178
+ this.stats.swaps++;
179
+ this.stats.swapMs += Date.now() - started;
180
+ this.log(`swap done in=${space.name} ms=${Date.now() - started}`);
181
+ }
182
+ async forward(client, id, method, params) {
183
+ const reply = await this.engineSend(method, params);
184
+ this.send(client, { ...reply, id });
185
+ }
186
+ async engineCall(method, params = []) {
187
+ const reply = await this.engineSend(method, params);
188
+ if (reply.error)
189
+ throw new Error(`Kakapo ${method}: ${typeof reply.error === "string" ? reply.error : reply.error.message ?? JSON.stringify(reply.error)}`);
190
+ return reply.result;
191
+ }
192
+ engineSend(method, params) {
193
+ const engine = this.engine;
194
+ if (!engine || engine.readyState !== WebSocket.OPEN)
195
+ return Promise.reject(new Error("Kakapo is not connected."));
196
+ const id = this.nextUpstreamId++;
197
+ return new Promise((resolve, reject) => {
198
+ this.pending.set(id, { resolve, reject });
199
+ engine.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }), (error) => {
200
+ if (error && this.pending.delete(id))
201
+ reject(error);
202
+ });
203
+ });
204
+ }
205
+ fromEngine(data, isBinary) {
206
+ const bytes = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
207
+ if (isBinary) {
208
+ if (bytes.length < 48)
209
+ return;
210
+ const end = bytes.subarray(0, 16).indexOf(0);
211
+ const token = bytes.subarray(0, end === -1 ? 16 : end).toString("utf8");
212
+ this.deliver(token, (socket) => socket.send(bytes, { binary: true }));
213
+ return;
214
+ }
215
+ let message;
216
+ try {
217
+ message = JSON.parse(bytes.toString("utf8"));
218
+ }
219
+ catch {
220
+ return;
221
+ }
222
+ const isReply = Object.hasOwn(message, "result") || Object.hasOwn(message, "error") ||
223
+ (typeof message.method === "string" && !Object.hasOwn(message, "params"));
224
+ if (typeof message.id === "number" && isReply && this.pending.has(message.id)) {
225
+ const pending = this.pending.get(message.id);
226
+ this.pending.delete(message.id);
227
+ pending.resolve(message);
228
+ return;
229
+ }
230
+ if (typeof message.token === "string")
231
+ this.deliver(message.token, (socket) => socket.send(bytes.toString("utf8")));
232
+ }
233
+ deliver(token, send) {
234
+ const owner = this.tokenOwner.get(token);
235
+ if (owner) {
236
+ this.tokenOwner.delete(token);
237
+ owner.tokens.delete(token);
238
+ if (owner.socket.readyState === WebSocket.OPEN)
239
+ send(owner.socket);
240
+ }
241
+ this.tokenWaiters.get(token)?.();
242
+ }
243
+ reply(client, id, result, error) {
244
+ if (id === undefined || id === null)
245
+ return;
246
+ if (error !== undefined)
247
+ this.send(client, { jsonrpc: "2.0", id, error: { code: -32000, message: error instanceof Error ? error.message : String(error) } });
248
+ else
249
+ this.send(client, { jsonrpc: "2.0", id, result });
250
+ }
251
+ send(client, message) {
252
+ if (client.socket.readyState === WebSocket.OPEN)
253
+ client.socket.send(JSON.stringify(message));
254
+ }
255
+ }
256
+ /** Tokens a call asks results for: Kakapo's token calls take an array of 1-15 byte strings as the first parameter. */
257
+ export function tokensOf(params) {
258
+ if (!Array.isArray(params) || !Array.isArray(params[0]))
259
+ return [];
260
+ const list = params[0];
261
+ if (!list.length || !list.every((t) => typeof t === "string" && t.length > 0 && Buffer.byteLength(t) <= 15))
262
+ return [];
263
+ return list;
264
+ }
@@ -3,7 +3,7 @@ import { type SceneHost, type SceneScreenshotOptions } from "../capabilities/sce
3
3
  import type { ArtifactRef, SparkInvocationContext } from "../capabilities.js";
4
4
  import type { MaterialsHost, MaterialStatus } from "../capabilities/materials.js";
5
5
  export type MaterialInspectionOptions = {
6
- views: SceneScreenshotOptions[];
6
+ views: Pick<SceneScreenshotOptions, "camera">[];
7
7
  /** Maximum compilation/resource wait, milliseconds. Defaults to 60 seconds. */
8
8
  timeoutMs?: number;
9
9
  };
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
- import { screenshotOptions } from "../capabilities/scene.js";
3
- export const materialInspectionSchema = z.object({ views: z.array(screenshotOptions).min(1), timeoutMs: z.number().int().positive().max(300000).optional() }).strict();
2
+ import { cameraScreenshotOptions } from "../capabilities/scene.js";
3
+ export const materialInspectionSchema = z.object({ views: z.array(cameraScreenshotOptions).min(1), timeoutMs: z.number().int().positive().max(300000).optional() }).strict();
4
4
  export async function inspectMaterial(host, captures, options, context) {
5
5
  const action = async () => {
6
6
  const frames = [];
@@ -1,6 +1,6 @@
1
1
  export { createSparkCapabilities, createSceneScriptCapabilities, type SparkHosts, type SparkRunFacts, } from "./spark-capabilities.js";
2
2
  export type { ArtifactRef, ExecutionReceipt, SparkArtifactResolver, SparkCapabilities, SparkInvocationContext, SparkSkill, } from "./capabilities.js";
3
- export type { WompSceneApi, SceneHost, SceneHealthHost, SceneSnapshot, SceneScreenshotOptions, } from "./capabilities/scene.js";
3
+ export type { WompSceneApi, SceneHost, SceneHealthHost, SceneSnapshot, SceneScreenshotOptions, SceneScreenshotFitted, SceneScreenshotFit, SceneScreenshotRequest, } from "./capabilities/scene.js";
4
4
  export type { WompSceneDraft } from "./capabilities/scene-draft.js";
5
5
  export type { AssetImportsHost, MeshImportRequest, ImageImportRequest, AssetImportResult, MeshImportRetryRequest, AssetImportWaitOptions, WompAssetImportsApi, } from "./capabilities/asset-imports.js";
6
6
  export type { AssetsHost, AssetListOptions, ConversationAsset, AssetPage, WompAssetsApi, } from "./capabilities/assets.js";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, statSync } from "node:fs";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { loadEnvFile } from "node:process";
5
+ import { parseArgs } from "node:util";
6
+ import path from "node:path";
7
+ import { SPARK_MODELS } from "./models.js";
8
+ import { compareQualityRuns, generateBenchSheet, listQualityCases, loadQualityCase, pairwiseReportMarkdown, reportMarkdown, runQualityBench, scoreExistingBenchRun } from "./quality-bench.js";
9
+ async function main() {
10
+ const { values } = parseArgs({ options: {
11
+ cases: { type: "string" }, only: { type: "string" }, split: { type: "string" },
12
+ repeat: { type: "string", default: "2" }, parallel: { type: "string", default: "32" },
13
+ model: { type: "string", default: "gpt-6.2-astra" }, reasoning: { type: "string", default: "xhigh" },
14
+ judge: { type: "boolean", default: false },
15
+ "kakapo-url": { type: "string" }, output: { type: "string" }, baseline: { type: "string" },
16
+ compare: { type: "string" }, ab: { type: "string" }, "score-only": { type: "string" }, sheet: { type: "string" },
17
+ focus: { type: "string" }, "view-filter": { type: "string" },
18
+ "timeout-minutes": { type: "string", default: "40" },
19
+ help: { type: "boolean" },
20
+ } });
21
+ const all = await listQualityCases();
22
+ if (values.help) {
23
+ console.log(`quality-bench [options]
24
+
25
+ Builds each case in parallel on one Kakapo through an in-process kakapo-mux, renders standardized same-camera views
26
+ (fixed 3/4, 4 sides, 5-view turntable, 2x2 grid, close-ups), counts deterministic SDF structure, and outputs one visual
27
+ comparison sheet per repeat (sheet-run-<n>.png) with per-phase timings and results.csv. AI judging is opt-in via --judge.
28
+ WARNING: makes paid Spark model calls (and AI judge calls when --judge or --ab is passed) and replaces the Kakapo scene.
29
+
30
+ --only <a,b> Run only these case IDs (alias for --cases); default: all (${all.join(", ")})
31
+ --cases <a,b> Same as --only
32
+ --split <tune|holdout> Filter cases by split in case.json (ignored if --only/--cases is set)
33
+ --repeat <n> Builds per case; default 2
34
+ --parallel <n> Builds at once; default 32
35
+ --model <id> Default: gpt-6.2-astra. Models: ${SPARK_MODELS.map((model) => model.id).join(", ")}
36
+ --reasoning <effort> Default: xhigh
37
+ --judge Enable AI vision judges (likeness + close-up checks); default: false
38
+ --kakapo-url <url> Default: KAKAPO_URL from .env, or ws://127.0.0.1:5502
39
+ --output <directory> New directory only; default: .spark/quality/<timestamp>
40
+ --baseline <dir|report> Baseline directory (for --ab) or report.json (for metric diffs)
41
+ --sheet <run-dir> Generate full-res sheet-run-<n>.png files for an existing run directory
42
+ --compare <report.json> Only rewrite report.md of --compare against --baseline; no builds
43
+ --ab <candidate-dir> Blinded order-swapped pairwise judge against --baseline directory; no builds
44
+ --score-only <run-dir> Re-render/score saved scene.json files in <run-dir> (recover after Kakapo crash)
45
+ --timeout-minutes <n> Per-build timeout; default 40`);
46
+ return;
47
+ }
48
+ if (values.sheet) {
49
+ const sheets = await generateBenchSheet(path.resolve(values.sheet));
50
+ console.log(sheets.length ? sheets.map((s) => `Sheet: ${s}`).join("\n") : "Sheets: none");
51
+ return;
52
+ }
53
+ if (values["score-only"]) {
54
+ if (existsSync(".env"))
55
+ loadEnvFile();
56
+ for (const k of ["ANTHROPIC_API_KEY", "GEMINI_API_KEY"])
57
+ if (!process.env[k]?.trim())
58
+ throw new Error(`${k} is required in the environment or .env.`);
59
+ const baseline = values.baseline ? JSON.parse(await readFile(values.baseline, "utf8")) : undefined;
60
+ const outDir = path.resolve(values["score-only"]);
61
+ await scoreExistingBenchRun(outDir, {
62
+ kakapoUrl: values["kakapo-url"] ?? process.env.KAKAPO_URL ?? "ws://127.0.0.1:5502",
63
+ baseline,
64
+ });
65
+ console.log(await readFile(path.join(outDir, "report.md"), "utf8"));
66
+ return;
67
+ }
68
+ if (values.ab) {
69
+ if (!values.baseline)
70
+ throw new Error("--ab needs --baseline <baseline-dir>.");
71
+ if (existsSync(".env"))
72
+ loadEnvFile();
73
+ if (!process.env.GEMINI_API_KEY?.trim())
74
+ throw new Error("GEMINI_API_KEY is required in the environment or .env.");
75
+ const report = await compareQualityRuns(path.resolve(values.baseline), path.resolve(values.ab), {
76
+ focus: values.focus,
77
+ viewFilter: values["view-filter"],
78
+ });
79
+ const o = report.overall;
80
+ const decisive = o.candidateWins + o.baselineWins;
81
+ console.log(pairwiseReportMarkdown(report));
82
+ console.log(`[autoresearch-begin]
83
+ candidate_win_rate: ${decisive ? (o.candidateWins / decisive).toFixed(3) : "0.500"}
84
+ candidate_wins: ${o.candidateWins}
85
+ baseline_wins: ${o.baselineWins}
86
+ ties: ${o.ties}
87
+ pairs: ${o.pairs}
88
+ order_consistency: ${o.pairs ? (o.consistent / o.pairs).toFixed(3) : "0.000"}
89
+ [autoresearch-end]`);
90
+ return;
91
+ }
92
+ if (values.compare) {
93
+ if (!values.baseline)
94
+ throw new Error("--compare needs --baseline.");
95
+ const report = JSON.parse(await readFile(values.compare, "utf8"));
96
+ const baseline = JSON.parse(await readFile(values.baseline, "utf8"));
97
+ const out = path.join(path.dirname(values.compare), "report.md");
98
+ await writeFile(out, reportMarkdown(report, baseline));
99
+ console.log(out);
100
+ return;
101
+ }
102
+ const model = SPARK_MODELS.find((item) => item.id === values.model);
103
+ if (!model)
104
+ throw new Error("Select a supported model using --model. See --help.");
105
+ const reasoning = values.reasoning;
106
+ if (!model.reasoningEfforts.includes(reasoning))
107
+ throw new Error("Unsupported reasoning effort for this model.");
108
+ const requestedCases = values.only ?? values.cases;
109
+ let cases = requestedCases ? requestedCases.split(",").map((c) => c.trim()).filter(Boolean) : all;
110
+ if (!requestedCases && values.split && values.split !== "all") {
111
+ const loaded = await Promise.all(all.map(loadQualityCase));
112
+ cases = loaded.filter((c) => c.split === values.split).map((c) => c.id);
113
+ if (!cases.length)
114
+ throw new Error(`No cases in split "${values.split}".`);
115
+ }
116
+ for (const c of cases)
117
+ if (!all.includes(c))
118
+ throw new Error(`Unknown case ${c}; cases: ${all.join(", ")}.`);
119
+ const repeat = Number(values.repeat), parallel = Number(values.parallel);
120
+ if (!Number.isSafeInteger(repeat) || repeat < 1 || !Number.isSafeInteger(parallel) || parallel < 1)
121
+ throw new Error("--repeat and --parallel take positive integers.");
122
+ const timeoutMs = Number(values["timeout-minutes"]) * 60_000;
123
+ if (existsSync(".env"))
124
+ loadEnvFile();
125
+ const key = { openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY", google: "GEMINI_API_KEY" }[model.provider];
126
+ const requiredKeys = new Set([key, ...(values.judge ? ["ANTHROPIC_API_KEY", "GEMINI_API_KEY"] : [])]);
127
+ for (const k of requiredKeys)
128
+ if (!process.env[k]?.trim())
129
+ throw new Error(`${k} is required in the environment or .env.`);
130
+ let baselineReport;
131
+ if (values.baseline) {
132
+ const resolvedBase = path.resolve(values.baseline);
133
+ const rp = existsSync(resolvedBase) && statSync(resolvedBase).isDirectory() ? path.join(resolvedBase, "report.json") : resolvedBase;
134
+ if (existsSync(rp))
135
+ baselineReport = JSON.parse(await readFile(rp, "utf8"));
136
+ }
137
+ const controller = new AbortController();
138
+ const stop = () => controller.abort(new Error("Benchmark interrupted."));
139
+ process.once("SIGINT", stop);
140
+ process.once("SIGTERM", stop);
141
+ const output = path.resolve(values.output ?? `.spark/quality/${new Date().toISOString().replaceAll(":", "-")}`);
142
+ console.log(`Results: ${output}`);
143
+ const report = await runQualityBench({
144
+ cases, repeat, parallel, judge: values.judge,
145
+ settings: { modelId: model.id, reasoningEffort: reasoning },
146
+ kakapoUrl: values["kakapo-url"] ?? process.env.KAKAPO_URL ?? "ws://127.0.0.1:5502",
147
+ output, timeoutMs, signal: controller.signal,
148
+ });
149
+ if (baselineReport)
150
+ await writeFile(path.join(output, "report.md"), reportMarkdown(report, baselineReport));
151
+ console.log(await readFile(path.join(output, "report.md"), "utf8"));
152
+ for (let i = 1; i <= repeat; i++)
153
+ console.log(`Visual sheet: ${path.join(output, `sheet-run-${i}.png`)}`);
154
+ process.exit(0);
155
+ }
156
+ main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
@@ -0,0 +1,13 @@
1
+ import type { QualityRunResult } from "./quality-bench.js";
2
+ export interface SheetRow {
3
+ caseId: string;
4
+ run: number;
5
+ runDir: string;
6
+ refFile: string;
7
+ result: QualityRunResult;
8
+ }
9
+ /**
10
+ * Generates one full-resolution lossless PNG sheet per repeat (`sheet-run-<n>.png`) with zero padding between tiles:
11
+ * [Reference | Fixed 3/4 | Front | Back | Top] per case row, plus a header bar with timings, cost, structure, and optional judge scores.
12
+ */
13
+ export declare function buildMasterSheet(outputDir: string, rows: SheetRow[]): Promise<string[]>;
@@ -0,0 +1,120 @@
1
+ // Full-resolution, zero-padding lossless PNG image sheets (`sheet-run-<n>.png`) for quality-bench runs.
2
+ // One sheet is exported per repeat/run; works with or without AI judging (--judge).
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ const esc = (s) => String(s ?? "")
6
+ .replaceAll("&", "&amp;")
7
+ .replaceAll("<", "&lt;")
8
+ .replaceAll(">", "&gt;")
9
+ .replaceAll('"', "&quot;");
10
+ function fmtSec(ms) {
11
+ if (typeof ms !== "number" || !Number.isFinite(ms))
12
+ return "–";
13
+ return ms >= 10_000 ? `${Math.round(ms / 1000)}s` : `${(ms / 1000).toFixed(1)}s`;
14
+ }
15
+ function fmtNum(v, digits = 2) {
16
+ return typeof v === "number" && Number.isFinite(v) ? v.toFixed(digits) : "–";
17
+ }
18
+ /**
19
+ * Generates one full-resolution lossless PNG sheet per repeat (`sheet-run-<n>.png`) with zero padding between tiles:
20
+ * [Reference | Fixed 3/4 | Front | Back | Top] per case row, plus a header bar with timings, cost, structure, and optional judge scores.
21
+ */
22
+ export async function buildMasterSheet(outputDir, rows) {
23
+ if (!rows.length)
24
+ return [];
25
+ const byRun = new Map();
26
+ for (const row of rows) {
27
+ const list = byRun.get(row.run) ?? [];
28
+ list.push(row);
29
+ byRun.set(row.run, list);
30
+ }
31
+ const outFiles = [];
32
+ for (const run of [...byRun.keys()].sort((a, b) => a - b)) {
33
+ const runRows = byRun.get(run).slice().sort((a, b) => a.caseId.localeCompare(b.caseId));
34
+ const outFile = path.join(outputDir, `sheet-run-${run}.png`);
35
+ await renderSheetFile(outFile, runRows);
36
+ outFiles.push(outFile);
37
+ }
38
+ return outFiles;
39
+ }
40
+ async function renderSheetFile(outFile, rows) {
41
+ const { default: sharp } = await import("sharp");
42
+ let tileW = 1280, tileH = 720;
43
+ for (const row of rows) {
44
+ const probe = [
45
+ path.join(row.runDir, "fixed-3q.jpg"),
46
+ path.join(row.runDir, "turntable-front.jpg"),
47
+ path.join(row.runDir, "turntable-quarter-l.jpg"),
48
+ ].find((p) => existsSync(p));
49
+ if (probe) {
50
+ const meta = await sharp(probe).metadata();
51
+ if (meta.width && meta.height) {
52
+ tileW = meta.width;
53
+ tileH = meta.height;
54
+ break;
55
+ }
56
+ }
57
+ }
58
+ const cols = 5, headerH = 64;
59
+ const rowW = cols * tileW;
60
+ const rowH = headerH + tileH;
61
+ const totalH = rows.length * rowH;
62
+ const composites = [];
63
+ for (let rIdx = 0; rIdx < rows.length; rIdx++) {
64
+ const row = rows[rIdx];
65
+ const y0 = rIdx * rowH;
66
+ const r = row.result;
67
+ const t = r.timings;
68
+ const timingStr = t
69
+ ? `build ${fmtSec(t.buildMs)} | render ${fmtSec(t.renderMs)}${t.judgeMs ? ` | judge ${fmtSec(t.judgeMs)}` : ""} | total ${fmtSec(r.durationMs)}`
70
+ : `total ${fmtSec(r.durationMs)}`;
71
+ const structStr = r.structure
72
+ ? `areas ${r.structure.areas} | curves ${r.structure.curves} | cubes ${r.structure.cubes} | seams ${r.structure.seams} | rib ${r.structure.ribbingDepth} | clusters ${r.structure.floatingClusters}`
73
+ : "";
74
+ const judgeStr = [
75
+ r.likeness ? `likeness ${fmtNum(r.likeness.mean)}` : "",
76
+ ...Object.entries(r.checks ?? {}).map(([k, v]) => `${k} ${fmtNum(v.mean)}`),
77
+ ].filter(Boolean).join(" | ");
78
+ const costStr = r.costUsd != null ? `$${r.costUsd.toFixed(2)}` : "$–";
79
+ const statusColor = r.error ? "#ef4444" : "#22c55e";
80
+ const headerSvg = Buffer.from(`<svg width="${rowW}" height="${headerH}">
81
+ <rect x="0" y="0" width="${rowW}" height="${headerH}" fill="#181b22"/>
82
+ <circle cx="26" cy="32" r="8" fill="${statusColor}"/>
83
+ <text x="46" y="28" font-family="Arial,sans-serif" font-size="22" font-weight="bold" fill="#f8fafc">${esc(row.caseId)} / run-${row.run} (${esc(r.status)}, ${esc(costStr)}, ${r.steps} steps) · ${esc(timingStr)}${judgeStr ? ` · ${esc(judgeStr)}` : ""}</text>
84
+ <text x="46" y="52" font-family="Arial,sans-serif" font-size="18" fill="#94a3b8">${esc(r.error ? `Error: ${r.error.slice(0, 180)}` : structStr)}</text>
85
+ </svg>`);
86
+ composites.push({ input: headerSvg, left: 0, top: y0 });
87
+ const candidates = [
88
+ ["REFERENCE", [row.refFile]],
89
+ ["FIXED 3/4", [path.join(row.runDir, "fixed-3q.jpg"), path.join(row.runDir, "turntable-quarter-l.jpg")]],
90
+ ["FRONT", [path.join(row.runDir, "fixed-front.jpg"), path.join(row.runDir, "turntable-front.jpg"), path.join(row.runDir, "side-nx.jpg")]],
91
+ ["BACK", [path.join(row.runDir, "fixed-back.jpg"), path.join(row.runDir, "turntable-back.jpg"), path.join(row.runDir, "side-px.jpg")]],
92
+ ["TOP / ISO", [path.join(row.runDir, "fixed-top.jpg"), path.join(row.runDir, "turntable-top.jpg"), path.join(row.runDir, "turntable-grid.jpg")]],
93
+ ];
94
+ for (let cIdx = 0; cIdx < candidates.length; cIdx++) {
95
+ const [label, paths] = candidates[cIdx];
96
+ const file = paths.find((p) => existsSync(p));
97
+ const left = cIdx * tileW;
98
+ const top = y0 + headerH;
99
+ const badge = Buffer.from(`<svg width="${tileW}" height="${tileH}"><rect x="12" y="12" width="156" height="34" rx="5" fill="rgba(15,18,25,0.75)"/><text x="22" y="35" font-family="Arial,sans-serif" font-size="20" font-weight="bold" fill="#f8fafc">${esc(label)}</text></svg>`);
100
+ const tileBuf = file
101
+ ? await sharp(file)
102
+ .resize(tileW, tileH, { fit: "contain", background: { r: 245, g: 247, b: 250, alpha: 1 } })
103
+ .composite([{ input: badge, top: 0, left: 0 }])
104
+ .png()
105
+ .toBuffer()
106
+ : await sharp({ create: { width: tileW, height: tileH, channels: 3, background: { r: 30, g: 34, b: 44 } } })
107
+ .composite([{ input: badge, top: 0, left: 0 }])
108
+ .png()
109
+ .toBuffer();
110
+ composites.push({ input: tileBuf, left, top });
111
+ }
112
+ }
113
+ await sharp({
114
+ create: { width: rowW, height: totalH, channels: 3, background: { r: 12, g: 14, b: 19 } },
115
+ limitInputPixels: false,
116
+ })
117
+ .composite(composites)
118
+ .png({ compressionLevel: 6 })
119
+ .toFile(outFile);
120
+ }