Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat: start the render service on demand, and ship it (Phase 11) (#71)
Matthew Kissinger6bacb171a475
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.mdindex 9d1b7084..8a97b32a 100644--- a/.agents/skills/kiln-setup-workspace/SKILL.md+++ b/.agents/skills/kiln-setup-workspace/SKILL.md@@ -36,13 +36,13 @@ Antigravity and Hermes get a generated launcher because each needs arguments orSetup asks for render mode `auto`: a GPU service when one answers on port 8000, CPU views otherwise. CPU views are honest about silhouette, proportion and contact and say nothing about colour, metalness or roughness, so without the service no render can confirm a material.-Offer to start it before launching the harness. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.+Offer to run its install. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.```bash-cd render-service && npm install && npm start+cd render-service && npm install```-Leave it running in its own terminal. The CLI picks up a service started at any time on its next call, while an MCP session resolves the service once at startup -- so starting it first is what gets in-loop renders material-faithful without a restart. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.## Verify the loadout before authoringdiff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.mdindex 9d1b7084..8a97b32a 100644--- a/.claude/skills/kiln-setup-workspace/SKILL.md+++ b/.claude/skills/kiln-setup-workspace/SKILL.md@@ -36,13 +36,13 @@ Antigravity and Hermes get a generated launcher because each needs arguments orSetup asks for render mode `auto`: a GPU service when one answers on port 8000, CPU views otherwise. CPU views are honest about silhouette, proportion and contact and say nothing about colour, metalness or roughness, so without the service no render can confirm a material.-Offer to start it before launching the harness. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.+Offer to run its install. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.```bash-cd render-service && npm install && npm start+cd render-service && npm install```-Leave it running in its own terminal. The CLI picks up a service started at any time on its next call, while an MCP session resolves the service once at startup -- so starting it first is what gets in-loop renders material-faithful without a restart. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.## Verify the loadout before authoringdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7cbc4a5..aa0e8955 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,39 @@Changes to `@kiln/engine`. Source and installable packages are distributed throughGitHub. The package is not published on the npm registry.+## The renderer starts itself, and now ships — 2026-09-11++- The MCP server **starts the GPU render service on demand**. Installing it+ (`cd render-service && npm install`) is the whole setup: there is no longer a+ second process to start first, and nothing to restart to pick one up. The+ first view that needs PBR shading starts the renderer, the rest of the session+ reuses it, and it stops when the server does. Measured end to end on the+ shipped bundle with nothing listening: the first `kiln_render` came back+ material-faithful from the GPU in 5.4 s, the second in 1.7 s.+ - A service already listening is **joined, not replaced**, and a session that+ merely found one does not stop it on the way out -- so one GPU shared by a+ batch of dispatched agents keeps working, and the agent that finishes first+ cannot pull the renderer out from under the others.+ - A machine that did not install the renderer is **unchanged**, deliberately+ and at the level of the attached port rather than the rendered result: the+ absence of a render port is what makes an ordinary CPU view read as ordinary+ instead of as a degrade.+ - `KILN_RENDER_PORT_URL` and `--render-port` short-circuit all of it, so a+ hosted or remote GPU is still exactly one flag. `KILN_RENDER_SERVICE_PORT`+ moves the local one off 8000.+ - The CLI is deliberately not on this path: a one-shot `kiln render` should not+ pay a GPU process's startup to draw one sheet.+- **`render-service/` now ships in the package.** The MCP server told every model+ that a GPU renderer "ships as render-service/ in this installation"; that was+ false for anyone installing from npm, because the directory was in no `files`+ entry. Its source travels with the package now (104 KB) while its ~94 MB of+ native dependencies stay an explicit opt-in install.+- `webgpu` 0.4.0 -> 0.6.0, smoked on hardware: 36/36 service unit tests, display+ conformance passed, end-to-end smoke all pass.+- A service started **for** you binds loopback; one you start yourself still binds+ every interface, which is what a container deployment needs. `HOST` is now+ honoured either way.+## Review surfaces say what they mean — 2026-09-11- `viewFidelity.exactArtifact` was a hard-coded `false` literal at everydiff --git a/coverage-thresholds.json b/coverage-thresholds.jsonindex dd04e9fc..5ec1eb08 100644--- a/coverage-thresholds.json+++ b/coverage-thresholds.json@@ -1,7 +1,7 @@{"measuredBaseline": {- "functions": 95.43,- "lines": 92.58,+ "functions": 95.25,+ "lines": 92.48,"measuredUnder": "[email protected]","measuredOn": "2026-09-11"},diff --git a/dist/build.json b/dist/build.jsonindex 884eb156..36914c5e 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"mcp": {- "identity": "sha256:ca1f79486d18694019163b2eb4f9089f45eae40f5473f955f82f48bb0b5d2e42",+ "identity": "sha256:09a4a00aa323b5f8132d94bfd3dc377cb4bd0bee6dcc6dc77c359b9f12342c58","engineVersion": "0.6.0","toolchain": "[email protected]",- "sourceHash": "bda3bc7c8a4d11a599737fd422fa0f27e25fcfcb55abc64492f74e2c590b4104",+ "sourceHash": "04616056755941791d5d5846726ddc2e684c15ec48b26d2f00d9b834264822b1","dependencyHash": "664eae40f28077bfed4798d9215cb8de7297287494a59d653c451e1343c08fc3","dependencies": {"@gltf-transform/core": "4.4.1",@@ -27,13 +27,13 @@},"target": "node","file": "mcp-server.mjs",- "bundleHash": "sha256:9f5096592b2c5712bacab8e989dbf887ad3a26932fcf5cf81f6ce1738b7c62c9"+ "bundleHash": "sha256:a4f2df38c4f57842dffdf67a4fb7dfe9f827a1106c4404634ca4b0527b239ead"},"cli": {- "identity": "sha256:ca1f79486d18694019163b2eb4f9089f45eae40f5473f955f82f48bb0b5d2e42",+ "identity": "sha256:09a4a00aa323b5f8132d94bfd3dc377cb4bd0bee6dcc6dc77c359b9f12342c58","engineVersion": "0.6.0","toolchain": "[email protected]",- "sourceHash": "bda3bc7c8a4d11a599737fd422fa0f27e25fcfcb55abc64492f74e2c590b4104",+ "sourceHash": "04616056755941791d5d5846726ddc2e684c15ec48b26d2f00d9b834264822b1","dependencyHash": "664eae40f28077bfed4798d9215cb8de7297287494a59d653c451e1343c08fc3","dependencies": {"@gltf-transform/core": "4.4.1",@@ -55,13 +55,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:ca28885ff6b93224c6c8d0ea9fc521b93bb09391db6b45adc1f52cce2f273550"+ "bundleHash": "sha256:d987928b2daaa394f1614ee3be8a26f5e4890f6531ed309bd0e4f1d684a92bf9"},"worker": {- "identity": "sha256:ca1f79486d18694019163b2eb4f9089f45eae40f5473f955f82f48bb0b5d2e42",+ "identity": "sha256:09a4a00aa323b5f8132d94bfd3dc377cb4bd0bee6dcc6dc77c359b9f12342c58","engineVersion": "0.6.0","toolchain": "[email protected]",- "sourceHash": "bda3bc7c8a4d11a599737fd422fa0f27e25fcfcb55abc64492f74e2c590b4104",+ "sourceHash": "04616056755941791d5d5846726ddc2e684c15ec48b26d2f00d9b834264822b1","dependencyHash": "664eae40f28077bfed4798d9215cb8de7297287494a59d653c451e1343c08fc3","dependencies": {"@gltf-transform/core": "4.4.1",@@ -86,10 +86,10 @@"bundleHash": "sha256:549c013d6ca1475a5bbfa5b7be9fc63894212da382a7501af227902622fa3946"},"agent-run": {- "identity": "sha256:ca1f79486d18694019163b2eb4f9089f45eae40f5473f955f82f48bb0b5d2e42",+ "identity": "sha256:09a4a00aa323b5f8132d94bfd3dc377cb4bd0bee6dcc6dc77c359b9f12342c58","engineVersion": "0.6.0","toolchain": "[email protected]",- "sourceHash": "bda3bc7c8a4d11a599737fd422fa0f27e25fcfcb55abc64492f74e2c590b4104",+ "sourceHash": "04616056755941791d5d5846726ddc2e684c15ec48b26d2f00d9b834264822b1","dependencyHash": "664eae40f28077bfed4798d9215cb8de7297287494a59d653c451e1343c08fc3","dependencies": {"@gltf-transform/core": "4.4.1",@@ -114,10 +114,10 @@"bundleHash": "sha256:5f9c212686fbcbc42254354ae9466e06b6b2b96ea0d49253720c7df1c512a82f"},"agent-providers": {- "identity": "sha256:ca1f79486d18694019163b2eb4f9089f45eae40f5473f955f82f48bb0b5d2e42",+ "identity": "sha256:09a4a00aa323b5f8132d94bfd3dc377cb4bd0bee6dcc6dc77c359b9f12342c58","engineVersion": "0.6.0","toolchain": "[email protected]",- "sourceHash": "bda3bc7c8a4d11a599737fd422fa0f27e25fcfcb55abc64492f74e2c590b4104",+ "sourceHash": "04616056755941791d5d5846726ddc2e684c15ec48b26d2f00d9b834264822b1","dependencyHash": "664eae40f28077bfed4798d9215cb8de7297287494a59d653c451e1343c08fc3","dependencies": {"@gltf-transform/core": "4.4.1",diff --git a/dist/cli.mjs b/dist/cli.mjsindex c5b52b08..581610d2 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -28524,6 +28524,109 @@ var init_registry2 = __esm(() => {};});+// src/render-service-host.ts+import { spawn as spawn2 } from "node:child_process";+import { existsSync as existsSync2 } from "node:fs";+import { fileURLToPath as fileURLToPath5 } from "node:url";+import { join as join6 } from "node:path";+function localRenderServicePort() {+ const raw = Number(process.env["KILN_RENDER_SERVICE_PORT"]);+ return Number.isInteger(raw) && raw > 0 && raw < 65536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;+}+function localRenderServiceUrl() {+ return `http://127.0.0.1:${localRenderServicePort()}`;+}+function renderServiceDir() {+ const override = process.env["KILN_RENDER_SERVICE_DIR"];+ if (override)+ return override;+ return fileURLToPath5(new URL("../render-service", import.meta.url));+}+function localRenderServiceState(dir = renderServiceDir()) {+ if (!existsSync2(join6(dir, "src/server.mjs")) || !existsSync2(join6(dir, "package.json")))+ return "not-packaged";+ if (!existsSync2(join6(dir, "node_modules/webgpu")) || !existsSync2(join6(dir, "node_modules/three")))+ return "dependencies-missing";+ return "ready";+}+function explainRenderServiceState(state, dir) {+ return state === "dependencies-missing" ? `the GPU render service is present but not installed; run \`npm install\` in ${dir}` : `this installation does not ship ${dir}`;+}+async function healthy(url, timeoutMs) {+ try {+ const res = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(timeoutMs) });+ if (!res.ok)+ return false;+ return (await res.json()).ok === true;+ } catch {+ return false;+ }+}+function nodeBinary() {+ const override = process.env["KILN_RENDER_SERVICE_NODE"];+ if (override)+ return override;+ return process.versions.bun ? "node" : process.execPath;+}+function stopLocalRenderService() {+ const running = child;+ child = undefined;+ if (!running || running.killed || running.exitCode !== null)+ return;+ running.kill();+}+function registerTeardown() {+ if (teardownRegistered)+ return;+ teardownRegistered = true;+ process.once("exit", stopLocalRenderService);+ for (const signal of ["SIGINT", "SIGTERM"])+ process.once(signal, () => {+ stopLocalRenderService();+ });+}+async function startLocalRenderService(dir = renderServiceDir()) {+ const url = localRenderServiceUrl();+ if (await healthy(url, 1500))+ return url;+ const state = localRenderServiceState(dir);+ if (state !== "ready")+ throw new Error(explainRenderServiceState(state, dir));+ registerTeardown();+ let stderr = "";+ child = spawn2(nodeBinary(), ["--import", join6(dir, "src/register-hooks.mjs"), join6(dir, "src/server.mjs")], {+ cwd: dir,+ env: {+ ...process.env,+ PORT: String(localRenderServicePort()),+ HOST: "127.0.0.1"+ },+ stdio: ["ignore", "ignore", "pipe"]+ });+ child.stderr?.on("data", (chunk) => {+ stderr = `${stderr}${chunk.toString()}`.slice(-2000);+ });+ const deadline = Date.now() + STARTUP_BUDGET_MS;+ while (Date.now() < deadline) {+ if (await healthy(url, 1000))+ return url;+ if (child.exitCode !== null || child.signalCode !== null) {+ if (await healthy(url, 1500))+ return url;+ child = undefined;+ throw new Error(`render service exited during startup${stderr.trim() ? `: ${stderr.trim().split(`+`).slice(-3).join(" ")}` : ""}`);+ }+ await new Promise((done) => setTimeout(done, STARTUP_POLL_MS));+ }+ stopLocalRenderService();+ throw new Error(`render service did not answer within ${STARTUP_BUDGET_MS}ms`);+}+var DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000, STARTUP_BUDGET_MS, STARTUP_POLL_MS = 250, child, teardownRegistered = false;+var init_render_service_host = __esm(() => {+ STARTUP_BUDGET_MS = Number(process.env["KILN_RENDER_SERVICE_STARTUP_MS"] ?? 60000);+});+// src/cli-render-mode.tsimport { createHash as createHash9 } from "node:crypto";function resolveRenderMode(value) {@@ -28575,6 +28678,15 @@ function makeRemoteRenderPort(url, token) {};};}+function makeLazyRenderPort(start, token) {+ let resolving;+ return async (req) => {+ resolving ??= start().then((url) => makeRemoteRenderPort(url, token), (err) => {+ throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);+ });+ return (await resolving)(req);+ };+}async function probeCaptureIdentity(url) {try {const response = await fetch(new URL("/health", url), {@@ -28639,7 +28751,7 @@ function describeDrawnBy(output, context) {}return "cpu raster (GPU configured; scene needs no PBR shading)";}-async function buildRenderPort(mode, portUrl) {+async function buildRenderPort(mode, portUrl, options) {const context = mode === "gpu" ? { viewRenderRequired: true } : {};const attach = (url, label) => {context.viewRenderPort = makeRemoteRenderPort(url, process.env["KILN_RENDER_TOKEN"]);@@ -28648,6 +28760,17 @@ async function buildRenderPort(mode, portUrl) {selected.set(context, label);return context;};+ const attachLazy = (start, label) => {+ let url;+ context.viewRenderPort = makeLazyRenderPort(async () => {+ url = await start();+ return url;+ }, process.env["KILN_RENDER_TOKEN"]);+ context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;+ context.captureCacheIdentity = () => url ? probeCaptureIdentity(url) : undefined;+ selected.set(context, label);+ return context;+ };if (mode === "cpu") {selected.set(context, "cpu raster");return context;@@ -28657,18 +28780,31 @@ async function buildRenderPort(mode, portUrl) {const envUrl = process.env["KILN_RENDER_PORT_URL"];if (envUrl)return attach(envUrl, `GPU service (${envUrl})`);- const rendererId = await probeRenderService(DEFAULT_LOCAL_PORT_URL);+ const localUrl = localRenderServiceUrl();+ const rendererId = await probeRenderService(localUrl);if (rendererId)- return attach(DEFAULT_LOCAL_PORT_URL, `GPU service (${rendererId})`);+ return attach(localUrl, `GPU service (${rendererId})`);+ if (options?.autoSpawn) {+ const dir = options.serviceDir ?? renderServiceDir();+ const state = options.start ? "ready" : localRenderServiceState(dir);+ if (state === "ready") {+ const start = options.start ?? (() => startLocalRenderService(dir));+ return attachLazy(start, "GPU service (started on demand)");+ }+ if (mode === "gpu")+ throw new Error(`no GPU render service is reachable, and ${explainRenderServiceState(state, dir)}.+` + "Set --render-port or KILN_RENDER_PORT_URL to point at one elsewhere, or use " + "--render auto to fall back to the CPU rasterizer.");+ }if (mode === "gpu") {throw new Error(`no GPU render service is reachable.-` + `Looked at ${DEFAULT_LOCAL_PORT_URL}; set --render-port or KILN_RENDER_PORT_URL to ` + "point somewhere else, or use --render auto to fall back to the CPU rasterizer.");+` + `Looked at ${localUrl}; set --render-port or KILN_RENDER_PORT_URL to ` + "point somewhere else, or use --render auto to fall back to the CPU rasterizer.");}selected.set(context, "cpu raster (no GPU service found)");return context;}-var DEFAULT_LOCAL_PORT_URL = "http://127.0.0.1:8000", HEALTH_PROBE_TIMEOUT_MS = 1500, HEALTH_PROBE_BUSY_TIMEOUT_MS = 8000, CLI_VIEW_RENDER_TIMEOUT_MS = 20000, selected;+var HEALTH_PROBE_TIMEOUT_MS = 1500, HEALTH_PROBE_BUSY_TIMEOUT_MS = 8000, CLI_VIEW_RENDER_TIMEOUT_MS = 20000, selected;var init_cli_render_mode = __esm(() => {+ init_render_service_host();selected = new WeakMap;});@@ -28676,7 +28812,7 @@ var init_cli_render_mode = __esm(() => {import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";import { readFileSync as readFileSync2 } from "node:fs";import { lstat as lstat2, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, realpath as realpath2, rename as rename2, rm, writeFile as writeFile3 } from "node:fs/promises";-import { dirname as dirname4, join as join6, relative as relative2, resolve as resolve5, sep } from "node:path";+import { dirname as dirname4, join as join7, relative as relative2, resolve as resolve5, sep } from "node:path";async function verifyAssetRecord(record) {for (const [name, info] of Object.entries(record.manifest.files)) {const bytes = record.files[name];@@ -28709,7 +28845,7 @@ class FileAssetLibrary {let path = root;for (const part of parts) {assetIdSchema.parse(part);- path = join6(path, part);+ path = join7(path, part);try {const entry = await lstat2(path);if (entry.isSymbolicLink())@@ -28752,7 +28888,7 @@ class FileAssetLibrary {return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId));}async file(dir, name, limit = ASSET_LIMIT) {- const path = join6(dir, name);+ const path = join7(dir, name);const info = await lstat2(path);if (!info.isFile() || info.isSymbolicLink() || info.size > limit)throw new Error("Invalid collection file");@@ -28816,12 +28952,12 @@ class FileAssetLibrary {const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);const parent = dirname4(dest);await mkdir4(parent, { recursive: true });- const stage = join6(parent, `.write-${randomUUID3()}`);+ const stage = join7(parent, `.write-${randomUUID3()}`);await mkdir4(stage);try {for (const [name, bytes] of Object.entries(files))- await writeFile3(join6(stage, name), bytes, { flag: "wx" });- await writeFile3(join6(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}+ await writeFile3(join7(stage, name), bytes, { flag: "wx" });+ await writeFile3(join7(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}`, {flag: "wx"});@@ -28843,7 +28979,7 @@ class FileAssetLibrary {}function collectionConfigPath(env = process.env) {const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve5(env.KILN_PROGRAM_STORE))) : process.cwd();- return join6(workspace, ".kiln", "collections.json");+ return join7(workspace, ".kiln", "collections.json");}function localAssetLibrary(env = process.env) {if (env.KILN_COLLECTIONS) {@@ -28863,7 +28999,7 @@ function localAssetLibrary(env = process.env) {throw error;}const workspace = dirname4(dirname4(config));- return new FileAssetLibrary({ project: join6(workspace, "assets", "kiln") });+ return new FileAssetLibrary({ project: join7(workspace, "assets", "kiln") });}var digest4 = (bytes) => `sha256:${createHash10("sha256").update(bytes).digest("hex")}`;var init_assets_node = __esm(() => {@@ -28873,10 +29009,10 @@ var init_assets_node = __esm(() => {// src/asset-viewer.tsimport { createServer } from "node:http";import { readFile as readFile5 } from "node:fs/promises";-import { dirname as dirname5, join as join7 } from "node:path";-import { fileURLToPath as fileURLToPath5 } from "node:url";+import { dirname as dirname5, join as join8 } from "node:path";+import { fileURLToPath as fileURLToPath6 } from "node:url";async function startAssetViewer(library, options = {}) {- const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join7(dirname5(fileURLToPath5(import.meta.url)), "..", "dist", "viewer") : join7(dirname5(fileURLToPath5(import.meta.url)), "viewer"));+ const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join8(dirname5(fileURLToPath6(import.meta.url)), "..", "dist", "viewer") : join8(dirname5(fileURLToPath6(import.meta.url)), "viewer"));const server = createServer(async (req, res) => {res.setHeader("X-Content-Type-Options", "nosniff");res.setHeader("Referrer-Policy", "no-referrer");@@ -28937,7 +29073,7 @@ async function startAssetViewer(library, options = {}) {return;}res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' blob: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");- return send(await readFile5(join7(staticDirectory, file[0])), file[1]);+ return send(await readFile5(join8(staticDirectory, file[0])), file[1]);} catch (error) {res.statusCode = 400;send(JSON.stringify({ error: error instanceof Error ? error.message : "Asset unavailable" }));diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjsindex 1c407a15..9450afc3 100644--- a/dist/mcp-server.mjs+++ b/dist/mcp-server.mjs@@ -26136,7 +26136,7 @@ async function readAssetResource(library, uri) {// src/mcp-server.tsimport { serveStdio } from "@modelcontextprotocol/server/stdio";import { AsyncLocalStorage } from "async_hooks";-import { fileURLToPath as fileURLToPath5 } from "url";+import { fileURLToPath as fileURLToPath6 } from "url";// src/tools/registry.tsinit_capture_cache();@@ -28167,7 +28167,112 @@ function createKilnAssetDefs(context) {// src/cli-render-mode.tsimport { createHash as createHash8 } from "node:crypto";-var DEFAULT_LOCAL_PORT_URL = "http://127.0.0.1:8000";++// src/render-service-host.ts+import { spawn as spawn2 } from "node:child_process";+import { existsSync as existsSync2 } from "node:fs";+import { fileURLToPath as fileURLToPath3 } from "node:url";+import { join as join3 } from "node:path";+var DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000;+function localRenderServicePort() {+ const raw = Number(process.env["KILN_RENDER_SERVICE_PORT"]);+ return Number.isInteger(raw) && raw > 0 && raw < 65536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;+}+function localRenderServiceUrl() {+ return `http://127.0.0.1:${localRenderServicePort()}`;+}+var STARTUP_BUDGET_MS = Number(process.env["KILN_RENDER_SERVICE_STARTUP_MS"] ?? 60000);+var STARTUP_POLL_MS = 250;+function renderServiceDir() {+ const override = process.env["KILN_RENDER_SERVICE_DIR"];+ if (override)+ return override;+ return fileURLToPath3(new URL("../render-service", import.meta.url));+}+function localRenderServiceState(dir = renderServiceDir()) {+ if (!existsSync2(join3(dir, "src/server.mjs")) || !existsSync2(join3(dir, "package.json")))+ return "not-packaged";+ if (!existsSync2(join3(dir, "node_modules/webgpu")) || !existsSync2(join3(dir, "node_modules/three")))+ return "dependencies-missing";+ return "ready";+}+function explainRenderServiceState(state, dir) {+ return state === "dependencies-missing" ? `the GPU render service is present but not installed; run \`npm install\` in ${dir}` : `this installation does not ship ${dir}`;+}+async function healthy(url, timeoutMs) {+ try {+ const res = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(timeoutMs) });+ if (!res.ok)+ return false;+ return (await res.json()).ok === true;+ } catch {+ return false;+ }+}+function nodeBinary() {+ const override = process.env["KILN_RENDER_SERVICE_NODE"];+ if (override)+ return override;+ return process.versions.bun ? "node" : process.execPath;+}+var child;+var teardownRegistered = false;+function stopLocalRenderService() {+ const running = child;+ child = undefined;+ if (!running || running.killed || running.exitCode !== null)+ return;+ running.kill();+}+function registerTeardown() {+ if (teardownRegistered)+ return;+ teardownRegistered = true;+ process.once("exit", stopLocalRenderService);+ for (const signal of ["SIGINT", "SIGTERM"])+ process.once(signal, () => {+ stopLocalRenderService();+ });+}+async function startLocalRenderService(dir = renderServiceDir()) {+ const url = localRenderServiceUrl();+ if (await healthy(url, 1500))+ return url;+ const state = localRenderServiceState(dir);+ if (state !== "ready")+ throw new Error(explainRenderServiceState(state, dir));+ registerTeardown();+ let stderr = "";+ child = spawn2(nodeBinary(), ["--import", join3(dir, "src/register-hooks.mjs"), join3(dir, "src/server.mjs")], {+ cwd: dir,+ env: {+ ...process.env,+ PORT: String(localRenderServicePort()),+ HOST: "127.0.0.1"+ },+ stdio: ["ignore", "ignore", "pipe"]+ });+ child.stderr?.on("data", (chunk) => {+ stderr = `${stderr}${chunk.toString()}`.slice(-2000);+ });+ const deadline = Date.now() + STARTUP_BUDGET_MS;+ while (Date.now() < deadline) {+ if (await healthy(url, 1000))+ return url;+ if (child.exitCode !== null || child.signalCode !== null) {+ if (await healthy(url, 1500))+ return url;+ child = undefined;+ throw new Error(`render service exited during startup${stderr.trim() ? `: ${stderr.trim().split(`+`).slice(-3).join(" ")}` : ""}`);+ }+ await new Promise((done) => setTimeout(done, STARTUP_POLL_MS));+ }+ stopLocalRenderService();+ throw new Error(`render service did not answer within ${STARTUP_BUDGET_MS}ms`);+}++// src/cli-render-mode.tsvar HEALTH_PROBE_TIMEOUT_MS = 1500;var HEALTH_PROBE_BUSY_TIMEOUT_MS = 8000;var CLI_VIEW_RENDER_TIMEOUT_MS = 20000;@@ -28220,6 +28325,15 @@ function makeRemoteRenderPort(url, token) {};};}+function makeLazyRenderPort(start, token) {+ let resolving;+ return async (req) => {+ resolving ??= start().then((url) => makeRemoteRenderPort(url, token), (err) => {+ throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);+ });+ return (await resolving)(req);+ };+}async function probeCaptureIdentity(url) {try {const response = await fetch(new URL("/health", url), {@@ -28268,7 +28382,7 @@ async function probeRenderService(url) {return second.kind === "ok" ? second.rendererId : undefined;}var selected = new WeakMap;-async function buildRenderPort(mode, portUrl) {+async function buildRenderPort(mode, portUrl, options) {const context = mode === "gpu" ? { viewRenderRequired: true } : {};const attach = (url, label) => {context.viewRenderPort = makeRemoteRenderPort(url, process.env["KILN_RENDER_TOKEN"]);@@ -28277,6 +28391,17 @@ async function buildRenderPort(mode, portUrl) {selected.set(context, label);return context;};+ const attachLazy = (start, label) => {+ let url;+ context.viewRenderPort = makeLazyRenderPort(async () => {+ url = await start();+ return url;+ }, process.env["KILN_RENDER_TOKEN"]);+ context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;+ context.captureCacheIdentity = () => url ? probeCaptureIdentity(url) : undefined;+ selected.set(context, label);+ return context;+ };if (mode === "cpu") {selected.set(context, "cpu raster");return context;@@ -28286,12 +28411,24 @@ async function buildRenderPort(mode, portUrl) {const envUrl = process.env["KILN_RENDER_PORT_URL"];if (envUrl)return attach(envUrl, `GPU service (${envUrl})`);- const rendererId = await probeRenderService(DEFAULT_LOCAL_PORT_URL);+ const localUrl = localRenderServiceUrl();+ const rendererId = await probeRenderService(localUrl);if (rendererId)- return attach(DEFAULT_LOCAL_PORT_URL, `GPU service (${rendererId})`);+ return attach(localUrl, `GPU service (${rendererId})`);+ if (options?.autoSpawn) {+ const dir = options.serviceDir ?? renderServiceDir();+ const state = options.start ? "ready" : localRenderServiceState(dir);+ if (state === "ready") {+ const start = options.start ?? (() => startLocalRenderService(dir));+ return attachLazy(start, "GPU service (started on demand)");+ }+ if (mode === "gpu")+ throw new Error(`no GPU render service is reachable, and ${explainRenderServiceState(state, dir)}.+` + "Set --render-port or KILN_RENDER_PORT_URL to point at one elsewhere, or use " + "--render auto to fall back to the CPU rasterizer.");+ }if (mode === "gpu") {throw new Error(`no GPU render service is reachable.-` + `Looked at ${DEFAULT_LOCAL_PORT_URL}; set --render-port or KILN_RENDER_PORT_URL to ` + "point somewhere else, or use --render auto to fall back to the CPU rasterizer.");+` + `Looked at ${localUrl}; set --render-port or KILN_RENDER_PORT_URL to ` + "point somewhere else, or use --render auto to fall back to the CPU rasterizer.");}selected.set(context, "cpu raster (no GPU service found)");return context;@@ -28300,7 +28437,7 @@ async function buildRenderPort(mode, portUrl) {// src/program-store-node.tsimport { link, lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir as readdir2, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";import { randomUUID as randomUUID2 } from "node:crypto";-import { join as join3, resolve as resolve2 } from "node:path";+import { join as join4, resolve as resolve2 } from "node:path";class FileProgramStore {directory;constructor(directory) {@@ -28314,7 +28451,7 @@ class FileProgramStore {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat(join3(this.directory, entry.name))).size;+ bytes += (await stat(join4(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -28332,7 +28469,7 @@ class FileProgramStore {const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;if (canonical === undefined)throw this.notFound(ref);- const path = join3(this.directory, `${canonical.slice(7)}.js`);+ const path = join4(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat(path)).size > MAX_PROGRAM_BYTES)@@ -28351,7 +28488,7 @@ class FileProgramStore {return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);}async readHandle(handle) {- const path = join3(this.directory, "refs", `${handle}.ref`);+ const path = join4(this.directory, "refs", `${handle}.ref`);try {const info = await lstat2(path);if (!info.isFile() || info.size !== 71)@@ -28370,7 +28507,7 @@ class FileProgramStore {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join3(this.directory, "refs");+ const directory = join4(this.directory, "refs");await mkdir2(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -28378,11 +28515,11 @@ class FileProgramStore {return handle;if (owner !== undefined)continue;- const temporary = join3(directory, `.write-${randomUUID2()}`);+ const temporary = join4(directory, `.write-${randomUUID2()}`);await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link(temporary, join3(directory, `${handle}.ref`));+ await link(temporary, join4(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -28399,8 +28536,8 @@ class FileProgramStore {async put(code) {const ref = await programReference(code);await mkdir2(this.directory, { recursive: true });- const target = join3(this.directory, `${ref.slice(7)}.js`);- const temporary = join3(this.directory, `.write-${randomUUID2()}`);+ const target = join4(this.directory, `${ref.slice(7)}.js`);+ const temporary = join4(this.directory, `.write-${randomUUID2()}`);await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {@@ -28423,12 +28560,12 @@ function localProgramStore() {// src/direct-entry.tsimport { realpathSync } from "node:fs";import { resolve as resolve3 } from "node:path";-import { fileURLToPath as fileURLToPath3 } from "node:url";+import { fileURLToPath as fileURLToPath4 } from "node:url";function isDirectEntry(moduleUrl) {if (!process.argv[1])return false;try {- return realpathSync(resolve3(process.argv[1])) === realpathSync(fileURLToPath3(moduleUrl));+ return realpathSync(resolve3(process.argv[1])) === realpathSync(fileURLToPath4(moduleUrl));} catch {return false;}@@ -28442,7 +28579,7 @@ init_render();// src/program-store-node.tsimport { link as link2, lstat as lstat3, mkdir as mkdir3, readFile as readFile3, readdir as readdir3, stat as stat2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";import { randomUUID as randomUUID3 } from "node:crypto";-import { join as join4, resolve as resolve4 } from "node:path";+import { join as join5, resolve as resolve4 } from "node:path";class FileProgramStore2 {directory;constructor(directory) {@@ -28456,7 +28593,7 @@ class FileProgramStore2 {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat2(join4(this.directory, entry.name))).size;+ bytes += (await stat2(join5(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -28474,7 +28611,7 @@ class FileProgramStore2 {const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;if (canonical === undefined)throw this.notFound(ref);- const path = join4(this.directory, `${canonical.slice(7)}.js`);+ const path = join5(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat2(path)).size > MAX_PROGRAM_BYTES)@@ -28493,7 +28630,7 @@ class FileProgramStore2 {return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);}async readHandle(handle) {- const path = join4(this.directory, "refs", `${handle}.ref`);+ const path = join5(this.directory, "refs", `${handle}.ref`);try {const info = await lstat3(path);if (!info.isFile() || info.size !== 71)@@ -28512,7 +28649,7 @@ class FileProgramStore2 {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join4(this.directory, "refs");+ const directory = join5(this.directory, "refs");await mkdir3(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -28520,11 +28657,11 @@ class FileProgramStore2 {return handle;if (owner !== undefined)continue;- const temporary = join4(directory, `.write-${randomUUID3()}`);+ const temporary = join5(directory, `.write-${randomUUID3()}`);await writeFile3(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link2(temporary, join4(directory, `${handle}.ref`));+ await link2(temporary, join5(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -28541,8 +28678,8 @@ class FileProgramStore2 {async put(code) {const ref = await programReference(code);await mkdir3(this.directory, { recursive: true });- const target = join4(this.directory, `${ref.slice(7)}.js`);- const temporary = join4(this.directory, `.write-${randomUUID3()}`);+ const target = join5(this.directory, `${ref.slice(7)}.js`);+ const temporary = join5(this.directory, `.write-${randomUUID3()}`);await writeFile3(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {@@ -28572,7 +28709,7 @@ import {utimes,writeFile as writeFile4} from "node:fs/promises";-import { join as join5, resolve as resolve5 } from "node:path";+import { join as join6, resolve as resolve5 } from "node:path";var keyPattern = /^sha256:[a-f0-9]{64}$/;var filePattern = /^[a-f0-9]{64}\.json$/;var digest3 = (text) => createHash9("sha256").update(text).digest("hex");@@ -28589,7 +28726,7 @@ class FileBuildCache {path(key) {if (!keyPattern.test(key))throw new Error("Invalid build cache key.");- return join5(this.directory, `${key.slice(7)}.json`);+ return join6(this.directory, `${key.slice(7)}.json`);}async get(key) {const path = this.path(key);@@ -28617,7 +28754,7 @@ class FileBuildCache {if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))return;await mkdir4(this.directory, { recursive: true });- const temporary = join5(this.directory, `.write-${randomUUID4()}`);+ const temporary = join6(this.directory, `.write-${randomUUID4()}`);await writeFile4(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });try {await rename2(temporary, path);@@ -28631,7 +28768,7 @@ class FileBuildCache {for (const name of await readdir4(this.directory)) {if (!filePattern.test(name))continue;- const path = join5(this.directory, name);+ const path = join6(this.directory, name);try {const item = await stat3(path);entries.push({ path, size: item.size, used: item.mtimeMs });@@ -28652,7 +28789,7 @@ class FileBuildCache {import { createHash as createHash10 } from "node:crypto";import { readFile as readFile5, readdir as readdir5, realpath as realpath2, stat as stat4 } from "node:fs/promises";import { createRequire } from "node:module";-import { dirname as dirname2, join as join6, relative as relative2 } from "node:path";+import { dirname as dirname2, join as join7, relative as relative2 } from "node:path";var digest4 = (bytes) => createHash10("sha256").update(bytes).digest("hex");var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;async function installedRuntimeIdentity(root, limits = {}) {@@ -28660,7 +28797,7 @@ async function installedRuntimeIdentity(root, limits = {}) {let files = 0;const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;const maxFiles = limits.maxFiles ?? 40000;- const manifest = async (directory) => JSON.parse(await readFile5(join6(directory, "package.json"), "utf8"));+ const manifest = async (directory) => JSON.parse(await readFile5(join7(directory, "package.json"), "utf8"));let readers = 0;const waiting = [];const read = async (path) => {@@ -28686,17 +28823,17 @@ async function installedRuntimeIdentity(root, limits = {}) {const pkg = await manifest(root);if (pkg.name !== "@kiln/engine")throw new Error("Not a Kiln installation.");- const build = JSON.parse(await readFile5(join6(root, "dist", "build.json"), "utf8"));+ const build = JSON.parse(await readFile5(join7(root, "dist", "build.json"), "utf8"));const worker = build.entries?.worker;if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))throw new Error("No valid packaged worker identity.");- const workerHash = `sha256:${digest4(await read(join6(root, "dist", worker.file)))}`;+ const workerHash = `sha256:${digest4(await read(join7(root, "dist", worker.file)))}`;if (worker.bundleHash !== workerHash)throw new Error("Packaged worker differs from its build manifest.");const records = [];const visited = new Map;async function resolvePackage(parent, name) {- const require2 = createRequire(join6(parent, "package.json"));+ const require2 = createRequire(join7(parent, "package.json"));let found;try {found = require2.resolve(`${name}/package.json`);@@ -28705,7 +28842,7 @@ async function installedRuntimeIdentity(root, limits = {}) {found = require2.resolve(name);} catch {for (const modules of require2.resolve.paths(name) ?? []) {- const candidate = join6(modules, name);+ const candidate = join7(modules, name);try {if ((await manifest(candidate)).name === name)return await realpath2(candidate);@@ -28731,7 +28868,7 @@ async function installedRuntimeIdentity(root, limits = {}) {return (await Promise.all(entries.map(async (entry) => {if (entry.name === "node_modules" || entry.name === ".git")return [];- const path = join6(directory, entry.name);+ const path = join7(directory, entry.name);if (entry.isSymbolicLink())throw new Error("Dependency contains an untracked internal symlink.");if (entry.isDirectory())@@ -28797,8 +28934,8 @@ async function installedRuntimeIdentity(root, limits = {}) {}// src/local-runtime.ts-import { dirname as dirname3, join as join7, resolve as resolve6 } from "node:path";-import { fileURLToPath as fileURLToPath4 } from "node:url";+import { dirname as dirname3, join as join8, resolve as resolve6 } from "node:path";+import { fileURLToPath as fileURLToPath5 } from "node:url";var scope = 0;function integer2(env, name, fallback, min, max) {const value = env[name] === undefined ? fallback : Number(env[name]);@@ -28882,7 +29019,7 @@ function createLocalToolContext(base = {}, env = process.env) {localExecution};}-async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath4(new URL("../", import.meta.url))) {+async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath5(new URL("../", import.meta.url))) {const context = createLocalToolContext(base, env);const managed = () => {const identity = context.evaluatorCacheIdentity;@@ -28920,7 +29057,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve6(env.KILN_BUILD_CACHE_DIR ?? join7(store instanceof FileProgramStore2 ? dirname3(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve6(env.KILN_BUILD_CACHE_DIR ?? join8(store instanceof FileProgramStore2 ? dirname3(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -28942,12 +29079,12 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst// src/mcp-server.tsvar MCP_SERVER_NAME = "kiln";var MCP_SERVER_VERSION = "0.6.0";-var packagedSkillsDir = fileURLToPath5(new URL("../skills", import.meta.url));+var packagedSkillsDir = fileURLToPath6(new URL("../skills", import.meta.url));var MCP_SERVER_INSTRUCTIONS = `Kiln turns JavaScript you write into GLB 3D assets and returns rendered views for review.Work by reference. Send a program once to kiln_validate or kiln_render; the result carries a programRef. Keep it exactly as returned, including a short p_ handle, and use it for every later view and edit. kiln_source with that ref and a literal query returns exact edit anchors, and kiln_edit with that ref plus edits returns a new ref and renders by default. Do not resend a whole program to change part of it.-Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material. When materialFaithful is false and the task concerns appearance, say so rather than concluding from a CPU view: material-faithful views come from the GPU render service that ships as render-service/ in this installation, which has its own npm install and is resolved once at server startup.+Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material. When materialFaithful is false and the task concerns appearance, say so rather than concluding from a CPU view: material-faithful views come from the GPU render service that ships as render-service/ in this installation. It has its own npm install; once installed it is started on demand by the first view that needs it, so there is no order to get right and no session to restart.Detailed workflows ship beside this server as Agent Skills, one directory each under ${packagedSkillsDir}:- kiln-setup-workspace: create a managed workspace for authoring, and verify its tools came up@@ -29094,7 +29231,7 @@ function createKilnMcpServer(context = {}) {}if (isDirectEntry(import.meta.url)) {const mode = resolveRenderMode(process.env["KILN_RENDER"] ?? "auto");- const context = await createPackagedLocalToolContext(await buildRenderPort(mode, process.env["KILN_RENDER_PORT_URL"]));+ const context = await createPackagedLocalToolContext(await buildRenderPort(mode, process.env["KILN_RENDER_PORT_URL"], { autoSpawn: true }));context.programStore = localProgramStore();context.assetLibrary = localAssetLibrary();const deliveryBase = process.env["KILN_ASSET_DOWNLOAD_BASE_URL"];diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.mdindex cac253fa..6ebebee6 100644--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md@@ -1131,5 +1131,125 @@ independently verified; 9.2 is the one that looks like the same bug class as 9.1| 9.4 | `kiln_screenshot_animation` requires a `clip` name and `frameTimes` normalized to 0..1, and neither is stated in the author skill or the camera recipes. The run guessed the clip name from its own `createClip` call and hit a validation error on seconds-valued frame times. **Done 2026-09-11.** The program contract now states that `clip` is required and matched by name, that `frameTimes` is 1..9 strictly increasing phases in 0..1 rather than seconds, and that a frozen-looking clip means `unresolvedTracks` -- a joint-name mismatch || 9.5 | `arrayRadial` count semantics are not inferable from the signature plus the example: whether the source mesh survives as the copy at index 0 had to be deduced from a mesh count. **Done 2026-09-11.** Both array helpers now say it outright: `count` is the TOTAL including the source, which survives as copy 0, so the call returns count-1 new instances || 9.6 | CLI `--out` does not create parent directories, failing with a bare `ENOENT` *after* the build succeeded and printed a `programRef`. Invisible from the README, whose example writes into the cwd | Done 2026-09-11 -- `prepareDestination` in `src/cli-output.ts`, applied at every CLI destination: `render --out`, `render --views`, `generate`, `source <ref> --out` and `export --out`. Guarded by `src/__tests__/cli-out-directories.test.ts` |-| 9.7 | The MCP server resolves the render service once before its first connection, so a service started afterwards is invisible until the session restarts, while the CLI picks it up on the next call. Re-probe lazily when a render needs PBR and no port is attached, with a short negative cache -- the probe's `absent` path is a refused localhost connection. Pending; collapses the guidance to "start it whenever" and deletes the restart caveat from the workspace guide and the setup skill. Not folded into the Phase 7 documentation commit because `captureViewsViaPort` owns the deadline and degrade policy and the change deserves its own TDD |+| 9.7 | The MCP server resolves the render service once before its first connection, so a service started afterwards is invisible until the session restarts, while the CLI picks it up on the next call. **Done 2026-09-11, and by a wider route than a lazy re-probe: see Phase 11.** Re-probing would have cured the symptom while leaving the user two processes to sequence. The server now starts the service itself, so there is nothing to have started first and nothing to restart || 9.8 | Narrow the generated per-harness configuration to suppress user-level skills and MCP servers where each harness supports it. The blind run inherited roughly twenty unrelated skills and four unrelated servers. This is the only option that reduces inherited context rather than reporting it, and it needs vendor documentation per harness first: configuration that validates and silently does nothing is the `${PLUGIN_ROOT}` failure class. Pending |++## Phase 11 -- The renderer moves to where the users are++Taken 2026-09-11. The render service was built for a hosted deployment: Graviton+instances running the engine, a RunPod GPU running the renderer, one HTTP hop+between them. That deployment is gone, and the people running this now are+running both halves on one laptop through an MCP server their coding harness+starts for them. The socket between the two is still right -- headless WebGPU+needs Node loader hooks Bun does not run, so the renderer cannot live in+process -- but everything around it still assumed an operator who starts+services in a known order.++Two things followed from that, and they are the whole phase.++### 11.1 -- The renderer is started on demand, not found or not at all++`buildRenderPort` gained an opt-in `autoSpawn`, which the MCP server passes and+the CLI deliberately does not: a one-shot `kiln render` should not pay a GPU+process's startup to draw one sheet, whereas a session amortizes it over+everything that follows.++Three properties carry the design.++**It attaches only where a renderer could actually run.** `localRenderServiceState`+answers from the filesystem alone -- no socket, no process, no GPU query -- and+`auto` attaches nothing unless it says `ready`. This is not an optimization. The+absence of `context.viewRenderPort` is exactly what `describeDrawnBy` reads to+call a CPU render ordinary rather than a degrade, so a hopeful port on a machine+with no renderer would make every ordinary render on every CPU-only machine+report itself as an incident. That is the Phase 9 defect class, and it would have+been worse than 9.7.++**It joins before it starts, and stops only what it started.** The shared port is+the documented 8000 rather than an ephemeral one, so a batch of dispatched agents+converges on one renderer instead of holding a GPU context each; the spawn also+re-probes if the child loses the port race. `stopLocalRenderService` kills+`child`, which stays undefined on the join path -- so the second agent to exit+cannot pull the renderer out from under the others, which would have shown up as+flat-white materials and no error anywhere.++**It adds no second deadline.** The lazy port awaits the start rather than failing+fast and warming in the background, because `captureViewsViaPort` already owns a+deadline for one in-loop call and already degrades to the CPU rasterizer when it+expires. A start that outruns it costs one CPU view and the next render has the+GPU. A second budget here would be the duplicated degrade policy AGENTS.md+forbids. A start that FAILS is cached as failed: a renderer that could not start+will not start for the next view, and a spawn per render would stall the loop.++`KILN_RENDER_PORT_URL` and `--render-port` short-circuit ahead of all of it, so+the hosted path this replaced is still exactly one flag.++**Measured end to end on the shipped bundle**, driven over stdio by a real MCP+client with nothing listening on 8000: first `kiln_render` returned in 5.4 s with+`materialFaithful: true` from `dawn-vulkan:nvidia-geforce-gtx-1660-ti` -- start,+GPU init, build and render, inside the 20 s in-loop deadline, so the first render+was material-faithful rather than the CPU view the design allows for. Second+render 1.7 s on the same service. The service was gone after the client+disconnected, and the server's stderr held one line. That last part is not+incidental: stdout is the MCP transport and the service greets its own boot on+stdout, so the child is spawned `stdio: ['ignore','ignore','pipe']`. One+`listening on :8000` line in that stream is a protocol error for every tool call+after it.++### 11.2 -- `render-service/` now ships++The MCP `instructions` string tells every model that material-faithful views come+from a renderer that "ships as render-service/ in this installation". That+sentence was false for anyone who installed from npm: the directory was in no+`files` entry, so a plugin user could not start a GPU renderer at all. Its source+now ships (15 files, 104 KB; tests and the Dockerfile stay out), while the ~94 MB+of native dependencies remain a deliberate opt-in install. `smoke-package.mjs`+asserts it both in the tarball and in a real installation, and walks the exact+`new URL('../render-service', import.meta.url)` arithmetic the bundle resolves+rather than trusting three paths to sit where the server will look.++`webgpu` moved 0.4.0 -> 0.6.0 in the same pass and was smoked on hardware: 36/36+unit tests, display conformance passed, end-to-end smoke ALL PASS.++Two failures found while doing it, **both pre-existing and both confirmed against+0.4.0 before being called that**:++- The smoke's health check pinned `lightingPresetIds` to exactly+ `['neutral-studio-v1']`, so adding `gallery-studio-v1` turned it red and left it+ red. Fixed to assert membership plus capability backing. A smoke that always+ reports one failure is a smoke nobody reads.+- `material-conformance.mjs` fails its albedo check with `lumaSpread: 0`, its+ textures failing to load as `blob:nodedata:` URLs. Not a general texture defect:+ a real textured example rendered through the on-demand path came back correctly+ textured. Harness-specific and open.++### A note on binding++`server.listen(PORT)` bound every interface. For a service the user starts that+is their call and the container deployment needs it, so the default is unchanged;+`HOST` is now honoured and the on-demand start passes `127.0.0.1`. Choosing to+put a renderer on somebody's LAN is not a choice to make on their behalf.++| ID | Task | State |+| --- | --- | --- |+| 11.1 | Start the packaged render service on demand from the MCP server, join one already listening, stop only what was started | Done 2026-09-11; closes 9.7 |+| 11.2 | Ship `render-service/` in the package so the `instructions` claim is true, and move `webgpu` to 0.6.0 | Done 2026-09-11, smoked on hardware |+| 11.3 | `material-conformance.mjs` cannot load `blob:nodedata:` textures, so its albedo/normal/ORM checks assert against an untextured render. Pre-existing on 0.4.0; real assets texture correctly | Open |+| 11.4 | Give the CLI the same on-demand start behind an explicit flag. Deliberately excluded: a one-shot render should not pay a GPU startup, and `auto` must stay instant on a CPU-only machine | Not planned; revisit if asked |++### 6.4 is not independent of 6.2++Attempted and stopped, 2026-09-11. Unpinning `pages.yml` from `windows-2022`+cannot be done without first deciding 6.2, and the ledger was wrong to separate+them. All 83 provenance records carry a `posterReceipt`, and+`verifyRecordedPoster` asserts `artifactHash` against a GLB rebuilt on the+runner. Measured rather than assumed: `abyssal-surveyor` records+`eb18c8e8ec9b1c6f...` and rebuilds on Linux as `300ece4cd5de6dbc...`, so the+first example fails and so would the other 82. The Windows pin is not an+incidental choice of runner -- it IS the workaround for `artifactHash` hashing+bytes that serialization is free to change. Removing it means either re-recording+83 receipts on Linux, which only moves the pin, or changing what a poster receipt+asserts, which is 6.2. The maintainer's call on 6.1/6.3 -- that the gallery images+are display assets -- points at narrowing the receipt to `sourceHash` and+`imageHash`, the two claims that are platform-stable and that the gallery+actually makes. That remains a decision, not a task.diff --git a/docs/rendering.md b/docs/rendering.mdindex 52dfa06d..004837db 100644--- a/docs/rendering.md+++ b/docs/rendering.md@@ -17,10 +17,32 @@ CPU views show silhouette, orientation, proportion, and contact. They do not repout, headless three.js `WebGPURenderer` on Dawn. No browser and no X server.```bash-cd render-service && npm install && npm start+cd render-service && npm install```-The service listens on port 8000, where `auto` looks by default. If the server sets `RENDER_SERVICE_TOKEN`, set the matching `KILN_RENDER_TOKEN` in the client environment; a health check can succeed while unauthenticated render requests return 401. For a remote service, supply `--render-port URL`. See the service README for deployment and authentication options.+That install is the only manual step. Once it has run, the MCP server starts the service itself on the+first view that needs PBR shading, reuses it for the rest of the session, and stops it on the way out.+There is no order to get right: a session that never renders a material never starts a renderer, and+nothing has to be restarted to pick one up.++Start it by hand instead when you want it to outlive any one session — a batch of dispatched agents+sharing one GPU is the usual reason:++```bash+cd render-service && npm start+```++Either way the service listens on port 8000, where `auto` looks by default, and the first process to+claim the port wins: a service already listening is joined rather than replaced, and a session that+merely found one does not stop it on exit. Set `KILN_RENDER_SERVICE_PORT` to move it. A hand-started+service binds every interface, which is what a container deployment needs; one started on your behalf+binds loopback only, because that choice is not ours to make for you.++If the server sets `RENDER_SERVICE_TOKEN`, set the matching `KILN_RENDER_TOKEN` in the client environment; a health check can succeed while unauthenticated render requests return 401. For a remote service, supply `--render-port URL` or set `KILN_RENDER_PORT_URL` — either short-circuits every local path above, so a hosted GPU stays one flag. See the service README for deployment and authentication options.++The CLI is deliberately not on the on-demand path. A one-shot `kiln render` should not pay a GPU+process's startup to draw one sheet, so it uses a service that is already listening and otherwise+returns CPU views.In `auto` mode, an unavailable service falls back to CPU views. Read `degraded` and `degradeReason` before drawing conclusions about materials. Structural QA does not use image pixels.diff --git a/package.json b/package.jsonindex 56c2a30f..5023211b 100644--- a/package.json+++ b/package.json@@ -73,6 +73,10 @@".mcp.json","scripts/create-workspace.mjs","scripts/package-plugin.mjs",+ "render-service/src/",+ "render-service/package.json",+ "render-service/package-lock.json",+ "render-service/README.md","skills/","docs/","README.md",diff --git a/render-service/package-lock.json b/render-service/package-lock.jsonindex f76e61e4..f001fd91 100644--- a/render-service/package-lock.json+++ b/render-service/package-lock.json@@ -10,13 +10,13 @@"dependencies": {"pngjs": "^7.0.0","three": "0.185.1",- "webgpu": "0.4.0"+ "webgpu": "0.6.0"}},"node_modules/@webgpu/types": {- "version": "0.1.71",- "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.71.tgz",- "integrity": "sha512-mMy8/ODcKhab808co15eW+yN+HgXoQxRQHTiBV9Mrvl1r0ufnid7YOcI+gi4eUWSWl9ezD6TW2KXccrL8HCh2A==",+ "version": "0.1.72",+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.72.tgz",+ "integrity": "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw==","license": "BSD-3-Clause"},"node_modules/debug": {@@ -58,13 +58,13 @@"license": "MIT"},"node_modules/webgpu": {- "version": "0.4.0",- "resolved": "https://registry.npmjs.org/webgpu/-/webgpu-0.4.0.tgz",- "integrity": "sha512-F5pimn3Aoi0zWjuRdiVs5TnrUwSzD2lESBohsIUsqyitWkGRQlXU2fhV6ycXlQTa1bvAf3sjqiUpBEpmSQ5ptA==",+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/webgpu/-/webgpu-0.6.0.tgz",+ "integrity": "sha512-z44ZU/+ypPELgQrv+um3/5Eqcq7gOtVZAmaRfwujJMwGMRSa6+CmjIAvEWw7O68Y95cnEsywhbYlcChQTX+IQg==","hasInstallScript": true,"license": "MIT","dependencies": {- "@webgpu/types": "^0.1.69",+ "@webgpu/types": "^0.1.72","debug": "^4.4.0"}}diff --git a/render-service/package.json b/render-service/package.jsonindex a97150d2..e10cd199 100644--- a/render-service/package.json+++ b/render-service/package.json@@ -14,9 +14,9 @@"dependencies": {"pngjs": "^7.0.0","three": "0.185.1",- "webgpu": "0.4.0"+ "webgpu": "0.6.0"},"allowScripts": {- "[email protected]": true+ "[email protected]": true}}diff --git a/render-service/src/server.mjs b/render-service/src/server.mjsindex 8f684e2e..8907467f 100644--- a/render-service/src/server.mjs+++ b/render-service/src/server.mjs@@ -43,6 +43,11 @@ import {const PROCESS_STARTED_AT = performance.now();const PORT = Number(process.env.PORT ?? 8000);+// Unset binds every interface, which is what a container deployment needs and is+// the long-standing default here. A service started FOR the user -- by the MCP+// server's on-demand start -- passes 127.0.0.1 instead, because choosing on+// somebody's behalf to put a renderer on their LAN is not ours to choose.+const HOST = process.env.HOST || undefined;const TOKEN = process.env.RENDER_SERVICE_TOKEN ?? '';const MAX_BODY = 96 * 1024 * 1024; // 64MB base64 ≈ 48MB GLB, plus JSON overhead@@ -272,4 +277,4 @@ const server = createServer(async (req, res) => {}});-server.listen(PORT, () => console.log(`kiln-render-service listening on :${PORT}`));+server.listen(PORT, HOST, () => console.log(`kiln-render-service listening on ${HOST ?? '*'}:${PORT}`));diff --git a/render-service/test/smoke.mjs b/render-service/test/smoke.mjsindex 7ad204b7..a423c3f2 100644--- a/render-service/test/smoke.mjs+++ b/render-service/test/smoke.mjs@@ -53,7 +53,12 @@ check(health.capabilities.includes('render.targets.rectangular-v1') &&health.capabilities.includes('render.outputs.sha256-v1') &&Array.isArray(health.lightingPresetIds) &&- JSON.stringify(health.lightingPresetIds) === JSON.stringify(['neutral-studio-v1']) &&+ // Membership, not equality. Pinning the whole list meant that adding+ // gallery-studio-v1 turned this check red and left it red -- a smoke that+ // always reports one failure is a smoke nobody reads. What actually matters+ // is that every advertised preset is backed by a declared capability.+ health.lightingPresetIds.includes('neutral-studio-v1') &&+ health.lightingPresetIds.every((id) => health.capabilities.includes(`render.profile.${id}`)) &&typeof health.backend === 'string' && health.backend.length > 0 &&health.presentationProfile === 'neutral-studio-v1' &&health.authRequired === true,diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 83b16d40..1c2b18bf 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -86,6 +86,11 @@ try {assert(pack.files.some((entry) => entry.path === 'scripts/create-workspace.mjs'));assert(pack.files.some((entry) => entry.path === 'plugin.json'));assert(pack.files.some((entry) => entry.path === '.claude-plugin/plugin.json'));+ // The MCP server tells every model that a GPU renderer "ships as render-service/+ // in this installation". That sentence was false for anyone installing from npm+ // until this line existed, and the on-demand start has nothing to start without it.+ assert(pack.files.some((entry) => entry.path === 'render-service/src/server.mjs'));+ assert(!pack.files.some((entry) => entry.path.startsWith('render-service/test/')));assert(!pack.files.some((entry) => entry.path.includes('__tests__') || entry.path.endsWith('.test.ts')));}receipt.tarballSha256 = sha(await readFile(receipt.tarball));@@ -96,8 +101,15 @@ try {const runtime = join(install, 'node_modules/@kiln/engine');const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));receipt.engineVersion = pkg.version;- for (const required of ['dist/cli.mjs', 'dist/mcp-server.mjs', 'dist/evaluator-worker.mjs', 'scripts/create-workspace.mjs', 'plugin.json', '.claude-plugin/plugin.json'])+ for (const required of ['dist/cli.mjs', 'dist/mcp-server.mjs', 'dist/evaluator-worker.mjs', 'scripts/create-workspace.mjs', 'plugin.json', '.claude-plugin/plugin.json', 'render-service/src/server.mjs', 'render-service/src/register-hooks.mjs', 'render-service/package.json'])assert((await stat(join(runtime, required))).isFile(), `Missing installed package file: ${required}`);+ // `renderServiceDir()` is `new URL('../render-service', import.meta.url)` from the+ // bundle. Walk that exact arithmetic against the real installation rather than+ // trusting that the three paths above happen to sit where the server will look.+ assert(+ (await stat(fileURLToPath(new URL('../render-service/src/server.mjs', pathToFileURL(join(runtime, 'dist/mcp-server.mjs')))))).isFile(),+ 'render-service is not where the MCP bundle resolves it',+ );receipt.bundleHashes = { cli: sha(await readFile(join(runtime, 'dist/cli.mjs'))), mcp: sha(await readFile(join(runtime, 'dist/mcp-server.mjs'))) };assert((await readFile(join(runtime, 'dist/cli.mjs'), 'utf8')).startsWith('#!/usr/bin/env node'));assert.match(await command([join(runtime, 'dist/cli.mjs'), '--help'], root), /kiln render/, 'Direct Node CLI must print help');diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.mdindex 9d1b7084..8a97b32a 100644--- a/skills/kiln-setup-workspace/SKILL.md+++ b/skills/kiln-setup-workspace/SKILL.md@@ -36,13 +36,13 @@ Antigravity and Hermes get a generated launcher because each needs arguments orSetup asks for render mode `auto`: a GPU service when one answers on port 8000, CPU views otherwise. CPU views are honest about silhouette, proportion and contact and say nothing about colour, metalness or roughness, so without the service no render can confirm a material.-Offer to start it before launching the harness. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.+Offer to run its install. It lives in the engine installation rather than the workspace, and it is a separate package with a native dependency, so its install is its own step and is not covered by installing the engine.```bash-cd render-service && npm install && npm start+cd render-service && npm install```-Leave it running in its own terminal. The CLI picks up a service started at any time on its next call, while an MCP session resolves the service once at startup -- so starting it first is what gets in-loop renders material-faithful without a restart. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.## Verify the loadout before authoringdiff --git a/src/__tests__/render-service-host.test.ts b/src/__tests__/render-service-host.test.tsnew file mode 100644index 00000000..fb5364d0--- /dev/null+++ b/src/__tests__/render-service-host.test.ts@@ -0,0 +1,198 @@+/**+ * Starting the GPU render service that ships beside this package.+ *+ * Before this existed, `buildRenderPort` probed port 8000 exactly once, before+ * the MCP server's first connection, and a service started one second later was+ * invisible until the session restarted (ledger 9.7). The documented cure was an+ * ordering instruction -- start the renderer BEFORE the harness starts the+ * server -- which is unfollowable when the harness owns the server's lifecycle.+ *+ * Two contracts matter here and they pull in opposite directions.+ *+ * The first: a machine that cannot run the renderer must behave EXACTLY as it+ * did before. `describeDrawnBy` reads `context.viewRenderPort` to decide whether+ * a CPU view is ordinary or an incident, so attaching a hopeful port on a+ * machine with no renderer installed would make every ordinary render report+ * itself as a degrade. That is the Phase 9 defect class -- a review surface that+ * misreports a correct result -- and it is worse than the problem being fixed.+ *+ * The second: where the renderer IS installed, a render that needs PBR should+ * get it without anyone having sequenced two processes by hand.+ */+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';++import { afterEach, describe, expect, it } from 'bun:test';++import {+ localRenderServiceState,+ startLocalRenderService,+ stopLocalRenderService,+} from '../render-service-host';+import { buildRenderPort, makeLazyRenderPort } from '../cli-render-mode';++const servers: Server[] = [];+const directories: string[] = [];++afterEach(async () => {+ await Promise.all(+ servers.splice(0).map((s) => new Promise<void>((done) => s.close(() => done()))),+ );+ await Promise.all(directories.splice(0).map((d) => rm(d, { recursive: true, force: true })));+});++/** A stand-in render service that answers `/health` and `/render`. */+function serve(): Promise<string> {+ const server = createServer((req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ if (req.url === '/health') {+ res.end(JSON.stringify({ ok: true, rendererId: 'test-renderer' }));+ return;+ }+ res.end(JSON.stringify({ ok: true, rendererId: 'test-renderer', views: [] }));+ });+ servers.push(server);+ return new Promise((done) => {+ server.listen(0, '127.0.0.1', () =>+ done(`http://127.0.0.1:${(server.address() as AddressInfo).port}`),+ );+ });+}++async function scratch(): Promise<string> {+ const base = resolve(import.meta.dir, '../../tmp');+ await mkdir(base, { recursive: true });+ const dir = await mkdtemp(join(base, 'render-service-'));+ directories.push(dir);+ return dir;+}++describe('localRenderServiceState', () => {+ it('separates "not shipped" from "shipped but not installed"', async () => {+ const absent = join(await scratch(), 'nothing-here');+ expect(localRenderServiceState(absent)).toBe('not-packaged');++ const shipped = await scratch();+ await mkdir(join(shipped, 'src'), { recursive: true });+ await writeFile(join(shipped, 'src/server.mjs'), '// server\n');+ await writeFile(join(shipped, 'package.json'), '{"name":"kiln-render-service"}\n');+ // The 94 MB of native WebGPU dependencies are a deliberate opt-in install.+ // Shipping the source without them is the normal state of a fresh package.+ expect(localRenderServiceState(shipped)).toBe('dependencies-missing');++ await mkdir(join(shipped, 'node_modules/webgpu'), { recursive: true });+ await mkdir(join(shipped, 'node_modules/three'), { recursive: true });+ expect(localRenderServiceState(shipped)).toBe('ready');+ });+});++describe('buildRenderPort with autoSpawn', () => {+ it('attaches nothing when the renderer is not installed, so a CPU-only machine reads as ordinary', async () => {+ const context = await buildRenderPort('auto', undefined, {+ autoSpawn: true,+ serviceDir: join(await scratch(), 'nothing-here'),+ });+ // Not merely "renders on the CPU" -- `viewRenderPort` must be ABSENT, because+ // that absence is what `describeDrawnBy` reads to call a CPU view ordinary.+ expect(context.viewRenderPort).toBeUndefined();+ });++ it('leaves an explicit URL alone rather than starting anything', async () => {+ const url = await serve();+ let started = 0;+ const context = await buildRenderPort('auto', url, {+ autoSpawn: true,+ start: async () => {+ started += 1;+ return url;+ },+ });+ expect(context.viewRenderPort).toBeDefined();+ expect(started).toBe(0);+ });+});++describe('makeLazyRenderPort', () => {+ it('starts the service once, however many renders arrive', async () => {+ const url = await serve();+ let starts = 0;+ const port = makeLazyRenderPort(async () => {+ starts += 1;+ return url;+ });+ const glb = new Uint8Array([1, 2, 3]);+ await Promise.all([port({ glb }), port({ glb })]);+ await port({ glb });+ expect(starts).toBe(1);+ });++ it('says the renderer could not start, rather than failing silently', async () => {+ const port = makeLazyRenderPort(async () => {+ throw new Error('webgpu: no adapter');+ });+ // `captureViewsViaPort` turns a thrown port into `{ok:false, reason}` and+ // degrades to the CPU rasterizer, so the message here is what a model reads+ // as `degradeReason`. It has to name the renderer, not just the error.+ expect(port({ glb: new Uint8Array([1]) })).rejects.toThrow(/render service/i);+ expect(port({ glb: new Uint8Array([1]) })).rejects.toThrow(/no adapter/);+ });++ it('does not retry a start that already failed', async () => {+ let starts = 0;+ const port = makeLazyRenderPort(async () => {+ starts += 1;+ throw new Error('webgpu: no adapter');+ });+ const glb = new Uint8Array([1]);+ await port({ glb }).catch(() => undefined);+ await port({ glb }).catch(() => undefined);+ // A renderer that cannot start will not start on the next view either, and+ // paying a spawn per render would stall the loop it is meant to serve.+ expect(starts).toBe(1);+ });+});++describe('startLocalRenderService', () => {+ it('joins a renderer that is already listening, and does not take it down on the way out', async () => {+ // The documented way to drive a batch of agents is one shared GPU service.+ // If starting meant "start MY renderer" and stopping meant "stop whatever is+ // on the port", the second agent to finish would pull the renderer out from+ // under the others -- with no error anywhere, just flat-white materials.+ const url = await serve();+ const port = new URL(url).port;+ const previous = process.env['KILN_RENDER_SERVICE_PORT'];+ process.env['KILN_RENDER_SERVICE_PORT'] = port;+ try {+ // A directory with no renderer in it: if this returns, it joined rather+ // than started, because starting from here is impossible.+ const empty = join(await scratch(), 'nothing-here');+ expect(await startLocalRenderService(empty)).toBe(`http://127.0.0.1:${port}`);++ stopLocalRenderService();+ const after = await fetch(new URL('/health', url));+ expect(((await after.json()) as { ok?: boolean }).ok).toBe(true);+ } finally {+ if (previous === undefined) delete process.env['KILN_RENDER_SERVICE_PORT'];+ else process.env['KILN_RENDER_SERVICE_PORT'] = previous;+ }+ });++ it('refuses to start what this installation cannot run, and says which of the two it is', async () => {+ const previous = process.env['KILN_RENDER_SERVICE_PORT'];+ // A port nothing is on, so the join probe fails and the install check decides.+ process.env['KILN_RENDER_SERVICE_PORT'] = '1';+ try {+ const shipped = await scratch();+ await mkdir(join(shipped, 'src'), { recursive: true });+ await writeFile(join(shipped, 'src/server.mjs'), '// server\n');+ await writeFile(join(shipped, 'package.json'), '{}\n');+ expect(startLocalRenderService(shipped)).rejects.toThrow(/npm install/);+ expect(startLocalRenderService(join(shipped, 'absent'))).rejects.toThrow(/does not ship/);+ } finally {+ if (previous === undefined) delete process.env['KILN_RENDER_SERVICE_PORT'];+ else process.env['KILN_RENDER_SERVICE_PORT'] = previous;+ }+ });+});diff --git a/src/cli-render-mode.ts b/src/cli-render-mode.tsindex e39843f5..466e6bfc 100644--- a/src/cli-render-mode.ts+++ b/src/cli-render-mode.ts@@ -11,25 +11,28 @@ import { createHash } from 'node:crypto';* explicitly asked for a guarantee and would rather know than get a quiet downgrade.** There is no GPU dependency to install. Both local and remote GPU are the same HTTP- * render service, so this package installs and runs identically on a machine with no- * GPU at all — which is why `auto` is a safe default.+ * render service — there is no in-process GPU adapter to import, because headless+ * WebGPU needs Node loader hooks that Bun does not run — so this package installs+ * and runs identically on a machine with no GPU at all, which is why `auto` is a+ * safe default. One code path, and a GPU on another machine works exactly like one+ * on this one.+ *+ * Where `auto` LOOKS for a local one, and where {@link RenderPortOptions.autoSpawn}+ * would start one, both resolve through `localRenderServiceUrl` so the two can never+ * disagree about where it lives.*/import type { PbrRenderPort, PbrRenderResult } from './composer/render-port';+import {+ explainRenderServiceState,+ localRenderServiceState,+ localRenderServiceUrl,+ renderServiceDir,+ startLocalRenderService,+} from './render-service-host';import type { KilnToolContext } from './tools/registry';export type RenderMode = 'auto' | 'cpu' | 'gpu';-/**- * Where `auto` looks for a GPU renderer when no URL was given.- *- * Local and remote GPU are the same thing here: an HTTP service that takes GLB- * bytes and returns PNG views. There is no in-process GPU adapter to import —- * headless WebGPU needs Node loader hooks that Bun does not run, so the renderer- * lives behind a socket in both cases. That is a simplification, not a limitation:- * one code path, and a GPU on another machine works exactly like one on this one.- */-const DEFAULT_LOCAL_PORT_URL = 'http://127.0.0.1:8000';-/** Health probe budget. Short: `auto` must not stall a CPU-only machine. */const HEALTH_PROBE_TIMEOUT_MS = 1_500;@@ -124,6 +127,37 @@ export function makeRemoteRenderPort(url: string, token?: string): PbrRenderPort};}+/**+ * A port that gets a renderer listening on its first call, then behaves exactly+ * like {@link makeRemoteRenderPort} for the rest of the session.+ *+ * It deliberately AWAITS the start rather than failing fast and warming in the+ * background. `captureViewsViaPort` already owns a deadline for one in-loop call+ * and degrades to the CPU rasterizer when it expires, so a slow start is already+ * handled by the policy that handles a slow render -- and adding a second budget+ * here would be the duplicated degrade policy AGENTS.md forbids. A start that+ * outruns the in-loop deadline costs one CPU view; the service keeps warming and+ * the next render gets it.+ *+ * A start that FAILS is cached as failed. A renderer that could not start will+ * not start for the next view either, and re-attempting a spawn per render would+ * stall the loop this exists to serve.+ */+export function makeLazyRenderPort(start: () => Promise<string>, token?: string): PbrRenderPort {+ let resolving: Promise<PbrRenderPort> | undefined;+ return async (req) => {+ resolving ??= start().then(+ (url) => makeRemoteRenderPort(url, token),+ (err: unknown) => {+ throw new Error(+ `render service could not start: ${err instanceof Error ? err.message : String(err)}`,+ );+ },+ );+ return (await resolving)(req);+ };+}+/** Fresh attestation per capture; unknown/older/unreachable services bypass cell reuse. */export async function probeCaptureIdentity(url: string): Promise<string | undefined> {try {@@ -253,6 +287,27 @@ interface ViewFidelityLike {degradeReason?: string;}+/** Host policy for {@link buildRenderPort}. Every field is opt-in. */+export interface RenderPortOptions {+ /**+ * Start the render service that ships with this installation when no renderer+ * is already listening. Off by default, and deliberately so: a one-shot CLI+ * invocation should not pay a GPU process's startup to draw one sheet, whereas+ * a long-lived MCP server amortizes it across a whole session.+ *+ * Attaching happens ONLY where a renderer could actually run. On a machine that+ * did not install one, `viewRenderPort` stays absent and the session is+ * byte-identical to one built without this option -- which is what keeps+ * `describeDrawnBy` reporting an ordinary CPU render as ordinary rather than as+ * a degrade.+ */+ autoSpawn?: boolean;+ /** Injection seam for tests: how a service gets started. */+ start?: () => Promise<string>;+ /** Injection seam for tests: where the packaged render service lives. */+ serviceDir?: string;+}+/*** Resolve the requested mode into a tool context. An absent `viewRenderPort` means* the CPU rasterizer — byte-identical to the behavior before ports existed.@@ -260,6 +315,7 @@ interface ViewFidelityLike {export async function buildRenderPort(mode: RenderMode,portUrl: string | undefined,+ options?: RenderPortOptions,): Promise<KilnToolContext> {const context: KilnToolContext = mode === 'gpu' ? { viewRenderRequired: true } : {};const attach = (url: string, label: string): KilnToolContext => {@@ -269,6 +325,19 @@ export async function buildRenderPort(selected.set(context, label);return context;};+ const attachLazy = (start: () => Promise<string>, label: string): KilnToolContext => {+ let url: string | undefined;+ context.viewRenderPort = makeLazyRenderPort(async () => {+ url = await start();+ return url;+ }, process.env['KILN_RENDER_TOKEN']);+ context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;+ // Nothing to attest until a producer exists. `undefined` bypasses cell reuse,+ // which is the correct reading of "no renderer has drawn anything yet".+ context.captureCacheIdentity = () => (url ? probeCaptureIdentity(url) : undefined);+ selected.set(context, label);+ return context;+ };if (mode === 'cpu') {selected.set(context, 'cpu raster');@@ -283,13 +352,32 @@ export async function buildRenderPort(const envUrl = process.env['KILN_RENDER_PORT_URL'];if (envUrl) return attach(envUrl, `GPU service (${envUrl})`);- const rendererId = await probeRenderService(DEFAULT_LOCAL_PORT_URL);- if (rendererId) return attach(DEFAULT_LOCAL_PORT_URL, `GPU service (${rendererId})`);+ const localUrl = localRenderServiceUrl();+ const rendererId = await probeRenderService(localUrl);+ if (rendererId) return attach(localUrl, `GPU service (${rendererId})`);++ // Nothing is listening. If this installation can start one, hand back a port+ // that will -- lazily, so a session that never renders a material never pays+ // for a GPU process, and so the start is not in front of the first connection.+ if (options?.autoSpawn) {+ const dir = options.serviceDir ?? renderServiceDir();+ const state = options.start ? 'ready' : localRenderServiceState(dir);+ if (state === 'ready') {+ const start = options.start ?? (() => startLocalRenderService(dir));+ return attachLazy(start, 'GPU service (started on demand)');+ }+ if (mode === 'gpu')+ throw new Error(+ `no GPU render service is reachable, and ${explainRenderServiceState(state, dir)}.\n` ++ 'Set --render-port or KILN_RENDER_PORT_URL to point at one elsewhere, or use ' ++ '--render auto to fall back to the CPU rasterizer.',+ );+ }if (mode === 'gpu') {throw new Error('no GPU render service is reachable.\n' +- `Looked at ${DEFAULT_LOCAL_PORT_URL}; set --render-port or KILN_RENDER_PORT_URL to ` ++ `Looked at ${localUrl}; set --render-port or KILN_RENDER_PORT_URL to ` +'point somewhere else, or use --render auto to fall back to the CPU rasterizer.',);}diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex a298179d..a351958d 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -51,7 +51,7 @@ export const MCP_SERVER_INSTRUCTIONS = `Kiln turns JavaScript you write into GLBWork by reference. Send a program once to kiln_validate or kiln_render; the result carries a programRef. Keep it exactly as returned, including a short p_ handle, and use it for every later view and edit. kiln_source with that ref and a literal query returns exact edit anchors, and kiln_edit with that ref plus edits returns a new ref and renders by default. Do not resend a whole program to change part of it.-Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material. When materialFaithful is false and the task concerns appearance, say so rather than concluding from a CPU view: material-faithful views come from the GPU render service that ships as render-service/ in this installation, which has its own npm install and is resolved once at server startup.+Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material. When materialFaithful is false and the task concerns appearance, say so rather than concluding from a CPU view: material-faithful views come from the GPU render service that ships as render-service/ in this installation. It has its own npm install; once installed it is started on demand by the first view that needs it, so there is no order to get right and no session to restart.Detailed workflows ship beside this server as Agent Skills, one directory each under ${packagedSkillsDir}:- kiln-setup-workspace: create a managed workspace for authoring, and verify its tools came up@@ -280,10 +280,13 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {if (isDirectEntry(import.meta.url)) {const mode = resolveRenderMode(process.env['KILN_RENDER'] ?? 'auto');- // Resolved once, before the first connection: probing a render service per- // connection would put a network round trip in front of every client attach.+ // One probe before the first connection, so no client attach waits on a network+ // round trip -- but NOT a decision that lasts the session. `autoSpawn` hands+ // back a port that starts the packaged renderer on the first view that needs+ // one, which is the only ordering a user can actually achieve: the harness owns+ // this process's lifecycle, so "start the renderer first" was never theirs to do.const context = await createPackagedLocalToolContext(- await buildRenderPort(mode, process.env['KILN_RENDER_PORT_URL']),+ await buildRenderPort(mode, process.env['KILN_RENDER_PORT_URL'], { autoSpawn: true }),);context.programStore = localProgramStore();context.assetLibrary = localAssetLibrary();diff --git a/src/render-service-host.ts b/src/render-service-host.tsnew file mode 100644index 00000000..8ed2f0b4--- /dev/null+++ b/src/render-service-host.ts@@ -0,0 +1,214 @@+/**+ * Starting the GPU render service that ships beside this package.+ *+ * This is host code, not engine code. The engine never opens a socket and never+ * starts a process; `captureViewsViaPort` stays the single owner of the deadline,+ * the renderer/PNG validation and the never-throw degrade to the CPU rasterizer.+ * Everything here is upstream of that: it decides whether a renderer can exist on+ * this machine and, if so, gets one listening. Nothing in this module is imported+ * by a deterministic render path, and `node:child_process` must not reach one.+ *+ * Why it exists. The render service is reached over HTTP in every case -- local+ * and remote are the same socket -- because headless WebGPU needs Node loader+ * hooks that Bun does not run. That is a good simplification, but it left the+ * local case with a process-ordering problem: the service had to be listening+ * BEFORE the MCP server resolved its port, and the MCP server is started by a+ * coding harness, not by the user. "Start the renderer first" is not an+ * instruction anyone can follow when they do not own the second process.+ *+ * The hosted deployment is untouched. `KILN_RENDER_PORT_URL` and `--render-port`+ * short-circuit ahead of any of this, so a RunPod or Graviton deployment remains+ * one flag and never starts anything locally.+ */+import { spawn, type ChildProcess } from 'node:child_process';+import { existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';++/**+ * The port a locally started service listens on -- deliberately the SAME port the+ * README tells people to start one on by hand, rather than an ephemeral one.+ *+ * An ephemeral port would give every session its own renderer, and a batch of+ * dispatched agents would then hold one GPU context each. On the shared port the+ * first session to arrive starts the service and the rest find it already+ * listening, which is exactly what the documented manual setup produces. It also+ * means an auto-started service and a hand-started one are indistinguishable.+ */+export const DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000;++/**+ * Read per call rather than captured at module load, so a machine whose 8000 is+ * already spoken for can move the renderer with one variable — and so a test can+ * exercise the join path without reserving the real port.+ */+export function localRenderServicePort(): number {+ const raw = Number(process.env['KILN_RENDER_SERVICE_PORT']);+ return Number.isInteger(raw) && raw > 0 && raw < 65_536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;+}++export function localRenderServiceUrl(): string {+ return `http://127.0.0.1:${localRenderServicePort()}`;+}++/** How long a starting service has to answer `/health` before it is called failed. */+const STARTUP_BUDGET_MS = Number(process.env['KILN_RENDER_SERVICE_STARTUP_MS'] ?? 60_000);+const STARTUP_POLL_MS = 250;++/**+ * `render-service/` relative to this module.+ *+ * URL arithmetic only, and it lands correctly from both entry shapes for the same+ * reason `packagedSkillsDir` does: in source this module is `src/*.ts`, and in a+ * package it has been bundled into `dist/*.mjs`. Both sit one level below the+ * installation root.+ */+export function renderServiceDir(): string {+ const override = process.env['KILN_RENDER_SERVICE_DIR'];+ if (override) return override;+ return fileURLToPath(new URL('../render-service', import.meta.url));+}++/**+ * Whether a renderer could be started here, answered from the filesystem alone --+ * no socket, no process, no GPU query.+ *+ * The distinction between the two negative answers is the whole point. Callers+ * must not attach a render port on either of them, because an attached port is+ * what makes `describeDrawnBy` report an ordinary CPU render as a degrade. But+ * they are different things to say to a user: one is "this package did not ship+ * the renderer", the other is "run its install".+ */+export type LocalRenderServiceState = 'ready' | 'dependencies-missing' | 'not-packaged';++export function localRenderServiceState(dir = renderServiceDir()): LocalRenderServiceState {+ if (!existsSync(join(dir, 'src/server.mjs')) || !existsSync(join(dir, 'package.json')))+ return 'not-packaged';+ // The native WebGPU binding is the install that actually costs something, and+ // it is the one that is absent in a fresh package. `three` is checked with it+ // so a half-finished install does not read as ready.+ if (!existsSync(join(dir, 'node_modules/webgpu')) || !existsSync(join(dir, 'node_modules/three')))+ return 'dependencies-missing';+ return 'ready';+}++/** The advice line for a state that cannot render, phrased for whoever has to act. */+export function explainRenderServiceState(state: LocalRenderServiceState, dir: string): string {+ return state === 'dependencies-missing'+ ? `the GPU render service is present but not installed; run \`npm install\` in ${dir}`+ : `this installation does not ship ${dir}`;+}++/** One `/health` request, answering only "is it listening and well". */+async function healthy(url: string, timeoutMs: number): Promise<boolean> {+ try {+ const res = await fetch(new URL('/health', url), { signal: AbortSignal.timeout(timeoutMs) });+ if (!res.ok) return false;+ return ((await res.json()) as { ok?: boolean }).ok === true;+ } catch {+ return false;+ }+}++/**+ * The Node binary to run the service with.+ *+ * Not `process.execPath`: under Bun that is the Bun binary, and the service needs+ * Node's `--import` loader hooks, which is the reason the renderer lives behind a+ * socket in the first place. When we ARE Node, its own path is the most reliable+ * answer available and needs no PATH lookup; otherwise `node` is resolved by the+ * platform, including `node.exe` on Windows.+ */+function nodeBinary(): string {+ const override = process.env['KILN_RENDER_SERVICE_NODE'];+ if (override) return override;+ return process.versions.bun ? 'node' : process.execPath;+}++let child: ChildProcess | undefined;+let teardownRegistered = false;++/** Kill a service this process started. A service it merely found is left alone. */+export function stopLocalRenderService(): void {+ const running = child;+ child = undefined;+ if (!running || running.killed || running.exitCode !== null) return;+ running.kill();+}++function registerTeardown(): void {+ if (teardownRegistered) return;+ teardownRegistered = true;+ // `exit` cannot await, and it does not need to: killing is synchronous. The+ // signal handlers exist because a harness shutting a server down sends one, and+ // without them the renderer would outlive the process that started it.+ process.once('exit', stopLocalRenderService);+ for (const signal of ['SIGINT', 'SIGTERM'] as const)+ process.once(signal, () => {+ stopLocalRenderService();+ });+}++/**+ * Get a local render service listening, and return its base URL.+ *+ * Joins one that is already listening before starting anything, so two sessions+ * racing for the shared port converge on one renderer rather than fighting over+ * it -- including the case where our own spawn loses the race and exits on+ * EADDRINUSE, which is why the loop re-probes rather than trusting the child.+ *+ * Throws when no renderer can be got. Callers turn that into a degrade; this+ * function does not decide policy.+ */+export async function startLocalRenderService(dir = renderServiceDir()): Promise<string> {+ const url = localRenderServiceUrl();+ // Join before starting. A renderer someone else is running is a renderer, and+ // this branch is also what keeps `stopLocalRenderService` honest: `child` stays+ // undefined, so leaving this process never takes down a service it found. A+ // batch of dispatched agents sharing one GPU depends on exactly that.+ if (await healthy(url, 1_500)) return url;++ const state = localRenderServiceState(dir);+ if (state !== 'ready') throw new Error(explainRenderServiceState(state, dir));++ registerTeardown();+ let stderr = '';+ child = spawn(+ nodeBinary(),+ ['--import', join(dir, 'src/register-hooks.mjs'), join(dir, 'src/server.mjs')],+ {+ cwd: dir,+ env: {+ ...process.env,+ PORT: String(localRenderServicePort()),+ // Loopback, where the documented manual start binds every interface. We+ // are choosing on the user's behalf here, so the narrow choice is the+ // right one; the Docker deployment sets its own HOST and is unaffected.+ HOST: '127.0.0.1',+ },+ // NEVER `inherit`: stdout is the MCP transport, and the service greets its+ // own boot on stdout. One `listening on :8000` line in that stream is a+ // protocol error for every tool call after it.+ stdio: ['ignore', 'ignore', 'pipe'],+ },+ );+ child.stderr?.on('data', (chunk: Buffer) => {+ stderr = `${stderr}${chunk.toString()}`.slice(-2_000);+ });++ const deadline = Date.now() + STARTUP_BUDGET_MS;+ while (Date.now() < deadline) {+ if (await healthy(url, 1_000)) return url;+ if (child.exitCode !== null || child.signalCode !== null) {+ // Losing the port race is a success: somebody else's renderer is listening.+ if (await healthy(url, 1_500)) return url;+ child = undefined;+ throw new Error(+ `render service exited during startup${stderr.trim() ? `: ${stderr.trim().split('\n').slice(-3).join(' ')}` : ''}`,+ );+ }+ await new Promise((done) => setTimeout(done, STARTUP_POLL_MS));+ }+ stopLocalRenderService();+ throw new Error(`render service did not answer within ${STARTUP_BUDGET_MS}ms`);+}