Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

feat: open-source release — CLI, Agent Plugin, and GPU render service

Matt Kissinger868e89f2b43d
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 00000000..998e140a
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
+ "name": "kiln",
+ "description": "Kiln — author 3D assets as code, with a vision-in-the-loop agent that renders its own work and looks at it",
+ "owner": {
+ "name": "Matt Kissinger"
+ },
+ "plugins": [
+ {
+ "name": "kiln",
+ "description": "Author 3D assets as code: your agent writes a Kiln program, renders it, looks at the six-view contact sheet, and fixes what it sees. Outputs a game-ready GLB.",
+ "author": { "name": "Matt Kissinger" },
+ "category": "development",
+ "source": "./"
+ }
+ ]
+}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
new file mode 100644
index 00000000..e51096af
--- /dev/null
+++ b/.claude-plugin/plugin.json
@@ -0,0 +1,31 @@
+{
+ "name": "kiln",
+ "description": "Author 3D assets as code: your agent writes a Kiln program, renders it, looks at the six-view contact sheet, and fixes what it sees. Outputs a game-ready GLB.",
+ "version": "0.6.0",
+ "author": {
+ "name": "Matt Kissinger"
+ },
+ "homepage": "https://github.com/matthew-kissinger/kiln",
+ "license": "MIT",
+ "keywords": [
+ "3d",
+ "glb",
+ "gltf",
+ "asset-generation",
+ "three.js",
+ "gamedev"
+ ],
+ "mcpServers": {
+ "kiln": {
+ "type": "stdio",
+ "command": "bun",
+ "args": [
+ "run",
+ "${CLAUDE_PLUGIN_ROOT}/src/mcp-server.ts"
+ ],
+ "env": {
+ "KILN_RENDER": "auto"
+ }
+ }
+ }
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 61de8b19..328dd4b7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -13,6 +13,11 @@ concurrency:
permissions:
contents: read
+env:
+ # Views must be byte-reproducible in CI: never let a runner that happens to have
+ # a GPU render service reachable change what the golden-image tests compare.
+ KILN_RENDER: cpu
+
jobs:
checks:
name: typecheck · lint · test
diff --git a/AGENTS.md b/AGENTS.md
index efcf0156..cb236ccd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,34 +2,48 @@
## Scope
-This repository is the private `@kiln/engine` source of truth. It turns model-authored TypeScript into
-GLB assets and includes deterministic rendering, validation/QA, primitives, agent tools, arena
-ranking, and scene composition. Product UI, API, auth, storage, AgentCore runtime, SDK, realtime, and
-IaC belong in the sibling `../kiln-studio/` repository; do not implement those here.
+This repository turns model-authored source into GLB assets. It includes deterministic rendering,
+validation/QA, primitives, the agent tool surface, arena ranking, scene composition, a CLI, and an
+Agent Plugin (MCP server + skills).
Read [README.md](./README.md) before changing exports or package contents. Runtime code is under
`src/`; tests are colocated as `*.test.ts` or under `__tests__/`. Repository-only checks live under
`scripts/`. The package intentionally ships TypeScript source through the explicit `files` and
`exports` lists in `package.json`.
+## The tool registry is the single source of truth
+
+`src/tools/registry.ts` owns tool names, descriptions, and schemas. Two skins consume it: the
+in-process Strands tools (`src/agent/tools.ts`) and the stdio MCP server. **Both must iterate the
+registry** — never hand-write a tool definition in a skin, or the transports drift apart and the
+repo's central claim stops being true. There is a test that asserts name parity; keep it passing.
+
+Prefer an explicit terminal submit tool over `structuredOutputSchema` in the in-process loop: the
+latter's coexistence with a full tool set is provider-dependent, while a submit tool is unambiguous
+everywhere. The MCP surface has no submit tool, because there the host agent writes the file itself.
+
## Host-injected render and cache boundaries
-The engine defines the host-injected `PbrRenderPort`; Studio owns the HTTP adapter, authentication,
-environment configuration, production service, and EMF telemetry. Exported `captureViewsViaPort` is
-the single owner of the deadline, renderer/PNG validation, grid composition, and never-throw CPU
-fallback. Do not duplicate that degrade policy in a host or introduce network/service knowledge into
-the deterministic engine paths.
+The engine defines the host-injected `PbrRenderPort`. Exported `captureViewsViaPort` is the **single
+owner** of the deadline, renderer/PNG validation, grid composition, and never-throw CPU fallback. Do
+not duplicate that degrade policy in a host or introduce network/service knowledge into the
+deterministic engine paths.
-The port is injected twice, for different jobs, and their deadlines must stay separate. The host
-calls it once after the loop for the artifact sheet, where nothing is blocked and a long deadline is
+The port is injected twice, for different jobs, and their deadlines must stay separate. A host calls
+it once after the loop for the artifact sheet, where nothing is blocked and a long deadline is
correct. `KilnToolContext.viewRenderPort` injects it into `kiln_render` for the IN-LOOP grid, where a
slow render blocks the agent mid-thought — that deadline is its own per-call argument and belongs far
-lower. Never collapse the two onto one value. Routing there is conditional on
-`sceneNeedsPbrShading(root)`: bound texture or `metalness > 0`, never material type, because
-`gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial` and are indistinguishable
-after construction. Host telemetry still rides `onViewsRendered`, while every unified `kiln_render`
-result also carries model-visible `ViewFidelityV1`; a geometry-flat CPU image must never be treated as
-material evidence. Keep the input schema stable unless the active program explicitly versions it.
+lower. Never collapse the two onto one value.
+
+Routing is conditional on `sceneNeedsPbrShading(root)`: bound texture or `metalness > 0`, never
+material type, because `gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial` and
+are indistinguishable after construction. Host telemetry rides `onViewsRendered`, while every unified
+`kiln_render` result also carries model-visible `ViewFidelityV1`; a geometry-flat CPU image must never
+be treated as material evidence. Keep the input schema stable unless the active change explicitly
+versions it — the tool definition is cached, and changing it invalidates that cache.
+
+**The GPU is a view producer only, never gate evidence.** `QaContext` is deliberately image-free so a
+QA rule structurally cannot read a render buffer. Do not add pixels to it.
`src/views/renderer-id.ts` runs `readFileSync` at MODULE LOAD. Reach `CPU_RASTER_RENDERER_ID` through
the lazy `await import('../views')` that render paths already use; a static import puts a `node:fs`
@@ -43,8 +57,8 @@ Preserve that distinction and the provider usage fields when changing model rout
## Toolchain and validation
-Supported CI toolchain: Bun `1.3.14`; Node `22.23.1`; npm `12.0.1`. Do not use a Bun canary or implicit latest for a
-release gate.
+Supported toolchain: Bun `1.3.14`; Node `22.23.1`; npm `12.0.1`. Do not use a Bun canary or implicit
+latest for a release gate.
```bash
bun install --frozen-lockfile
@@ -61,38 +75,17 @@ and enforces the checked-in line/function ratchet in `bunfig.toml`. Raise thresh
do not lower them without an explicit measured rationale. Live model tests are opt-in only via
`bun run test:live` and may spend money.
+Tests and CI pin `KILN_RENDER=cpu`. The coverage ratchet must not vary by whether the runner has a
+GPU.
+
Use strict test-driven development for behavior changes: add a focused failing test, observe the
expected failure, implement the smallest fix, and rerun both the focused and full gates. Preserve
determinism and do not add `Date.now()` or `Math.random()` to render/rasterizer compute paths.
-## Engine consumption and package boundary
-
-Studio consumes a committed tarball, never a path link. After an approved engine change, refresh it
-from Studio—not from this repository:
-
-```bash
-cd ../kiln-studio
-bun run sync:engine
-bun install
-```
-
-Do not hand-edit `../kiln-studio/agent-runtime/vendor/kiln-engine.tgz`. Before handing off, inspect a
-package dry run and ensure tests, repository scripts, coverage output, and `AGENTS.md` have not entered
-the tarball.
-
-Container-manifest trap: Studio's local root `node_modules` can hide missing production dependencies.
-The API image installs its own manifest with Bun; the Agent image installs
-`agent-runtime/package.json` with `npm --legacy-peer-deps`. Engine optional provider peers must be
-explicit in every consuming image manifest that needs them. Follow `../kiln-studio/CLAUDE.md` and its
-current container boot-validation runbook before any deployment.
-
## Safety
-- Keep the raw engine/tool surface private; Studio `/v1` is the approved external product boundary.
-- Never print, read unnecessarily, or commit provider keys, AWS credentials, `.env*`, or secrets.
+- Never print, read unnecessarily, or commit provider keys, cloud credentials, `.env*`, or secrets.
- Keep normal validation offline. Do not invoke live providers unless explicitly requested.
-- Do not deploy, commit, push, force-push, create remotes/releases, mutate AWS, or publish packages
- without explicit user approval. Production changes belong to Studio's guarded deploy flow.
-- Do not edit the historical `pixel-forge` repository or use it as a build dependency.
-- Do not edit the workspace root or sibling Studio while performing an engine-only task, except when
- the user explicitly expands scope or requests the documented tarball synchronization.
+- Do not commit, push, force-push, create remotes/releases, or publish packages without explicit user
+ approval.
+- Live model and arena runs spend money. Keep them manual and out of CI.
diff --git a/README.md b/README.md
index 51f7ded0..5c96cb12 100644
--- a/README.md
+++ b/README.md
@@ -1,125 +1,259 @@
-# @kiln/engine
+# Kiln
-The **Kiln 3D engine** — a sentence in, a game-ready GLB out. A model-agnostic
-Strands agent loop drives a tool surface (`list → validate → render → screenshot →
-finalize`) over a primitive/CSG library, a deterministic pure-CPU rasterizer that
-lets the model *see* its asset, and post-bake grading (instanceability, palette
-consolidation). Plus a Bradley-Terry pairwise **arena** for ranking. A scene **composer** (a THREE-free
-placement core — layout, overlap resolution, a small scene DSL — plus its own Strands
-agent loop) arranges many finished assets into one coherent, overlap-free scene.
+**A vision-in-the-loop code-generation agent that builds 3D assets as source code.**
-Extracted from the `pixel-forge` monorepo (`packages/core/src/kiln`) as a lean,
-self-contained package: **no Playwright, no 2D image SDKs, no FBX/imposter/LOD
-pipeline** — just the text-to-GLB engine Kiln Studio runs in production.
+Kiln turns a sentence into a game-ready GLB by having a model *write a program*, look at what it
+rendered, and fix it — not by sampling a mesh. The output is a small program with named parts, not
+an opaque blob: editable, diffable, parametric, and readable by the next agent that touches it.
-> **Private package.** Not published to npm. Consumed by the `kiln-studio` app via a
-> **committed tarball** (`agent-runtime/vendor/kiln-engine.tgz`, refreshed by `sync:engine`)
-> for local dev, CI, and both Docker images — NOT a path-link (`file:../kiln` hits a Windows
-> `EPERM` copying native deps). See `../plan/`.
+![Six-view contact sheet of a procedurally generated stone well](examples/hero-sheet.png)
-## External Access Boundary
+*The contact sheet the model looks at — `examples/well.kiln.js`, 472 triangles, three PBR materials
+with bound albedo/normal/ARM maps:*
+`bun run kiln render examples/well.kiln.js --views sheet.png`
-Do not expose this engine package, its raw tool surface, or its composer harness directly to external
-users. The approved private developer interface lives in the sibling `kiln-studio` repo:
+## What this is
-- Studio `/v1` is the product contract for REST, SDK, and future AgentCore Gateway MCP tools.
-- Studio owns `DeveloperClient` auth, scopes, quotas, audit, S3/Dynamo ownership, and artifact URLs.
-- The generation AgentCore Runtime and this engine stay private execution infrastructure.
-- Product-level tools may expose asset/pack/scene planning, validation, generation, composition, and
- downloads, but not raw `kiln_render`, `kiln_screenshot`, `scene_place`, `scene_render`,
- `scene_finalize`, transcripts, storage keys, or provider keys.
+A working reference implementation of an agent loop that can **see its own work**:
-For current access and distribution decisions, see
-`../kiln-studio/docs/launch/11-private-developer-platform-prod-handoff.md`.
+```
+list primitives -> write program -> validate (AST) -> render -> look at six views -> fix -> finalize
+```
+
+The interesting parts are architectural, and they generalize past 3D:
+
+- **One tool definition, two transports.** [`src/tools/registry.ts`](src/tools/registry.ts) is the
+ single source of truth. The in-process Strands skin and the MCP server both iterate it, so tool
+ names and schemas cannot drift apart.
+- **Deterministic gates, kept separate from model judgment.** Self-intersection, part connectivity,
+ triangle budget, and AST validation all fail closed with no model call. `QaContext` is
+ deliberately image-free so a QA rule *structurally cannot* read a render buffer.
+- **A render port with a fail-closed degrade.** `captureViewsViaPort` owns the deadline, PNG
+ validation, grid composition, and a never-throw fallback. Renderers are swappable; correctness
+ does not depend on which one ran.
+- **Budgets and compaction** as first-class concerns, because agent loops that render images run
+ out of context and money.
+
+## What this is not
-## Install
+- **Not photoreal reconstruction.** Output is stylized to mid-fidelity procedural geometry. If you
+ want a scanned-looking mesh, use a diffusion model — Trellis, Hunyuan3D and friends are better at
+ that, and it isn't close.
+- **Not a mesh generator.** No diffusion, no photogrammetry, no point cloud. A model writes code;
+ the code builds geometry.
+- **Not novel in category.** [img2threejs](https://github.com/img2threejs/img2threejs) is an
+ architectural peer running the same essential loop. Kiln differs in being TypeScript/Strands, in
+ running its vision loop with no browser required, and in its deterministic gate layer.
+- A single reference view cannot reveal hidden sides. Assets are inferred, not measured.
+
+## Quickstart
+
+**No API key required.** Render an existing Kiln program and look at the result:
```bash
+git clone https://github.com/matthew-kissinger/kiln && cd kiln
bun install
-bun run typecheck # tsc --noEmit
-bun run test # bun test (offline; live agent tests gated behind KILN_SPIKE_LIVE=1)
-bun run test:coverage # LCOV report plus the checked coverage ratchet
+bun run kiln render examples/crate.kiln.js --out crate.glb --views sheet.png
```
-The reliability baseline is **95.38% functions / 91.80% lines**. CI enforces
-non-regression ratchets of 92% functions and 91% lines and uploads `coverage/lcov.info`.
-Threshold decreases require an explicit measured rationale.
+That exercises the geometry build, the QA gates, and the rasterizer with no model and no key. The
+default `--render auto` briefly looks for a local GPU render service and falls back to the CPU
+rasterizer when there is none, so this works unchanged on a machine with no GPU.
+
+To generate from a prompt, set one provider key and:
+
+```bash
+bun run kiln generate "a weathered wooden crate" --out crate.glb
+```
+
+## Rendering: three modes
+
+Kiln renders the views the model looks at, and there are three ways to do it. All three are in this
+repository; none requires a cloud account.
+
+```bash
+--render auto # default: local GPU service if one is up, else CPU
+--render cpu # force the deterministic CPU rasterizer
+--render gpu # force GPU; error rather than degrade
+--render-port <url> # a GPU render service anywhere, local or remote
+```
+
+### What the difference actually looks like
+
+The same program — the well above — rendered both ways:
+
+| CPU rasterizer | GPU PBR |
+|---|---|
+| ![Well rendered flat-shaded, brickwork invisible](examples/well-cpu.png) | ![Same well with brick texture and normal relief visible](examples/well-gpu.png) |
+
+Geometry is equally legible in both: silhouette, proportion, orientation, part contact. But the
+brick curb is **flat grey** on the CPU. Not dimmer — *absent*. The albedo, normal, and ARM maps that
+make it stone simply do not exist in a flat-shaded render, and neither does the metal on the
+windlass.
+
+**If your assets have textures or metal, use the GPU.** That is most real assets, and it is why
+`auto` reaches for a GPU first. The CPU rasterizer is the floor that guarantees the loop runs
+anywhere — CI, a container, a laptop with no GPU — not the target.
+
+This is also why every render reports `viewFidelity`. When `materialFaithful` is false the agent is
+told, in band, that it may judge geometry and **not** material. An agent that cannot see a texture
+must not conclude the texture is wrong.
+
+| | CPU raster | GPU PBR |
+|---|---|---|
+| Why it exists | Runs where there is no GPU at all | Material, texture, and metal legibility |
+| Cost | None | A render service, local or remote |
+| Determinism | Byte-identical | Varies by driver and adapter |
+| Honest about | Silhouette, proportion, orientation, contact | All of that, plus material |
+| Role | Guaranteed floor and fallback | What you want for textured assets |
+
+### Running the GPU renderer
+
+[`render-service/`](render-service/) in this repository is the renderer: GLB bytes in, PBR PNG views
+out, headless three.js `WebGPURenderer` on Dawn. No browser and no X server.
+
+```bash
+cd render-service && npm install && npm start
+```
+
+That is **gpu (local)**. It listens on `:8000`, which is where `--render auto` looks, so nothing else
+needs configuring — the next `kiln render` picks it up and says so:
+
+```
+sheet.png (GPU dawn-d3d12:nvidia-geforce-rtx-3070:D3D12 driver version 32.0.16.1074)
+```
+
+For **gpu (remote)**, run the same service on a GPU box (there is a `Dockerfile`) and point at it:
+
+```bash
+kiln render asset.kiln.js --render-port https://your-renderer.example --views sheet.png
+```
+
+The service refuses to boot on a software adapter, so a driver regression gives you a renderer that
+will not start rather than one that silently renders on CPU and lies about it.
+
+With nothing reachable, `auto` falls back to the CPU rasterizer, which is why a machine with no GPU
+needs no configuration at all. `captureViewsViaPort` owns the deadline, PNG validation, grid
+composition, and a never-throw fallback: a slow or broken renderer costs fidelity, never correctness.
+
+**The GPU is a view producer only — it is never gate evidence.** QA rules never see pixels.
+
+## Use it from your agent
+
+Kiln ships as an [Agent Plugin](https://agentplugins.codes/): an MCP server exposing the tool
+surface, plus skills that teach an agent how to use it well. It works in Claude Code, Codex CLI,
+Cursor, and any other client supporting the standard.
+
+The MCP server exposes the **raw tools**, which means *your* agent is the author — it writes the
+program, looks at the render, and iterates using its own model. No separate provider key, no nested
+agent loop.
+
+Note that in this mode your harness supplies both the author and the vision judge. The
+deterministic gates still run independently, but the eyes/judge separation the production system
+maintained is collapsed. That is a deliberate trade for portability.
+
+## Tool surface
+
+| Tool | What it does |
+|---|---|
+| `kiln_list_primitives` | the primitive/helper catalog with signatures |
+| `kiln_validate` | AST validation — syntax, structure, infinite loops, recursion, triangle budget |
+| `kiln_render` | build the scene, return metrics **and** the six-view sheet, in one call |
+| `kiln_screenshot_animation` | frames of an `animate()` program, so motion is visible too |
+| `kiln_view_interior` | interior camera, for anything enterable |
+| `kiln_inspect` | close-up orbit camera on a named part |
+
+Every one of these comes from a factory in [`src/tools/registry.ts`](src/tools/registry.ts); no
+transport hand-writes a definition, and `src/mcp-parity.test.ts` is what keeps that true.
+
+`kiln_render` here is the *unified* definition — the one that returns metrics and pixels together,
+accepts a custom camera capture, routes to the GPU when the scene needs PBR shading, and reports
+`viewFidelity` so the agent knows whether it may judge material from what it is looking at. The
+engine also carries a frozen four-tool bench baseline whose `kiln_screenshot` is CPU-only by
+construction; the in-process loop still runs that baseline plus a terminal `kiln_submit`. Shipping
+the baseline over MCP would have meant shipping a surface the render port can never reach.
## Subpath exports
-The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by subpath:
+The engine ships TypeScript source; consume by subpath:
| Import | What |
|---|---|
-| `@kiln/engine/agent` | the Strands agent loop, model factory, tool surface, edit buffer, unified-diff |
-| `@kiln/engine/render` | GLB build + serialize, `grade`/`optimize`/`snap`, `composeScene` (the core bake) |
-| `@kiln/engine/palette` | canonical `OPTIMIZED_PALETTE` + directive (pure data, browser-safe) |
-| `@kiln/engine/views` | the pure-CPU six-view rasterizer + `node:zlib` PNG encoder (`kiln_screenshot`) |
-| `@kiln/engine/arena` | Bradley-Terry + adaptive pairwise sampling (pure math) |
-| `@kiln/engine/validation` | structural validator + AST analysis (acorn) |
-| `@kiln/engine/primitives` | the 70+ primitive/helper registry |
-| `@kiln/engine/material-resources`, `/texture-resolver` | trusted-host approved texture registry and bounded resolver injection; generated code sees only approved resource IDs |
-| `@kiln/engine/prompt`, `/prompt-api`, `/list-primitives` | system-prompt generation + catalog |
-| `@kiln/engine/metrics`, `/inspect` | instanceability grade + scene-structure analysis |
-| `@kiln/engine/contracts` | browser-safe asset and integration contracts, including `IntegrationManifestV1` and the semantic role vocabulary (`KILN_SEMANTIC_ROLES`, `semanticRole`, `semanticRoleMatches`, `hasSemanticRole`) |
-| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (canonical `WorldDocumentV2`, strict reconciliation, sockets/zones/paths/spawns, deterministic terrain, collider/reachability contracts, presentation receipts, `WorldPackageV2`, layout/overlap/DSL) + bounded compose and post-compose integration loops (`runKilnComposer`, `runKilnWorldIntegration`) |
-| `@kiln/engine/world-runtime` | dependency-free browser-safe heightfield V1 parser/codec/hash/sampler/mesh projection; Studio `sync:engine` may copy this exact leaf and stamp its source SHA so frontend/Play run the Engine-owned implementation without importing the Engine package |
-
-Composer V2 uses one canonical-world authority. For a fresh scene, run the ordinary composer,
-migrate its evaluated candidate with `migrateSceneModelV1ToWorldDocumentV2`, then pass that world to
-`runKilnWorldIntegration`. For refine, merge the migrated candidate into the parent with
-`reconcileWorldDocumentV2Candidate` first; that preserves terrain/authored/runtime state and applies
-locked asset-swap semantics. The bounded integration loop renders and finalizes the same world state
-its `scene_world_*` tools mutate. Pass one `generationCallBudget` through both `runKilnComposer` and
-`runKilnWorldIntegration` so the host settles one aggregate allowance; the integration stage otherwise
-requires an explicit positive `maxSteps`, with no hidden second-stage call allowance.
-Collider artifacts, reachability reports, presentation documents, and `WorldPackageV2` are strict,
-canonical, hash-bound contracts. They preserve source compatibility by extending `WorldDocumentV2`
-additively; browser capture and runtime consumption must still verify the declared external artifact
-bytes rather than trusting paths or labels.
-Heightfield artifact SHA-256 binds the exact bytes from
-`encodeHeightfieldArtifactV1`; portable asset paths remain the additive package contract
-`models/<generationId>.glb`.
-
-Finished renders include `integrationManifest`, a versioned sidecar with the artifact
-hash, metres/+Y-up axes, bounds, grounding offset, selected default scene, role, render
-metrics, and structural QA. Consumers that only have GLB bytes can derive the same
-sidecar with `inspectGlbIntegration(bytes)` from `@kiln/engine/render`; the inspection
-path parses the artifact and never executes model-authored source code. Visual quality
-remains explicitly `not_assessed` until a browser QA loop evaluates the asset in its
-actual scene.
+| `kiln/tools` | the tool registry — the single source of truth, and free of any agent SDK |
+| `kiln/agent` | the Strands agent loop, model factory, tool surface, edit buffer, unified diff |
+| `kiln/render` | GLB build + serialize, grade/optimize/snap, `composeScene` |
+| `kiln/views` | the pure-CPU six-view rasterizer + `node:zlib` PNG encoder |
+| `kiln/validation` | structural validator + AST analysis (acorn) |
+| `kiln/primitives` | the primitive/helper registry |
+| `kiln/qa` | the deterministic QA gate registry and corpora |
+| `kiln/arena` | Bradley-Terry + adaptive pairwise sampling, for model bake-offs |
+| `kiln/palette` | canonical `OPTIMIZED_PALETTE` + directive (pure data, browser-safe) |
+| `kiln/metrics`, `kiln/inspect` | instanceability grade + scene-structure analysis |
+| `kiln/contracts` | asset and integration contracts, `IntegrationManifestV1`, semantic roles |
+| `kiln/composer` | THREE-free scene composition — layout, overlap resolution, scene DSL |
+
+Finished renders include `integrationManifest`, a versioned sidecar carrying the artifact hash,
+metres/+Y-up axes, bounds, grounding offset, default scene, role, render metrics, and structural QA.
+Consumers holding only GLB bytes can derive the same sidecar with `inspectGlbIntegration(bytes)`;
+that path parses the artifact and never executes model-authored source.
+
+Visual quality stays explicitly `not_assessed` until something actually looks at the asset in its
+real scene. Structural validation is not a visual pass.
+
+## Determinism
+
+Render and rasterizer compute paths use no `Date.now()` or `Math.random()`, so CPU six-view output
+is byte-reproducible — the basis for golden-image tests. Inject seeds and timestamps at the
+boundary.
+
+## Tests
+
+```bash
+bun run typecheck
+bun run test # offline; live agent tests gated behind KILN_SPIKE_LIVE=1
+bun run test:coverage # LCOV plus the checked coverage ratchet
+```
+
+Baseline is **95.38% functions / 91.80% lines** across 130 test files. CI enforces non-regression
+ratchets of 92% and 91% and uploads `coverage/lcov.info`.
+Threshold decreases require an explicit measured rationale.
+Tests pin `KILN_RENDER=cpu` so coverage cannot vary by runner GPU.
## Dependencies
Runtime: `three`, `@gltf-transform/*`, `manifold-3d` (CSG, WASM), `three-subdivide`,
-`acorn`/`acorn-walk`, `zod`, `@openrouter/ai-sdk-provider`, plus lazy-loaded `sharp`
-(texture decode) and `xatlasjs` (UV atlas). The agent stack —
-`@strands-agents/sdk` + `@ai-sdk/provider` — is an **optional peer**: install it only
-when you use `@kiln/engine/agent`.
+`acorn`/`acorn-walk`, `zod`, plus lazy-loaded `sharp` (texture decode) and `xatlasjs` (UV atlas).
+The agent stack — `@strands-agents/sdk` + `@ai-sdk/provider` — is an **optional peer**: install it
+only if you use `kiln/agent`.
-### `@ai-sdk/provider` is pinned to v3 by Strands, not by us
+Textures are eight [Poly Haven](https://polyhaven.com) CC0 families, embedded with source provenance
+retained. Runtime output is self-contained and never calls Poly Haven.
-Do not bump `@ai-sdk/provider` to v4 or `@openrouter/ai-sdk-provider` to v3. The blocker is
-`@strands-agents/sdk`: every version through **1.11.1** peers `@ai-sdk/provider@^3.0.0`, and its
-`VercelModel` — which every OpenRouter model here is wrapped in — is typed against
-`LanguageModelV3`. A type cast does not help, because Strands emits V3 shapes at *runtime*:
-`vercel.js` sends `{type: 'file', data: <bare bytes>}` where V4 expects `{type: 'data', data}`, and
-`{type: 'file-data', ...}`, which does not exist in V4 at all.
+### `@ai-sdk/provider` is pinned to v3 by Strands, not by us
-`@ai-sdk/provider` v4 itself is purely additive, and our only real code change would be one string
-(`'file-data'` → `'file'`) in three files — which is exactly why this looks deceptively easy. Stay on
-`@openrouter/[email protected]` until Strands ships v4 support.
+Do not bump `@ai-sdk/provider` to v4 or `@openrouter/ai-sdk-provider` to v3. Every
+`@strands-agents/sdk` version through 1.11.1 peers `@ai-sdk/provider@^3.0.0`, and its `VercelModel`
+is typed against `LanguageModelV3`. A cast does not help, because Strands emits V3 shapes at
+*runtime*: `vercel.js` sends `{type: 'file', data: <bare bytes>}` where V4 expects
+`{type: 'data', data}`, plus `{type: 'file-data', ...}`, which does not exist in V4 at all.
-Note also that the `ai` package is an unused devDependency here; the engine imports it nowhere, so
-"migrate `ai` v6 → v7" is not the task it appears to be.
+v4 is purely additive and the only real change here would be one string in three files — which is
+exactly why it looks deceptively easy. Stay on `@openrouter/[email protected]` until Strands
+ships v4 support.
-## Determinism
+## History
-Render/rasterizer compute paths are deterministic — no `Date.now()` / `Math.random()` —
-so six-view output is byte-reproducible (the basis for golden-image tests). Inject
-seeds/timestamps at the boundary.
+Kiln was a commercial text-to-3D product. It is shut down; this is the engine, which is the half
+that stays true regardless of how the product did.
-## Provenance
+Some of the design here reflects constraints that no longer apply — most visibly the CPU rasterizer,
+which exists because the production agent runtime container had no GPU. Where an original decision
+made sense only for a hosted multi-tenant product, this repo does the thing that makes sense for an
+open one, and `docs/history/` records what the production system did and why.
-Initial extraction from `pixel-forge@d396c10`, file history preserved via
+Initially extracted from the `pixel-forge` monorepo with file history preserved via
`git subtree split`. See `CHANGELOG.md`.
+
+## License
+
+MIT. See [LICENSE](LICENSE).
diff --git a/bun.lock b/bun.lock
index 964fabd3..2ff3590d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8,6 +8,8 @@
"@gltf-transform/core": "^4.4.1",
"@gltf-transform/extensions": "^4.4.1",
"@gltf-transform/functions": "^4.4.1",
+ "@modelcontextprotocol/client": "^2.0.0",
+ "@modelcontextprotocol/server": "^2.0.0",
"@openrouter/ai-sdk-provider": "^2.10.0",
"@types/three": "^0.185.1",
"acorn": "^8.17.0",
@@ -188,7 +190,13 @@
"@jscadui/3mf-export": ["@jscadui/[email protected]", "", {}, "sha512-y5vZktqCjyi7wA38zqNlLIdZUIRZoOO9vCjLzwmL4bR0hk7B/Zm1IeffzJPFe1vFc0C1IEv3hm8caDv3doRk9g=="],
- "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
+ "@modelcontextprotocol/client": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
+
+ "@modelcontextprotocol/core": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
+
+ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],
+
+ "@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="],
diff --git a/docs/history/production-architecture.md b/docs/history/production-architecture.md
new file mode 100644
index 00000000..90c0fbda
--- /dev/null
+++ b/docs/history/production-architecture.md
@@ -0,0 +1,116 @@
+# What the production system did, and why
+
+Kiln was a commercial text-to-3D product. It is shut down. This document records what the hosted
+system looked like, because several decisions still visible in this repo only make sense against
+that background — and because the reasoning is the interesting part.
+
+Nothing here is required to use the engine. It is history.
+
+## The shape of it
+
+```
+Browser / SDK / MCP client
+ |
+ CloudFront -> ALB -> ECS Fargate API (Bun, Hono)
+ |
+ Bedrock AgentCore Runtime (the generation loop; a BYO TypeScript container)
+ |
+ this engine (vendored) -> GLB + six-view sheet
+ |
+ private S3 artifacts, DynamoDB state, Cognito identity
+```
+
+An `AgentCore Gateway` projected a subset of the product API as hosted MCP tools. A separate
+Cloudflare Durable Objects tier handled realtime presence. A private GPU render service ran on
+RunPod serverless, outside the AWS release identity.
+
+## Decisions that outlived the product
+
+These are still in the code and still correct.
+
+### The render port owns its own degrade
+
+`captureViewsViaPort` — in the engine, not the host — owns the deadline, PNG decode and count
+validation, grid composition, and a never-throw fallback to the CPU rasterizer. The host adapter
+deliberately just builds a request, POSTs it, and maps the response; its thrown errors are
+*intentional*, because the shell catches them.
+
+This was the right call in production and it is the right call here. It means a renderer is
+swappable without correctness depending on which one ran, and it is why adding a local GPU adapter
+was a small change rather than a risky one.
+
+### The GPU is a view producer, never gate evidence
+
+`QaContext` is image-free by construction, so a QA rule cannot structurally read a render buffer.
+Deterministic gates see geometry only.
+
+The reason: GPU output varies by driver and adapter. If a gate could read pixels, gate results would
+vary by hardware, and a passing build on one machine would fail on another. Keeping the expensive,
+non-deterministic eye out of the judge path is what makes the gates trustworthy.
+
+### Two injection seams, two deadlines
+
+The port is injected twice. Once after the loop, for the artifact sheet — nothing waits on it, so a
+long deadline (120s in production) is correct. Once inside `kiln_render`, for the grid the model
+actually looks at — that one blocks the agent mid-thought, so it got 6s.
+
+Collapsing those onto one value breaks one of the two jobs. In production, using the post-loop
+deadline in-loop would have stalled every first render of a session, because serverless GPU cold
+resume measured 14-43 seconds.
+
+### Conditional GPU routing
+
+Originally the GPU ran only *after* the loop. That meant the model authored materials it could never
+see: it wrote `pbrMaterial(...)`, then checked its work against a flat-shaded image that cannot show
+whether the result reads as wet stone or as plastic.
+
+Routing GPU renders into the loop fixed that, conditionally — `sceneNeedsPbrShading` checks bound
+textures and `metalness > 0`, and nothing else. Material *type* is deliberately not consulted,
+because `gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial` and are
+indistinguishable after construction. Roughness is not a signal either, since `gameMaterial` sets it
+by default.
+
+## Decisions that were product-specific, and are reversed here
+
+### Raw tools were never exposed over MCP
+
+The product had an explicit "External Access Boundary": never expose raw `kiln_render`,
+`kiln_screenshot`, `scene_place`, transcripts, storage keys, or provider keys to external callers.
+The hosted MCP surface was a five-tool progressive-discovery facade
+(`status` / `operations.search` / `operations.describe` / `operations.execute` / `resources.get`)
+over the product API, where a generate call dispatched into the AgentCore runtime and returned a
+finished artifact.
+
+That existed because the product had tenancy, billing, quotas, and per-caller scopes to protect, and
+because the paid operation catalog was too large to put in a model's context.
+
+**This repo does the opposite.** There is no tenancy and no billing, the tool set is small, and
+exposing the raw registry over MCP is the entire point: your agent becomes the author. The
+progressive-discovery pattern was a good answer to a problem this repo does not have.
+
+### The CPU rasterizer was a constraint, not a preference
+
+`src/views/raster.ts` exists because the production agent runtime container had no GPU and no
+browser: it shipped with `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`, Playwright is unsupported under Bun
+on Windows, and `headless-gl` is WebGL1 while three >= r163 requires WebGL2. So: a dependency-free
+scanline z-buffer rasterizer, flat lambert, base color only.
+
+It turned out to be worth keeping for reasons that had nothing to do with the original constraint —
+it is deterministic, it needs no install, and it is sufficient for silhouette, proportion,
+orientation, and contact. But it was never chosen as the better renderer, and this repo does not
+pretend otherwise.
+
+### Quotas, spend reservations, and approval envelopes
+
+The product metered real money per call: durable fenced ownership, caller-scoped idempotency, spend
+reservations, provider-usage checkpoints, and recovery-safe settlement. None of that ships here.
+
+Call budgets *do* ship, because bounding an agent loop's calls is a genuine engineering concern
+independent of billing.
+
+### The vendored tarball seam
+
+The engine reached the product as a committed tarball refreshed by a `sync:engine` script, rather
+than a path link, because `file:../kiln` hits a Windows `EPERM` copying native dependencies across
+two private repositories. With one public repo and normal package resolution, that machinery is
+unnecessary.
diff --git a/docs/install.md b/docs/install.md
new file mode 100644
index 00000000..819dae15
--- /dev/null
+++ b/docs/install.md
@@ -0,0 +1,109 @@
+# Installing Kiln in an agent harness
+
+Kiln exposes one tool surface over two transports. Pick the one your harness speaks.
+
+Everything below needs [Bun](https://bun.sh) on `PATH` — the package ships TypeScript source rather
+than a build artifact, which is also why the entry point is a `.ts` file.
+
+```bash
+git clone https://github.com/matthew-kissinger/kiln && cd kiln
+bun install
+```
+
+Verify before wiring anything up:
+
+```bash
+bun run kiln render examples/crate.kiln.js --out crate.glb --views sheet.png
+```
+
+That runs the full geometry build, the QA gates, and the rasterizer with no model, no network, no
+GPU, and no key. If it produces a GLB and a contact sheet, the engine is fine and any later problem
+is transport configuration.
+
+## As an MCP server
+
+Point your client at `src/mcp-server.ts` with an **absolute** path. The server resolves every
+internal path from `import.meta.url` and never reads `process.cwd()`, so the working directory the
+client launches it in does not matter — only that the script path is right.
+
+```json
+{
+ "mcpServers": {
+ "kiln": {
+ "type": "stdio",
+ "command": "bun",
+ "args": ["run", "/absolute/path/to/kiln/src/mcp-server.ts"],
+ "env": { "KILN_RENDER": "auto" }
+ }
+ }
+}
+```
+
+Set `KILN_RENDER` to `cpu` to pin the deterministic rasterizer, or `gpu` to fail loudly rather than
+degrade. `KILN_RENDER_PORT_URL` (plus `KILN_RENDER_TOKEN`) routes views to a GPU render service.
+
+**For textured or metallic assets, run the GPU renderer** — it ships in this repository:
+
+```bash
+cd render-service && npm install && npm start
+```
+
+It listens on `:8000`, which is where `auto` looks, so the MCP server picks it up with no further
+configuration. See [`render-service/README.md`](../render-service/README.md) and the render-modes
+section of the [README](../README.md).
+
+Your agent gets six tools and is the author: it writes the program, looks at the render, and
+iterates with its own model. There is no nested agent loop and no second provider key.
+
+## As an Agent Plugin
+
+The repository is also a plugin package. Two manifest conventions exist as of late 2026 and Kiln
+ships both, because they disagree on filenames and on the path variable:
+
+| | Portable spec | Claude Code |
+|---|---|---|
+| Manifest | `plugin.json` | `.claude-plugin/plugin.json` |
+| MCP config | `mcp.json` | inline `mcpServers` in the manifest |
+| Plugin-root variable | `${PLUGIN_ROOT}` | `${CLAUDE_PLUGIN_ROOT}` |
+| Skills | `skills/<name>/SKILL.md` | same |
+
+The skills are the same files in both cases. Installing the plugin gives you the MCP tools *and*
+the three skills that teach an agent to use them well:
+
+| Skill | When it fires |
+|---|---|
+| `kiln-author-asset` | create, model, build, or refine an asset |
+| `kiln-qa-asset` | wire a finished GLB into a real project and prove it works |
+| `kiln-compose-scene` | lay out several finished GLBs into one scene |
+
+Together they cost about 215 tokens of always-on context; the bodies load only when a skill fires.
+
+### Claude Code
+
+```bash
+claude plugin marketplace add matthew-kissinger/kiln
+claude plugin install kiln@kiln
+```
+
+Verify with `claude mcp list` — you want `plugin:kiln:kiln … ✔ Connected`.
+
+Claude Code's MCP config is declared **inline in `.claude-plugin/plugin.json`** rather than in a
+root `.mcp.json`. That is deliberate: `.mcp.json` at a repository root is also Claude Code's
+*project*-scoped config, where `${CLAUDE_PLUGIN_ROOT}` is undefined, so shipping one would hand
+every contributor who opens this repo a broken server entry and a warning. Declaring it in the
+manifest works identically for installed users and leaves the repo clean for contributors.
+
+## In-process, without MCP
+
+If your harness is TypeScript and you would rather skip the transport, import the registry directly.
+[`examples/strands-harness.ts`](../examples/strands-harness.ts) is the whole integration in about
+sixty lines, including both render-port injection seams.
+
+```ts
+import { createKilnToolRegistry } from 'kiln/tools';
+```
+
+`kiln/tools` is the framework-agnostic core and imports no agent SDK, so porting to a harness that
+is not Strands does not drag Strands along. Each def carries `name`, `description`, a zod
+`inputSchema`, and `run`. Mapping those four fields is the entire adapter — `src/mcp-server.ts` is
+one such adapter and `src/agent/tools.ts` is another.
diff --git a/examples/crate.glb b/examples/crate.glb
new file mode 100644
index 00000000..da306781
Binary files /dev/null and b/examples/crate.glb differ
diff --git a/examples/crate.kiln.js b/examples/crate.kiln.js
new file mode 100644
index 00000000..02db50e1
--- /dev/null
+++ b/examples/crate.kiln.js
@@ -0,0 +1,91 @@
+// A weathered wooden crate.
+//
+// This is what a Kiln program looks like: a `meta` const, a `build()` that
+// returns a scene root, and named parts you can read, diff, and edit by hand.
+// Render it with:
+//
+// bun run kiln render examples/crate.kiln.js --out crate.glb --views sheet.png
+//
+// Kiln's frame is +X forward, +Y up, +Z right. Everything sits on Y=0.
+
+const meta = { name: 'WeatheredCrate', category: 'prop' };
+
+function build() {
+ const root = createRoot('WeatheredCrate');
+
+ const plank = gameMaterial(0x8a6a43, { roughness: 0.85 });
+ const plankDark = gameMaterial(0x6f5335, { roughness: 0.9 });
+ const iron = gameMaterial(0x4a4a4f, { metalness: 0.8, roughness: 0.45 });
+
+ const S = 0.9; // crate edge length
+ const H = S / 2;
+ const T = 0.045; // board thickness
+ const BOARD = S / 3 - 0.012;
+ const FACE = H + T / 2; // outer surface of a wall board
+ const OUT = FACE + 0.007; // banding sits proud of the planks so it reads
+
+ // Four walls, each three horizontal boards, so the silhouette reads as
+ // planks rather than a solid cube. Axis-aligned: no rotation needed.
+ const faces = [
+ { name: 'Front', geo: [T, BOARD, S], at: (y) => [H, y, 0] },
+ { name: 'Back', geo: [T, BOARD, S], at: (y) => [-H, y, 0] },
+ { name: 'Right', geo: [S, BOARD, T], at: (y) => [0, y, H] },
+ { name: 'Left', geo: [S, BOARD, T], at: (y) => [0, y, -H] },
+ ];
+
+ for (const face of faces) {
+ for (let i = 0; i < 3; i++) {
+ const y = H + (i - 1) * (S / 3);
+ createPart(`${face.name}Board${i}`, boxGeo(face.geo[0], face.geo[1], face.geo[2]), i === 1 ? plankDark : plank, {
+ position: face.at(y),
+ parent: root,
+ });
+ }
+ }
+
+ // Lid and floor.
+ createPart('Lid', boxGeo(S - 0.01, T, S - 0.01), plank, {
+ position: [0, S - T / 2, 0],
+ parent: root,
+ });
+ createPart('Floor', boxGeo(S - 0.01, T, S - 0.01), plankDark, {
+ position: [0, T / 2, 0],
+ parent: root,
+ });
+
+ // Corner posts give the crate its edges and hide the panel seams.
+ for (const sx of [-1, 1]) {
+ for (const sz of [-1, 1]) {
+ const tag = `${sx > 0 ? 'F' : 'B'}${sz > 0 ? 'R' : 'L'}`;
+ createPart(`Post_${tag}`, boxGeo(0.075, S, 0.075), plankDark, {
+ position: [sx * FACE, H, sz * FACE],
+ parent: root,
+ });
+ }
+ }
+
+ // Iron banding near the top and bottom. Metal is deliberately present so the
+ // GPU render path has something the flat CPU raster cannot show.
+ const bands = [0.16, S - 0.16];
+ for (let b = 0; b < bands.length; b++) {
+ const y = bands[b];
+ createPart(`BandFront${b}`, boxGeo(0.014, 0.055, S + 0.02), iron, {
+ position: [OUT, y, 0],
+ parent: root,
+ });
+ createPart(`BandBack${b}`, boxGeo(0.014, 0.055, S + 0.02), iron, {
+ position: [-OUT, y, 0],
+ parent: root,
+ });
+ createPart(`BandRight${b}`, boxGeo(S + 0.02, 0.055, 0.014), iron, {
+ position: [0, y, OUT],
+ parent: root,
+ });
+ createPart(`BandLeft${b}`, boxGeo(S + 0.02, 0.055, 0.014), iron, {
+ position: [0, y, -OUT],
+ parent: root,
+ });
+ }
+
+ return root;
+}
diff --git a/examples/hero-sheet.png b/examples/hero-sheet.png
new file mode 100644
index 00000000..59e01bcc
Binary files /dev/null and b/examples/hero-sheet.png differ
diff --git a/examples/strands-harness.ts b/examples/strands-harness.ts
new file mode 100644
index 00000000..4e31c86f
--- /dev/null
+++ b/examples/strands-harness.ts
@@ -0,0 +1,61 @@
+/**
+ * The whole point of the tool registry, in one file.
+ *
+ * `createKilnToolRegistry` is the single source of truth for Kiln's tool surface.
+ * This example drives it from a Strands agent in-process; `src/mcp-server.ts` drives
+ * the same defs over stdio MCP. Nothing here is Kiln-specific plumbing — swap the
+ * agent framework and the registry still works, which is the property that makes
+ * this port to another harness roughly this long.
+ *
+ * bun run examples/strands-harness.ts "a weathered wooden crate"
+ *
+ * Requires `@strands-agents/sdk` (an optional peer) and a provider key.
+ */
+import { Agent } from '@strands-agents/sdk';
+
+import { makeKilnTools } from '../src/agent/tools';
+import type { PbrRenderPort } from '../src/composer/render-port';
+
+/**
+ * Seam one: the in-loop view renderer.
+ *
+ * Absent means every render stays on the CPU rasterizer — the engine never opens a
+ * socket itself. A host supplies the HTTP adapter, auth, and configuration; the
+ * engine's `captureViewsViaPort` keeps sole ownership of the deadline, PNG
+ * validation, grid composition, and the never-throw fallback. Returning `ok: false`
+ * here is not an error path, it is the designed degrade.
+ */
+const stubPort: PbrRenderPort = async () => ({
+ ok: false,
+ rendererId: 'stub:no-gpu',
+});
+
+// Seam two, `viewRenderTimeoutMs`, is deliberately separate. This deadline bounds
+// ONE in-loop call, which blocks the agent mid-thought, so it is far shorter than
+// the deadline a host would use for a post-loop artifact sheet that nothing waits
+// on. Collapsing the two onto a single value is the mistake this API exists to
+// prevent.
+const sink: { code?: string } = {};
+const tools = makeKilnTools(sink, {
+ viewRenderPort: stubPort,
+ viewRenderTimeoutMs: 6_000,
+});
+
+const agent = new Agent({
+ model: process.env['KILN_MODEL'] ?? 'anthropic/claude-opus-4-6',
+ systemPrompt:
+ 'You generate exportable 3D game assets as Kiln programs. List the primitives, ' +
+ 'write the program, validate it, render it, LOOK at the six-view sheet, fix what ' +
+ 'you see, then call kiln_submit with the final code.',
+ tools: tools as never,
+ name: 'kiln-harness-example',
+});
+
+const prompt = process.argv[2] ?? 'a weathered wooden crate';
+await agent.invoke(prompt);
+
+// `kiln_submit` is the terminal action: it writes the model's final program into the
+// sink rather than returning it through the transcript. Over MCP there is no submit,
+// because there the host agent already holds the program text.
+if (!sink.code) throw new Error('agent finished without calling kiln_submit');
+console.log(sink.code);
diff --git a/examples/well-cpu.png b/examples/well-cpu.png
new file mode 100644
index 00000000..cadd016b
Binary files /dev/null and b/examples/well-cpu.png differ
diff --git a/examples/well-gpu.png b/examples/well-gpu.png
new file mode 100644
index 00000000..59e01bcc
Binary files /dev/null and b/examples/well-gpu.png differ
diff --git a/examples/well.glb b/examples/well.glb
new file mode 100644
index 00000000..6b87075f
Binary files /dev/null and b/examples/well.glb differ
diff --git a/examples/well.kiln.js b/examples/well.kiln.js
new file mode 100644
index 00000000..05430d40
--- /dev/null
+++ b/examples/well.kiln.js
@@ -0,0 +1,87 @@
+// A small textured structure: the kind of thing people actually generate.
+//
+// Three real PBR materials with bound Poly Haven albedo/normal/ARM maps — brick
+// stone, weathered wood, painted iron. On the CPU rasterizer this reads as three
+// flat greys; the texture and normal detail only exist in a GPU render.
+const meta = { name: 'StoneWell', category: 'environment', role: 'poi' };
+
+async function build() {
+ const root = createRoot('StoneWell');
+
+ const stone = await materialRecipe('kiln.material.stone.v1', {
+ textureResources: {
+ baseColor: 'kiln.texture.brick-wall-albedo.v1',
+ normal: 'kiln.texture.brick-wall-normal.v1',
+ metallicRoughness: 'kiln.texture.brick-wall-arm.v1',
+ },
+ });
+ const wood = await materialRecipe('kiln.material.wood.v1', {
+ baseColor: '#6a4a2c',
+ });
+ const iron = await materialRecipe('kiln.material.painted-metal.v1', {
+ baseColor: '#3f4348',
+ roughness: 0.42,
+ metalness: 0.9,
+ });
+
+ // Curb: a ring of blocks, so the brick texture wraps a real surface.
+ const R = 0.72;
+ const SEGMENTS = 16;
+ for (let i = 0; i < SEGMENTS; i++) {
+ const a = (i / SEGMENTS) * Math.PI * 2;
+ const block = createPart(`Curb_${i}`, boxGeo(0.30, 0.46, 0.30), stone, {
+ position: [Math.cos(a) * R, 0.23, Math.sin(a) * R],
+ parent: root,
+ });
+ block.rotation.y = -a;
+ boxUnwrap(block.geometry);
+ }
+
+ // Base course, slightly proud, so the curb reads as sitting on something.
+ const base = createPart('Base', cylinderGeo(R + 0.20, R + 0.20, 0.10, 24), stone, {
+ position: [0, 0.05, 0],
+ parent: root,
+ });
+ cylinderUnwrap(base.geometry);
+
+ // Posts and crossbeam.
+ const POST = R + 0.02;
+ for (const sz of [-1, 1]) {
+ createPart(`Post_${sz > 0 ? 'R' : 'L'}`, boxGeo(0.13, 1.30, 0.13), wood, {
+ position: [0, 1.11, sz * POST],
+ parent: root,
+ });
+ }
+ createPart('Beam', boxGeo(0.13, 0.13, 2 * POST + 0.13), wood, {
+ position: [0, 1.82, 0],
+ parent: root,
+ });
+
+ // Windlass drum and crank — the metal that flat shading cannot show. The drum
+ // is long enough to seat INTO both posts; short of that the connectivity gate
+ // correctly reports it as floating.
+ const drum = createPart('Windlass', cylinderXGeo(0.09, 0.09, 2 * POST - 0.06, 16), iron, {
+ position: [0, 1.60, 0],
+ parent: root,
+ });
+ drum.rotation.y = Math.PI / 2;
+ createPart('CrankArm', boxGeo(0.05, 0.26, 0.05), iron, {
+ position: [0, 1.47, POST + 0.14],
+ parent: root,
+ });
+ createPart('CrankHandle', cylinderXGeo(0.035, 0.035, 0.20, 12), iron, {
+ position: [0, 1.34, POST + 0.22],
+ parent: root,
+ });
+
+ // Roof.
+ for (const sz of [-1, 1]) {
+ const panel = createPart(`Roof_${sz > 0 ? 'R' : 'L'}`, boxGeo(1.05, 0.05, 0.86), wood, {
+ position: [0, 2.02, sz * 0.40],
+ parent: root,
+ });
+ panel.rotation.x = sz * 0.42;
+ }
+
+ return root;
+}
diff --git a/mcp.json b/mcp.json
new file mode 100644
index 00000000..9c30a03e
--- /dev/null
+++ b/mcp.json
@@ -0,0 +1,12 @@
+{
+ "mcpServers": {
+ "kiln": {
+ "type": "stdio",
+ "command": "bun",
+ "args": ["run", "${PLUGIN_ROOT}/src/mcp-server.ts"],
+ "env": {
+ "KILN_RENDER": "auto"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
index a91b93d9..d72a2860 100644
--- a/package.json
+++ b/package.json
@@ -12,8 +12,13 @@
"node": "22.23.1",
"npm": "12.0.1"
},
+ "bin": {
+ "kiln": "./src/cli.ts"
+ },
"exports": {
+ ".": "./src/cli.ts",
"./agent": "./src/agent/index.ts",
+ "./tools": "./src/tools/registry.ts",
"./arena": "./src/arena/index.ts",
"./render": "./src/render.ts",
"./evaluator": "./src/evaluator/index.ts",
@@ -52,11 +57,12 @@
"CHANGELOG.md"
],
"scripts": {
+ "kiln": "bun src/cli.ts",
"check:toolchain": "bun scripts/check-toolchain.mjs",
"typecheck": "tsc --noEmit",
"build": "tsc --noEmit",
- "test": "KILN_SPIKE_LIVE=0 bun test",
- "test:coverage": "KILN_SPIKE_LIVE=0 bun test --coverage && bun scripts/check-coverage.mjs",
+ "test": "KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts",
+ "test:coverage": "KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts --coverage && bun scripts/check-coverage.mjs",
"test:live": "KILN_SPIKE_LIVE=1 bun test",
"lint": "biome check ."
},
@@ -64,6 +70,8 @@
"@gltf-transform/core": "^4.4.1",
"@gltf-transform/extensions": "^4.4.1",
"@gltf-transform/functions": "^4.4.1",
+ "@modelcontextprotocol/client": "^2.0.0",
+ "@modelcontextprotocol/server": "^2.0.0",
"@openrouter/ai-sdk-provider": "^2.10.0",
"@types/three": "^0.185.1",
"acorn": "^8.17.0",
diff --git a/plugin.json b/plugin.json
new file mode 100644
index 00000000..31d38fb9
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://agentplugins.codes/schema/v1.0.0/plugin.json",
+ "name": "kiln",
+ "displayName": "Kiln",
+ "description": "Author 3D assets as code: your agent writes a Kiln program, renders it, looks at the six-view contact sheet, and fixes what it sees. Outputs a game-ready GLB.",
+ "version": "0.6.0",
+ "license": "MIT",
+ "homepage": "https://github.com/matthew-kissinger/kiln",
+ "keywords": ["3d", "glb", "gltf", "asset-generation", "three.js", "gamedev"]
+}
diff --git a/render-service/.gitignore b/render-service/.gitignore
new file mode 100644
index 00000000..99e79fa2
--- /dev/null
+++ b/render-service/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+test/out/
+test/fixtures/*
+!test/fixtures/material-channels-v1.glb
+!test/fixtures/material-channels-v1.manifest.json
+*.log
diff --git a/render-service/Dockerfile b/render-service/Dockerfile
new file mode 100644
index 00000000..0ab4ffdf
--- /dev/null
+++ b/render-service/Dockerfile
@@ -0,0 +1,27 @@
+# kiln-render-service: GLB in, PBR PNG views out. Dawn/WebGPU + three.js headless.
+FROM node:24-bookworm-slim
+
+# libglvnd0/libegl1/libgl1/libglx0: B1 finding — the injected NVIDIA Vulkan ICD
+# init-fails (NULL vkCreateInstance) without the GLVND dispatch libs, and Dawn
+# then silently lands on a software renderer. vulkan-tools kept for debuggability.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ libvulkan1 vulkan-tools \
+ libglvnd0 libegl1 libgl1 libglx0 ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
+
+# graphics is REQUIRED for Vulkan; utility,compute (the common example value)
+# silently yields no ICD and software fallback.
+ENV NVIDIA_VISIBLE_DEVICES=all
+ENV NVIDIA_DRIVER_CAPABILITIES=graphics,compute,utility
+ENV PORT=8000
+
+WORKDIR /app
+COPY package.json ./
+RUN npm install --no-audit --no-fund && npm rebuild webgpu
+
+COPY src/ ./src/
+
+EXPOSE 8000
+# Boot asserts a hardware adapter and exits 1 otherwise — a driver regression
+# yields a service that will not start, never one that renders on CPU silently.
+CMD ["node", "--import", "./src/register-hooks.mjs", "src/server.mjs"]
diff --git a/render-service/README.md b/render-service/README.md
new file mode 100644
index 00000000..b190d05e
--- /dev/null
+++ b/render-service/README.md
@@ -0,0 +1,81 @@
+# render-service
+
+GLB bytes in, PBR PNG views out. Headless three.js `WebGPURenderer` on Dawn (the `webgpu` npm
+prebuilt) — no browser, no X server, no engine coupling. This is the **GPU** in Kiln's
+`--render gpu` and `--render-port`.
+
+It is a separate Node project on purpose: headless WebGPU needs Node loader hooks that Bun does not
+run, so the renderer lives behind a socket rather than inside the engine process. The upside is that
+local and remote GPU are the same code path — a GPU on another machine works exactly like one here.
+
+## Run it
+
+```bash
+npm install
+npm start
+```
+
+It listens on `:8000`, which is where `kiln --render auto` looks. Nothing else to configure:
+
+```bash
+cd .. && bun run kiln render examples/well.kiln.js --views sheet.png
+# sheet.png (GPU dawn-d3d12:nvidia-geforce-rtx-3070:D3D12 driver version 32.0.16.1074)
+```
+
+Set `PORT` to move it and `RENDER_SERVICE_TOKEN` to require auth. Point the engine at a non-default
+location with `--render-port <url>` or `KILN_RENDER_PORT_URL`.
+
+**The process refuses to boot on a software adapter.** A driver regression gives you a service that
+will not start, never one that quietly renders on CPU while reporting success.
+
+## Contract
+
+| Route | Body | Returns |
+|---|---|---|
+| `GET /health` | — | `{ok, rendererId, backend, adapter, capabilities, presentationProfile, lightingPresetIds}` |
+| `POST /render` (legacy) | `{glb_base64, size?=384, views?, beauty_size?, background?}` | `{ok, rendererId, presentationProfile, timings, views[base64 png], beauty?}` |
+| `POST /render` (camera) | `{glb_base64, cameras, width, height, lighting_preset_id?}` | the above plus `{backend, cameras, width, height, lightingPresetId, viewSha256, outputSetSha256, cameraReceipts}` |
+| `POST /bake` | — | 501 |
+
+Auth, when `RENDER_SERVICE_TOKEN` is set, is the `x-render-token` header — **not** `Authorization`,
+because serverless edge gateways routinely consume that one before it reaches the process.
+
+`views` is an optional array of `[x,y,z]` camera directions (max 12); the default is the six-view set
+matching the engine's grid conventions. A request for N views returns exactly N PNGs in request
+order — truncating or padding would silently reshape a grid whose geometry was chosen from that
+length, so an over-long list is rejected rather than trimmed.
+
+Renders serialize through a single GPU queue. `rendererId` (e.g.
+`dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100`) is honest producer identity and must accompany any
+downstream use of the output.
+
+Camera mode is additive and exact: 1-12 perspective cameras with `position`, `target`, `up`,
+`fovDeg`, `aspect`, `near`, `far`. Integer `width`/`height` are required, bounded 1-4096, capped at
+16,777,216 total pixels, and every camera aspect must equal `width / height`. It is mutually
+exclusive with `views`, `size`, and `beauty_size`. The only lighting identity is `neutral-studio-v1`;
+`/health.lightingPresetIds` advertises the registry.
+
+## Docker
+
+```bash
+docker build -t kiln-render-service .
+docker run --gpus all -p 8000:8000 kiln-render-service
+```
+
+The image installs `libglvnd0 libegl1 libgl1 libglx0` deliberately: without the GLVND dispatch libs
+an injected NVIDIA Vulkan ICD init-fails with a NULL `vkCreateInstance` and Dawn lands on a software
+renderer. `NVIDIA_DRIVER_CAPABILITIES` must include `graphics` — the commonly-copied
+`utility,compute` yields no ICD and a silent software fallback.
+
+## Tests
+
+```bash
+npm test # contract, material fixture, presentation presets
+npm run smoke # end-to-end against a real adapter
+```
+
+These are `node:test` and are not part of the engine's `bun test` suite.
+
+## License
+
+MIT, same as the engine.
diff --git a/render-service/package-lock.json b/render-service/package-lock.json
new file mode 100644
index 00000000..f76e61e4
--- /dev/null
+++ b/render-service/package-lock.json
@@ -0,0 +1,72 @@
+{
+ "name": "kiln-render-service",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "kiln-render-service",
+ "version": "0.1.0",
+ "dependencies": {
+ "pngjs": "^7.0.0",
+ "three": "0.185.1",
+ "webgpu": "0.4.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==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/pngjs": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz",
+ "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.19.0"
+ }
+ },
+ "node_modules/three": {
+ "version": "0.185.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
+ "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
+ "license": "MIT"
+ },
+ "node_modules/webgpu": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/webgpu/-/webgpu-0.4.0.tgz",
+ "integrity": "sha512-F5pimn3Aoi0zWjuRdiVs5TnrUwSzD2lESBohsIUsqyitWkGRQlXU2fhV6ycXlQTa1bvAf3sjqiUpBEpmSQ5ptA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "@webgpu/types": "^0.1.69",
+ "debug": "^4.4.0"
+ }
+ }
+ }
+}
diff --git a/render-service/package.json b/render-service/package.json
new file mode 100644
index 00000000..96eeacc7
--- /dev/null
+++ b/render-service/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "kiln-render-service",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.",
+ "scripts": {
+ "start": "node --import ./src/register-hooks.mjs src/server.mjs",
+ "test": "node --test test/contract.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs",
+ "smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs",
+ "conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"
+ },
+ "dependencies": {
+ "pngjs": "^7.0.0",
+ "three": "0.185.1",
+ "webgpu": "0.4.0"
+ },
+ "allowScripts": {
+ }
+}
diff --git a/render-service/src/contract.mjs b/render-service/src/contract.mjs
new file mode 100644
index 00000000..6a8996b6
--- /dev/null
+++ b/render-service/src/contract.mjs
@@ -0,0 +1,473 @@
+import { createHash } from 'node:crypto';
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_IDS,
+ isPresentationPresetId,
+} from './presentation-presets.mjs';
+
+// Singular export retained for existing Engine/Studio callers. The plural list
+// is the registry-backed source of truth for strict ID validation and discovery.
+export const SUPPORTED_LIGHTING_PRESET_ID = DEFAULT_PRESENTATION_PRESET_ID;
+export const SUPPORTED_LIGHTING_PRESET_IDS = PRESENTATION_PRESET_IDS;
+export const RENDER_FIDELITY_VERSION = 'kiln.render-fidelity.v1';
+export const RENDER_FIDELITY_PRODUCER = 'kiln-render-service';
+export const RENDER_OPERATIONAL_EVIDENCE_VERSION = 'kiln.render-operational.v1';
+export const RENDER_OUTCOME_CODES = Object.freeze([
+ 'health_ok',
+ 'gpu_success',
+ 'auth_rejected',
+ 'request_rejected',
+ 'not_implemented',
+ 'route_not_found',
+ 'render_failed',
+]);
+export const MAX_VIEW_DIRS = 12;
+export const MAX_CAMERAS = 12;
+export const MIN_CAMERA_DIMENSION = 1;
+export const MAX_CAMERA_DIMENSION = 4096;
+// Includes every camera in the request. This admits one 4K frame, eight 1080p
+// frames, or twelve 720p frames while bounding transient MSAA/depth allocation.
+export const MAX_CAMERA_TOTAL_PIXELS = 16_777_216;
+
+export const DEFAULT_VIEW_DIRS = Object.freeze([
+ Object.freeze([1, 0.35, 1]),
+ Object.freeze([-1, 0.35, 1]),
+ Object.freeze([1, 0.35, -1]),
+ Object.freeze([-1, 0.35, -1]),
+ Object.freeze([0, 1, 0.001]),
+ Object.freeze([0.001, -1, 0.001]),
+]);
+
+function badRequest(message) {
+ return Object.assign(new Error(message), { status: 400 });
+}
+
+function supportedPresetMessage(field) {
+ return SUPPORTED_LIGHTING_PRESET_IDS.length === 1
+ ? `${field} must be ${SUPPORTED_LIGHTING_PRESET_ID}`
+ : `${field} must be one of: ${SUPPORTED_LIGHTING_PRESET_IDS.join(', ')}`;
+}
+
+const RENDER_OUTCOME_CODE_SET = new Set(RENDER_OUTCOME_CODES);
+const MAX_OPERATIONAL_MS = 86_400_000;
+const MAX_OPERATIONAL_QUEUE_DEPTH = 10_000;
+const OPERATIONAL_EVIDENCE_KEYS = new Set([
+ 'outcomeCode',
+ 'queueWaitMs',
+ 'queueDepthAtEnqueue',
+ 'concurrencyAtStart',
+ 'firstRenderInProcess',
+ 'workerAgeMsAtStart',
+]);
+
+/** Stable low-cardinality outcome for structured request logs and metrics extraction. */
+export function httpRenderOutcomeCode({ method, path, status }) {
+ if (status === 401) return 'auth_rejected';
+ if (status === 501) return 'not_implemented';
+ if (status === 404) return 'route_not_found';
+ if (status === 400 || status === 413) return 'request_rejected';
+ if (method === 'GET' && (path === '/health' || path === '/ping') && status >= 200 && status < 300) {
+ return 'health_ok';
+ }
+ if (method === 'POST' && path === '/render' && status >= 200 && status < 300) {
+ return 'gpu_success';
+ }
+ return 'render_failed';
+}
+
+function nonNegativeFinite(value, path) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ throw badRequest(`${path} must be a non-negative finite number`);
+ }
+ return value;
+}
+
+/**
+ * Produce the bounded, identifier-free queue/worker envelope consumed by R2.8
+ * metrics extraction. Oversized valid observations are capped rather than
+ * failing a completed render; malformed internal values still fail closed.
+ */
+export function buildRenderOperationalEvidenceV1(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw badRequest('render operational evidence must be an object');
+ }
+ for (const key of Object.keys(input)) {
+ if (!OPERATIONAL_EVIDENCE_KEYS.has(key)) throw badRequest(`${key} is unknown`);
+ }
+ if (!RENDER_OUTCOME_CODE_SET.has(input.outcomeCode)) {
+ throw badRequest('outcomeCode is not supported');
+ }
+ const queueWaitMs = nonNegativeFinite(input.queueWaitMs, 'queueWaitMs');
+ const workerAgeMsAtStart = nonNegativeFinite(input.workerAgeMsAtStart, 'workerAgeMsAtStart');
+ if (!Number.isInteger(input.queueDepthAtEnqueue) || input.queueDepthAtEnqueue < 0) {
+ throw badRequest('queueDepthAtEnqueue must be a non-negative integer');
+ }
+ if (input.concurrencyAtStart !== 1) {
+ throw badRequest('concurrencyAtStart must be 1 for the serial GPU queue');
+ }
+ if (typeof input.firstRenderInProcess !== 'boolean') {
+ throw badRequest('firstRenderInProcess must be boolean');
+ }
+
+ const evidenceClamped = queueWaitMs > MAX_OPERATIONAL_MS
+ || workerAgeMsAtStart > MAX_OPERATIONAL_MS
+ || input.queueDepthAtEnqueue > MAX_OPERATIONAL_QUEUE_DEPTH;
+ return {
+ version: RENDER_OPERATIONAL_EVIDENCE_VERSION,
+ outcomeCode: input.outcomeCode,
+ queueWaitMs: +Math.min(queueWaitMs, MAX_OPERATIONAL_MS).toFixed(1),
+ queueDepthAtEnqueue: Math.min(input.queueDepthAtEnqueue, MAX_OPERATIONAL_QUEUE_DEPTH),
+ concurrencyAtStart: 1,
+ concurrencyLimit: 1,
+ workerPhase: input.firstRenderInProcess ? 'first-render' : 'warm-render',
+ workerAgeMsAtStart: +Math.min(workerAgeMsAtStart, MAX_OPERATIONAL_MS).toFixed(1),
+ evidenceClamped,
+ };
+}
+
+/** Provider/GPU-free serial queue with explicit start evidence for every job. */
+export function createSerialRenderQueue(options = {}) {
+ const now = options.now ?? (() => performance.now());
+ if (typeof now !== 'function') throw badRequest('serial render queue now must be a function');
+ const processStartedAt = options.processStartedAt ?? now();
+ if (!Number.isFinite(processStartedAt)) {
+ throw badRequest('serial render queue processStartedAt must be finite');
+ }
+
+ let tail = Promise.resolve();
+ let queuedJobs = 0;
+ let activeJobs = 0;
+ let renderJobsStarted = 0;
+ return Object.freeze({
+ enqueue(job) {
+ if (typeof job !== 'function') throw badRequest('serial render queue job must be a function');
+ const enqueuedAt = now();
+ const queueDepthAtEnqueue = activeJobs + queuedJobs;
+ queuedJobs++;
+ const runJob = async () => {
+ queuedJobs--;
+ activeJobs++;
+ const firstRenderInProcess = renderJobsStarted === 0;
+ renderJobsStarted++;
+ const startedAt = now();
+ const start = {
+ queueWaitMs: startedAt - enqueuedAt,
+ queueDepthAtEnqueue,
+ concurrencyAtStart: activeJobs,
+ firstRenderInProcess,
+ workerAgeMsAtStart: startedAt - processStartedAt,
+ };
+ try {
+ return await job(start);
+ } finally {
+ activeJobs--;
+ }
+ };
+ const run = tail.then(runJob, runJob);
+ tail = run.catch(() => { });
+ return run;
+ },
+ });
+}
+
+function finiteTuple3(value, path) {
+ if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) {
+ throw badRequest(`${path} must be [x,y,z] finite numbers`);
+ }
+ return [...value];
+}
+
+function finiteNumber(value, path) {
+ if (!Number.isFinite(value)) throw badRequest(`${path} must be finite`);
+ return value;
+}
+
+function pixelDimension(value, path) {
+ if (
+ !Number.isInteger(value)
+ || value < MIN_CAMERA_DIMENSION
+ || value > MAX_CAMERA_DIMENSION
+ ) {
+ throw badRequest(
+ `${path} must be an integer in [${MIN_CAMERA_DIMENSION},${MAX_CAMERA_DIMENSION}]`,
+ );
+ }
+ return value;
+}
+
+/** Legacy direction validation. Returned arrays are cloned; defaults are mutable copies. */
+export function validateViewDirs(views) {
+ if (views === undefined || views === null || (Array.isArray(views) && views.length === 0)) {
+ return DEFAULT_VIEW_DIRS.map((view) => [...view]);
+ }
+ if (!Array.isArray(views)) throw badRequest('views must be an array of [x,y,z] directions');
+ if (views.length > MAX_VIEW_DIRS) {
+ throw badRequest(`views has ${views.length} entries; the maximum is ${MAX_VIEW_DIRS}`);
+ }
+ return views.map((value, index) => {
+ const direction = finiteTuple3(value, `views[${index}]`);
+ if (Math.hypot(...direction) < 1e-9) {
+ throw badRequest(`views[${index}] must not be the zero vector`);
+ }
+ return direction;
+ });
+}
+
+/** Strict camera-mode parser shared by HTTP and direct renderer callers. */
+export function validateCameraMode(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw badRequest('camera render options must be an object');
+ }
+ if (!Array.isArray(input.cameras) || input.cameras.length < 1 || input.cameras.length > MAX_CAMERAS) {
+ throw badRequest(`cameras must contain 1..${MAX_CAMERAS} entries`);
+ }
+ const width = pixelDimension(input.width, 'width');
+ const height = pixelDimension(input.height, 'height');
+ const totalPixels = width * height * input.cameras.length;
+ if (!Number.isSafeInteger(totalPixels) || totalPixels > MAX_CAMERA_TOTAL_PIXELS) {
+ throw badRequest(
+ `camera request has ${totalPixels} total pixels; maximum is ${MAX_CAMERA_TOTAL_PIXELS}`,
+ );
+ }
+ const targetAspect = width / height;
+ const cameras = input.cameras.map((value, index) => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw badRequest(`cameras[${index}] must be an object`);
+ }
+ const allowed = new Set(['position', 'target', 'up', 'fovDeg', 'aspect', 'near', 'far']);
+ for (const key of Object.keys(value)) {
+ if (!allowed.has(key)) throw badRequest(`cameras[${index}].${key} is unknown`);
+ }
+ const position = finiteTuple3(value.position, `cameras[${index}].position`);
+ const target = finiteTuple3(value.target, `cameras[${index}].target`);
+ const up = finiteTuple3(value.up, `cameras[${index}].up`);
+ const view = target.map((component, axis) => component - position[axis]);
+ const viewLength = Math.hypot(...view);
+ const upLength = Math.hypot(...up);
+ if (viewLength < 1e-9) throw badRequest(`cameras[${index}].target must differ from position`);
+ if (upLength < 1e-9) throw badRequest(`cameras[${index}].up must be non-zero`);
+ const cross = [
+ view[1] * up[2] - view[2] * up[1],
+ view[2] * up[0] - view[0] * up[2],
+ view[0] * up[1] - view[1] * up[0],
+ ];
+ if (Math.hypot(...cross) <= viewLength * upLength * 1e-9) {
+ throw badRequest(`cameras[${index}].up must not be collinear with view`);
+ }
+ const fovDeg = finiteNumber(value.fovDeg, `cameras[${index}].fovDeg`);
+ const aspect = finiteNumber(value.aspect, `cameras[${index}].aspect`);
+ const near = finiteNumber(value.near, `cameras[${index}].near`);
+ const far = finiteNumber(value.far, `cameras[${index}].far`);
+ if (fovDeg <= 0 || fovDeg >= 180) {
+ throw badRequest(`cameras[${index}].fovDeg must be in (0,180)`);
+ }
+ if (aspect <= 0) throw badRequest(`cameras[${index}].aspect must be positive`);
+ if (near <= 0) throw badRequest(`cameras[${index}].near must be positive`);
+ if (far <= near) throw badRequest(`cameras[${index}].far must exceed near`);
+ if (Math.abs(aspect - targetAspect) > Math.max(1, targetAspect) * 1e-9) {
+ throw badRequest(`cameras[${index}].aspect must equal width/height`);
+ }
+ return { position, target, up, fovDeg, aspect, near, far };
+ });
+ const lightingPresetId = input.lightingPresetId === undefined
+ ? SUPPORTED_LIGHTING_PRESET_ID
+ : input.lightingPresetId;
+ if (!isPresentationPresetId(lightingPresetId)) {
+ throw badRequest(supportedPresetMessage('lighting_preset_id'));
+ }
+ return { cameras, width, height, lightingPresetId, totalPixels };
+}
+
+/** Parse only render-mode fields; GLB/auth/body-size validation remains in the server. */
+export function validateRenderMode(body) {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw badRequest('render body must be an object');
+ }
+ if (body.cameras !== undefined) {
+ if (body.views !== undefined || body.size !== undefined || body.beauty_size !== undefined) {
+ throw badRequest('camera mode is mutually exclusive with views, size, and beauty_size');
+ }
+ if (body.background !== undefined) {
+ throw badRequest('camera mode cannot override the neutral-studio-v1 background');
+ }
+ const allowed = new Set([
+ 'glb_base64',
+ 'input_glb_sha256',
+ 'cameras',
+ 'width',
+ 'height',
+ 'lighting_preset_id',
+ ]);
+ for (const key of Object.keys(body)) {
+ if (body[key] !== undefined && !allowed.has(key)) {
+ throw badRequest(`camera mode field ${key} is unknown`);
+ }
+ }
+ const camera = validateCameraMode({
+ cameras: body.cameras,
+ width: body.width,
+ height: body.height,
+ lightingPresetId: body.lighting_preset_id,
+ });
+ return { mode: 'camera', ...camera };
+ }
+ if (body.width !== undefined || body.height !== undefined || body.lighting_preset_id !== undefined) {
+ throw badRequest('width, height, and lighting_preset_id require cameras');
+ }
+ return {
+ mode: 'legacy',
+ viewDirs: validateViewDirs(body.views),
+ size: body.size,
+ beautySize: body.beauty_size,
+ background: body.background,
+ };
+}
+
+export function sha256(bytes) {
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
+}
+
+const SHA256_IDENTITY_RE = /^sha256:[0-9a-f]{64}$/;
+
+/**
+ * Compute the identity of the exact GLB bytes the renderer will consume. A new
+ * caller may also assert its expected identity; legacy callers omit the claim
+ * and still receive the computed identity in the response.
+ */
+export function validateInputGlbIdentity(bytes, claimedIdentity) {
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
+ throw badRequest('GLB identity requires non-empty bytes');
+ }
+ const actual = sha256(bytes);
+ if (claimedIdentity === undefined) return actual;
+ if (typeof claimedIdentity !== 'string' || !SHA256_IDENTITY_RE.test(claimedIdentity)) {
+ throw badRequest('input_glb_sha256 must be sha256:<64 lowercase hex characters>');
+ }
+ if (claimedIdentity !== actual) {
+ throw badRequest('input_glb_sha256 does not match glb_base64 bytes');
+ }
+ return actual;
+}
+
+const FIDELITY_TIMING_KEYS = new Set([
+ 'loadMs',
+ 'viewsMs',
+ 'beautyMs',
+ 'totalMs',
+ 'queueWaitMs',
+ 'queueAndTotalMs',
+]);
+
+function cloneCamera(camera) {
+ return {
+ position: [...camera.position],
+ target: [...camera.target],
+ up: [...camera.up],
+ fovDeg: camera.fovDeg,
+ aspect: camera.aspect,
+ near: camera.near,
+ far: camera.far,
+ };
+}
+
+/**
+ * Mint the additive renderer-side fidelity receipt only after all identity and
+ * camera/profile claims have been checked against the request and actual result.
+ *
+ * `exactArtifact` is deliberately false: this service attests the exact GLB
+ * bytes it rendered, but only the caller knows whether those bytes are the
+ * persisted/final artifact rather than an in-loop or derivative GLB.
+ */
+export function buildRenderFidelityV1({
+ rendererId,
+ inputGlbSha256,
+ presentationProfile,
+ renderMode,
+ resolvedCameras,
+ timings,
+}) {
+ if (
+ typeof rendererId !== 'string'
+ || rendererId.trim() !== rendererId
+ || rendererId.length < 1
+ || rendererId.length > 160
+ ) {
+ throw badRequest('rendererId must be a non-empty string of at most 160 characters');
+ }
+ if (typeof inputGlbSha256 !== 'string' || !SHA256_IDENTITY_RE.test(inputGlbSha256)) {
+ throw badRequest('inputGlbSha256 must be sha256:<64 lowercase hex characters>');
+ }
+ if (!isPresentationPresetId(presentationProfile)) {
+ throw badRequest(supportedPresetMessage('presentationProfile'));
+ }
+ if (!renderMode || (renderMode.mode !== 'camera' && renderMode.mode !== 'legacy')) {
+ throw badRequest('renderMode must be a validated camera or legacy render mode');
+ }
+ if (!Array.isArray(resolvedCameras)) {
+ throw badRequest('resolvedCameras must be an array');
+ }
+
+ const requestedCameras = renderMode.mode === 'camera'
+ ? renderMode.cameras.map(cloneCamera)
+ : [];
+ if (
+ resolvedCameras.length !== requestedCameras.length
+ || JSON.stringify(resolvedCameras) !== JSON.stringify(requestedCameras)
+ ) {
+ throw badRequest('resolved cameras do not match the validated requested cameras');
+ }
+
+ if (!timings || typeof timings !== 'object' || Array.isArray(timings)) {
+ throw badRequest('timings must be an object');
+ }
+ const checkedTimings = {};
+ for (const [key, value] of Object.entries(timings)) {
+ if (!FIDELITY_TIMING_KEYS.has(key)) throw badRequest(`timings.${key} is unknown`);
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ throw badRequest(`timings.${key} must be a non-negative finite number`);
+ }
+ checkedTimings[key] = value;
+ }
+ if (checkedTimings.totalMs === undefined || checkedTimings.queueAndTotalMs === undefined) {
+ throw badRequest('timings must include totalMs and queueAndTotalMs');
+ }
+ if (checkedTimings.queueAndTotalMs < checkedTimings.totalMs) {
+ throw badRequest('timings.queueAndTotalMs must be at least totalMs');
+ }
+ if (
+ checkedTimings.queueWaitMs !== undefined
+ && checkedTimings.queueWaitMs > checkedTimings.queueAndTotalMs
+ ) {
+ throw badRequest('timings.queueWaitMs must not exceed queueAndTotalMs');
+ }
+
+ return {
+ version: RENDER_FIDELITY_VERSION,
+ producer: RENDER_FIDELITY_PRODUCER,
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId,
+ inputGlbSha256,
+ degraded: false,
+ presentationProfile,
+ renderMode: renderMode.mode,
+ requestedCameras,
+ resolvedCameras: resolvedCameras.map(cloneCamera),
+ timings: checkedTimings,
+ };
+}
+
+/** Canonical identity of an ordered output set; it is not a composite-image hash. */
+export function outputSetSha256(outputs) {
+ const hash = createHash('sha256');
+ hash.update('kiln-render-output-set-v1\0');
+ for (const output of outputs) {
+ const size = Buffer.allocUnsafe(4);
+ size.writeUInt32BE(output.byteLength);
+ hash.update(size);
+ hash.update(output);
+ }
+ return `sha256:${hash.digest('hex')}`;
+}
diff --git a/render-service/src/gpu.mjs b/render-service/src/gpu.mjs
new file mode 100644
index 00000000..4116fcf2
--- /dev/null
+++ b/render-service/src/gpu.mjs
@@ -0,0 +1,90 @@
+// GPU acquisition and the anti-software guard.
+//
+// Two facts B1a/B1 established that this module encodes:
+// 1. Dawn's Node binding leaves adapter.isFallbackAdapter undefined on every
+// platform tested (win32/D3D12, linux/Vulkan) — the spec flag is unusable.
+// The guard is vendor/description matching.
+// 2. A container can pass every CUDA check (nvidia-smi works) while Vulkan
+// silently lands on llvmpipe — missing GLVND dispatch libs do exactly this.
+// So the guard must fail CLOSED, at boot, not at first render.
+import { create, globals } from 'webgpu';
+
+Object.assign(globalThis, globals);
+
+const SOFTWARE_RE = /swiftshader|lavapipe|llvmpipe|software|microsoft basic/i;
+
+let state = null;
+let shuttingDown = false;
+
+/**
+ * Declare that teardown has begun, so a device torn down on the way out is not
+ * reported as a fault. Exported for the shutdown path and for tests.
+ */
+export function markGpuShutdown() {
+ shuttingDown = true;
+}
+
+/**
+ * A lost device is unrecoverable here: the renderer context and /health both
+ * answer from cached state, so the worker would stay 200-healthy while failing
+ * every render. Exiting non-zero is the only way the orchestrator learns to
+ * replace it. `reason: 'destroyed'` is our own teardown, never a fault.
+ * @param {{reason?: string}} info
+ */
+export function shouldExitOnDeviceLost(info) {
+ return !shuttingDown && info?.reason !== 'destroyed';
+}
+
+export function adapterSummary(adapter) {
+ const i = adapter.info ?? {};
+ return {
+ vendor: i.vendor ?? '',
+ architecture: i.architecture ?? '',
+ device: i.device ?? '',
+ description: i.description ?? '',
+ };
+}
+
+export function isSoftwareAdapter(adapter) {
+ const { vendor, device, description } = adapterSummary(adapter);
+ return SOFTWARE_RE.test(`${vendor} ${device} ${description}`);
+}
+
+export async function acquireGpu({ allowSoftware = false } = {}) {
+ if (state) return state;
+ const gpu = create([]);
+ try {
+ Object.defineProperty(globalThis, 'navigator', { value: { gpu }, configurable: true });
+ } catch {
+ try { Object.defineProperty(globalThis.navigator, 'gpu', { value: gpu, configurable: true }); } catch { /* three gets device directly */ }
+ }
+ const adapter = await gpu.requestAdapter({ powerPreference: 'high-performance' });
+ if (!adapter) throw new Error('no WebGPU adapter: no usable Vulkan/D3D12/Metal device visible to Dawn');
+ const software = isSoftwareAdapter(adapter);
+ if (software && !allowSoftware) {
+ const { description } = adapterSummary(adapter);
+ throw new Error(`software adapter refused (fail closed): ${description}. ` +
+ 'On Linux this usually means the NVIDIA Vulkan ICD failed to init - check GLVND libs (libegl1/libgl1/libglvnd0).');
+ }
+ const device = await adapter.requestDevice({
+ requiredFeatures: [...adapter.features],
+ });
+ // Health is not liveness without this. Signals are deliberately left on Node's
+ // default (immediate termination) — no JS runs after them, so the handler
+ // cannot fire on a container stop; 'beforeExit' covers a drained event loop.
+ process.once('beforeExit', markGpuShutdown);
+ device.lost.then((info) => {
+ if (!shouldExitOnDeviceLost(info)) return;
+ console.error(JSON.stringify({
+ evt: 'device_lost',
+ reason: info?.reason ?? 'unknown',
+ message: info?.message ?? '',
+ }));
+ process.exit(1);
+ });
+ const summary = adapterSummary(adapter);
+ const backend = process.platform === 'win32' ? 'd3d12' : process.platform === 'darwin' ? 'metal' : 'vulkan';
+ const rendererId = `dawn-${backend}:${summary.device || summary.vendor}:${summary.description}`.slice(0, 160);
+ state = { gpu, adapter, device, summary, software, backend, rendererId };
+ return state;
+}
diff --git a/render-service/src/health-contract.mjs b/render-service/src/health-contract.mjs
new file mode 100644
index 00000000..ba248ccb
--- /dev/null
+++ b/render-service/src/health-contract.mjs
@@ -0,0 +1,32 @@
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_CAPABILITIES,
+ PRESENTATION_PRESET_IDS,
+} from './presentation-presets.mjs';
+
+/** Provider-free health contract shared by the HTTP route and unit tests. */
+export const RENDER_CAPABILITIES = Object.freeze([
+ 'render.views',
+ 'render.views.checked',
+ 'render.cameras.perspective-v1',
+ 'render.targets.rectangular-v1',
+ 'render.outputs.sha256-v1',
+ 'render.fidelity.v1',
+ 'render.operational-evidence.v1',
+ ...PRESENTATION_PRESET_CAPABILITIES,
+ 'render.beauty',
+ 'auth.x-render-token',
+]);
+
+export function buildHealthDocument(gpuState, authRequired) {
+ return {
+ ok: true,
+ rendererId: gpuState.rendererId,
+ backend: gpuState.backend,
+ adapter: gpuState.summary,
+ capabilities: RENDER_CAPABILITIES,
+ presentationProfile: DEFAULT_PRESENTATION_PRESET_ID,
+ lightingPresetIds: [...PRESENTATION_PRESET_IDS],
+ authRequired: Boolean(authRequired),
+ };
+}
diff --git a/render-service/src/presentation-presets.mjs b/render-service/src/presentation-presets.mjs
new file mode 100644
index 00000000..dd7d1eff
--- /dev/null
+++ b/render-service/src/presentation-presets.mjs
@@ -0,0 +1,129 @@
+// Renderer-owned, versioned presentation definitions. Requests select an ID;
+// no caller-controlled light/color/exposure object crosses the HTTP boundary.
+
+const PRESET_KEYS = Object.freeze([
+ 'id', 'environment', 'background', 'exposure', 'ambient',
+ 'sun', 'key', 'fill', 'rim', 'shadows',
+]);
+const ACTIVE_DIRECTIONAL_KEYS = Object.freeze([
+ 'enabled', 'color', 'intensity', 'position', 'castsShadow',
+]);
+const DISABLED_DIRECTIONAL_KEYS = Object.freeze(['enabled']);
+
+function exactKeys(value, expected, path) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new TypeError(`${path} must be an object`);
+ }
+ const actual = Object.keys(value).sort();
+ const wanted = [...expected].sort();
+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
+ throw new TypeError(`${path} keys must be exactly ${wanted.join(', ')}`);
+ }
+}
+
+function finite(value, path, { minimum = -Infinity } = {}) {
+ if (!Number.isFinite(value) || value < minimum) throw new TypeError(`${path} must be finite >= ${minimum}`);
+}
+
+function color(value, path) {
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffff) {
+ throw new TypeError(`${path} must be a 24-bit color integer`);
+ }
+}
+
+function tuple(value, length, path, validate) {
+ if (!Array.isArray(value) || value.length !== length) throw new TypeError(`${path} must have ${length} entries`);
+ value.forEach((entry, index) => validate(entry, `${path}[${index}]`));
+}
+
+function validateDirectional(value, path) {
+ exactKeys(value, value?.enabled === false ? DISABLED_DIRECTIONAL_KEYS : ACTIVE_DIRECTIONAL_KEYS, path);
+ if (typeof value.enabled !== 'boolean') throw new TypeError(`${path}.enabled must be boolean`);
+ if (!value.enabled) return;
+ color(value.color, `${path}.color`);
+ finite(value.intensity, `${path}.intensity`, { minimum: 0 });
+ tuple(value.position, 3, `${path}.position`, finite);
+ if (typeof value.castsShadow !== 'boolean') throw new TypeError(`${path}.castsShadow must be boolean`);
+}
+
+function validatePreset(preset) {
+ exactKeys(preset, PRESET_KEYS, 'presentation preset');
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*-v[1-9][0-9]*$/.test(preset.id)) {
+ throw new TypeError('presentation preset id must end in a positive version');
+ }
+ exactKeys(preset.environment, ['type', 'sigma'], `${preset.id}.environment`);
+ if (preset.environment.type !== 'room') throw new TypeError(`${preset.id}.environment.type must be room`);
+ finite(preset.environment.sigma, `${preset.id}.environment.sigma`, { minimum: 0 });
+ if (!/^#[0-9a-f]{6}$/.test(preset.background)) {
+ throw new TypeError(`${preset.id}.background must be lowercase #rrggbb`);
+ }
+ finite(preset.exposure, `${preset.id}.exposure`, { minimum: 0 });
+ exactKeys(preset.ambient, ['type', 'sky', 'ground', 'intensity'], `${preset.id}.ambient`);
+ if (preset.ambient.type !== 'hemisphere') throw new TypeError(`${preset.id}.ambient.type must be hemisphere`);
+ color(preset.ambient.sky, `${preset.id}.ambient.sky`);
+ color(preset.ambient.ground, `${preset.id}.ambient.ground`);
+ finite(preset.ambient.intensity, `${preset.id}.ambient.intensity`, { minimum: 0 });
+ for (const role of ['sun', 'key', 'fill', 'rim']) validateDirectional(preset[role], `${preset.id}.${role}`);
+ exactKeys(
+ preset.shadows,
+ ['enabled', 'type', 'mapSize', 'bias', 'normalBias', 'radius'],
+ `${preset.id}.shadows`,
+ );
+ if (typeof preset.shadows.enabled !== 'boolean') throw new TypeError(`${preset.id}.shadows.enabled must be boolean`);
+ if (preset.shadows.type !== 'pcf-soft') throw new TypeError(`${preset.id}.shadows.type must be pcf-soft`);
+ tuple(preset.shadows.mapSize, 2, `${preset.id}.shadows.mapSize`, (entry, path) => {
+ if (!Number.isInteger(entry) || entry < 1 || entry > 8192) throw new TypeError(`${path} must be an integer in [1,8192]`);
+ });
+ finite(preset.shadows.bias, `${preset.id}.shadows.bias`);
+ finite(preset.shadows.normalBias, `${preset.id}.shadows.normalBias`, { minimum: 0 });
+ finite(preset.shadows.radius, `${preset.id}.shadows.radius`, { minimum: 0 });
+ return preset;
+}
+
+function deepFreeze(value) {
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
+ for (const child of Object.values(value)) deepFreeze(child);
+ return Object.freeze(value);
+}
+
+const definitions = [
+ validatePreset({
+ id: 'neutral-studio-v1',
+ environment: { type: 'room', sigma: 0.04 },
+ background: '#aab1bc',
+ exposure: 1.38,
+ ambient: { type: 'hemisphere', sky: 0xffffff, ground: 0x6f7888, intensity: 2 },
+ // The v1 studio rig has no separate sun. Retaining this explicit disabled
+ // role lets future world-oriented IDs add one without changing the schema.
+ sun: { enabled: false },
+ key: { enabled: true, color: 0xffffff, intensity: 3, position: [4, 7, 5], castsShadow: false },
+ fill: { enabled: true, color: 0xdce8ff, intensity: 1.8, position: [-4, 3, 2], castsShadow: false },
+ rim: { enabled: true, color: 0xffead6, intensity: 1.2, position: [-2, 5, -5], castsShadow: false },
+ // These are the WebGPU/three.js controls the renderer knows how to apply.
+ // Disabled preserves the exact pre-registry v1 visual behavior.
+ shadows: {
+ enabled: false,
+ type: 'pcf-soft',
+ mapSize: [1024, 1024],
+ bias: 0,
+ normalBias: 0,
+ radius: 1,
+ },
+ }),
+];
+
+for (const definition of definitions) deepFreeze(definition);
+export const PRESENTATION_PRESET_IDS = Object.freeze(definitions.map(({ id }) => id));
+export const DEFAULT_PRESENTATION_PRESET_ID = PRESENTATION_PRESET_IDS[0];
+export const PRESENTATION_PRESET_CAPABILITIES = Object.freeze(
+ PRESENTATION_PRESET_IDS.map((id) => `render.profile.${id}`),
+);
+const registry = Object.freeze(Object.fromEntries(definitions.map((preset) => [preset.id, preset])));
+
+export function isPresentationPresetId(id) {
+ return typeof id === 'string' && Object.hasOwn(registry, id);
+}
+
+export function getPresentationPreset(id) {
+ return isPresentationPresetId(id) ? registry[id] : undefined;
+}
diff --git a/render-service/src/register-hooks.mjs b/render-service/src/register-hooks.mjs
new file mode 100644
index 00000000..d1327187
--- /dev/null
+++ b/render-service/src/register-hooks.mjs
@@ -0,0 +1,2 @@
+import { register } from 'node:module';
+register('./three-alias-hooks.mjs', import.meta.url);
diff --git a/render-service/src/renderer.mjs b/render-service/src/renderer.mjs
new file mode 100644
index 00000000..fc7bf6b1
--- /dev/null
+++ b/render-service/src/renderer.mjs
@@ -0,0 +1,373 @@
+// GLB bytes -> PBR PNG views. Headless three.js WebGPURenderer, RenderTarget-only.
+//
+// B1a engineering notes encoded here:
+// - bare 'three' is aliased to 'three/webgpu' via module hooks (see register-hooks.mjs);
+// loading this module without the hooks would split three's class identity.
+// - Renderer.init() starts an internal loop via self.requestAnimationFrame — shimmed.
+// - GLTFLoader's ImageBitmapLoader path yields fake bitmaps that Dawn uploads as
+// black; decoded images are converted to DataTexture (writeTexture path).
+// - WebGPU readback rows are already top-down: no Y flip.
+import { PNG } from 'pngjs';
+import { acquireGpu } from './gpu.mjs';
+import { validateRenderMode } from './contract.mjs';
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_IDS,
+ getPresentationPreset,
+} from './presentation-presets.mjs';
+
+export { MAX_VIEW_DIRS, validateViewDirs } from './contract.mjs';
+
+globalThis.self = globalThis;
+globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(performance.now()), 16);
+globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
+
+// PNG-only decode for GLB-embedded images; JPEG assets degrade to materials without maps.
+globalThis.createImageBitmap = async (blob) => {
+ const buf = Buffer.from(await blob.arrayBuffer());
+ if (buf[0] !== 0x89 || buf[1] !== 0x50) throw new Error('only PNG images supported in GLB');
+ const png = PNG.sync.read(buf);
+ return { width: png.width, height: png.height, data: new Uint8Array(png.data), close() { } };
+};
+
+const THREE = await import('three/webgpu');
+const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
+const { RoomEnvironment } = await import('three/addons/environments/RoomEnvironment.js');
+
+/**
+ * Fixed, versioned presentation profile for every GPU view sheet. The GPU path
+ * is the intentional beauty/inspection upgrade; it does not try to imitate the
+ * flat CPU fallback. Keep these values deterministic so sheets remain directly
+ * comparable across models and runs.
+ */
+export const PRESENTATION_PROFILE_ID = DEFAULT_PRESENTATION_PRESET_ID;
+const defaultPresentation = getPresentationPreset(PRESENTATION_PROFILE_ID);
+// Compatibility exports retain their exact shapes/values while the renderer
+// itself now consumes the registry definition below.
+export const PRESENTATION_BACKGROUND = defaultPresentation.background;
+export const PRESENTATION_EXPOSURE = defaultPresentation.exposure;
+export const PRESENTATION_LIGHTS = Object.freeze({
+ hemisphere: Object.freeze({
+ sky: defaultPresentation.ambient.sky,
+ ground: defaultPresentation.ambient.ground,
+ intensity: defaultPresentation.ambient.intensity,
+ }),
+ ...Object.fromEntries(['key', 'fill', 'rim'].map((role) => [role, Object.freeze({
+ color: defaultPresentation[role].color,
+ intensity: defaultPresentation[role].intensity,
+ position: defaultPresentation[role].position,
+ })])),
+});
+
+/**
+ * Ceiling on views per request. One render target is pooled per view at each
+ * size, and the caller pays for every extra render, so this is a real resource
+ * bound rather than a formality. The engine caps its own grid at 9 cells; the
+ * headroom is for a caller that wants a few diagnostic angles alongside.
+ */
+let ctx = null;
+
+/**
+ * Render sizes a caller may ask for. Pools are keyed by size, hold MSAA targets,
+ * and are never evicted — so a free 64..2048 range would let a caller mint ~1985
+ * of them (hundreds of MB apiece at the top end) and exhaust VRAM on a warm
+ * worker. Requests snap UP to the next allowed size, so a caller always gets at
+ * least the detail it asked for. Add a rung only if a real consumer needs it.
+ */
+export const ALLOWED_RENDER_SIZES = Object.freeze([128, 256, 384, 512, 768, 1024, 2048]);
+
+/** Snap to the smallest allowed size that is >= requested (largest if beyond). */
+export function snapRenderSize(requested) {
+ const n = Number.isFinite(requested) ? requested : 384;
+ return ALLOWED_RENDER_SIZES.find((s) => s >= n) ?? ALLOWED_RENDER_SIZES.at(-1);
+}
+
+const _rtPools = new Map();
+function rtPool(size, count) {
+ const pool = _rtPools.get(size) ?? [];
+ while (pool.length < count) pool.push(new THREE.RenderTarget(size, size, { depthBuffer: true, samples: 4 }));
+ _rtPools.set(size, pool);
+ return pool.slice(0, count);
+}
+
+export async function initRenderer(opts = {}) {
+ if (ctx) return ctx;
+ const gpuState = await acquireGpu(opts);
+ const fakeCanvas = {
+ width: 4, height: 4, style: {},
+ addEventListener() { }, removeEventListener() { }, dispatchEvent() { },
+ getContext() { throw new Error('default canvas context requested — RT-only expectation violated'); },
+ };
+ const renderer = new THREE.WebGPURenderer({ canvas: fakeCanvas, device: gpuState.device, antialias: false });
+ await renderer.init();
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = PRESENTATION_EXPOSURE;
+
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const environments = new Map(PRESENTATION_PRESET_IDS.map((id) => {
+ const preset = getPresentationPreset(id);
+ return [id, pmrem.fromScene(new RoomEnvironment(), preset.environment.sigma).texture];
+ }));
+ const environment = environments.get(PRESENTATION_PROFILE_ID);
+
+ const loader = new GLTFLoader();
+ ctx = { renderer, environment, environments, loader, gpuState, device: gpuState.device };
+ return ctx;
+}
+
+function toDataTextures(root) {
+ root.traverse((o) => {
+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
+ for (const slot of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap']) {
+ const tex = mat[slot];
+ if (tex?.image?.data && !tex.isDataTexture) {
+ const dt = new THREE.DataTexture(tex.image.data, tex.image.width, tex.image.height, THREE.RGBAFormat);
+ dt.colorSpace = tex.colorSpace; dt.flipY = tex.flipY;
+ dt.wrapS = tex.wrapS; dt.wrapT = tex.wrapT;
+ dt.magFilter = tex.magFilter; dt.minFilter = THREE.LinearMipmapLinearFilter;
+ dt.generateMipmaps = true; dt.needsUpdate = true;
+ mat[slot] = dt; mat.needsUpdate = true;
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Release the GPU resources this request's parse allocated. `ctx.environment` is
+ * seeded into the visited set because it is shared across every request and
+ * disposing it would break every later render; pooled render targets are never
+ * reached from here for the same reason. three removes its own dispose listener
+ * on the first call, so re-disposing a shared texture is a no-op.
+ */
+function disposeGltf(gltf) {
+ const seen = new Set(ctx?.environments?.values() ?? [ctx?.environment]);
+ const dispose = (r) => {
+ if (!r || seen.has(r)) return;
+ seen.add(r);
+ r.dispose();
+ };
+ for (const root of gltf.scenes?.length ? gltf.scenes : [gltf.scene]) {
+ root?.traverse((o) => {
+ dispose(o.geometry);
+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {
+ if (seen.has(mat)) continue;
+ for (const v of Object.values(mat)) if (v?.isTexture) dispose(v);
+ dispose(mat);
+ }
+ });
+ }
+}
+
+function applyPresentationPreset(renderer, scene, root, preset, environment) {
+ renderer.toneMappingExposure = preset.exposure;
+ renderer.shadowMap.enabled = preset.shadows.enabled;
+ if (preset.shadows.enabled) renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ scene.background = new THREE.Color(preset.background);
+ scene.environment = environment;
+
+ const ambient = preset.ambient;
+ scene.add(new THREE.HemisphereLight(ambient.sky, ambient.ground, ambient.intensity));
+ for (const role of ['sun', 'key', 'fill', 'rim']) {
+ const lightSpec = preset[role];
+ if (!lightSpec.enabled) continue;
+ const light = new THREE.DirectionalLight(lightSpec.color, lightSpec.intensity);
+ light.position.set(...lightSpec.position);
+ light.castShadow = preset.shadows.enabled && lightSpec.castsShadow;
+ if (light.castShadow) {
+ light.shadow.mapSize.set(...preset.shadows.mapSize);
+ light.shadow.bias = preset.shadows.bias;
+ light.shadow.normalBias = preset.shadows.normalBias;
+ light.shadow.radius = preset.shadows.radius;
+ }
+ scene.add(light);
+ }
+ if (preset.shadows.enabled) {
+ root.traverse((object) => {
+ if (!object.isMesh) return;
+ object.castShadow = true;
+ object.receiveShadow = true;
+ });
+ }
+}
+
+function orthoCam(center, radius, dir) {
+ const cam = new THREE.OrthographicCamera(-radius, radius, radius, -radius, 0.01, radius * 6);
+ cam.position.copy(center.clone().add(new THREE.Vector3(...dir).normalize().multiplyScalar(radius * 2.5)));
+ cam.lookAt(center);
+ cam.updateMatrixWorld();
+ return cam;
+}
+
+function beautyCam(center, boxRadius) {
+ const cam = new THREE.PerspectiveCamera(35, 1, 0.01, boxRadius * 10);
+ cam.position.copy(center.clone().add(new THREE.Vector3(1, 0.55, 1).normalize().multiplyScalar(boxRadius * 2.1)));
+ cam.lookAt(center);
+ cam.updateMatrixWorld();
+ return cam;
+}
+
+function exactPerspectiveCam(spec) {
+ const cam = new THREE.PerspectiveCamera(spec.fovDeg, spec.aspect, spec.near, spec.far);
+ cam.position.set(...spec.position);
+ cam.up.set(...spec.up);
+ cam.lookAt(new THREE.Vector3(...spec.target));
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld(true);
+ return cam;
+}
+
+async function readPng(renderer, rt, w, h) {
+ const pixels = await renderer.readRenderTargetPixelsAsync(rt, 0, 0, w, h);
+ const png = new PNG({ width: w, height: h });
+ Buffer.from(pixels.buffer, pixels.byteOffset, w * h * 4).copy(png.data);
+ // Fast encode: deflate 1 + no row filtering is ~10x quicker than the adaptive
+ // default and consumers read pixels, not bytes (image tokens scale with
+ // dimensions, not file size).
+ return PNG.sync.write(png, { deflateLevel: 1, filterType: 0 });
+}
+
+/**
+ * Render a GLB into PNG views.
+ * @param {Buffer} glbBytes
+ * @param {{size?: number, viewDirs?: number[][], beautySize?: number, background?: string,
+ * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}} opts
+ * @returns {Promise<{views: Buffer[], beauty: Buffer|null, timings: object,
+ * cameras?: object[], width?: number, height?: number, lightingPresetId?: string}>}
+ */
+export async function renderGlb(glbBytes, opts = {}) {
+ const { renderer, environments, loader } = await initRenderer();
+ const renderMode = validateRenderMode({
+ cameras: opts.cameras,
+ width: opts.width,
+ height: opts.height,
+ lighting_preset_id: opts.lightingPresetId,
+ views: opts.viewDirs,
+ size: opts.size,
+ beauty_size: opts.beautySize,
+ background: opts.background,
+ });
+ // Snapped, not clamped: pooled render targets are keyed by size and never
+ // evicted, so an unbounded key space is a caller-controlled VRAM leak. The
+ // beauty target below is allocated per request and disposed, so it keeps a
+ // plain clamp — it has no pool to poison.
+ const size = renderMode.mode === 'legacy' ? snapRenderSize(renderMode.size ?? 384) : null;
+ const beautySize = renderMode.mode === 'legacy' && renderMode.beautySize
+ ? Math.min(Math.max(renderMode.beautySize, 128), 4096)
+ : null;
+ const viewDirs = renderMode.mode === 'legacy' ? renderMode.viewDirs : null;
+ const presentationPresetId = renderMode.mode === 'camera'
+ ? renderMode.lightingPresetId
+ : PRESENTATION_PROFILE_ID;
+ const presentation = getPresentationPreset(presentationPresetId);
+
+ const t0 = performance.now();
+ const ab = glbBytes.buffer.slice(glbBytes.byteOffset, glbBytes.byteOffset + glbBytes.byteLength);
+ const gltf = await new Promise((res, rej) => loader.parse(ab, '', res, rej));
+ let scene = null;
+ const requestTargets = [];
+ try {
+ toDataTextures(gltf.scene);
+ const tLoad = performance.now();
+
+ scene = new THREE.Scene();
+ applyPresentationPreset(renderer, scene, gltf.scene, presentation, environments.get(presentationPresetId));
+ // Legacy callers retain their historical escape hatch. Exact camera mode is
+ // preset-ID-only and validateRenderMode rejects a background field.
+ if (renderMode.mode === 'legacy' && opts.background !== undefined) {
+ scene.background = new THREE.Color(opts.background);
+ }
+ scene.add(gltf.scene);
+
+ if (renderMode.mode === 'camera') {
+ // Exact milestone targets are deliberately request-owned and rectangular;
+ // unlike the bounded square legacy pool, no camera dimensions survive the
+ // request. Submit every camera first, then read back in request order.
+ for (const camera of renderMode.cameras) {
+ const target = new THREE.RenderTarget(renderMode.width, renderMode.height, {
+ depthBuffer: true,
+ samples: 4,
+ });
+ requestTargets.push(target);
+ renderer.setRenderTarget(target);
+ renderer.render(scene, exactPerspectiveCam(camera));
+ }
+ const views = [];
+ for (const target of requestTargets) {
+ views.push(await readPng(renderer, target, renderMode.width, renderMode.height));
+ }
+ const tEnd = performance.now();
+ return {
+ views,
+ beauty: null,
+ cameras: renderMode.cameras,
+ width: renderMode.width,
+ height: renderMode.height,
+ lightingPresetId: renderMode.lightingPresetId,
+ timings: {
+ loadMs: +(tLoad - t0).toFixed(1),
+ viewsMs: +(tEnd - tLoad).toFixed(1),
+ beautyMs: 0,
+ totalMs: +(tEnd - t0).toFixed(1),
+ },
+ };
+ }
+
+ const box = new THREE.Box3().setFromObject(gltf.scene);
+ const center = box.getCenter(new THREE.Vector3());
+ const sizes = box.getSize(new THREE.Vector3());
+ const orthoRadius = Math.max(sizes.x, sizes.y, sizes.z) * 0.72 + 1e-3;
+
+ // One RT per view, pooled across requests (alloc is pure overhead). Submit
+ // every render first, then read back — a mid-loop readback forces a full GPU
+ // sync per view.
+ const rts = rtPool(size, viewDirs.length);
+ viewDirs.forEach((dir, i) => {
+ renderer.setRenderTarget(rts[i]);
+ renderer.render(scene, orthoCam(center, orthoRadius, dir));
+ });
+ const views = [];
+ for (const vrt of rts) {
+ views.push(await readPng(renderer, vrt, size, size));
+ }
+ const tViews = performance.now();
+
+ let beauty = null;
+ if (beautySize) {
+ const rtB = new THREE.RenderTarget(beautySize, beautySize, { depthBuffer: true, samples: 4 });
+ renderer.setRenderTarget(rtB);
+ renderer.render(scene, beautyCam(center, sizes.length() * 0.62 + 1e-3));
+ beauty = await readPng(renderer, rtB, beautySize, beautySize);
+ rtB.dispose();
+ }
+ const tEnd = performance.now();
+
+ return {
+ views,
+ beauty,
+ timings: {
+ loadMs: +(tLoad - t0).toFixed(1),
+ viewsMs: +(tViews - tLoad).toFixed(1),
+ beautyMs: beauty ? +(tEnd - tViews).toFixed(1) : 0,
+ totalMs: +(tEnd - t0).toFixed(1),
+ },
+ };
+ } finally {
+ // Every request parses its own copy and toDataTextures uploads fresh GPU
+ // textures for it; a warm worker that skips this accumulates every asset it
+ // has ever rendered. Readback is complete by here, so nothing in flight can
+ // still reference what we release. Runs on the throwing path too.
+ //
+ // Swallowed deliberately: this runs after the response value is built, so
+ // letting cleanup throw would turn a completed render into a 500. A leak is
+ // the better failure than losing work already paid for on the GPU.
+ try {
+ renderer.setRenderTarget(null);
+ for (const target of requestTargets) target.dispose();
+ scene?.clear();
+ disposeGltf(gltf);
+ } catch (e) {
+ console.warn(JSON.stringify({ evt: 'dispose-failed', error: String(e?.message ?? e) }));
+ }
+ }
+}
diff --git a/render-service/src/server.mjs b/render-service/src/server.mjs
new file mode 100644
index 00000000..64b2908f
--- /dev/null
+++ b/render-service/src/server.mjs
@@ -0,0 +1,273 @@
+// HTTP surface. Contract (plan B2):
+// GET /health, /ping -> 200 {ok, rendererId, adapter, capabilities, authRequired}
+// (never 503: a software or absent adapter aborts boot below,
+// so a listening server always implies a hardware adapter)
+// POST /render legacy: {glb_base64, input_glb_sha256?, size?, views?, beauty_size?, background?}
+// POST /render camera: {glb_base64, input_glb_sha256?, cameras, width, height,
+// lighting_preset_id?}
+// -> 200 legacy response unchanged, or exact camera
+// receipt metadata + ordered output identities
+// (`input_glb_sha256` opts into an additive,
+// hash-verified material-fidelity receipt)
+// -> 400 on a malformed/over-long views[] (max 12).
+// Exactly one PNG comes back per requested view,
+// in request order — the caller composites a grid
+// whose shape it chose from that length, so this
+// rejects rather than truncating.
+// POST /bake -> 501 (texture bakes are a later workstream)
+// Auth: $RENDER_SERVICE_TOKEN on POST routes (required if set; boot warns loudly
+// when unset), supplied as either `x-render-token: <token>` or
+// `Authorization: Bearer <token>`. The custom header exists because RunPod's
+// load-balancer gateway consumes Authorization for its own edge API-key auth, so
+// gateway callers can never deliver an app-layer bearer token through it.
+// Renders are serialized: one GPU, one queue.
+import { createServer } from 'node:http';
+import {
+ PRESENTATION_PROFILE_ID,
+ initRenderer,
+ renderGlb,
+} from './renderer.mjs';
+import { acquireGpu } from './gpu.mjs';
+import { buildHealthDocument } from './health-contract.mjs';
+import {
+ buildRenderFidelityV1,
+ buildRenderOperationalEvidenceV1,
+ createSerialRenderQueue,
+ httpRenderOutcomeCode,
+ outputSetSha256,
+ sha256,
+ validateInputGlbIdentity,
+ validateRenderMode,
+} from './contract.mjs';
+
+const PROCESS_STARTED_AT = performance.now();
+const PORT = Number(process.env.PORT ?? 8000);
+const TOKEN = process.env.RENDER_SERVICE_TOKEN ?? '';
+
+const MAX_BODY = 96 * 1024 * 1024; // 64MB base64 ≈ 48MB GLB, plus JSON overhead
+const MAX_GLB = 48 * 1024 * 1024;
+
+// Boot assertion: a software adapter must prevent the service from starting at all,
+// so a driver regression yields a service that will not boot rather than one that
+// silently renders everything on CPU.
+let gpuState;
+try {
+ gpuState = await acquireGpu();
+ await initRenderer();
+} catch (e) {
+ console.error(`FATAL: ${e.message}`);
+ process.exit(1);
+}
+console.log(`adapter: ${JSON.stringify(gpuState.summary)}`);
+console.log(`rendererId: ${gpuState.rendererId}`);
+if (!TOKEN) console.warn('WARNING: RENDER_SERVICE_TOKEN unset — POST routes are UNAUTHENTICATED');
+
+const renderQueue = createSerialRenderQueue({ processStartedAt: PROCESS_STARTED_AT });
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (c) => {
+ total += c.length;
+ if (total > MAX_BODY) { reject(Object.assign(new Error('body too large'), { status: 413 })); req.destroy(); return; }
+ chunks.push(c);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks)));
+ req.on('error', reject);
+ });
+}
+
+function send(res, status, obj) {
+ const body = JSON.stringify(obj);
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });
+ res.end(body);
+}
+
+const server = createServer(async (req, res) => {
+ const started = performance.now();
+ // Accumulated across the handler and emitted exactly once by done(). Only
+ // names and sizes go in here — never a token, a header value, or GLB bytes.
+ // Path only, never the query string: nothing here accepts a token as a query
+ // parameter, but logging the raw URL would make any future one a disclosure.
+ const log = {
+ method: req.method,
+ path: String(req.url ?? '').split('?')[0].slice(0, 200),
+ auth: 'not-required',
+ };
+ const done = (status, obj) => {
+ send(res, status, obj);
+ const outcomeCode = httpRenderOutcomeCode({
+ method: log.method,
+ path: log.path,
+ status,
+ });
+ console.log(JSON.stringify({
+ evt: 'request',
+ ...log,
+ outcomeCode,
+ status,
+ ...(status >= 400 && obj?.error ? { error: obj.error } : {}),
+ ms: +(performance.now() - started).toFixed(1),
+ }));
+ };
+ try {
+ // /ping: RunPod load-balancer health convention (200 = healthy). The boot
+ // assertion guarantees a listening server implies a hardware adapter.
+ if (req.method === 'GET' && (req.url === '/health' || req.url === '/ping')) {
+ // Capability advertisement, not decoration: a GitHub-build endpoint carries
+ // no commit stamp, so this is the only way a caller can tell WHICH build is
+ // live before depending on a feature. The pure builder is contract-tested
+ // without booting a GPU and advertises every registry ID explicitly.
+ return done(200, buildHealthDocument(gpuState, Boolean(TOKEN)));
+ }
+ if (req.method === 'POST' && (req.url === '/render' || req.url === '/bake')) {
+ if (TOKEN) {
+ const auth = req.headers.authorization ?? '';
+ const custom = req.headers['x-render-token'] ?? '';
+ if (auth !== `Bearer ${TOKEN}` && custom !== TOKEN) {
+ log.auth = 'rejected';
+ return done(401, { ok: false, error: 'unauthorized' });
+ }
+ // Which header carried it, never the value: the gateway strips
+ // Authorization, so this distinguishes a gateway caller from a direct one.
+ log.auth = 'ok';
+ log.authVia = custom === TOKEN ? 'x-render-token' : 'authorization';
+ } else {
+ log.auth = 'disabled';
+ }
+ if (req.url === '/bake') return done(501, { ok: false, error: 'bake not implemented yet' });
+
+ const raw = await readBody(req);
+ log.bodyBytes = raw.length;
+ let body;
+ try { body = JSON.parse(raw.toString('utf8')); } catch { return done(400, { ok: false, error: 'invalid JSON' }); }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ return done(400, { ok: false, error: 'JSON body must be an object' });
+ }
+ if (typeof body.glb_base64 !== 'string' || !body.glb_base64) {
+ return done(400, { ok: false, error: 'glb_base64 (string) required' });
+ }
+ const glb = Buffer.from(body.glb_base64, 'base64');
+ log.glbBytes = glb.length;
+ if (glb.length < 20 || glb.readUInt32LE(0) !== 0x46546c67) {
+ return done(400, { ok: false, error: 'not a GLB (bad magic)' });
+ }
+ if (glb.length > MAX_GLB) return done(413, { ok: false, error: 'GLB too large' });
+ // New fidelity-aware callers assert the identity they sent. Legacy callers
+ // omit it and retain their exact historical response shape.
+ let inputGlbSha256;
+ try { inputGlbSha256 = validateInputGlbIdentity(glb, body.input_glb_sha256); }
+ catch (e) { return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) }); }
+ const fidelityRequested = body.input_glb_sha256 !== undefined;
+ log.inputGlbSha256 = inputGlbSha256;
+ // Validated BEFORE the queue: malformed exact cameras or legacy views are
+ // immediate 400s, not GPU-queue work. renderGlb validates again for direct callers.
+ let renderMode;
+ try { renderMode = validateRenderMode(body); }
+ catch (e) { return done(e.status ?? 400, { ok: false, error: String(e.message ?? e) }); }
+ log.renderMode = renderMode.mode;
+ if (renderMode.mode === 'camera') {
+ log.camerasRequested = renderMode.cameras.length;
+ log.width = renderMode.width;
+ log.height = renderMode.height;
+ log.totalPixels = renderMode.totalPixels;
+ log.lightingPresetId = renderMode.lightingPresetId;
+ log.backend = gpuState.backend;
+ log.rendererId = gpuState.rendererId;
+ } else {
+ log.viewsRequested = renderMode.viewDirs.length;
+ }
+
+ const t0 = performance.now();
+ const queued = await renderQueue.enqueue(async (operationalStart) => {
+ log.renderOperationalStart = operationalStart;
+ return {
+ operationalStart,
+ result: await renderGlb(glb, renderMode.mode === 'camera'
+ ? {
+ cameras: renderMode.cameras,
+ width: renderMode.width,
+ height: renderMode.height,
+ lightingPresetId: renderMode.lightingPresetId,
+ background: renderMode.background,
+ }
+ : {
+ size: renderMode.size,
+ viewDirs: renderMode.viewDirs,
+ beautySize: renderMode.beautySize,
+ background: renderMode.background,
+ }),
+ };
+ });
+ const result = queued.result;
+ const timings = {
+ ...result.timings,
+ queueWaitMs: +queued.operationalStart.queueWaitMs.toFixed(1),
+ queueAndTotalMs: +(performance.now() - t0).toFixed(1),
+ };
+ log.views = result.views.length;
+ log.beauty = Boolean(result.beauty);
+ log.timings = timings;
+ const viewSha256 = result.views.map(sha256);
+ const outputSetHash = outputSetSha256(result.views);
+ if (renderMode.mode === 'camera') log.outputSetSha256 = outputSetHash;
+ const appliedPresentationProfile = result.lightingPresetId ?? PRESENTATION_PROFILE_ID;
+ const fidelity = fidelityRequested
+ ? buildRenderFidelityV1({
+ rendererId: gpuState.rendererId,
+ inputGlbSha256,
+ presentationProfile: appliedPresentationProfile,
+ renderMode,
+ resolvedCameras: result.cameras ?? [],
+ timings,
+ })
+ : undefined;
+ const operationalEvidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'gpu_success',
+ ...queued.operationalStart,
+ });
+ log.operationalEvidence = operationalEvidence;
+ delete log.renderOperationalStart;
+ return done(200, {
+ ok: true,
+ rendererId: gpuState.rendererId,
+ presentationProfile: appliedPresentationProfile,
+ timings,
+ views: result.views.map((b) => b.toString('base64')),
+ ...(result.beauty ? { beauty: result.beauty.toString('base64') } : {}),
+ ...(fidelity ? { inputGlbSha256, fidelity, operationalEvidence } : {}),
+ ...(renderMode.mode === 'camera' ? {
+ backend: gpuState.backend,
+ cameras: result.cameras,
+ width: result.width,
+ height: result.height,
+ lightingPresetId: result.lightingPresetId,
+ viewSha256,
+ outputSetSha256: outputSetHash,
+ cameraReceipts: result.cameras.map((camera, index) => ({
+ index,
+ camera,
+ width: result.width,
+ height: result.height,
+ outputSha256: viewSha256[index],
+ })),
+ } : {}),
+ });
+ }
+ done(404, { ok: false, error: 'not found' });
+ } catch (e) {
+ if (log.renderOperationalStart && !log.operationalEvidence) {
+ try {
+ log.operationalEvidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'render_failed',
+ ...log.renderOperationalStart,
+ });
+ } catch { /* never mask the original render failure with metrics evidence */ }
+ delete log.renderOperationalStart;
+ }
+ done(e.status ?? 500, { ok: false, error: String(e.message ?? e) });
+ }
+});
+
+server.listen(PORT, () => console.log(`kiln-render-service listening on :${PORT}`));
diff --git a/render-service/src/three-alias-hooks.mjs b/render-service/src/three-alias-hooks.mjs
new file mode 100644
index 00000000..24ce2dac
--- /dev/null
+++ b/render-service/src/three-alias-hooks.mjs
@@ -0,0 +1,6 @@
+// three/addons import bare 'three', which resolves to the WebGL build and splits
+// class identity against 'three/webgpu'. Alias every bare 'three' to the WebGPU build.
+export function resolve(specifier, context, next) {
+ if (specifier === 'three') return next('three/webgpu', context);
+ return next(specifier, context);
+}
diff --git a/render-service/test/contract.test.mjs b/render-service/test/contract.test.mjs
new file mode 100644
index 00000000..311a2ba8
--- /dev/null
+++ b/render-service/test/contract.test.mjs
@@ -0,0 +1,429 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ MAX_CAMERA_TOTAL_PIXELS,
+ MAX_CAMERAS,
+ RENDER_FIDELITY_PRODUCER,
+ RENDER_FIDELITY_VERSION,
+ RENDER_OPERATIONAL_EVIDENCE_VERSION,
+ RENDER_OUTCOME_CODES,
+ SUPPORTED_LIGHTING_PRESET_ID,
+ buildRenderOperationalEvidenceV1,
+ buildRenderFidelityV1,
+ createSerialRenderQueue,
+ httpRenderOutcomeCode,
+ outputSetSha256,
+ sha256,
+ validateInputGlbIdentity,
+ validateCameraMode,
+ validateRenderMode,
+ validateViewDirs,
+} from '../src/contract.mjs';
+
+const camera = (overrides = {}) => ({
+ position: [12, 8, 15],
+ target: [0, 1, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 500,
+ ...overrides,
+});
+
+const exactBody = (overrides = {}) => ({
+ glb_base64: 'not-used-by-mode-parser',
+ cameras: [camera()],
+ width: 1280,
+ height: 720,
+ lighting_preset_id: SUPPORTED_LIGHTING_PRESET_ID,
+ ...overrides,
+});
+
+const throws400 = (fn, pattern) => {
+ assert.throws(fn, (error) => error?.status === 400 && pattern.test(error.message));
+};
+
+describe('provider-free render contract', () => {
+ it('keeps the legacy direction request shape and defaults unchanged', () => {
+ const parsed = validateRenderMode({ size: 384, beauty_size: 1024 });
+ assert.equal(parsed.mode, 'legacy');
+ assert.equal(parsed.size, 384);
+ assert.equal(parsed.beautySize, 1024);
+ assert.equal(parsed.viewDirs.length, 6);
+ parsed.viewDirs[0][0] = 99;
+ assert.equal(validateViewDirs(undefined)[0][0], 1);
+
+ const requested = [[1, 0, 0], [0, 0, -1]];
+ const directions = validateViewDirs(requested);
+ assert.deepEqual(directions, requested);
+ assert.notEqual(directions, requested);
+ assert.notEqual(directions[0], requested[0]);
+ });
+
+ it('normalizes one exact camera mode and clones all transport tuples', () => {
+ const body = exactBody();
+ const parsed = validateRenderMode(body);
+ assert.deepEqual(parsed, {
+ mode: 'camera',
+ cameras: [camera()],
+ width: 1280,
+ height: 720,
+ lightingPresetId: SUPPORTED_LIGHTING_PRESET_ID,
+ totalPixels: 1280 * 720,
+ });
+ assert.notEqual(parsed.cameras, body.cameras);
+ assert.notEqual(parsed.cameras[0].position, body.cameras[0].position);
+ assert.equal(validateRenderMode({ ...body, lighting_preset_id: undefined }).lightingPresetId,
+ SUPPORTED_LIGHTING_PRESET_ID);
+ assert.equal(validateRenderMode({
+ ...body,
+ input_glb_sha256: `sha256:${'a'.repeat(64)}`,
+ }).mode, 'camera');
+ });
+
+ it('rejects mixed legacy and exact selectors in either direction', () => {
+ for (const legacy of [{ views: [[1, 0, 0]] }, { size: 512 }, { beauty_size: 1024 }]) {
+ throws400(() => validateRenderMode({ ...exactBody(), ...legacy }), /mutually exclusive/);
+ }
+ throws400(() => validateRenderMode({ ...exactBody(), mystery_option: true }), /unknown/);
+ throws400(() => validateRenderMode({ ...exactBody(), background: '#000000' }), /cannot override/);
+ for (const cameraOnly of [{ width: 1 }, { height: 1 }, { lighting_preset_id: SUPPORTED_LIGHTING_PRESET_ID }]) {
+ throws400(() => validateRenderMode(cameraOnly), /require cameras/);
+ }
+ });
+
+ it('bounds dimensions, camera count, and total transient pixels', () => {
+ throws400(() => validateCameraMode({ cameras: [], width: 1, height: 1 }), /1\.\.12/);
+ throws400(() => validateCameraMode({
+ cameras: Array.from({ length: MAX_CAMERAS + 1 }, () => camera({ aspect: 1 })),
+ width: 1,
+ height: 1,
+ }), /1\.\.12/);
+ throws400(() => validateCameraMode({ cameras: [camera()], width: 0, height: 720 }), /width/);
+ throws400(() => validateCameraMode({ cameras: [camera()], width: 1280, height: 4097 }), /height/);
+ throws400(() => validateCameraMode({
+ cameras: [camera({ aspect: 1 }), camera({ aspect: 1 })],
+ width: 4096,
+ height: 4096,
+ }), /total pixels/);
+ const boundary = validateCameraMode({
+ cameras: [camera({ aspect: 1 })],
+ width: 4096,
+ height: 4096,
+ });
+ assert.equal(boundary.totalPixels, MAX_CAMERA_TOTAL_PIXELS);
+ });
+
+ it('fails closed on malformed or ambiguous perspective cameras', () => {
+ const base = { cameras: [camera()], width: 1280, height: 720 };
+ throws400(() => validateCameraMode({ ...base, cameras: [{ ...camera(), surprise: true }] }), /unknown/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ position: [0, 0] })] }), /position/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ target: [12, 8, 15] })] }), /differ/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ up: [0, 0, 0] })] }), /non-zero/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ up: [12, 7, 15] })] }), /collinear/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ fovDeg: 180 })] }), /fovDeg/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ near: 0 })] }), /near/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ far: 0.05 })] }), /far/);
+ throws400(() => validateCameraMode({ ...base, cameras: [camera({ aspect: 1 })] }), /width\/height/);
+ throws400(() => validateCameraMode({ ...base, lightingPresetId: 'dramatic-night-v1' }), /neutral-studio-v1/);
+ });
+
+ it('binds ordered output identity without pretending it is a composite hash', () => {
+ const first = Buffer.from('first');
+ const second = Buffer.from('second');
+ assert.match(sha256(first), /^sha256:[0-9a-f]{64}$/);
+ assert.equal(outputSetSha256([first, second]), outputSetSha256([first, second]));
+ assert.notEqual(outputSetSha256([first, second]), outputSetSha256([second, first]));
+ assert.notEqual(outputSetSha256([first, second]), outputSetSha256([Buffer.concat([first, second])]));
+ });
+
+ it('computes the exact input GLB identity and fails closed on a claimed mismatch', () => {
+ const glb = Buffer.from('glTF exact bytes');
+ const identity = validateInputGlbIdentity(glb);
+ assert.equal(identity, sha256(glb));
+ assert.equal(validateInputGlbIdentity(glb, identity), identity);
+ throws400(
+ () => validateInputGlbIdentity(glb, 'sha256:not-a-digest'),
+ /input_glb_sha256 must be sha256/,
+ );
+ throws400(
+ () => validateInputGlbIdentity(glb, sha256(Buffer.from('different bytes'))),
+ /does not match glb_base64 bytes/,
+ );
+ });
+
+ it('builds a frozen additive full-material fidelity receipt for exact camera bytes', () => {
+ const mode = validateRenderMode(exactBody());
+ const inputGlbSha256 = sha256(Buffer.from('glTF exact bytes'));
+ const timings = {
+ loadMs: 2.5,
+ viewsMs: 8,
+ beautyMs: 0,
+ totalMs: 10.5,
+ queueAndTotalMs: 12,
+ };
+ const receipt = buildRenderFidelityV1({
+ rendererId: 'dawn-vulkan:test-device',
+ inputGlbSha256,
+ presentationProfile: SUPPORTED_LIGHTING_PRESET_ID,
+ renderMode: mode,
+ resolvedCameras: mode.cameras,
+ timings,
+ });
+
+ assert.deepEqual(receipt, {
+ version: RENDER_FIDELITY_VERSION,
+ producer: RENDER_FIDELITY_PRODUCER,
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ // The service attests the exact bytes it rendered, not whether those bytes
+ // are the caller's persisted/final artifact.
+ exactArtifact: false,
+ rendererId: 'dawn-vulkan:test-device',
+ inputGlbSha256,
+ degraded: false,
+ presentationProfile: SUPPORTED_LIGHTING_PRESET_ID,
+ renderMode: 'camera',
+ requestedCameras: [camera()],
+ resolvedCameras: [camera()],
+ timings: {
+ loadMs: 2.5,
+ viewsMs: 8,
+ beautyMs: 0,
+ totalMs: 10.5,
+ queueAndTotalMs: 12,
+ },
+ });
+ assert.notEqual(receipt.requestedCameras, mode.cameras);
+ assert.notEqual(receipt.resolvedCameras, mode.cameras);
+ assert.notEqual(receipt.timings, timings);
+ });
+
+ it('rejects forged camera/profile/timing fidelity instead of minting a false receipt', () => {
+ const mode = validateRenderMode(exactBody());
+ const common = {
+ rendererId: 'dawn-vulkan:test-device',
+ inputGlbSha256: sha256(Buffer.from('glTF exact bytes')),
+ presentationProfile: SUPPORTED_LIGHTING_PRESET_ID,
+ renderMode: mode,
+ resolvedCameras: mode.cameras,
+ timings: { totalMs: 10, queueAndTotalMs: 12 },
+ };
+ throws400(
+ () => buildRenderFidelityV1({ ...common, presentationProfile: 'other-profile' }),
+ /presentationProfile must be neutral-studio-v1/,
+ );
+ throws400(
+ () => buildRenderFidelityV1({
+ ...common,
+ resolvedCameras: [camera({ position: [99, 8, 15] })],
+ }),
+ /resolved cameras do not match/,
+ );
+ throws400(
+ () => buildRenderFidelityV1({ ...common, timings: { totalMs: -1 } }),
+ /timings.totalMs must be a non-negative finite number/,
+ );
+ throws400(
+ () => buildRenderFidelityV1({ ...common, timings: { totalMs: 1, secretMs: 2 } }),
+ /timings.secretMs is unknown/,
+ );
+ throws400(
+ () => buildRenderFidelityV1({
+ ...common,
+ timings: { totalMs: 10, queueAndTotalMs: 9 },
+ }),
+ /queueAndTotalMs must be at least totalMs/,
+ );
+ throws400(
+ () => buildRenderFidelityV1({
+ ...common,
+ timings: { totalMs: 10, queueWaitMs: 13, queueAndTotalMs: 12 },
+ }),
+ /queueWaitMs must not exceed queueAndTotalMs/,
+ );
+ });
+
+ it('keeps legacy fidelity additive with no invented perspective cameras', () => {
+ const mode = validateRenderMode({ views: [[1, 0, 0]], size: 384 });
+ const receipt = buildRenderFidelityV1({
+ rendererId: 'dawn-vulkan:test-device',
+ inputGlbSha256: sha256(Buffer.from('glTF exact bytes')),
+ presentationProfile: SUPPORTED_LIGHTING_PRESET_ID,
+ renderMode: mode,
+ resolvedCameras: [],
+ timings: { totalMs: 10, queueAndTotalMs: 12 },
+ });
+ assert.equal(receipt.renderMode, 'legacy');
+ assert.deepEqual(receipt.requestedCameras, []);
+ assert.deepEqual(receipt.resolvedCameras, []);
+ });
+
+ it('maps HTTP outcomes to one frozen low-cardinality code set', () => {
+ assert.deepEqual(RENDER_OUTCOME_CODES, [
+ 'health_ok',
+ 'gpu_success',
+ 'auth_rejected',
+ 'request_rejected',
+ 'not_implemented',
+ 'route_not_found',
+ 'render_failed',
+ ]);
+ assert.equal(httpRenderOutcomeCode({ method: 'GET', path: '/health', status: 200 }), 'health_ok');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 200 }), 'gpu_success');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 401 }), 'auth_rejected');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 400 }), 'request_rejected');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 413 }), 'request_rejected');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/bake', status: 501 }), 'not_implemented');
+ assert.equal(httpRenderOutcomeCode({ method: 'GET', path: '/missing', status: 404 }), 'route_not_found');
+ assert.equal(httpRenderOutcomeCode({ method: 'POST', path: '/render', status: 500 }), 'render_failed');
+ });
+
+ it('builds bounded queue/concurrency evidence with only stable fields', () => {
+ const evidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'gpu_success',
+ queueWaitMs: 24.25,
+ queueDepthAtEnqueue: 2,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: true,
+ workerAgeMsAtStart: 1_234.5,
+ });
+ assert.deepEqual(evidence, {
+ version: RENDER_OPERATIONAL_EVIDENCE_VERSION,
+ outcomeCode: 'gpu_success',
+ queueWaitMs: 24.3,
+ queueDepthAtEnqueue: 2,
+ concurrencyAtStart: 1,
+ concurrencyLimit: 1,
+ workerPhase: 'first-render',
+ workerAgeMsAtStart: 1_234.5,
+ evidenceClamped: false,
+ });
+ assert.deepEqual(Object.keys(evidence).sort(), [
+ 'concurrencyAtStart',
+ 'concurrencyLimit',
+ 'evidenceClamped',
+ 'outcomeCode',
+ 'queueDepthAtEnqueue',
+ 'queueWaitMs',
+ 'version',
+ 'workerAgeMsAtStart',
+ 'workerPhase',
+ ]);
+ });
+
+ it('caps operational evidence without creating unbounded values or identifiers', () => {
+ const evidence = buildRenderOperationalEvidenceV1({
+ outcomeCode: 'render_failed',
+ queueWaitMs: 999_999_999,
+ queueDepthAtEnqueue: 99_999,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: false,
+ workerAgeMsAtStart: 999_999_999,
+ });
+ assert.deepEqual(evidence, {
+ version: RENDER_OPERATIONAL_EVIDENCE_VERSION,
+ outcomeCode: 'render_failed',
+ queueWaitMs: 86_400_000,
+ queueDepthAtEnqueue: 10_000,
+ concurrencyAtStart: 1,
+ concurrencyLimit: 1,
+ workerPhase: 'warm-render',
+ workerAgeMsAtStart: 86_400_000,
+ evidenceClamped: true,
+ });
+ });
+
+ it('rejects malformed operational evidence and unknown outcome cardinality', () => {
+ const common = {
+ outcomeCode: 'gpu_success',
+ queueWaitMs: 1,
+ queueDepthAtEnqueue: 0,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: false,
+ workerAgeMsAtStart: 2,
+ };
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, outcomeCode: 'gpu:test-device-123' }),
+ /outcomeCode is not supported/,
+ );
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, queueWaitMs: -1 }),
+ /queueWaitMs must be a non-negative finite number/,
+ );
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, queueDepthAtEnqueue: 1.5 }),
+ /queueDepthAtEnqueue must be a non-negative integer/,
+ );
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, concurrencyAtStart: 2 }),
+ /concurrencyAtStart must be 1/,
+ );
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, firstRenderInProcess: 'yes' }),
+ /firstRenderInProcess must be boolean/,
+ );
+ throws400(
+ () => buildRenderOperationalEvidenceV1({ ...common, privateRequestId: 'high-cardinality' }),
+ /privateRequestId is unknown/,
+ );
+ });
+
+ it('serial queue reports jobs ahead, concurrency one, and first versus warm start', async () => {
+ let now = 100;
+ const queue = createSerialRenderQueue({ now: () => now, processStartedAt: 0 });
+ let releaseFirst;
+ const firstGate = new Promise((resolve) => { releaseFirst = resolve; });
+ const starts = [];
+ const first = queue.enqueue(async (start) => {
+ starts.push(start);
+ await firstGate;
+ return 'first';
+ });
+ await Promise.resolve();
+ assert.deepEqual(starts[0], {
+ queueWaitMs: 0,
+ queueDepthAtEnqueue: 0,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: true,
+ workerAgeMsAtStart: 100,
+ });
+
+ now = 110;
+ const second = queue.enqueue(async (start) => {
+ starts.push(start);
+ return 'second';
+ });
+ await Promise.resolve();
+ assert.equal(starts.length, 1, 'the second job must not overlap the first');
+
+ now = 130;
+ releaseFirst();
+ assert.equal(await first, 'first');
+ assert.equal(await second, 'second');
+ assert.deepEqual(starts[1], {
+ queueWaitMs: 20,
+ queueDepthAtEnqueue: 1,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: false,
+ workerAgeMsAtStart: 130,
+ });
+ });
+
+ it('serial queue settles a failed render and still starts the next job warm', async () => {
+ let now = 10;
+ const queue = createSerialRenderQueue({ now: () => now, processStartedAt: 0 });
+ await assert.rejects(queue.enqueue(async () => { throw new Error('device lost'); }), /device lost/);
+ now = 20;
+ const next = await queue.enqueue(async (start) => start);
+ assert.deepEqual(next, {
+ queueWaitMs: 0,
+ queueDepthAtEnqueue: 0,
+ concurrencyAtStart: 1,
+ firstRenderInProcess: false,
+ workerAgeMsAtStart: 20,
+ });
+ });
+});
diff --git a/render-service/test/fixtures/material-channels-v1.glb b/render-service/test/fixtures/material-channels-v1.glb
new file mode 100644
index 00000000..2fc9ff89
Binary files /dev/null and b/render-service/test/fixtures/material-channels-v1.glb differ
diff --git a/render-service/test/fixtures/material-channels-v1.manifest.json b/render-service/test/fixtures/material-channels-v1.manifest.json
new file mode 100644
index 00000000..69257e26
--- /dev/null
+++ b/render-service/test/fixtures/material-channels-v1.manifest.json
@@ -0,0 +1,71 @@
+{
+ "schemaVersion": 1,
+ "fixtureId": "material-channels-v1",
+ "glbSha256": "sha256:8ef3e9e5f28303639fc1d28c8648dda2494aed4c11b74ad17cb30b7726a59a9e",
+ "render": {
+ "width": 768,
+ "height": 512,
+ "lightingPresetId": "neutral-studio-v1",
+ "cameras": [
+ {
+ "position": [
+ 0,
+ 0,
+ 10
+ ],
+ "target": [
+ 0,
+ 0,
+ 0
+ ],
+ "up": [
+ 0,
+ 1,
+ 0
+ ],
+ "fovDeg": 35,
+ "aspect": 1.5,
+ "near": 0.1,
+ "far": 100
+ }
+ ]
+ },
+ "regions": {
+ "AlbedoChecker": [
+ 115,
+ 68,
+ 231,
+ 184
+ ],
+ "NormalResponse": [
+ 326,
+ 68,
+ 442,
+ 184
+ ],
+ "SharedOrmResponse": [
+ 537,
+ 68,
+ 653,
+ 184
+ ],
+ "AoResponse": [
+ 115,
+ 328,
+ 231,
+ 444
+ ],
+ "EmissiveResponse": [
+ 326,
+ 328,
+ 442,
+ 444
+ ],
+ "AlphaResponse": [
+ 537,
+ 328,
+ 653,
+ 444
+ ]
+ }
+}
diff --git a/render-service/test/generate-material-fixture.mjs b/render-service/test/generate-material-fixture.mjs
new file mode 100644
index 00000000..575f82c2
--- /dev/null
+++ b/render-service/test/generate-material-fixture.mjs
@@ -0,0 +1,264 @@
+import { createHash } from 'node:crypto';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { PNG } from 'pngjs';
+
+const IMAGE_SIZE = 16;
+const PANEL_SIZE = 1.8;
+const PANEL_CENTERS = Object.freeze({
+ AlbedoChecker: [-2.6, 1.6, 0],
+ NormalResponse: [0, 1.6, 0],
+ SharedOrmResponse: [2.6, 1.6, 0],
+ AoResponse: [-2.6, -1.6, 0],
+ EmissiveResponse: [0, -1.6, 0],
+ AlphaResponse: [2.6, -1.6, 0],
+});
+const CAMERA = Object.freeze({
+ position: [0, 0, 10],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 35,
+ aspect: 1.5,
+ near: 0.1,
+ far: 100,
+});
+const WIDTH = 768;
+const HEIGHT = 512;
+
+function pngBytes(pixel) {
+ const png = new PNG({ width: IMAGE_SIZE, height: IMAGE_SIZE });
+ for (let y = 0; y < IMAGE_SIZE; y += 1) {
+ for (let x = 0; x < IMAGE_SIZE; x += 1) {
+ const rgba = pixel(x, y);
+ const offset = (y * IMAGE_SIZE + x) * 4;
+ for (let channel = 0; channel < 4; channel += 1) png.data[offset + channel] = rgba[channel];
+ }
+ }
+ return PNG.sync.write(png, { deflateLevel: 9, filterType: 0 });
+}
+
+function sourceImages() {
+ const checker = (x, y) => ((Math.floor(x / 4) + Math.floor(y / 4)) % 2) === 0;
+ return [
+ {
+ name: 'AlbedoChecker',
+ bytes: pngBytes((x, y) => checker(x, y) ? [245, 245, 245, 255] : [18, 18, 18, 255]),
+ },
+ {
+ name: 'NormalSplit',
+ bytes: pngBytes((x) => x < IMAGE_SIZE / 2 ? [32, 128, 224, 255] : [224, 128, 224, 255]),
+ },
+ {
+ name: 'SharedOrm',
+ bytes: pngBytes((x, y) => [
+ x < IMAGE_SIZE / 2 ? 32 : 255,
+ y < IMAGE_SIZE / 2 ? 32 : 224,
+ checker(x, y) ? 24 : 232,
+ 255,
+ ]),
+ },
+ {
+ name: 'EmissiveChecker',
+ bytes: pngBytes((x, y) => checker(x, y) ? [255, 32, 8, 255] : [0, 0, 0, 255]),
+ },
+ {
+ name: 'AlphaChecker',
+ bytes: pngBytes((x, y) => checker(x, y) ? [32, 255, 64, 255] : [255, 32, 192, 0]),
+ },
+ ];
+}
+
+function align4(value) {
+ return (value + 3) & ~3;
+}
+
+function panelRegion([x, y], insetWorld = 0.18) {
+ const half = PANEL_SIZE / 2 - insetWorld;
+ const tanHalf = Math.tan(CAMERA.fovDeg * Math.PI / 360);
+ const project = (worldX, worldY) => ({
+ x: WIDTH * (1 + worldX / (10 * tanHalf * CAMERA.aspect)) / 2,
+ y: HEIGHT * (1 - worldY / (10 * tanHalf)) / 2,
+ });
+ const topLeft = project(x - half, y + half);
+ const bottomRight = project(x + half, y - half);
+ return [
+ Math.ceil(topLeft.x),
+ Math.ceil(topLeft.y),
+ Math.floor(bottomRight.x),
+ Math.floor(bottomRight.y),
+ ];
+}
+
+function appendBuffer(parts, bufferViews, bytes, extra = {}) {
+ const offset = parts.reduce((total, part) => total + part.length, 0);
+ const view = { buffer: 0, byteOffset: offset, byteLength: bytes.length, ...extra };
+ bufferViews.push(view);
+ parts.push(bytes);
+ const padding = align4(bytes.length) - bytes.length;
+ if (padding) parts.push(Buffer.alloc(padding));
+ return bufferViews.length - 1;
+}
+
+function floatBuffer(values) {
+ const bytes = Buffer.alloc(values.length * 4);
+ values.forEach((value, index) => bytes.writeFloatLE(value, index * 4));
+ return bytes;
+}
+
+function uint16Buffer(values) {
+ const bytes = Buffer.alloc(values.length * 2);
+ values.forEach((value, index) => bytes.writeUInt16LE(value, index * 2));
+ return bytes;
+}
+
+function encodeGlb(json, bin) {
+ const source = Buffer.from(JSON.stringify(json), 'utf8');
+ const jsonLength = align4(source.length);
+ const jsonChunk = Buffer.alloc(jsonLength, 0x20);
+ source.copy(jsonChunk);
+ const binLength = align4(bin.length);
+ const binChunk = Buffer.alloc(binLength);
+ bin.copy(binChunk);
+ const glb = Buffer.alloc(12 + 8 + jsonChunk.length + 8 + binChunk.length);
+ glb.writeUInt32LE(0x46546c67, 0);
+ glb.writeUInt32LE(2, 4);
+ glb.writeUInt32LE(glb.length, 8);
+ glb.writeUInt32LE(jsonChunk.length, 12);
+ glb.writeUInt32LE(0x4e4f534a, 16);
+ jsonChunk.copy(glb, 20);
+ const binHeader = 20 + jsonChunk.length;
+ glb.writeUInt32LE(binChunk.length, binHeader);
+ glb.writeUInt32LE(0x004e4942, binHeader + 4);
+ binChunk.copy(glb, binHeader + 8);
+ return glb;
+}
+
+export function buildMaterialChannelsFixture() {
+ const parts = [];
+ const bufferViews = [];
+ const positionView = appendBuffer(parts, bufferViews, floatBuffer([
+ -0.9, -0.9, 0, 0.9, -0.9, 0, 0.9, 0.9, 0, -0.9, 0.9, 0,
+ ]), { target: 34962 });
+ const normalView = appendBuffer(parts, bufferViews, floatBuffer([
+ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
+ ]), { target: 34962 });
+ const tangentView = appendBuffer(parts, bufferViews, floatBuffer([
+ 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1,
+ ]), { target: 34962 });
+ const uv0View = appendBuffer(parts, bufferViews, floatBuffer([
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ ]), { target: 34962 });
+ const uv1View = appendBuffer(parts, bufferViews, floatBuffer([
+ 0, 1, 1, 1, 1, 0, 0, 0,
+ ]), { target: 34962 });
+ const indexView = appendBuffer(parts, bufferViews, uint16Buffer([0, 1, 2, 0, 2, 3]), { target: 34963 });
+
+ const images = sourceImages();
+ const imageJson = images.map((image) => ({
+ name: image.name,
+ bufferView: appendBuffer(parts, bufferViews, image.bytes),
+ mimeType: 'image/png',
+ }));
+ const bin = Buffer.concat(parts);
+ const primitive = (material) => ({
+ attributes: { POSITION: 0, NORMAL: 1, TANGENT: 2, TEXCOORD_0: 3, TEXCOORD_1: 4 },
+ indices: 5,
+ material,
+ mode: 4,
+ });
+ const materialNames = Object.keys(PANEL_CENTERS);
+ const json = {
+ asset: { version: '2.0', generator: 'kiln-render-service material-channels-v1' },
+ scene: 0,
+ scenes: [{ nodes: materialNames.map((_, index) => index) }],
+ nodes: materialNames.map((name, index) => ({
+ name: `${name}Panel`,
+ mesh: index,
+ translation: PANEL_CENTERS[name],
+ })),
+ meshes: materialNames.map((name, index) => ({ name: `${name}Mesh`, primitives: [primitive(index)] })),
+ materials: [
+ {
+ name: 'AlbedoChecker',
+ pbrMetallicRoughness: { baseColorTexture: { index: 0 }, metallicFactor: 0, roughnessFactor: 1 },
+ doubleSided: true,
+ },
+ {
+ name: 'NormalResponse',
+ pbrMetallicRoughness: { baseColorFactor: [0.62, 0.62, 0.62, 1], metallicFactor: 0, roughnessFactor: 0.7 },
+ normalTexture: { index: 1, scale: 1 },
+ doubleSided: true,
+ },
+ {
+ name: 'SharedOrmResponse',
+ pbrMetallicRoughness: {
+ baseColorFactor: [0.62, 0.62, 0.62, 1],
+ metallicFactor: 1,
+ roughnessFactor: 1,
+ metallicRoughnessTexture: { index: 2 },
+ },
+ occlusionTexture: { index: 2, strength: 1 },
+ doubleSided: true,
+ },
+ {
+ name: 'AoResponse',
+ pbrMetallicRoughness: { baseColorFactor: [0.72, 0.72, 0.72, 1], metallicFactor: 0, roughnessFactor: 0.9 },
+ occlusionTexture: { index: 2, strength: 1 },
+ doubleSided: true,
+ },
+ {
+ name: 'EmissiveResponse',
+ pbrMetallicRoughness: { baseColorFactor: [0.01, 0.01, 0.01, 1], metallicFactor: 0, roughnessFactor: 1 },
+ emissiveTexture: { index: 3 },
+ emissiveFactor: [1, 1, 1],
+ doubleSided: true,
+ },
+ {
+ name: 'AlphaResponse',
+ pbrMetallicRoughness: { baseColorTexture: { index: 4 }, metallicFactor: 0, roughnessFactor: 0.8 },
+ alphaMode: 'MASK',
+ alphaCutoff: 0.5,
+ doubleSided: true,
+ },
+ ],
+ samplers: [{ magFilter: 9728, minFilter: 9728, wrapS: 33071, wrapT: 33071 }],
+ textures: imageJson.map((_, index) => ({ sampler: 0, source: index })),
+ images: imageJson,
+ buffers: [{ byteLength: bin.length }],
+ bufferViews,
+ accessors: [
+ { bufferView: positionView, componentType: 5126, count: 4, type: 'VEC3', min: [-0.9, -0.9, 0], max: [0.9, 0.9, 0] },
+ { bufferView: normalView, componentType: 5126, count: 4, type: 'VEC3' },
+ { bufferView: tangentView, componentType: 5126, count: 4, type: 'VEC4' },
+ { bufferView: uv0View, componentType: 5126, count: 4, type: 'VEC2' },
+ { bufferView: uv1View, componentType: 5126, count: 4, type: 'VEC2' },
+ { bufferView: indexView, componentType: 5123, count: 6, type: 'SCALAR', min: [0], max: [3] },
+ ],
+ };
+ const glb = encodeGlb(json, bin);
+ const manifest = {
+ schemaVersion: 1,
+ fixtureId: 'material-channels-v1',
+ glbSha256: `sha256:${createHash('sha256').update(glb).digest('hex')}`,
+ render: {
+ width: WIDTH,
+ height: HEIGHT,
+ lightingPresetId: 'neutral-studio-v1',
+ cameras: [CAMERA],
+ },
+ regions: Object.fromEntries(Object.entries(PANEL_CENTERS).map(([name, center]) => [name, panelRegion(center)])),
+ };
+ return { glb, manifest };
+}
+
+async function main() {
+ const outputDir = resolve(dirname(fileURLToPath(import.meta.url)), 'fixtures');
+ const { glb, manifest } = buildMaterialChannelsFixture();
+ await mkdir(outputDir, { recursive: true });
+ await writeFile(resolve(outputDir, 'material-channels-v1.glb'), glb);
+ await writeFile(resolve(outputDir, 'material-channels-v1.manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+ process.stdout.write(`wrote material-channels-v1.glb (${glb.length} bytes, ${manifest.glbSha256})\n`);
+}
+
+if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) await main();
diff --git a/render-service/test/material-conformance.mjs b/render-service/test/material-conformance.mjs
new file mode 100644
index 00000000..f4b0fb52
--- /dev/null
+++ b/render-service/test/material-conformance.mjs
@@ -0,0 +1,146 @@
+// Opt-in, provider-free R2.9 hardware conformance. This intentionally does not
+// run under `npm test`: CI always validates the embedded GLB structure while a
+// workstation/worker with a real WebGPU adapter can exercise material response.
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { PNG } from 'pngjs';
+
+const fixtureUrl = new URL('./fixtures/material-channels-v1.glb', import.meta.url);
+const manifestUrl = new URL('./fixtures/material-channels-v1.manifest.json', import.meta.url);
+const noHardware = /(?:no webgpu adapter|no usable .*device|software adapter refused|couldn(?:'|’)t find a suitable webgpu backend|requestadapter.*(?:failed|null)|(?:vulkan|d3d12|metal).*(?:unavailable|not found|failed to init))/i;
+
+// A fixture with embedded PNG buffer views has no reason to cross a network
+// boundary. Fail closed if a loader regression ever attempts to do so.
+Object.defineProperty(globalThis, 'fetch', {
+ configurable: true,
+ writable: true,
+ value: async () => { throw new Error('network disabled in local material conformance'); },
+});
+
+function pixelsIn(png, [x0, y0, x1, y1]) {
+ const pixels = [];
+ for (let y = y0; y < y1; y += 1) {
+ for (let x = x0; x < x1; x += 1) {
+ const offset = (y * png.width + x) * 4;
+ pixels.push([png.data[offset], png.data[offset + 1], png.data[offset + 2]]);
+ }
+ }
+ return pixels;
+}
+
+function luma([r, g, b]) {
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
+
+function mean(values) {
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
+}
+
+function percentile(values, fraction) {
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor((sorted.length - 1) * fraction)];
+}
+
+function summarize(pixels) {
+ const luminance = pixels.map(luma);
+ const means = [0, 1, 2].map((channel) => mean(pixels.map((pixel) => pixel[channel])));
+ return {
+ meanRgb: means.map((value) => +value.toFixed(1)),
+ meanLuma: +mean(luminance).toFixed(1),
+ lumaSpread: +(percentile(luminance, 0.9) - percentile(luminance, 0.1)).toFixed(1),
+ };
+}
+
+function halves(png, region, axis = 'x') {
+ const [x0, y0, x1, y1] = region;
+ if (axis === 'x') {
+ const middle = Math.floor((x0 + x1) / 2);
+ return [pixelsIn(png, [x0, y0, middle, y1]), pixelsIn(png, [middle, y0, x1, y1])];
+ }
+ const middle = Math.floor((y0 + y1) / 2);
+ return [pixelsIn(png, [x0, y0, x1, middle]), pixelsIn(png, [x0, middle, x1, y1])];
+}
+
+function lumaDelta(groups) {
+ return Math.abs(mean(groups[0].map(luma)) - mean(groups[1].map(luma)));
+}
+
+function colorDistance(a, b) {
+ return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2);
+}
+
+async function main() {
+ const [glb, manifestText] = await Promise.all([readFile(fixtureUrl), readFile(manifestUrl, 'utf8')]);
+ const manifest = JSON.parse(manifestText);
+ let rendered;
+ try {
+ const { renderGlb } = await import('../src/renderer.mjs');
+ rendered = await renderGlb(glb, {
+ cameras: manifest.render.cameras,
+ width: manifest.render.width,
+ height: manifest.render.height,
+ lightingPresetId: manifest.render.lightingPresetId,
+ });
+ } catch (error) {
+ const message = String(error?.message ?? error);
+ if (noHardware.test(message)) {
+ process.stdout.write(`SKIP material GPU conformance: no usable hardware WebGPU adapter (${message})\n`);
+ process.exit(0);
+ }
+ throw error;
+ }
+
+ assert.equal(rendered.views.length, 1, 'one fixed camera must produce one PNG');
+ const png = PNG.sync.read(rendered.views[0]);
+ assert.equal(png.width, manifest.render.width);
+ assert.equal(png.height, manifest.render.height);
+ const region = (name) => manifest.regions[name];
+ const stats = Object.fromEntries(Object.entries(manifest.regions).map(([name, box]) => [
+ name,
+ summarize(pixelsIn(png, box)),
+ ]));
+
+ assert.ok(stats.AlbedoChecker.lumaSpread >= 45,
+ `albedo checker did not modulate base color: ${stats.AlbedoChecker.lumaSpread}`);
+
+ const normalDelta = lumaDelta(halves(png, region('NormalResponse')));
+ assert.ok(normalDelta >= 3,
+ `normal map halves did not change lighting response: ${normalDelta.toFixed(1)}`);
+
+ assert.ok(stats.SharedOrmResponse.lumaSpread >= 5,
+ `shared ORM channels did not change material response: ${stats.SharedOrmResponse.lumaSpread}`);
+
+ const aoDelta = lumaDelta(halves(png, region('AoResponse')));
+ assert.ok(aoDelta >= 5, `AO red channel did not occlude one half: ${aoDelta.toFixed(1)}`);
+
+ const emissivePixels = pixelsIn(png, region('EmissiveResponse'));
+ const emissive = summarize(emissivePixels);
+ assert.ok(emissive.lumaSpread >= 30, `emissive checker response is flat: ${emissive.lumaSpread}`);
+ assert.ok(percentile(emissivePixels.map((pixel) => pixel[0]), 0.9) >=
+ percentile(emissivePixels.map((pixel) => pixel[1]), 0.9) + 35,
+ 'emissive red channel is not visibly dominant');
+
+ const backgroundSamples = [
+ [png.data[0], png.data[1], png.data[2]],
+ (() => { const i = (png.width - 1) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
+ (() => { const i = ((png.height - 1) * png.width) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
+ (() => { const i = (png.width * png.height - 1) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; })(),
+ ];
+ const background = [0, 1, 2].map((channel) => mean(backgroundSamples.map((pixel) => pixel[channel])));
+ const alphaPixels = pixelsIn(png, region('AlphaResponse'));
+ const backgroundFraction = alphaPixels.filter((pixel) => colorDistance(pixel, background) <= 8).length / alphaPixels.length;
+ assert.ok(backgroundFraction >= 0.2 && backgroundFraction <= 0.8,
+ `alpha mask must expose both material and background: ${(backgroundFraction * 100).toFixed(1)}% background`);
+
+ process.stdout.write(`${JSON.stringify({
+ result: 'PASS',
+ fixtureId: manifest.fixtureId,
+ normalHalfLumaDelta: +normalDelta.toFixed(1),
+ aoHalfLumaDelta: +aoDelta.toFixed(1),
+ alphaBackgroundFraction: +backgroundFraction.toFixed(3),
+ regions: stats,
+ })}\n`);
+ process.exit(0);
+}
+
+await main();
diff --git a/render-service/test/material-fixture.test.mjs b/render-service/test/material-fixture.test.mjs
new file mode 100644
index 00000000..e769d932
--- /dev/null
+++ b/render-service/test/material-fixture.test.mjs
@@ -0,0 +1,108 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { describe, it } from 'node:test';
+import { PNG } from 'pngjs';
+import { buildMaterialChannelsFixture } from './generate-material-fixture.mjs';
+
+const fixtureUrl = new URL('./fixtures/material-channels-v1.glb', import.meta.url);
+const manifestUrl = new URL('./fixtures/material-channels-v1.manifest.json', import.meta.url);
+const MATERIAL_CHANNELS_V1_SHA256 = 'sha256:8ef3e9e5f28303639fc1d28c8648dda2494aed4c11b74ad17cb30b7726a59a9e';
+
+function sha256(bytes) {
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
+}
+
+function parseGlb(bytes) {
+ assert.equal(bytes.readUInt32LE(0), 0x46546c67, 'GLB magic');
+ assert.equal(bytes.readUInt32LE(4), 2, 'GLB version');
+ assert.equal(bytes.readUInt32LE(8), bytes.length, 'GLB declared length');
+ const jsonLength = bytes.readUInt32LE(12);
+ assert.equal(bytes.readUInt32LE(16), 0x4e4f534a, 'JSON chunk type');
+ const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8').trim());
+ const binHeader = 20 + jsonLength;
+ assert.equal(bytes.readUInt32LE(binHeader + 4), 0x004e4942, 'BIN chunk type');
+ const binLength = bytes.readUInt32LE(binHeader);
+ const bin = bytes.subarray(binHeader + 8, binHeader + 8 + binLength);
+ return { json, bin };
+}
+
+function imageBytes(glb, image) {
+ assert.equal(image.mimeType, 'image/png');
+ assert.equal(image.uri, undefined, `${image.name} must not use an external URI`);
+ assert.ok(Number.isInteger(image.bufferView), `${image.name} must be embedded`);
+ const view = glb.json.bufferViews[image.bufferView];
+ return glb.bin.subarray(view.byteOffset ?? 0, (view.byteOffset ?? 0) + view.byteLength);
+}
+
+function channelRange(png, channel) {
+ const values = [];
+ for (let i = channel; i < png.data.length; i += 4) values.push(png.data[i]);
+ return { min: Math.min(...values), max: Math.max(...values) };
+}
+
+describe('material channel conformance fixture', () => {
+ it('is byte-deterministic and bound to its checked-in SHA-256 manifest', async () => {
+ const checkedIn = await readFile(fixtureUrl);
+ const manifest = JSON.parse(await readFile(manifestUrl, 'utf8'));
+ const generated = buildMaterialChannelsFixture();
+ assert.equal(Buffer.compare(checkedIn, generated.glb), 0);
+ assert.equal(sha256(checkedIn), MATERIAL_CHANNELS_V1_SHA256);
+ assert.equal(manifest.glbSha256, sha256(checkedIn));
+ assert.deepEqual(manifest, generated.manifest);
+ });
+
+ it('embeds every required PNG and binds every PBR channel explicitly', async () => {
+ const glb = parseGlb(await readFile(fixtureUrl));
+ const byName = Object.fromEntries(glb.json.materials.map((material) => [material.name, material]));
+ const albedo = byName.AlbedoChecker;
+ const normal = byName.NormalResponse;
+ const orm = byName.SharedOrmResponse;
+ const ao = byName.AoResponse;
+ const emissive = byName.EmissiveResponse;
+ const alpha = byName.AlphaResponse;
+
+ assert.ok(albedo.pbrMetallicRoughness.baseColorTexture);
+ assert.ok(normal.normalTexture);
+ assert.ok(orm.pbrMetallicRoughness.metallicRoughnessTexture);
+ assert.equal(
+ orm.pbrMetallicRoughness.metallicRoughnessTexture.index,
+ orm.occlusionTexture.index,
+ 'ORM material must share one packed texture for MR and AO',
+ );
+ assert.equal(ao.occlusionTexture.index, orm.occlusionTexture.index);
+ assert.ok(emissive.emissiveTexture);
+ assert.deepEqual(emissive.emissiveFactor, [1, 1, 1]);
+ assert.ok(alpha.pbrMetallicRoughness.baseColorTexture);
+ assert.equal(alpha.alphaMode, 'MASK');
+ assert.equal(alpha.alphaCutoff, 0.5);
+
+ assert.equal(glb.json.images.length, 5);
+ for (const image of glb.json.images) {
+ const png = PNG.sync.read(imageBytes(glb, image));
+ assert.equal(png.width, 16);
+ assert.equal(png.height, 16);
+ }
+ for (const mesh of glb.json.meshes) {
+ const attributes = mesh.primitives[0].attributes;
+ assert.ok(Number.isInteger(attributes.TEXCOORD_0));
+ assert.ok(Number.isInteger(attributes.TEXCOORD_1));
+ assert.ok(Number.isInteger(attributes.TANGENT));
+ }
+ });
+
+ it('pins high-contrast source pixels for each statistical GPU assertion', async () => {
+ const glb = parseGlb(await readFile(fixtureUrl));
+ const decoded = Object.fromEntries(glb.json.images.map((image) => [
+ image.name,
+ PNG.sync.read(imageBytes(glb, image)),
+ ]));
+ assert.deepEqual(channelRange(decoded.AlbedoChecker, 0), { min: 18, max: 245 });
+ assert.deepEqual(channelRange(decoded.NormalSplit, 0), { min: 32, max: 224 });
+ assert.deepEqual(channelRange(decoded.SharedOrm, 0), { min: 32, max: 255 });
+ assert.deepEqual(channelRange(decoded.SharedOrm, 1), { min: 32, max: 224 });
+ assert.deepEqual(channelRange(decoded.SharedOrm, 2), { min: 24, max: 232 });
+ assert.deepEqual(channelRange(decoded.EmissiveChecker, 0), { min: 0, max: 255 });
+ assert.deepEqual(channelRange(decoded.AlphaChecker, 3), { min: 0, max: 255 });
+ });
+});
diff --git a/render-service/test/presentation-presets.test.mjs b/render-service/test/presentation-presets.test.mjs
new file mode 100644
index 00000000..776b72f4
--- /dev/null
+++ b/render-service/test/presentation-presets.test.mjs
@@ -0,0 +1,100 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ DEFAULT_PRESENTATION_PRESET_ID,
+ PRESENTATION_PRESET_CAPABILITIES,
+ PRESENTATION_PRESET_IDS,
+ getPresentationPreset,
+ isPresentationPresetId,
+} from '../src/presentation-presets.mjs';
+import { buildHealthDocument, RENDER_CAPABILITIES } from '../src/health-contract.mjs';
+import {
+ SUPPORTED_LIGHTING_PRESET_ID,
+ SUPPORTED_LIGHTING_PRESET_IDS,
+ buildRenderFidelityV1,
+ sha256,
+ validateRenderMode,
+} from '../src/contract.mjs';
+
+const camera = {
+ position: [0, 0, 5],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 35,
+ aspect: 1,
+ near: 0.1,
+ far: 100,
+};
+
+function recursivelyFrozen(value) {
+ if (!value || typeof value !== 'object') return true;
+ return Object.isFrozen(value) && Object.values(value).every(recursivelyFrozen);
+}
+
+describe('versioned presentation preset registry', () => {
+ it('pins neutral-studio-v1 to the byte/visual-equivalent renderer values', () => {
+ assert.equal(DEFAULT_PRESENTATION_PRESET_ID, 'neutral-studio-v1');
+ assert.deepEqual(PRESENTATION_PRESET_IDS, ['neutral-studio-v1']);
+ assert.equal(Object.isFrozen(PRESENTATION_PRESET_IDS), true);
+ assert.equal(Object.isFrozen(PRESENTATION_PRESET_CAPABILITIES), true);
+ assert.equal(SUPPORTED_LIGHTING_PRESET_ID, DEFAULT_PRESENTATION_PRESET_ID);
+ assert.equal(SUPPORTED_LIGHTING_PRESET_IDS, PRESENTATION_PRESET_IDS);
+ assert.deepEqual(getPresentationPreset('neutral-studio-v1'), {
+ id: 'neutral-studio-v1',
+ environment: { type: 'room', sigma: 0.04 },
+ background: '#aab1bc',
+ exposure: 1.38,
+ ambient: { type: 'hemisphere', sky: 0xffffff, ground: 0x6f7888, intensity: 2 },
+ sun: { enabled: false },
+ key: { enabled: true, color: 0xffffff, intensity: 3, position: [4, 7, 5], castsShadow: false },
+ fill: { enabled: true, color: 0xdce8ff, intensity: 1.8, position: [-4, 3, 2], castsShadow: false },
+ rim: { enabled: true, color: 0xffead6, intensity: 1.2, position: [-2, 5, -5], castsShadow: false },
+ shadows: {
+ enabled: false,
+ type: 'pcf-soft',
+ mapSize: [1024, 1024],
+ bias: 0,
+ normalBias: 0,
+ radius: 1,
+ },
+ });
+ assert.equal(recursivelyFrozen(getPresentationPreset('neutral-studio-v1')), true);
+ });
+
+ it('resolves by ID only and rejects unknown IDs at the request and receipt boundaries', () => {
+ assert.equal(isPresentationPresetId('neutral-studio-v1'), true);
+ assert.equal(isPresentationPresetId('dramatic-night-v1'), false);
+ assert.equal(getPresentationPreset('dramatic-night-v1'), undefined);
+ assert.throws(() => validateRenderMode({
+ cameras: [camera], width: 512, height: 512, lighting_preset_id: 'dramatic-night-v1',
+ }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ for (const nonId of [null, { exposure: 2 }, ['neutral-studio-v1']]) {
+ assert.throws(() => validateRenderMode({
+ cameras: [camera], width: 512, height: 512, lighting_preset_id: nonId,
+ }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ }
+ const renderMode = validateRenderMode({ cameras: [camera], width: 512, height: 512 });
+ assert.throws(() => buildRenderFidelityV1({
+ rendererId: 'dawn-vulkan:test',
+ inputGlbSha256: sha256(Buffer.from('glb')),
+ presentationProfile: 'dramatic-night-v1',
+ renderMode,
+ resolvedCameras: renderMode.cameras,
+ timings: { totalMs: 1 },
+ }), (error) => error?.status === 400 && /neutral-studio-v1/.test(error.message));
+ });
+
+ it('advertises every registry ID through provider-free health contract data', () => {
+ assert.deepEqual(PRESENTATION_PRESET_CAPABILITIES, ['render.profile.neutral-studio-v1']);
+ assert.ok(PRESENTATION_PRESET_CAPABILITIES.every((capability) => RENDER_CAPABILITIES.includes(capability)));
+ const health = buildHealthDocument({
+ rendererId: 'dawn-vulkan:test',
+ backend: 'vulkan',
+ summary: { vendor: 'test' },
+ }, true);
+ assert.equal(health.presentationProfile, 'neutral-studio-v1');
+ assert.deepEqual(health.lightingPresetIds, ['neutral-studio-v1']);
+ assert.notEqual(health.lightingPresetIds, PRESENTATION_PRESET_IDS);
+ assert.equal(health.authRequired, true);
+ });
+});
diff --git a/render-service/test/smoke.mjs b/render-service/test/smoke.mjs
new file mode 100644
index 00000000..7ad204b7
--- /dev/null
+++ b/render-service/test/smoke.mjs
@@ -0,0 +1,348 @@
+// End-to-end smoke: boots the server in-process, hits /health and /render with a
+// real GLB, validates PNG output, exercises auth and the bad-input paths.
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { PNG } from 'pngjs';
+
+process.env.PORT = process.env.PORT ?? '8199';
+process.env.RENDER_SERVICE_TOKEN = process.env.RENDER_SERVICE_TOKEN ?? 'smoke-token';
+const PORT = process.env.PORT;
+const TOKEN = process.env.RENDER_SERVICE_TOKEN;
+
+const here = dirname(fileURLToPath(import.meta.url));
+const glbPath = process.env.SMOKE_GLB ?? join(here, 'fixtures', 'model.glb');
+
+await import('../src/server.mjs');
+await new Promise((r) => setTimeout(r, 300));
+
+const base = `http://127.0.0.1:${PORT}`;
+let failures = 0;
+const check = (name, cond, extra = '') => {
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ' ' + extra : ''}`);
+ if (!cond) failures++;
+};
+
+// The server logs to stdout in-process, so intercepting console.log is the only
+// way to assert on the request line. done() writes it synchronously before the
+// client's fetch can settle, so the line is always present on return.
+async function capturingLog(fn) {
+ const lines = [];
+ const real = console.log;
+ console.log = (...args) => { lines.push(args.join(' ')); };
+ try {
+ const value = await fn();
+ return { value, lines, text: lines.join('\n') };
+ } finally {
+ console.log = real;
+ }
+}
+
+const requestLines = (lines) => lines
+ .map((l) => { try { return JSON.parse(l); } catch { return null; } })
+ .filter((o) => o?.evt === 'request');
+
+const health = await (await fetch(`${base}/health`)).json();
+check('health ok', health.ok === true, health.rendererId);
+check(
+ 'health advertises capabilities + auth posture',
+ Array.isArray(health.capabilities) &&
+ health.capabilities.includes('auth.x-render-token') &&
+ health.capabilities.includes('render.profile.neutral-studio-v1') &&
+ health.capabilities.includes('render.cameras.perspective-v1') &&
+ 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']) &&
+ typeof health.backend === 'string' && health.backend.length > 0 &&
+ health.presentationProfile === 'neutral-studio-v1' &&
+ health.authRequired === true,
+ JSON.stringify(health.capabilities),
+);
+
+const noAuth = await fetch(`${base}/render`, { method: 'POST', body: '{}' });
+check('unauthenticated render rejected', noAuth.status === 401);
+
+// The gateway path cannot use Authorization (RunPod consumes it at the edge),
+// so the custom header must authenticate on its own.
+const customHeader = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN }, body: 'nope',
+});
+check('x-render-token accepted (reaches body validation)', customHeader.status === 400);
+
+const wrongCustom = await capturingLog(() => fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': 'wrong-token' }, body: '{}',
+}));
+check('wrong x-render-token rejected', wrongCustom.value.status === 401);
+const rejectedLine = requestLines(wrongCustom.lines)[0];
+check(
+ 'rejected auth is logged as such',
+ rejectedLine?.status === 401 && rejectedLine?.auth === 'rejected' && rejectedLine?.path === '/render',
+ JSON.stringify(rejectedLine),
+);
+check(
+ 'no token value in the rejected line',
+ !wrongCustom.text.includes(TOKEN) && !wrongCustom.text.includes('wrong-token'),
+);
+
+const badJson = await fetch(`${base}/render`, {
+ method: 'POST', headers: { authorization: `Bearer ${TOKEN}` }, body: 'nope',
+});
+check('invalid JSON rejected', badJson.status === 400);
+
+const badGlb = await fetch(`${base}/render`, {
+ method: 'POST', headers: { authorization: `Bearer ${TOKEN}` },
+ body: JSON.stringify({ glb_base64: Buffer.from('not a glb').toString('base64') }),
+});
+check('bad GLB magic rejected', badGlb.status === 400);
+
+const glb = readFileSync(glbPath);
+const t0 = performance.now();
+const rendered = await capturingLog(async () => (await fetch(`${base}/render`, {
+ method: 'POST', headers: { authorization: `Bearer ${TOKEN}` },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
+})).json());
+const r = rendered.value;
+const wallMs = (performance.now() - t0).toFixed(1);
+
+check('render ok', r.ok === true);
+check('six views', Array.isArray(r.views) && r.views.length === 6);
+check('rendererId present', typeof r.rendererId === 'string' && r.rendererId.startsWith('dawn-'));
+check('render reports the fixed presentation profile', r.presentationProfile === 'neutral-studio-v1');
+const png0 = Buffer.from(r.views?.[0] ?? '', 'base64');
+check('view is PNG', png0[0] === 0x89 && png0[1] === 0x50, `${png0.length}B`);
+const decodedView0 = PNG.sync.read(png0);
+const corner = decodedView0.data.subarray(0, 3);
+const cornerLuma = Math.round(0.2126 * corner[0] + 0.7152 * corner[1] + 0.0722 * corner[2]);
+check(
+ 'studio backdrop stays neutral and visibly above black',
+ cornerLuma >= 90 && Math.max(...corner) - Math.min(...corner) <= 32,
+ `rgb=${[...corner].join(',')} luma=${cornerLuma}`,
+);
+const beauty = Buffer.from(r.beauty ?? '', 'base64');
+check('beauty is PNG', beauty[0] === 0x89 && beauty[1] === 0x50, `${beauty.length}B`);
+console.log(`timings: ${JSON.stringify(r.timings)} wall=${wallMs}ms`);
+
+// One structured line per request is the only service-side evidence a production
+// degrade ever happened; §2.2(a)'s client-side view is otherwise the sole witness.
+const renderLine = requestLines(rendered.lines)[0];
+check(
+ 'render emits one request log line',
+ requestLines(rendered.lines).length === 1 && renderLine?.evt === 'request',
+ JSON.stringify(renderLine),
+);
+check(
+ 'log line carries method/path/status/auth',
+ renderLine?.method === 'POST' && renderLine?.path === '/render' &&
+ renderLine?.status === 200 && renderLine?.auth === 'ok' &&
+ renderLine?.authVia === 'authorization',
+);
+check(
+ 'log line carries byte counts and timings',
+ renderLine?.glbBytes === glb.length && renderLine?.bodyBytes > glb.length &&
+ renderLine?.views === 6 && renderLine?.beauty === true &&
+ typeof renderLine?.timings?.totalMs === 'number' && renderLine?.ms > 0,
+ `glbBytes=${renderLine?.glbBytes} ms=${renderLine?.ms}`,
+);
+check('no token or GLB payload in the log line', !rendered.text.includes(TOKEN) &&
+ !rendered.text.includes(glb.toString('base64').slice(0, 32)));
+
+const out = join(here, 'out');
+mkdirSync(out, { recursive: true });
+if (r.ok) {
+ writeFileSync(join(out, 'smoke-view0.png'), png0);
+ if (beauty.length) writeFileSync(join(out, 'smoke-beauty.png'), beauty);
+}
+
+// second render: warm-path timing, and proof that per-render disposal releases
+// only what the request owned — the pooled RTs and the shared environment map
+// must survive it, so a repeat of the same fixture has to produce the same grid.
+// Byte-equality is a same-process, same-device claim only; the port is
+// contractually a non-deterministic view producer across GPU tiers.
+const { initRenderer } = await import('../src/renderer.mjs');
+const { renderer } = await initRenderer();
+// After render 1 the RT pool and the PMREM environment are already allocated, so
+// this baseline isolates exactly what a request allocates and must give back.
+const mem1 = { ...renderer.info.memory };
+const t1 = performance.now();
+const r2 = await (await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 384, beauty_size: 1024 }),
+})).json();
+check('warm render ok', r2.ok === true, `wall=${(performance.now() - t1).toFixed(1)}ms gpu=${JSON.stringify(r2.timings)}`);
+check('repeat render matches first view count', r2.views?.length === r.views?.length, `${r2.views?.length} vs ${r.views?.length}`);
+const png0b = Buffer.from(r2.views?.[0] ?? '', 'base64');
+const beautyB = Buffer.from(r2.beauty ?? '', 'base64');
+check('repeat render still produces PNGs', png0b[0] === 0x89 && png0b[1] === 0x50 &&
+ beautyB[0] === 0x89 && beautyB[1] === 0x50, `${png0b.length}B ${beautyB.length}B`);
+check('repeat render byte-identical to first', png0b.equals(png0), `${png0.length}B vs ${png0b.length}B`);
+
+const mem2 = renderer.info.memory;
+const grew = (k) => mem2[k] - mem1[k];
+check(
+ 'render allocations are returned, not accumulated',
+ grew('textures') <= 0 && grew('texturesSize') <= 0 && grew('geometries') <= 0,
+ `textures ${mem1.textures}->${mem2.textures} bytes ${mem1.texturesSize}->${mem2.texturesSize} geometries ${mem1.geometries}->${mem2.geometries}`,
+);
+
+// Render-target pools are keyed by size and never evicted, so the set of
+// reachable keys must be bounded no matter what a caller asks for.
+const { snapRenderSize, ALLOWED_RENDER_SIZES } = await import('../src/renderer.mjs');
+const snappedKeys = new Set();
+for (let n = -50; n <= 4200; n += 7) snappedKeys.add(snapRenderSize(n));
+snappedKeys.add(snapRenderSize(undefined));
+snappedKeys.add(snapRenderSize(Number.NaN));
+check(
+ 'every requestable size snaps into the allowlist',
+ [...snappedKeys].every((s) => ALLOWED_RENDER_SIZES.includes(s)),
+ `${snappedKeys.size} distinct keys from ~600 requests`,
+);
+check(
+ 'snapping rounds up, so a caller never gets less detail than it asked for',
+ snapRenderSize(385) === 512 && snapRenderSize(384) === 384 && snapRenderSize(9999) === 2048,
+ `385->${snapRenderSize(385)} 384->${snapRenderSize(384)} 9999->${snapRenderSize(9999)}`,
+);
+
+// Variable view counts (T3.3). The engine picks a grid shape and composites the
+// reply into it, so the count that comes back must equal the count requested —
+// exactly, in request order. Silently truncating an over-long list (what this
+// service used to do) shows up client-side as a mystery degrade with no hint
+// that the request itself was the problem.
+const { validateViewDirs, MAX_VIEW_DIRS } = await import('../src/renderer.mjs');
+
+const nineDirs = [
+ [1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1], [0, 1, 0.001],
+ [0.7, 0.5, 0.7], [0, -1, 0.001], [-0.7, 0.5, -0.7], [0.7, -0.35, 0.7],
+];
+const nine = await (await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 128, views: nineDirs }),
+})).json();
+check('nine requested views produce nine PNGs', nine.ok === true && nine.views?.length === 9,
+ `${nine.views?.length ?? nine.error}`);
+
+const one = await (await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), size: 128, views: [[0.7, 0.5, 0.7]] }),
+})).json();
+check('a single requested view produces a single PNG', one.ok === true && one.views?.length === 1,
+ `${one.views?.length ?? one.error}`);
+
+const exactCamera = {
+ position: [4, 3, 6],
+ target: [0, 0.8, 0],
+ up: [0, 1, 0],
+ fovDeg: 48,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 100,
+};
+const cameraMemBefore = { ...renderer.info.memory };
+const cameraRendered = await capturingLog(async () => (await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ cameras: [exactCamera],
+ width: 320,
+ height: 180,
+ lighting_preset_id: 'neutral-studio-v1',
+ }),
+})).json());
+const cameraResult = cameraRendered.value;
+const cameraPng = PNG.sync.read(Buffer.from(cameraResult.views?.[0] ?? '', 'base64'));
+check('exact perspective camera render returns its rectangular PNG',
+ cameraResult.ok === true && cameraPng.width === 320 && cameraPng.height === 180,
+ `${cameraPng.width}x${cameraPng.height}`);
+check('camera response echoes actual renderer provenance and exact transport',
+ cameraResult.rendererId === health.rendererId && cameraResult.backend === health.backend &&
+ cameraResult.presentationProfile === 'neutral-studio-v1' &&
+ cameraResult.lightingPresetId === 'neutral-studio-v1' &&
+ cameraResult.width === 320 && cameraResult.height === 180 &&
+ JSON.stringify(cameraResult.cameras) === JSON.stringify([exactCamera]));
+check('camera response binds each output and the ordered output set',
+ /^sha256:[0-9a-f]{64}$/.test(cameraResult.viewSha256?.[0] ?? '') &&
+ /^sha256:[0-9a-f]{64}$/.test(cameraResult.outputSetSha256 ?? '') &&
+ cameraResult.cameraReceipts?.[0]?.outputSha256 === cameraResult.viewSha256[0] &&
+ cameraResult.cameraReceipts?.[0]?.width === 320 && cameraResult.cameraReceipts?.[0]?.height === 180);
+const cameraMemAfter = renderer.info.memory;
+check('camera targets are request-owned and disposed after readback',
+ cameraMemAfter.textures <= cameraMemBefore.textures &&
+ cameraMemAfter.texturesSize <= cameraMemBefore.texturesSize,
+ `textures ${cameraMemBefore.textures}->${cameraMemAfter.textures} ` +
+ `bytes ${cameraMemBefore.texturesSize}->${cameraMemAfter.texturesSize}`);
+const cameraLine = requestLines(cameraRendered.lines)[0];
+check('camera log carries bounded dimensions/profile/output identity without payloads',
+ cameraLine?.renderMode === 'camera' && cameraLine?.camerasRequested === 1 &&
+ cameraLine?.width === 320 && cameraLine?.height === 180 &&
+ cameraLine?.lightingPresetId === 'neutral-studio-v1' &&
+ cameraLine?.backend === health.backend && cameraLine?.rendererId === health.rendererId &&
+ cameraLine?.outputSetSha256 === cameraResult.outputSetSha256 &&
+ !cameraRendered.text.includes(glb.toString('base64').slice(0, 32)));
+
+const mixedMode = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ cameras: [exactCamera], width: 320, height: 180, size: 320,
+ }),
+});
+check('camera mode rejects legacy square sizing before queueing', mixedMode.status === 400);
+
+const unsupportedLight = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ cameras: [exactCamera], width: 320, height: 180,
+ lighting_preset_id: 'dramatic-night-v1',
+ }),
+});
+check('camera mode rejects unsupported lighting identities', unsupportedLight.status === 400);
+
+const overriddenBackground = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ cameras: [exactCamera], width: 320, height: 180,
+ background: '#000000',
+ }),
+});
+check('camera mode rejects background overrides that would falsify its profile',
+ overriddenBackground.status === 400);
+
+const tooMany = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({
+ glb_base64: glb.toString('base64'),
+ views: Array.from({ length: MAX_VIEW_DIRS + 1 }, () => [1, 0, 0]),
+ }),
+});
+const tooManyBody = await tooMany.json();
+check('an over-long views list is rejected, not truncated',
+ tooMany.status === 400 && /maximum is 12/.test(tooManyBody.error ?? ''), tooManyBody.error);
+
+const malformed = await fetch(`${base}/render`, {
+ method: 'POST', headers: { 'x-render-token': TOKEN },
+ body: JSON.stringify({ glb_base64: glb.toString('base64'), views: [['a', 'b', 'c']] }),
+});
+check('a malformed view vector is rejected before it becomes a NaN camera',
+ malformed.status === 400, `status ${malformed.status}`);
+
+const threw = (v) => { try { validateViewDirs(v); return false; } catch { return true; } };
+check('validateViewDirs defaults on undefined and on an empty list',
+ validateViewDirs(undefined).length === 6 && validateViewDirs([]).length === 6);
+check('validateViewDirs returns a valid list unchanged (no truncation, no reorder)',
+ JSON.stringify(validateViewDirs(nineDirs)) === JSON.stringify(nineDirs));
+check('validateViewDirs rejects the shapes that render as plausible nonsense',
+ threw('nope') && threw([[1, 0]]) && threw([[1, 0, 0, 0]]) && threw([[1, Number.NaN, 0]]) &&
+ threw([[0, 0, 0]]) && threw(Array.from({ length: MAX_VIEW_DIRS + 1 }, () => [1, 0, 0])));
+
+// Device-loss policy. Real loss cannot be injected through Dawn's Node binding,
+// so assert the decision itself; markGpuShutdown mutates module state, hence last.
+const { shouldExitOnDeviceLost, markGpuShutdown } = await import('../src/gpu.mjs');
+check('lost device exits the worker', shouldExitOnDeviceLost({ reason: 'unknown' }) === true);
+check('our own destroy is not a fault', shouldExitOnDeviceLost({ reason: 'destroyed' }) === false);
+markGpuShutdown();
+check('loss during shutdown is not a fault', shouldExitOnDeviceLost({ reason: 'unknown' }) === false);
+
+console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
+process.exit(failures ? 1 : 0);
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
index d362454e..302dfa68 100644
--- a/scripts/reliability.test.mjs
+++ b/scripts/reliability.test.mjs
@@ -42,8 +42,12 @@ describe('repository reliability contracts', () => {
const workflow = await readText('.github/workflows/ci.yml');
expect(pkg.scripts['test:coverage']).toBe(
- 'KILN_SPIKE_LIVE=0 bun test --coverage && bun scripts/check-coverage.mjs',
+ 'KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts --coverage && bun scripts/check-coverage.mjs',
);
+ // Views must be byte-reproducible: a runner that happens to reach a GPU render
+ // service must not be able to change what the golden-image tests compare.
+ expect(pkg.scripts['test']).toContain('KILN_RENDER=cpu');
+ expect(workflow).toContain('KILN_RENDER: cpu');
expect(bunfig).toContain('coverageReporter = ["text", "lcov"]');
expect(bunfig).not.toContain('coverageThreshold =');
expect(bunfig).toContain('coveragePathIgnorePatterns = [');
@@ -64,8 +68,11 @@ describe('repository reliability contracts', () => {
expect(Buffer.byteLength(agents)).toBeGreaterThan(0);
expect(Buffer.byteLength(agents)).toBeLessThan(12 * 1024);
expect(agents).toContain('bun run test:coverage');
- expect(agents).toContain('bun run sync:engine');
- expect(agents).toContain('npm --legacy-peer-deps');
- expect(agents).toContain('Do not deploy, commit, push');
+ // The invariants an editor will otherwise trip over. These are the claims this
+ // repository actually makes, so AGENTS.md must keep naming them.
+ expect(agents).toContain('captureViewsViaPort');
+ expect(agents).toContain('never gate evidence');
+ expect(agents).toContain('src/tools/registry.ts');
+ expect(agents).toContain('Do not commit, push');
});
});
diff --git a/skills/kiln-author-asset/SKILL.md b/skills/kiln-author-asset/SKILL.md
new file mode 100644
index 00000000..2fe27b86
--- /dev/null
+++ b/skills/kiln-author-asset/SKILL.md
@@ -0,0 +1,89 @@
+---
+name: kiln-author-asset
+description: Author a 3D asset as a Kiln program, then render it and look at the result until it is right. Use when asked to create, model, build, or refine a 3D asset, prop, vehicle, character, building, or GLB file, or when a project needs a game-ready model that does not exist yet.
+license: MIT
+---
+
+# Author a Kiln asset
+
+You are the author. Kiln gives you a sandbox of geometry primitives, a validator, a renderer, and a
+camera — you write the program and judge the pictures. Nothing here calls another model.
+
+## The loop
+
+1. **`kiln_list_primitives`** — read the catalog before writing anything. Signatures matter; guessing
+ them wastes a render. Filter by category when you only need one area.
+2. **Write the program.** A `meta` const, a `build()` returning a scene root, optionally `animate()`.
+3. **`kiln_validate`** — cheap. Catches syntax errors, a missing `build()`, infinite loops, recursion,
+ and keyframe typos before you spend a render on them.
+4. **`kiln_render`** — builds the scene and returns metrics *and* the six-view contact sheet in one
+ call: triangles, meshes, materials, bounding box, `lowestPart`, an instanceability grade, and the
+ image. **Actually look at the image.** This is the step that makes the whole thing work, and it is
+ the step that is easiest to skip.
+5. Fix what you see. Go back to 3.
+6. Write the final program to a `.kiln.js` file in the project.
+
+A build failure returns an error and **no image**, so you never get a picture of a model that did not
+build. If `kiln_render` returns without pixels, read the error rather than rendering again.
+
+## Reading the contact sheet
+
+The grid is Front / Right / Back on the top row, Left / Top / 3-4 on the bottom. Kiln's frame is
+**+X forward, +Y up, +Z right**, and assets sit on **Y=0**.
+
+Check, in this order:
+
+- **Orientation.** The nose, muzzle, or face belongs in the Front cell. A vehicle facing sideways is
+ the single most common failure and it is invisible in metrics.
+- **Grounding.** `lowestPart` should touch Y=0. Anything below grade must be
+ deliberate — earthworks, a keel — never wheels, feet, or equipment.
+- **Attachment.** Floating parts show as gaps in the orthographic cells. The 3-4 view hides them;
+ the axis-aligned views do not.
+- **Silhouette and proportion.** Squint at the Front and Right cells. If the shape does not read as
+ the thing at thumbnail size, more detail will not save it.
+- **Symmetry.** The Top cell is where mirrored parts reveal that they are not mirrored.
+
+Use **`kiln_inspect`** for a close-up orbit on a named part when a cell is too small to judge, and
+**`kiln_screenshot_animation`** when the program has an `animate()`.
+
+## Rules that save renders
+
+- Build the silhouette first, then subdivide. Detail on a wrong shape is wasted work.
+- Name parts for what they are. The names survive into the GLB and are how the next agent, and the
+ game engine, address them.
+- Reuse materials. The instanceability grade is driven by distinct-material count, and fewer shared
+ materials grade higher.
+- Prefer a few well-placed primitives over many small ones. Triangle budget is a soft warning, not a
+ wall, but a 40k-triangle crate is a mistake.
+- If two consecutive renders look the same, you are not changing what you think you are changing.
+ Re-read the program instead of rendering a third time.
+
+## What the render can and cannot tell you
+
+**Read `viewFidelity` on every render.** It is the render telling you what it is honest about:
+
+- `materialFaithful: true` — GPU PBR shading. Judge material, texture, roughness, metalness,
+ emissive response, normal relief. This is a real picture of the surface.
+- `materialFaithful: false` — flat-shaded CPU raster. Judge silhouette, proportion, orientation,
+ contact, and part attachment **only**. Do not comment on colour accuracy, texture, or whether
+ something looks metallic. It cannot show you that: a polished steel part and a grey plastic part
+ render identically.
+
+When `degraded` is set, `degradeReason` says why the GPU did not draw. A degrade is not a failure —
+the geometry findings are still valid — but it does bound what you are allowed to conclude.
+
+If material read matters and you only have the CPU raster, say plainly that material appearance was
+not verified rather than implying it was. Running a GPU render service and pointing
+`KILN_RENDER_PORT_URL` at it is what changes that.
+
+**Structural validation is not a visual pass, and neither is a passing render.** A program that
+builds cleanly can still look wrong. Only the picture tells you, and only if you look.
+
+## Reporting
+
+Say what you changed and why, name what still does not match, and never call a feature "done" when
+it is only "improved". If a gate passed but the asset reads badly, say both.
+
+Read [references/program-contract.md](references/program-contract.md) before writing the first
+program: file shape, the `meta` fields, the strict +X-forward coordinate contract, `createPart`
+auto-parenting, and what the sandbox forbids.
diff --git a/skills/kiln-author-asset/references/program-contract.md b/skills/kiln-author-asset/references/program-contract.md
new file mode 100644
index 00000000..8c139345
--- /dev/null
+++ b/skills/kiln-author-asset/references/program-contract.md
@@ -0,0 +1,80 @@
+# The Kiln program contract
+
+Read this when you are about to write or repair a `.kiln.js` program. The
+[SKILL.md](../SKILL.md) loop assumes you already know this shape.
+
+## File shape
+
+A program is plain JavaScript with **no imports and no exports**. Primitives and helpers arrive as
+globals. Three top-level declarations matter:
+
+```js
+const meta = { name: 'AssetName', category: 'prop', role: 'prop' };
+
+function build() {
+ const root = createRoot('AssetName');
+ // ...
+ return root;
+}
+
+function animate(root) { // optional
+ return [clip]; // THREE.AnimationClip[]
+}
+```
+
+`build()` may be **sync or async**. Mark it `async` if you use any CSG op (`boolUnion`, `boolDiff`,
+`boolIntersect`, `hull`) or any bevel/sweep op (`roundedBoxGeo`, `extrudeProfile`,
+`revolveProfile`) — those await WASM.
+
+An `export` statement is a validation error, not a style problem: the program is evaluated in a
+sandbox, not imported as a module.
+
+## `meta`
+
+| Field | Meaning |
+|---|---|
+| `name` | the asset name; also the conventional root node name |
+| `category` | picks the advisory triangle reference point (see below) |
+| `role` | how the asset sits in a scene — drives composition layout |
+
+`role` is one of `ground`, `building`, `wonder`, `poi`, `prop`, `fill`, `vehicle`. It is the field a
+scene composer reads later, so set it deliberately even for a standalone asset.
+
+## The coordinate contract
+
+This is strict, and violating it is the most common failure that metrics cannot catch:
+
+- **+X** = forward / nose / muzzle
+- **+Y** = up
+- **+Z** = asset right
+- Ground rests at **Y = 0**
+
+Vehicles, aircraft, weapons, boats, and buildings all follow this frame. If a part points forward,
+build it along +X. If a part spans left-to-right, build it along Z. Do not let each asset invent its
+own forward axis — a scene composed of assets with private conventions is unfixable.
+
+## `createPart` auto-parents
+
+```js
+// WRONG — double-adds
+parent.add(createPart('Name', geo, mat, { parent: parentObj }));
+
+// RIGHT
+createPart('Name', geo, mat, { parent: parentObj });
+```
+
+`createPivot(name, position, parent)` is positional and takes **no rotation**. If you need a rotated
+group, set rotation on the returned object after creating it.
+
+## Triangle budgets are advisory
+
+`kiln_validate` emits an informational nudge when an asset is far past the reference point for its
+category — 25k for `prop`, 40k for `character`/`vehicle`/`vegetation`, 60k for `building`, 120k for
+`environment`, 40k default. **These never gate.** Triangles are not the cost driver; draw calls are.
+Keep the detail if the silhouette needs it, and reuse materials to keep draw calls down.
+
+## What the sandbox forbids
+
+No `globalThis`/`global`/`process`, no network, no dynamic `import`/`eval`/`Function`, no constructor
+chains, and no raw `THREE.DataTexture`/`ShaderMaterial`/`RawShaderMaterial`. The validator rejects
+these before a render, so hitting one costs a round trip, not a mystery.
diff --git a/skills/kiln-compose-scene/SKILL.md b/skills/kiln-compose-scene/SKILL.md
new file mode 100644
index 00000000..d072140a
--- /dev/null
+++ b/skills/kiln-compose-scene/SKILL.md
@@ -0,0 +1,59 @@
+---
+name: kiln-compose-scene
+description: Lay out several finished GLBs into one scene — resolve placements from each asset's integration manifest, prove the layout is overlap-free, and export a single composed GLB. Use for multi-asset layouts, levels, worlds, dioramas, kits, or scene refinement.
+license: MIT
+---
+
+# Compose a scene from finished assets
+
+Composition is a separate problem from authoring. Each asset already knows its own units, bounds,
+and ground offset; your job is to place them relative to each other and prove the result holds
+together before exporting.
+
+## Workflow
+
+1. **Collect the parts.** Every input is a finished GLB on disk. Name each one — the name survives
+ into the composed scene and is how anything downstream addresses it.
+2. **Read each manifest.** `inspectGlbIntegration(bytes)` from `kiln/render` gives you
+ `bounds`, `ground.offsetToGround`, `defaultScene`, and `assessedRole` per asset. Placement
+ derived from anything else is a guess.
+3. **Place by role, not by category.** See the table below.
+4. **Prove it.** `findOverlaps` / `isOverlapFree` from `kiln/composer` take world-space AABBs and
+ return violations; `summarizeOverlaps` makes them readable. Zero overlaps is a floor, not a pass.
+5. **Export.** `composeSceneGLB(parts, opts)` from `kiln/render` merges the placed GLBs into one
+ document — textures copied losslessly, `dedup()` collapsing repeated blueprints so thirty
+ identical fence posts cost one geometry, and materials consolidated to a few draws. A corrupt
+ part becomes a warning and is skipped rather than failing the whole export.
+6. **Hand off to QA.** Apply `kiln-qa-asset` to the composed scene inside the real project. A layout
+ that validates can still be unplayable.
+
+## Placement by role
+
+| Role | Placement intent |
+|---|---|
+| `ground` | the base plane everything else sits on; place first |
+| `building` | structural edges and enclosure; defines where the player cannot go |
+| `wonder` | the readable anchor — the thing visible from anywhere, placed for sightlines |
+| `poi` | landmarks that orient the player at mid-range |
+| `vehicle` | along traversal paths, aligned to the direction of travel |
+| `prop` | dressing, placed without blocking movement or camera |
+| `fill` | density; the first thing to cut when the scene gets busy |
+
+## Rules
+
+- **Derive scale and ground contact from `bounds` and `offsetToGround`.** Do not infer scale from
+ what the asset is supposed to be — a "crate" can be authored at any size, and the manifest is the
+ only thing that knows which.
+- **Respect the shared frame.** Every asset is +X forward, +Y up, +Z right, sitting on Y=0. Rotate
+ at placement time; never re-author an asset to fix a scene-level orientation choice.
+- **Check the things a bounding box cannot see:** camera spawn position, traversal routes,
+ occlusion, collision, clipping, and dead empty space. `kiln/composer` also exposes reachability
+ and ground-sampling helpers for exactly this.
+- **A plausible manifest is not a QA result.** Overlap-free, grounded, and correctly scaled is the
+ precondition for looking at the scene, not a substitute for it.
+
+## Reporting
+
+Name the assets placed, the transforms applied, any parts skipped by the exporter, the overlap
+result, and what has *not* been verified — which is everything about how the scene feels until
+something has run it and looked.
diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.md
new file mode 100644
index 00000000..a9609d5f
--- /dev/null
+++ b/skills/kiln-qa-asset/SKILL.md
@@ -0,0 +1,64 @@
+---
+name: kiln-qa-asset
+description: Wire a finished GLB into the user's actual project and prove it works by looking at it running, then repair what fails. Use after generating or receiving a 3D asset, when integrating a model into a game or web app, or when asked whether an asset is actually usable.
+license: MIT
+---
+
+# QA an asset in the real project
+
+A structurally valid GLB is not a usable asset. This skill is the step between "it built" and "it
+works in the thing you are shipping". It is renderer, framework, and art-style agnostic.
+
+## Workflow
+
+1. **Verify the file.** Check GLB magic (`glTF`), that the JSON chunk parses, and the byte length.
+ Distinguish a missing optional file from a corrupt required one — they have different fixes.
+2. **Derive the integration manifest.** `inspectGlbIntegration(bytes)` from `kiln/render` returns a
+ `kiln.integration-manifest.v1` from the artifact alone. Read it *before* writing any transform.
+ Never synthesize the fields by eyeballing the model.
+3. **Wire it into the project's own stack.** Their loader, their scene graph, their build. Do not
+ introduce a new renderer or framework to make the asset easier to test.
+4. **Run the real project in a browser and look at it.** Load, controls, camera, traversal, layout,
+ responsive behavior, console and page errors. Screenshot and *inspect the screenshot*. DOM
+ assertions do not prove that a scene looks right.
+5. **Repair, then re-run.** Fix application code, camera, lighting, or placement first — most
+ "asset problems" are integration problems. Regenerate the asset only for an actual asset defect.
+ Re-run the failed journey plus the regressions it could touch.
+6. **Report candidly.** What worked, what failed, what was confusing, what you repaired, what risk
+ remains. Link every claim to the evidence that supports it.
+
+## What the manifest tells you
+
+| Field | Use it for |
+|---|---|
+| `units` / `axes` | always metres, +X forward / +Y up / +Z right — mismatched imports show here |
+| `bounds` | scale relative to the project's own objects; never guess scale from category |
+| `ground.offsetToGround`, `ground.grounded` | the exact Y correction to sit the asset on the floor |
+| `defaultScene` | which scene to instantiate; a missing default breaks many loaders |
+| `renderMetrics.drawCalls`, `uniqueMaterials` | runtime cost, which is draw calls, not triangles |
+| `structuralQa` | validator errors/warnings that survived generation |
+| `artifactSha256` | that the file you are wiring is the file you were given |
+
+**`visualQa` is always `not_assessed`.** That is literal, and it is the reason this skill exists.
+Nothing upstream has looked at the asset in its real scene. You are the first thing that does.
+
+## Failures worth checking for specifically
+
+- **Scale.** Correct-looking in isolation, wrong next to a character controller.
+- **Ground contact.** `offsetToGround` applied in the wrong direction sinks or floats the asset.
+- **Orientation.** An asset authored to the contract still lands sideways if the project's forward
+ axis differs. Fix it in the project's import transform, not by re-authoring the asset.
+- **Material read.** If the asset was authored against the flat-shaded CPU rasterizer, this is the
+ first time real lighting touches it. Metal and texture problems appear here or nowhere.
+- **Occlusion and collision.** Geometry that blocks the camera or traps the player.
+- **Draw calls.** A visually fine asset that costs 400 draws is a performance bug, not a win.
+
+## Boundaries
+
+- A successful load is not a QA result. Neither is a passing type check.
+- Never overwrite the user's files without consent, and never let a downloaded filename escape the
+ project root.
+- Stop after bounded repair attempts with a reproducible case and a precise next action, rather than
+ looping.
+- Do not soften the report to make it look complete. A named unresolved problem is more useful than
+ a clean summary that is wrong.
diff --git a/src/agent/run.ts b/src/agent/run.ts
index 92872fb5..5c18fc90 100644
--- a/src/agent/run.ts
+++ b/src/agent/run.ts
@@ -147,7 +147,7 @@ export interface RunKilnAgentOptions
/** Which agent tool surface to use. Resolved at call time: this option, else
* the KILN_TOOL_SURFACE env, else 'current'. The 'unified' surface is the
* buffer-based draft/view/edit/render/finalize set (render+screenshot
- * collapsed, no kiln_list_primitives) — the surface Kiln Studio runs in prod
+ * collapsed, no kiln_list_primitives) — the surface the Kiln Studio product ran in prod
* (KILN_TOOL_SURFACE=unified); 'current' remains the library default. */
toolSurface?: KilnToolSurface;
/** Agent name (for tracing). Default 'kiln-agent'. */
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index dad668c4..26199137 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -14,7 +14,7 @@
* Three factories: {@link makeKilnTools} (the library-default `current` generate
* surface), {@link makeKilnEditTools} (the `current` surgical-refine surface), and
* {@link makeKilnUnifiedTools} (the buffer-based `unified` surface, selected
- * via KILN_TOOL_SURFACE='unified' — what Kiln Studio runs in prod). The first two
+ * via KILN_TOOL_SURFACE='unified' — what the Kiln Studio product ran in prod). The first two
* stay byte-identical so the bench baseline does not move.
*/
import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strands-agents/sdk';
diff --git a/src/cli-render-mode.ts b/src/cli-render-mode.ts
new file mode 100644
index 00000000..395f1bb8
--- /dev/null
+++ b/src/cli-render-mode.ts
@@ -0,0 +1,191 @@
+/**
+ * Render-mode resolution for the CLI: `auto | cpu | gpu`, plus a remote port URL.
+ *
+ * The engine itself has no opinion here — it takes an optional `PbrRenderPort` and
+ * `captureViewsViaPort` owns the never-throw degrade to the CPU rasterizer. This
+ * module only decides WHICH port (if any) to hand it, and it must never throw for
+ * a missing or broken GPU: `auto` degrading silently to CPU is the whole point.
+ *
+ * `gpu` is the one mode that errors on unavailability, because a user who typed it
+ * 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.
+ */
+import type { PbrRenderPort, PbrRenderResult } from './composer/render-port';
+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;
+
+/**
+ * In-loop deadline. Far below the deadline appropriate for a post-loop artifact
+ * sheet, because this render blocks the caller while it runs. See AGENTS.md — the
+ * two deadlines must not be collapsed onto one value.
+ */
+export const CLI_VIEW_RENDER_TIMEOUT_MS = 20_000;
+
+export function resolveRenderMode(value: string): RenderMode {
+ if (value === 'auto' || value === 'cpu' || value === 'gpu') return value;
+ throw new Error(`--render must be auto, cpu or gpu (got: ${value})`);
+}
+
+/** Build a port that speaks the remote render service's HTTP contract. */
+export function makeRemoteRenderPort(url: string, token?: string): PbrRenderPort {
+ return async (req): Promise<PbrRenderResult> => {
+ const body: Record<string, unknown> = {
+ glb_base64: Buffer.from(req.glb).toString('base64'),
+ };
+ if (req.viewDirs) body['views'] = req.viewDirs;
+ if (req.size !== undefined) body['size'] = req.size;
+ if (req.beautySize !== undefined) body['beauty_size'] = req.beautySize;
+
+ const res = await fetch(new URL('/render', url), {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ // The RunPod-style edge gateway consumes `Authorization`, so app-layer
+ // auth rides a custom header instead.
+ ...(token ? { 'x-render-token': token } : {}),
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(CLI_VIEW_RENDER_TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`render service returned ${res.status}`);
+ const json = (await res.json()) as {
+ ok?: boolean;
+ rendererId?: string;
+ views?: string[];
+ error?: string;
+ };
+ if (!json.ok) throw new Error(json.error ?? 'render service reported failure');
+ return {
+ ok: true,
+ rendererId: json.rendererId ?? 'remote',
+ ...(json.views
+ ? { viewsPng: json.views.map((b64) => new Uint8Array(Buffer.from(b64, 'base64'))) }
+ : {}),
+ };
+ };
+}
+
+/**
+ * Probe a render service. Never throws — a missing GPU is the expected case on
+ * most machines, and `auto` degrading quietly to the CPU rasterizer is the point.
+ */
+async function probeRenderService(url: string): Promise<string | undefined> {
+ try {
+ const res = await fetch(new URL('/health', url), {
+ signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS),
+ });
+ if (!res.ok) return undefined;
+ const json = (await res.json()) as { ok?: boolean; rendererId?: string };
+ if (!json.ok) return undefined;
+ return json.rendererId ?? 'unknown-renderer';
+ } catch {
+ return undefined;
+ }
+}
+
+/** What actually got selected, for honest CLI reporting. */
+const selected = new WeakMap<object, string>();
+
+export function describeRenderMode(context: KilnToolContext): string {
+ return selected.get(context) ?? 'cpu raster';
+}
+
+/**
+ * The honest producer line for one completed screenshot.
+ *
+ * `describeRenderMode` reports what was CONFIGURED. That is not the same thing as
+ * what drew the pixels: `kiln_render` routes to the port only when the scene
+ * actually needs PBR shading, so a correctly-skipped GPU would otherwise be
+ * reported as though it had rendered. The tool output already carries the truth in
+ * its `kiln.view-fidelity.v1` block; this reads it rather than restating intent.
+ */
+export function describeDrawnBy(output: unknown, context: KilnToolContext): string {
+ const fidelity = (output as { viewFidelity?: ViewFidelityLike } | undefined)?.viewFidelity;
+ if (!fidelity) return describeRenderMode(context);
+
+ if (fidelity.materialFaithful) return `GPU ${fidelity.rendererId}`;
+
+ // `degraded` means "this scene wanted PBR and did not get it". With no port
+ // configured that is the documented default, not an incident, and reporting it
+ // as a degrade would make the ordinary no-GPU path look like a failure.
+ if (!context.viewRenderPort) return describeRenderMode(context);
+
+ if (fidelity.degraded) {
+ const why = fidelity.degradeReason ? `: ${fidelity.degradeReason}` : '';
+ return `cpu raster (GPU degraded${why})`;
+ }
+ // A port was configured and the render did not degrade, so the scene simply did
+ // not need PBR. Sending a flat, untextured scene to a GPU buys nothing the CPU
+ // rasterizer does not already draw correctly.
+ return 'cpu raster (GPU configured; scene needs no PBR shading)';
+}
+
+/** The fields of `kiln.view-fidelity.v1` this module reads. */
+interface ViewFidelityLike {
+ rendererId: string;
+ materialFaithful: boolean;
+ degraded: boolean;
+ degradeReason?: string;
+}
+
+/**
+ * Resolve the requested mode into a tool context. An absent `viewRenderPort` means
+ * the CPU rasterizer — byte-identical to the behavior before ports existed.
+ */
+export async function buildRenderPort(
+ mode: RenderMode,
+ portUrl: string | undefined,
+): Promise<KilnToolContext> {
+ const context: KilnToolContext = {};
+ const attach = (url: string, label: string): KilnToolContext => {
+ context.viewRenderPort = makeRemoteRenderPort(url, process.env['KILN_RENDER_TOKEN']);
+ context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;
+ selected.set(context, label);
+ return context;
+ };
+
+ if (mode === 'cpu') {
+ selected.set(context, 'cpu raster');
+ return context;
+ }
+
+ // An explicit URL is taken on trust: the user said where the renderer is, and a
+ // health probe that fails would only turn their explicit choice into a silent
+ // downgrade. `captureViewsViaPort` still degrades per-call if it does not answer.
+ if (portUrl) return attach(portUrl, `GPU service (${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);
+ if (rendererId) return attach(DEFAULT_LOCAL_PORT_URL, `GPU service (${rendererId})`);
+
+ 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 ` +
+ '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;
+}
diff --git a/src/cli.ts b/src/cli.ts
new file mode 100644
index 00000000..7e0e91e7
--- /dev/null
+++ b/src/cli.ts
@@ -0,0 +1,273 @@
+#!/usr/bin/env bun
+/**
+ * Kiln CLI — the entry point for humans and scripts.
+ *
+ * Two commands:
+ * render — execute an existing Kiln program to GLB + a six-view contact sheet.
+ * Offline: no model, no network, no key. This is the quickstart path,
+ * and the one that must keep working on a machine with nothing set up.
+ * generate — run the agent loop against a provider to author a program first.
+ *
+ * The view grid deliberately runs through the SAME `kiln_screenshot` registry def
+ * the agent calls, rather than reaching into the rasterizer directly, so the image
+ * a human sees is byte-identical to the image the model saw. Any drift between the
+ * two would be a bug we would rather fail loudly than paper over.
+ *
+ * Argument parsing is hand-rolled to keep the dependency surface at zero — this
+ * file is the one place a `commander`-shaped dependency would be tempting and is
+ * not worth it.
+ */
+import { readFile, writeFile } from 'node:fs/promises';
+import { resolve as resolvePath } from 'node:path';
+
+import { renderGLB } from './render';
+import type { KilnToolContext } from './tools/registry';
+import { kilnMcpToolDefs } from './mcp-server';
+import { resolveRenderMode, buildRenderPort, describeDrawnBy } from './cli-render-mode';
+import type { RenderMode } from './cli-render-mode';
+
+const USAGE = `kiln — vision-in-the-loop 3D asset generation
+
+USAGE
+ kiln render <program.js> [options] execute a Kiln program (offline, no key)
+ kiln generate "<prompt>" [options] author a program with a model, then render
+
+OPTIONS
+ --out <path> GLB output path (default: out.glb)
+ --views <path> contact sheet PNG path (default: none)
+ --render <mode> auto | cpu | gpu (default: auto)
+ --render-port <url> remote GPU render service
+ --model <id> model id for generate (default: env KILN_MODEL)
+ --max-steps <n> agent step cap (default: 24)
+ --category <name> prop | vehicle | character | architecture | vegetation
+ -h, --help this message
+
+EXAMPLES
+ kiln render examples/crate.kiln.js --out crate.glb --views sheet.png
+ kiln generate "a weathered wooden crate" --out crate.glb --views sheet.png
+ kiln render examples/crate.kiln.js --render cpu --views sheet.png
+`;
+
+interface Args {
+ command: string | undefined;
+ positional: string[];
+ out: string | undefined;
+ views: string | undefined;
+ render: RenderMode;
+ renderPort: string | undefined;
+ model: string | undefined;
+ maxSteps: number;
+ category: string | undefined;
+ help: boolean;
+}
+
+export function parseArgs(argv: readonly string[]): Args {
+ const args: Args = {
+ command: undefined,
+ positional: [],
+ out: undefined,
+ views: undefined,
+ render: 'auto',
+ renderPort: undefined,
+ model: process.env['KILN_MODEL'],
+ maxSteps: 24,
+ category: undefined,
+ help: false,
+ };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ const next = (): string => {
+ const v = argv[++i];
+ if (v === undefined) throw new Error(`${a} requires a value`);
+ return v;
+ };
+ switch (a) {
+ case '-h':
+ case '--help':
+ args.help = true;
+ break;
+ case '--out':
+ args.out = next();
+ break;
+ case '--views':
+ args.views = next();
+ break;
+ case '--render':
+ args.render = resolveRenderMode(next());
+ break;
+ case '--render-port':
+ args.renderPort = next();
+ break;
+ case '--model':
+ args.model = next();
+ break;
+ case '--category':
+ args.category = next();
+ break;
+ case '--max-steps': {
+ const n = Number(next());
+ if (!Number.isInteger(n) || n <= 0) throw new Error('--max-steps must be a positive integer');
+ args.maxSteps = n;
+ break;
+ }
+ default:
+ if (a.startsWith('-')) throw new Error(`unknown option: ${a}`);
+ if (args.command === undefined) args.command = a;
+ else args.positional.push(a);
+ }
+ }
+ return args;
+}
+
+/**
+ * Render one program to GLB bytes plus, optionally, the contact sheet.
+ * Shared by both commands so `generate` and `render` cannot diverge in output.
+ */
+async function emit(code: string, args: Args, context: KilnToolContext): Promise<void> {
+ const result = await renderGLB(code);
+ // Only write a GLB when one was asked for, or when it is the sole output —
+ // `--views sheet.png` alone should not litter the working directory.
+ const out = args.out ?? (args.views ? undefined : 'out.glb');
+ if (out) {
+ await writeFile(resolvePath(out), result.glb);
+ console.log(` ${out} ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
+ } else {
+ console.log(` ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
+ }
+ const bounds = result.integrationManifest.bounds;
+ if (bounds) {
+ const size = bounds.size ?? bounds.max;
+ if (Array.isArray(size)) {
+ console.log(` bounds ${size.map((n) => Number(n).toFixed(2)).join(' x ')} m`);
+ }
+ }
+ for (const w of result.warnings) console.log(` warning: ${w}`);
+
+ if (args.views) {
+ // The SAME def the MCP surface serves, so the CLI cannot render views through
+ // a path the agent never takes — and so `--render-port` actually fires, which
+ // the frozen baseline's CPU-only kiln_screenshot would silently ignore.
+ const def = kilnMcpToolDefs(context).find((d) => d.name === 'kiln_render');
+ if (!def) throw new Error('kiln_render is missing from the MCP tool surface');
+ const output = await def.run({ code });
+ const media = def.media?.(output);
+ if (!media) throw new Error('kiln_screenshot returned no image');
+ await writeFile(resolvePath(args.views), media.png);
+ // Report what actually drew the pixels, not what was configured. The engine
+ // routes to the port only when the scene needs PBR shading, so a GPU that was
+ // available and correctly skipped must not be reported as if it had drawn.
+ console.log(` ${args.views} (${describeDrawnBy(output, context)})`);
+ }
+}
+
+async function cmdRender(args: Args): Promise<number> {
+ const file = args.positional[0] ?? undefined;
+ if (!file) {
+ console.error('render requires a program path\n');
+ console.error(USAGE);
+ return 2;
+ }
+ const code = await readFile(resolvePath(file), 'utf8');
+ const context = await buildRenderPort(args.render, args.renderPort);
+ console.log(`rendering ${file}`);
+ await emit(code, args, context);
+ return 0;
+}
+
+async function cmdGenerate(args: Args): Promise<number> {
+ const prompt = args.positional.join(' ').trim();
+ if (!prompt) {
+ console.error('generate requires a prompt\n');
+ console.error(USAGE);
+ return 2;
+ }
+ if (!args.model) {
+ console.error('no model selected: pass --model <id> or set KILN_MODEL');
+ return 2;
+ }
+
+ // Imported lazily so `kiln render` never pulls the agent stack (an optional
+ // peer) into the process. A missing @strands-agents/sdk must not break the
+ // offline path, which is the one the quickstart promises works everywhere.
+ const [{ runKilnAgent }, { makeKilnModel, resolveKilnAgentModel }] = await Promise.all([
+ import('./agent/run'),
+ import('./agent/providers'),
+ ]);
+
+ const context = await buildRenderPort(args.render, args.renderPort);
+ const descriptor = resolveKilnAgentModel(args.model);
+ const model = makeKilnModel(descriptor);
+
+ console.log(`generating "${prompt}"`);
+ console.log(` model ${args.model} max-steps ${args.maxSteps} render ${args.render}`);
+
+ const run = await runKilnAgent({
+ model,
+ prompt,
+ maxSteps: args.maxSteps,
+ ...(args.category ? { category: args.category as never } : {}),
+ ...context,
+ } as never);
+
+ if (!run.code) {
+ console.error('the agent finished without submitting a program');
+ if (run.lastText) console.error(` last message: ${run.lastText.slice(0, 400)}`);
+ return 1;
+ }
+ console.log(` ${run.steps} steps, ${run.toolCalls.length} tool calls`);
+ // `generate` always writes the GLB: producing an asset is the point of the
+ // command, unlike `render`, where `--views` alone is a legitimate request.
+ const outPath = args.out ?? 'out.glb';
+ await emit(run.code, { ...args, out: outPath }, context);
+
+ const source = outPath.replace(/\.glb$/i, '.kiln.js');
+ await writeFile(resolvePath(source), run.code, 'utf8');
+ console.log(` ${source} (the program — edit and re-render it)`);
+ return 0;
+}
+
+export async function main(argv: readonly string[]): Promise<number> {
+ let args: Args;
+ try {
+ args = parseArgs(argv);
+ } catch (err) {
+ console.error(err instanceof Error ? err.message : String(err));
+ return 2;
+ }
+ if (args.help || !args.command) {
+ console.log(USAGE);
+ return args.command ? 0 : 2;
+ }
+ try {
+ switch (args.command) {
+ case 'render':
+ return await cmdRender(args);
+ case 'generate':
+ return await cmdGenerate(args);
+ default:
+ console.error(`unknown command: ${args.command}\n`);
+ console.error(USAGE);
+ return 2;
+ }
+ } catch (err) {
+ // Expected operator errors — an unreachable GPU, an unreadable program — are
+ // messages, not stack traces. KILN_DEBUG=1 restores the trace for real bugs.
+ if (process.env['KILN_DEBUG'] && err instanceof Error && err.stack) {
+ console.error(err.stack);
+ } else {
+ console.error(err instanceof Error ? err.message : String(err));
+ }
+ return 1;
+ }
+}
+
+if (import.meta.main) {
+ main(process.argv.slice(2))
+ .then((code) => {
+ process.exitCode = code;
+ })
+ .catch((err: unknown) => {
+ console.error(err instanceof Error ? (err.stack ?? err.message) : String(err));
+ process.exitCode = 1;
+ });
+}
diff --git a/src/mcp-parity.test.ts b/src/mcp-parity.test.ts
new file mode 100644
index 00000000..46af3caf
--- /dev/null
+++ b/src/mcp-parity.test.ts
@@ -0,0 +1,169 @@
+/**
+ * The repository's central claim, as a test.
+ *
+ * README says: "One tool definition, two transports. The in-process Strands skin and
+ * the MCP server both iterate it, so tool names and schemas cannot drift apart."
+ *
+ * If someone hand-writes a tool in either skin, that sentence becomes false. These
+ * tests are what stop that from happening quietly.
+ */
+import { describe, expect, it } from 'bun:test';
+import { Client, InMemoryTransport } from '@modelcontextprotocol/client';
+
+import {
+ createKilnToolRegistry,
+ createKilnRenderViewsDef,
+ createKilnInspectDef,
+ createKilnScreenshotAnimationDef,
+ createKilnViewInteriorDef,
+} from './tools/registry';
+import { makeKilnTools, KILN_SUBMIT_TOOL_NAME } from './agent/tools';
+import { runTool, kilnMcpToolDefs, createKilnMcpServer } from './mcp-server';
+
+/**
+ * List the tool surface the way a client sees it, over a real linked transport.
+ *
+ * Deliberately not a projection helper of our own: SDK v2 derives the advertised
+ * JSON Schema from the registry's zod schema itself, so the only assertion worth
+ * making is against what the SDK actually puts on the wire. A test against our own
+ * converter would have been a test of the converter, not of the surface.
+ */
+async function listToolsOverMcp(): Promise<{ name: string; description?: string; inputSchema: unknown }[]> {
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const server = createKilnMcpServer();
+ const client = new Client({ name: 'kiln-parity', version: '0' });
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ try {
+ const { tools } = await client.listTools();
+ return tools;
+ } finally {
+ await client.close();
+ await server.close();
+ }
+}
+
+describe('tool surface parity across transports', () => {
+ it('the MCP skin advertises its defs verbatim', async () => {
+ const defs = kilnMcpToolDefs();
+ const advertised = await listToolsOverMcp();
+
+ expect(advertised.map((t) => t.name)).toEqual(defs.map((d) => d.name));
+ for (let i = 0; i < defs.length; i++) {
+ // Descriptions are model-facing surface area. A skin that paraphrases is a
+ // skin that has drifted.
+ expect(advertised[i]!.description).toBe(defs[i]!.description);
+ }
+ });
+
+ it('every MCP def is a registry factory def, not a hand-written one', () => {
+ // The claim is "one tool definition, two transports". It survives only while
+ // no skin authors a def of its own, so compare against the factories rather
+ // than against a list of names someone could edit to match.
+ const factories = [
+ ...createKilnToolRegistry(),
+ createKilnRenderViewsDef(),
+ createKilnScreenshotAnimationDef(),
+ createKilnViewInteriorDef(),
+ createKilnInspectDef(),
+ ];
+ const canonical = new Map(factories.map((d) => [d.name, d.description]));
+
+ for (const def of kilnMcpToolDefs()) {
+ expect(canonical.has(def.name)).toBe(true);
+ expect(def.description).toBe(canonical.get(def.name) ?? '<missing>');
+ }
+ });
+
+ it('the MCP surface is composed for GPU capability, not the frozen baseline', () => {
+ // The baseline's kiln_screenshot never consults viewRenderPort, so shipping it
+ // over MCP would mean shipping a surface the render port can never reach. This
+ // pins the deliberate substitution: unified kiln_render instead of the
+ // baseline's metrics-only kiln_render plus CPU-only kiln_screenshot.
+ expect(kilnMcpToolDefs().map((d) => d.name)).toEqual([
+ 'kiln_list_primitives',
+ 'kiln_validate',
+ 'kiln_render',
+ 'kiln_screenshot_animation',
+ 'kiln_view_interior',
+ 'kiln_inspect',
+ ]);
+
+ const mcpRender = kilnMcpToolDefs().find((d) => d.name === 'kiln_render')!;
+ expect(mcpRender.description).toBe(createKilnRenderViewsDef().description);
+ // The substituted def is the one that can actually return an image.
+ expect(mcpRender.media).toBeDefined();
+ expect(kilnMcpToolDefs().map((d) => d.name)).not.toContain('kiln_screenshot');
+ });
+
+ it('both skins share the list/validate defs verbatim', () => {
+ const registry = createKilnToolRegistry();
+ const mcp = new Map(kilnMcpToolDefs().map((d) => [d.name, d.description]));
+ const strands = new Map(
+ makeKilnTools({}, {}).map((t) => {
+ const tool = t as { name: string; description?: string };
+ return [tool.name, tool.description];
+ }),
+ );
+
+ for (const name of ['kiln_list_primitives', 'kiln_validate']) {
+ const def = registry.find((d) => d.name === name)!;
+ expect(mcp.get(name)).toBe(def.description);
+ expect(strands.get(name)).toBe(def.description);
+ }
+ });
+
+ it("the in-process generate surface keeps the baseline plus a terminal submit", () => {
+ // Unchanged by the MCP recomposition: the engine's own loop still runs the
+ // frozen baseline, and still needs an unambiguous stopping action.
+ const baseline = new Set(createKilnToolRegistry().map((d) => d.name));
+ const names = makeKilnTools({}, {}).map((t) => (t as { name: string }).name);
+ for (const b of baseline) expect(names).toContain(b);
+ expect(names.filter((n) => !baseline.has(n)).sort()).toEqual([
+ 'kiln_screenshot_animation',
+ KILN_SUBMIT_TOOL_NAME,
+ ]);
+ });
+
+ it('every exposed schema reaches the client as usable JSON Schema', async () => {
+ // The SDK derives these from the registry's zod schemas. A def whose schema
+ // failed to convert would still register and would still be listed — it would
+ // just arrive with nothing a client could fill in, which is worse than a crash.
+ for (const tool of await listToolsOverMcp()) {
+ const schema = tool.inputSchema as { type?: string; properties?: object };
+ expect(schema.type).toBe('object');
+ expect(schema.properties).toBeDefined();
+ }
+ });
+
+ it('the MCP render def returns an image block, not a description of one', async () => {
+ const def = kilnMcpToolDefs().find((d) => d.name === 'kiln_render');
+ expect(def).toBeDefined();
+
+ const code = `
+const meta = { name: 'ParityCube', category: 'prop' };
+function build() {
+ const root = createRoot('ParityCube');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial(0x808080), { position: [0, 0.5, 0], parent: root });
+ return root;
+}
+`;
+ const result = await runTool(def!, { code });
+ const kinds = result.content.map((c) => c.type);
+ expect(kinds).toContain('image');
+ expect(kinds).toContain('text');
+
+ const image = result.content.find((c) => c.type === 'image') as { data: string };
+ // A PNG, base64-encoded: the agent literally sees the render.
+ expect(Buffer.from(image.data, 'base64').subarray(1, 4).toString('ascii')).toBe('PNG');
+ });
+
+ it('a failing tool call is an error result, not a thrown transport failure', async () => {
+ const def = kilnMcpToolDefs().find((d) => d.name === 'kiln_render');
+ const result = await runTool(def!, { code: 'this is not valid kiln source' }).catch(
+ () => undefined,
+ );
+ // Either the def handled it and returned content, or runTool surfaced it — what
+ // must never happen is an unhandled rejection killing the MCP session.
+ expect(result).toBeDefined();
+ });
+});
diff --git a/src/mcp-server.smoke.test.ts b/src/mcp-server.smoke.test.ts
new file mode 100644
index 00000000..cf11955f
--- /dev/null
+++ b/src/mcp-server.smoke.test.ts
@@ -0,0 +1,89 @@
+/**
+ * The published MCP entry point, exercised the way a client actually uses it.
+ *
+ * `mcp-parity.test.ts` proves the defs are projected faithfully; nothing there
+ * proves `bun run src/mcp-server.ts` starts, speaks the protocol, and puts real
+ * PNG bytes on the wire. This spawns the server as a subprocess over stdio and
+ * drives it with the reference client, so a broken entry point fails here rather
+ * than in someone's editor.
+ */
+import { describe, expect, it } from 'bun:test';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+import { kilnMcpToolDefs } from './mcp-server';
+
+const CUBE = `
+const meta = { name: 'SmokeCube', category: 'prop' };
+function build() {
+ const root = createRoot('SmokeCube');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial(0x808080), { position: [0, 0.5, 0], parent: root });
+ return root;
+}
+`;
+
+async function connect(): Promise<Client> {
+ const transport = new StdioClientTransport({
+ command: process.execPath,
+ args: ['run', 'src/mcp-server.ts'],
+ cwd: new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'),
+ // Pin CPU so the smoke result cannot vary with the runner's GPU.
+ env: { ...process.env, KILN_RENDER: 'cpu' } as Record<string, string>,
+ });
+ const client = new Client({ name: 'kiln-smoke', version: '0' });
+ await client.connect(transport);
+ return client;
+}
+
+describe('mcp server over real stdio', () => {
+ it('starts, handshakes, and serves the composed tool surface', async () => {
+ const client = await connect();
+ try {
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name)).toEqual(kilnMcpToolDefs().map((d) => d.name));
+ for (const t of tools) {
+ const schema = t.inputSchema as { type?: string; properties?: object };
+ expect(schema.type).toBe('object');
+ expect(schema.properties).toBeDefined();
+ }
+ } finally {
+ await client.close();
+ }
+ }, 120_000);
+
+ it('puts real PNG bytes on the wire for kiln_render', async () => {
+ const client = await connect();
+ try {
+ const res = (await client.callTool({
+ name: 'kiln_render',
+ arguments: { code: CUBE },
+ })) as { content: { type: string; data?: string }[] };
+
+ const image = res.content.find((c) => c.type === 'image');
+ expect(image).toBeDefined();
+ const bytes = Buffer.from(image!.data!, 'base64');
+ // Not a description of a render — the render.
+ expect(bytes.subarray(1, 4).toString('ascii')).toBe('PNG');
+ expect(bytes.byteLength).toBeGreaterThan(1_000);
+ } finally {
+ await client.close();
+ }
+ }, 120_000);
+
+ it('survives a malformed program without dropping the session', async () => {
+ const client = await connect();
+ try {
+ const res = (await client.callTool({
+ name: 'kiln_render',
+ arguments: { code: 'this is not valid kiln source' },
+ })) as { content: { type: string }[] };
+ // kiln_render never throws — it reports. Either way the session must live.
+ expect(res.content.length).toBeGreaterThan(0);
+
+ const after = await client.listTools();
+ expect(after.tools.length).toBeGreaterThan(0);
+ } finally {
+ await client.close();
+ }
+ }, 120_000);
+});
diff --git a/src/mcp-server.ts b/src/mcp-server.ts
new file mode 100644
index 00000000..5bea7337
--- /dev/null
+++ b/src/mcp-server.ts
@@ -0,0 +1,190 @@
+#!/usr/bin/env bun
+/**
+ * Kiln stdio MCP server — the second transport over `tools/registry.ts`.
+ *
+ * This exists so any MCP client (Claude Code, Codex CLI, Cursor, ...) can drive the
+ * Kiln tool surface directly, with the HOST's model as the author. That is the
+ * inverse of how the hosted product worked, where a single `generate` operation ran
+ * the engine's own agent loop server-side; see docs/history/production-architecture.md.
+ *
+ * The one invariant: tool names, descriptions, and schemas come from the registry and
+ * nowhere else. `agent/tools.ts` (in-process Strands) and this file are skins over the
+ * same defs, and `mcp-parity.test.ts` asserts they agree. Hand-writing a definition
+ * here would quietly break the claim the repository makes about itself.
+ *
+ * Registry defs carry zod schemas, and MCP SDK v2 accepts them directly as Standard
+ * Schema: the SDK derives the advertised JSON Schema and validates arguments before
+ * a handler runs. Nothing here converts or restates a schema, which is exactly why
+ * the two transports cannot drift.
+ *
+ * There is deliberately no `kiln_submit` here. Submit exists in the in-process loop to
+ * give the model an unambiguous terminal action; over MCP the host agent already has
+ * the program text and writes the file itself.
+ */
+import { McpServer } from '@modelcontextprotocol/server';
+import { serveStdio } from '@modelcontextprotocol/server/stdio';
+
+import {
+ createKilnToolRegistry,
+ createKilnRenderViewsDef,
+ createKilnInspectDef,
+ createKilnScreenshotAnimationDef,
+ createKilnViewInteriorDef,
+ type KilnToolDef,
+ type KilnToolContext,
+} from './tools/registry';
+import { buildRenderPort, resolveRenderMode } from './cli-render-mode';
+
+/** Server identity reported in the MCP handshake. */
+export const MCP_SERVER_NAME = 'kiln';
+export const MCP_SERVER_VERSION = '0.6.0';
+
+/** One MCP content block. Mirrors the SDK's `CallToolResult['content']` element. */
+type ContentBlock =
+ | { type: 'text'; text: string }
+ | { type: 'image'; data: string; mimeType: string };
+
+/**
+ * The structurally-typed subset of the SDK's `CallToolResult` this file produces.
+ *
+ * Declared locally rather than imported so `runTool` stays usable by callers that
+ * are not holding an SDK type (the parity test drives it directly), while still
+ * being assignable to what `registerTool` accepts.
+ *
+ * A type alias, not an interface, and that is load-bearing: the SDK's
+ * `CallToolResult` carries an index signature for protocol passthrough fields, and
+ * TypeScript grants an implicit index signature to type aliases but not to
+ * interfaces. As an interface this fails to satisfy the handler's return type, and
+ * the compiler reports it as an unrelated schema-overload error.
+ */
+export type KilnToolResult = {
+ content: ContentBlock[];
+ isError?: boolean;
+};
+
+/**
+ * The defs this transport exposes.
+ *
+ * Every entry comes from a factory in `tools/registry.ts` — nothing here is
+ * hand-written, which is the invariant `mcp-parity.test.ts` exists to hold.
+ *
+ * The composition mirrors the production unified surface rather than the frozen
+ * four-tool bench baseline, for one concrete reason: the baseline's
+ * `kiln_screenshot` is CPU-only by construction. Its schema is frozen, it takes no
+ * capture config, and it never consults `viewRenderPort`. `createKilnRenderViewsDef`
+ * is the def that collapses metrics and views into one call, routes to the GPU when
+ * the scene actually needs PBR shading, and reports `viewFidelity` so the agent
+ * knows whether it may judge material from the picture. Shipping the baseline pair
+ * here would mean shipping a surface on which the render port can never fire.
+ *
+ * `kiln_validate` stays standalone because, unlike the in-process unified surface,
+ * there is no draft buffer over MCP to fold validation into — the host agent holds
+ * the program text itself.
+ */
+export function kilnMcpToolDefs(context: KilnToolContext = {}): KilnToolDef[] {
+ const registry = createKilnToolRegistry(context);
+ const byName = (name: string): KilnToolDef => {
+ const def = registry.find((d) => d.name === name);
+ if (!def) throw new Error(`kilnMcpToolDefs: missing registry tool ${name}`);
+ return def;
+ };
+ return [
+ byName('kiln_list_primitives'),
+ byName('kiln_validate'),
+ createKilnRenderViewsDef(context),
+ createKilnScreenshotAnimationDef(context),
+ createKilnViewInteriorDef(context),
+ createKilnInspectDef(context),
+ ];
+}
+
+/**
+ * Run one def and shape its output as MCP content.
+ *
+ * Defs carrying a `media`/`mediaMulti` extractor return images, which is the whole
+ * point of `kiln_render`: the calling agent must literally see the render, not a
+ * description of it. The JSON that accompanies an image has its embedded base64
+ * stripped by the extractor, so pixels are never double-encoded onto the wire.
+ */
+export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnToolResult> {
+ const output = await def.run(args);
+
+ const multi = def.mediaMulti?.(output);
+ if (multi) {
+ return {
+ content: [
+ ...multi.pngs.map(
+ (png): ContentBlock => ({
+ type: 'image',
+ data: Buffer.from(png).toString('base64'),
+ mimeType: 'image/png',
+ }),
+ ),
+ { type: 'text', text: JSON.stringify(multi.json, null, 2) },
+ ],
+ };
+ }
+
+ const media = def.media?.(output);
+ if (media) {
+ return {
+ content: [
+ {
+ type: 'image',
+ data: Buffer.from(media.png).toString('base64'),
+ mimeType: 'image/png',
+ },
+ { type: 'text', text: JSON.stringify(media.json, null, 2) },
+ ],
+ };
+ }
+
+ return { content: [{ type: 'text', text: JSON.stringify(output, null, 2) }] };
+}
+
+/** Build the server, registering every def from the registry. */
+export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {
+ const server = new McpServer({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION });
+
+ for (const def of kilnMcpToolDefs(context)) {
+ server.registerTool(
+ def.name,
+ {
+ description: def.description,
+ // The registry's zod schema, passed straight through as Standard Schema.
+ // The SDK advertises the derived JSON Schema and validates arguments, so
+ // there is no second copy of the schema anywhere in this file. No cast:
+ // a cast here would silently decouple the advertised schema from the
+ // registry's, which is the one thing this file exists not to do.
+ inputSchema: def.inputSchema,
+ },
+ async (args: unknown): Promise<KilnToolResult> => {
+ try {
+ return await runTool(def, args);
+ } catch (err) {
+ // A tool error is a result, not a transport failure: the calling agent
+ // should see the message and correct its program rather than lose the
+ // session.
+ return {
+ isError: true,
+ content: [
+ { type: 'text' as const, text: err instanceof Error ? err.message : String(err) },
+ ],
+ };
+ }
+ },
+ );
+ }
+
+ return server;
+}
+
+if (import.meta.main) {
+ 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.
+ const context = await buildRenderPort(mode, process.env['KILN_RENDER_PORT_URL']);
+ // stdout is the MCP transport; diagnostics must never touch it.
+ console.error(`kiln MCP server on stdio (${mode})`);
+ void serveStdio(() => createKilnMcpServer(context));
+}
diff --git a/src/palette.ts b/src/palette.ts
index e9a5e146..dfb401b5 100644
--- a/src/palette.ts
+++ b/src/palette.ts
@@ -13,7 +13,7 @@
* stable so the future texture is deterministic; the implementer may tune
* individual color / metalness / roughness values without breaking that contract.
*
- * The rendered directive string is mirrored verbatim in Kiln Studio's `shared/`
+ * The rendered directive string was mirrored verbatim in the Kiln Studio product's `shared/`
* module as `OPTIMIZED_PALETTE_DIRECTIVE` (so that import-free, browser-critical
* module stays dependency-free); a parity test in kiln-studio asserts the two
* never drift.
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index b435d762..6d921a4f 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -3,10 +3,10 @@
*
* Four model-facing tools (list, validate, render, screenshot), each a thin
* wrapper over the existing kiln core functions. This registry is the single
- * source of truth for both the in-process-tool capability skin and the MCP
- * capability skin in the Kiln Bench spike: both adapters iterate
- * `kilnToolRegistry` so the tool names, descriptions, and behavior stay
- * identical across mechanisms.
+ * source of truth for every transport that exposes these tools: the in-process
+ * Strands skin (agent/tools.ts) and the stdio MCP server both iterate
+ * `kilnToolRegistry`, so tool names, descriptions, and behavior stay identical
+ * across mechanisms. Never hand-write a tool definition in a skin.
*
* A fifth def, `kilnRenderViewsDef`, collapses render + screenshot into one
* "see it" tool (metrics + six-view image from a single execution). It is
diff --git a/src/views/png.ts b/src/views/png.ts
index c7ad508f..55aa9672 100644
--- a/src/views/png.ts
+++ b/src/views/png.ts
@@ -1,7 +1,7 @@
/**
* Minimal PNG encoder + decoder (8-bit truecolor, no interlace) over node:zlib.
*
- * Deliberately dependency-free: this module must load inside the kiln-studio
+ * Deliberately dependency-free: this module had to load inside the Kiln Studio
* agent-runtime container and under Bun without native modules (sharp is NOT
* acceptable here). ~150 lines is cheaper than a dependency. The decoder exists
* so host-rendered per-view PNGs (PbrRenderPort) can be composited into the same
diff --git a/tsconfig.json b/tsconfig.json
index 81601258..6298734d 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -22,5 +22,5 @@
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
},
- "include": ["src/**/*.ts", "src/**/*.d.ts"]
+ "include": ["src/**/*.ts", "src/**/*.d.ts", "examples/**/*.ts"]
}