@womp/spark-agent 17.7.3 → 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.
@@ -1,5 +1,8 @@
1
1
  import type { KakapoAPI } from "@womp/kakapo-sdk";
2
- import type { SceneScreenshotOptions } from "./capabilities/scene.js";
2
+ import { type SceneScreenshotOptions } from "./capabilities/scene.js";
3
3
  import type { ExecutionScreenshot } from "./types.js";
4
- /** Convert explicit cameras at the native boundary; never fit or move the default view. */
4
+ /**
5
+ * Convert explicit cameras at the native boundary; never fit or move the default view. A fitted camera is refitted to
6
+ * the engine's capture aspect, and captured again if the image comes back at another aspect.
7
+ */
5
8
  export declare function captureSdkSceneScreenshot(api: KakapoAPI, input: SceneScreenshotOptions): Promise<ExecutionScreenshot>;
@@ -1,18 +1,40 @@
1
+ import { fitSceneCamera } from "./capabilities/scene.js";
1
2
  import { INTERNAL_UNITS_PER_MM, sceneUnitMultiplier, toEnginePosition } from "./coordinates.js";
2
- /** Convert explicit cameras at the native boundary; never fit or move the default view. */
3
+ /** Width / height of the last capture from each engine; the render size follows the viewer, so it is learned, not assumed. */
4
+ const captureAspects = new WeakMap();
5
+ /**
6
+ * Convert explicit cameras at the native boundary; never fit or move the default view. A fitted camera is refitted to
7
+ * the engine's capture aspect, and captured again if the image comes back at another aspect.
8
+ */
3
9
  export async function captureSdkSceneScreenshot(api, input) {
10
+ const remember = (image) => {
11
+ if (image.width > 0 && image.height > 0)
12
+ captureAspects.set(api, image.width / image.height);
13
+ return image;
14
+ };
4
15
  if (!input.camera)
5
- return api.captureScreenshot({ timeoutMs: 30_000 });
16
+ return remember(await api.captureScreenshot({ timeoutMs: 30_000 }));
6
17
  // Read authoritative project units without returning another full-scene copy.
7
18
  await api.refreshScene({ returnScene: false });
8
19
  const units = sceneUnitMultiplier(api.getSceneProperties().unit_multiplier);
9
- const camera = {
10
- ...input.camera,
11
- position: toEnginePosition(input.camera.position, units),
12
- target: toEnginePosition(input.camera.target, units),
20
+ const capture = async (scene) => {
21
+ const camera = {
22
+ ...scene,
23
+ position: toEnginePosition(scene.position, units),
24
+ target: toEnginePosition(scene.target, units),
25
+ };
26
+ if (camera.orthographicWidth !== undefined)
27
+ camera.orthographicWidth *= INTERNAL_UNITS_PER_MM / units;
28
+ await api.setCamera(camera);
29
+ return remember(await api.captureScreenshot({ camera, timeoutMs: 30_000 }));
13
30
  };
14
- if (camera.orthographicWidth !== undefined)
15
- camera.orthographicWidth *= INTERNAL_UNITS_PER_MM / units;
16
- await api.setCamera(camera);
17
- return api.captureScreenshot({ camera, timeoutMs: 30_000 });
31
+ const { fitted } = input;
32
+ if (!fitted)
33
+ return capture(input.camera);
34
+ const aspect = captureAspects.get(api) ?? 16 / 9;
35
+ const image = await capture(fitSceneCamera(fitted, aspect));
36
+ const actual = image.width / image.height;
37
+ return Number.isFinite(actual) && actual > 0 && Math.abs(actual - aspect) > 0.01 * aspect
38
+ ? capture(fitSceneCamera(fitted, actual))
39
+ : image;
18
40
  }
@@ -9,7 +9,8 @@ export class SqliteSparkStore {
9
9
  ownershipToken;
10
10
  constructor(path, artifactBaseUrl = "/agent/artifacts") {
11
11
  this.artifactBaseUrl = artifactBaseUrl;
12
- mkdirSync(dirname(path), { recursive: true });
12
+ if (path !== ":memory:")
13
+ mkdirSync(dirname(path), { recursive: true });
13
14
  this.database = new DatabaseSync(path);
14
15
  const version = this.database.prepare("PRAGMA user_version").get()?.user_version;
15
16
  if (version !== 0 && version !== 1 && version !== 2 && version !== 3 && version !== 4 && version !== 5) {
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@womp/spark-agent",
3
- "version": "17.7.3",
3
+ "version": "17.8.0",
4
4
  "description": "Portable skills-based AI agent with local and durable chat transports for Womp",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "bin": {
9
9
  "spark-agent": "dist/cli.js",
10
- "simple-bench": "dist/simple-bench-cli.js",
11
10
  "agent-run": "dist/agent-run-cli.js",
12
- "intent-bench": "dist/intent-bench-cli.js"
11
+ "intent-bench": "dist/intent-bench-cli.js",
12
+ "quality-bench": "dist/quality-bench-cli.js"
13
13
  },
14
14
  "exports": {
15
15
  "./browser": {
@@ -97,9 +97,10 @@
97
97
  "lint": "yarn typecheck",
98
98
  "dev": "yarn build && concurrently --kill-others \"yarn dev:server\" \"yarn dev:web\"",
99
99
  "dev:server": "tsx src/cli.ts",
100
- "simple-bench": "tsx src/simple-bench-cli.ts",
101
100
  "agent-run": "tsx src/agent-run-cli.ts",
102
101
  "intent-bench": "tsx src/intent-bench-cli.ts",
102
+ "kakapo-mux": "tsx src/kakapo-mux-cli.ts",
103
+ "quality-bench": "tsx src/quality-bench-cli.ts",
103
104
  "dev:demo-account": "yarn build && concurrently --kill-others \"yarn dev:server --profile demo-account\" \"yarn dev:web\"",
104
105
  "dev:web": "vite --config web/vite.config.ts",
105
106
  "start": "node dist/cli.js",
@@ -122,6 +123,7 @@
122
123
  "express": "^5.2.1",
123
124
  "lodash": "4.18.1",
124
125
  "quickjs-emscripten-core": "0.32.0",
126
+ "ws": "^8.18.3",
125
127
  "zod": "4.5.4"
126
128
  },
127
129
  "devDependencies": {
@@ -131,6 +133,7 @@
131
133
  "@types/node": "^24.0.0",
132
134
  "@types/react": "^19.2.17",
133
135
  "@types/react-dom": "^19.2.3",
136
+ "@types/ws": "^8.18.1",
134
137
  "@vitejs/plugin-react": "^6.0.4",
135
138
  "concurrently": "^9.2.1",
136
139
  "lucide-react": "^1.26.0",
@@ -138,6 +141,7 @@
138
141
  "react-dom": "^19.2.8",
139
142
  "react-markdown": "^10.1.0",
140
143
  "remark-gfm": "^4.0.1",
144
+ "sharp": "^0.35.5",
141
145
  "tsx": "^4.23.1",
142
146
  "typescript": "^5.9.3",
143
147
  "vite": "^8.1.5"
@@ -1,64 +0,0 @@
1
- #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
3
- import { loadEnvFile } from "node:process";
4
- import { parseArgs } from "node:util";
5
- import path from "node:path";
6
- import { SPARK_MODELS } from "./models.js";
7
- import { BENCH_PROMPTS } from "./simple-bench-prompts.js";
8
- import { runSimpleBench } from "./simple-bench.js";
9
- async function main() {
10
- const { values } = parseArgs({ options: {
11
- model: { type: "string", default: "gpt-6-astra" }, reasoning: { type: "string", default: "high" },
12
- "kakapo-url": { type: "string" }, output: { type: "string" }, only: { type: "string" },
13
- "timeout-minutes": { type: "string", default: "30" },
14
- help: { type: "boolean" },
15
- } });
16
- if (values.help) {
17
- console.log(`simple-bench [options]
18
-
19
- Runs ${BENCH_PROMPTS.length} prompts sequentially against a dedicated Kakapo scene.
20
- WARNING: removes all objects/materials before every prompt and makes paid model calls.
21
- Stop other agents/editors using this Kakapo instance first.
22
-
23
- --model <id> Default: gpt-6-astra. Models: ${SPARK_MODELS.map((model) => model.id).join(", ")}
24
- --reasoning <effort> Default: high
25
- --kakapo-url <url> Default: KAKAPO_URL from .env, or ws://127.0.0.1:5502
26
- --output <directory> New directory only; default: .spark/bench/<timestamp>
27
- --only <id> ${BENCH_PROMPTS.map((prompt) => prompt.id).join(", ")}
28
- --timeout-minutes <n> Per-case timeout; default: 30`);
29
- return;
30
- }
31
- const model = SPARK_MODELS.find((item) => item.id === values.model);
32
- if (!model)
33
- throw new Error("Select a supported model using --model. See --help.");
34
- const reasoning = values.reasoning;
35
- if (!model.reasoningEfforts.includes(reasoning))
36
- throw new Error("Unsupported reasoning effort for this model.");
37
- const timeoutMs = Number(values["timeout-minutes"]) * 60_000;
38
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
39
- throw new Error("Invalid timeout.");
40
- if (existsSync(".env"))
41
- loadEnvFile();
42
- const key = { openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY", google: "GEMINI_API_KEY" }[model.provider];
43
- if (!process.env[key]?.trim())
44
- throw new Error(`${key} is required in the environment or .env.`);
45
- const controller = new AbortController();
46
- const stop = () => controller.abort(new Error("Benchmark interrupted."));
47
- process.once("SIGINT", stop);
48
- process.once("SIGTERM", stop);
49
- const output = path.resolve(values.output ?? `.spark/bench/${new Date().toISOString().replaceAll(":", "-")}`);
50
- console.log(`Results: ${output}`);
51
- try {
52
- if (!await runSimpleBench({
53
- settings: { modelId: model.id, reasoningEffort: reasoning },
54
- kakapoUrl: values["kakapo-url"] ?? process.env.KAKAPO_URL ?? "ws://127.0.0.1:5502",
55
- output, only: values.only, timeoutMs, signal: controller.signal,
56
- }))
57
- process.exitCode = 1;
58
- }
59
- finally {
60
- process.removeListener("SIGINT", stop);
61
- process.removeListener("SIGTERM", stop);
62
- }
63
- }
64
- main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
@@ -1,5 +0,0 @@
1
- export declare const BENCH_ORIENTATION = "Orient the object upright (+Y), with its front facing +Z and its base centered at the origin.";
2
- export declare const BENCH_PROMPTS: {
3
- prompt: string;
4
- id: string;
5
- }[];
@@ -1,12 +0,0 @@
1
- export const BENCH_ORIENTATION = "Orient the object upright (+Y), with its front facing +Z and its base centered at the origin.";
2
- export const BENCH_PROMPTS = [
3
- { id: "armchair", prompt: "Make a mustard-yellow upholstered armchair, 85 cm wide, 90 cm deep, and 85 cm tall. Give it a thick square seat cushion, a slightly reclined backrest, rounded armrests, and four short tapered wooden legs." },
4
- { id: "desk-lamp", prompt: "Make a matte-black desk lamp, 45 cm tall, with a circular base 18 cm in diameter, two slender articulated arms, and a conical shade 15 cm wide. Give the shade a white interior and a warm-white bulb." },
5
- { id: "coffee-mug", prompt: "Make a teal ceramic mug, 10 cm tall and 9 cm in diameter, with a gently rounded base, an open top, a thick rim, and a large C-shaped handle. Give it a cream-colored interior." },
6
- { id: "bookshelf", prompt: "Make a light-oak bookshelf, 180 cm tall, 90 cm wide, and 30 cm deep. Give it five evenly spaced open compartments, thick rectangular side panels, a solid back panel, and a recessed base." },
7
- { id: "backpack", prompt: "Make a navy-blue backpack, 45 cm tall, 30 cm wide, and 18 cm deep. Give it a rounded rectangular body, a large front zipper pocket, two padded shoulder straps, a top carry handle, and light-gray zipper pulls." },
8
- { id: "toaster", prompt: "Make a cream-colored two-slot toaster, 28 cm wide, 18 cm deep, and 20 cm tall. Give it rounded corners, a brushed-metal top, two long bread slots, a silver side lever, and a circular browning dial." },
9
- { id: "plant-pot", prompt: "Make a terracotta plant pot, 25 cm tall, tapering from a 30 cm opening to a 20 cm base. Give it a thick rolled rim and dark soil containing a small plant with six broad green leaves on short stems." },
10
- { id: "suitcase", prompt: "Make a burgundy hard-shell suitcase, 65 cm tall, 42 cm wide, and 26 cm deep. Give it rounded corners, five vertical ribs on each broad face, four black spinner wheels, a silver telescoping handle, and a black side carry handle." },
11
- { id: "dining-table", prompt: "Make a rectangular walnut dining table, 160 cm long, 90 cm wide, and 75 cm tall. Give it a 4 cm thick tabletop with softly rounded corners, four square tapered legs, and a recessed wooden apron beneath the top." },
12
- ].map(item => ({ ...item, prompt: `${item.prompt} ${BENCH_ORIENTATION}` }));
@@ -1,15 +0,0 @@
1
- import type { SparkRunSettings } from "./server/types.js";
2
- export { createBenchMetrics } from "./run-metrics.js";
3
- type BenchCost = {
4
- costUsd: number | null;
5
- costStatus: "estimated" | "partial" | "unavailable";
6
- };
7
- export declare function totalBenchCost(results: readonly BenchCost[]): BenchCost;
8
- export declare function runSimpleBench(options: {
9
- settings: SparkRunSettings;
10
- kakapoUrl: string;
11
- output: string;
12
- only?: string;
13
- timeoutMs: number;
14
- signal: AbortSignal;
15
- }): Promise<boolean>;
@@ -1,163 +0,0 @@
1
- import { once } from "node:events";
2
- import { mkdir, writeFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import { KakapoAPI } from "@womp/kakapo-sdk";
5
- import { benchCamera, benchGeometryIds } from "./bench-camera.js";
6
- import { SparkChatTransport } from "./client.js";
7
- import { createStandaloneSparkAgentApp } from "./server/standalone.js";
8
- import { BENCH_PROMPTS } from "./simple-bench-prompts.js";
9
- import { createBenchMetrics } from "./run-metrics.js";
10
- export { createBenchMetrics } from "./run-metrics.js";
11
- export function totalBenchCost(results) {
12
- const known = results.filter((result) => result.costUsd !== null);
13
- return {
14
- costUsd: known.length ? known.reduce((sum, result) => sum + result.costUsd, 0) : null,
15
- costStatus: !known.length ? "unavailable" : results.some((result) => result.costStatus !== "estimated") ? "partial" : "estimated",
16
- };
17
- }
18
- function costLabel(cost) {
19
- return cost.costUsd === null ? "cost unavailable" : `$${cost.costUsd.toFixed(4)} USD (${cost.costStatus})`;
20
- }
21
- export async function runSimpleBench(options) {
22
- const prompts = BENCH_PROMPTS.filter((item) => !options.only || item.id === options.only);
23
- if (!prompts.length)
24
- throw new Error("Unknown prompt ID. Use --help to list the available prompts.");
25
- // Never reuse a result directory or overwrite a previous benchmark.
26
- await mkdir(path.dirname(options.output), { recursive: true });
27
- await mkdir(options.output);
28
- const captures = new Map();
29
- const app = await createStandaloneSparkAgentApp({
30
- kakapoUrl: options.kakapoUrl,
31
- storagePath: path.join(options.output, "history.sqlite"),
32
- openAiApiKey: process.env.OPENAI_API_KEY,
33
- anthropicApiKey: process.env.ANTHROPIC_API_KEY,
34
- geminiApiKey: process.env.GEMINI_API_KEY,
35
- onScreenshot: (runId) => captures.set(runId, (captures.get(runId) ?? 0) + 1),
36
- });
37
- const server = app.listen(0, "127.0.0.1");
38
- const results = [];
39
- const startedAt = new Date().toISOString();
40
- const report = async () => {
41
- await writeFile(path.join(options.output, "results.json"), JSON.stringify({
42
- version: 1, startedAt, nodeVersion: process.version, settings: options.settings,
43
- timeoutMs: options.timeoutMs, camera: "fixed-three-quarter-v3", plannedPrompts: prompts.map((item) => item.id),
44
- totalCost: totalBenchCost(results), results,
45
- }, null, 2));
46
- const columns = ["id", "status", "steps", "readSkill", "executeJavaScript", "screenshots", "durationMs", "costUsd", "costStatus", "image", "error"];
47
- const quote = (value) => `"${String(value ?? "").replaceAll('"', '""')}"`;
48
- const total = { id: "TOTAL", ...totalBenchCost(results) };
49
- await writeFile(path.join(options.output, "results.csv"), [columns.join(","), ...[...results, total].map((result) => columns.map((key) => quote(result[key])).join(","))].join("\n"));
50
- };
51
- try {
52
- await once(server, "listening");
53
- const address = server.address();
54
- if (!address || typeof address === "string")
55
- throw new Error("Benchmark server did not start.");
56
- const base = `http://127.0.0.1:${address.port}/agent`;
57
- const transport = new SparkChatTransport({ api: base, getSettings: () => options.settings });
58
- for (const item of prompts) {
59
- options.signal.throwIfAborted();
60
- const result = { ...item, status: "failed", steps: 0, readSkill: 0, executeJavaScript: 0, screenshots: 0, durationMs: null, costUsd: null, costStatus: "unavailable" };
61
- const metrics = createBenchMetrics();
62
- let started;
63
- let ended;
64
- let usageComplete = false;
65
- const signal = AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]);
66
- try {
67
- console.log(`Running ${item.id}…`);
68
- const clear = await fetch(`${base}/scene/clear`, { method: "POST", headers: { "X-Spark-Action": "clear-scene" }, signal });
69
- const cleared = await clear.json();
70
- if (!clear.ok || cleared.warning)
71
- throw new Error(cleared.error ?? cleared.warning ?? "Scene cleanup failed.");
72
- const conversation = await transport.createConversation({ title: `simple-bench: ${item.id}` });
73
- result.conversationId = conversation.id;
74
- started = performance.now();
75
- const stream = await transport.sendMessages({
76
- trigger: "submit-message", chatId: conversation.id, messageId: undefined,
77
- messages: [{ id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: item.prompt }] }],
78
- abortSignal: signal,
79
- });
80
- for await (const value of stream) {
81
- const chunk = value;
82
- metrics.accept(chunk);
83
- if (chunk.type === "data-run-status") {
84
- result.runId = chunk.data.runId;
85
- result.status = chunk.data.status;
86
- if (chunk.data.error)
87
- result.error = chunk.data.error;
88
- }
89
- if (chunk.type === "error")
90
- result.error = chunk.errorText;
91
- }
92
- ended = performance.now();
93
- usageComplete = result.status === "completed";
94
- const saved = await transport.getConversation(conversation.id);
95
- await writeFile(path.join(options.output, `${item.id}.conversation.json`), JSON.stringify(saved, null, 2));
96
- const reply = saved.messages.filter((message) => message.role === "assistant").at(-1);
97
- await writeFile(path.join(options.output, `${item.id}.md`), reply?.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n\n") ?? "");
98
- if (result.status !== "completed")
99
- throw new Error(result.error ?? `Run ended with status ${result.status}.`);
100
- const api = new KakapoAPI({ url: options.kakapoUrl, requestTimeoutMs: 30_000 });
101
- try {
102
- await api.connect();
103
- const snapshot = await api.rpc("scene_state_get");
104
- await writeFile(path.join(options.output, `${item.id}.scene.json`), typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot));
105
- const ids = benchGeometryIds(api);
106
- const bounds = await api.getNodesBoundingBox(ids);
107
- const viewport = await api.captureScreenshot({});
108
- const camera = benchCamera(bounds, viewport.width / viewport.height);
109
- await writeFile(path.join(options.output, `${item.id}.framing.json`), JSON.stringify({ ids, bounds, width: viewport.width, height: viewport.height, cameras: { "three-quarter": camera } }, null, 2));
110
- const image = await api.captureScreenshot({ camera, timeoutMs: 30_000 });
111
- if (image.width !== viewport.width || image.height !== viewport.height)
112
- throw new Error("Viewport changed during benchmark capture.");
113
- await writeFile(path.join(options.output, `${item.id}.jpg`), image.data);
114
- result.image = `${item.id}.jpg`;
115
- }
116
- finally {
117
- api.disconnect();
118
- }
119
- }
120
- catch (error) {
121
- ended ??= performance.now();
122
- result.error = error instanceof Error ? error.message : String(error);
123
- result.status = signal.aborted ? "cancelled" : "failed";
124
- if (result.conversationId) {
125
- try {
126
- await transport.cancelRun(result.conversationId);
127
- }
128
- catch (cancelError) {
129
- result.error += ` Cancellation failed: ${String(cancelError)}`;
130
- }
131
- }
132
- }
133
- finally {
134
- result.durationMs = started === undefined ? null : Math.round((ended ?? performance.now()) - started);
135
- Object.assign(result, metrics.snapshot());
136
- if (started === undefined) {
137
- result.costUsd = 0;
138
- result.costStatus = "estimated";
139
- }
140
- else if (!usageComplete && result.costUsd !== null)
141
- result.costStatus = "partial";
142
- result.screenshots = result.runId ? captures.get(result.runId) ?? 0 : 0;
143
- results.push(result);
144
- await report();
145
- console.log(`${item.id}: ${result.status}, ${result.steps} steps, ${result.durationMs ?? 0} ms, ${costLabel(result)}`);
146
- console.log(`Benchmark total: ${costLabel(totalBenchCost(results))}`);
147
- }
148
- // Do not clear again after an uncertain mutation, failed cleanup or cancelled run.
149
- if (result.status !== "completed")
150
- break;
151
- }
152
- return results.every((result) => result.status === "completed") && results.length === prompts.length;
153
- }
154
- finally {
155
- try {
156
- await app.dispose();
157
- }
158
- finally {
159
- server.closeAllConnections();
160
- await new Promise((resolve) => server.close(() => resolve()));
161
- }
162
- }
163
- }