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: engine 0.2.0 - grade-lift gap, u32 indices, BYOK keys

Matt Kissinger5a50fdb2718c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc4e8dbd..43a6b049 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ for the consuming app's lockfile + tarball provenance, not public npm releases.
## [Unreleased]
+## [0.2.0] — 2026-07-02
+
+The release cut the 0.1.1 composer note promised: formally versions the scene composer
+surface (`@kiln/engine/composer`, `/composer/agent` — shipped in 0.1.x without a bump)
+plus the fixes below.
+
+### Fixed
+- **`auto` consolidation now fires on 4-material assets.** `PALETTE_MIN` dropped 5 → 4,
+ aligning the trigger with the instanceability rubric (grade B tops out at 3 materials,
+ so 4 is the first grade-C count). Previously a 4-material asset graded C and `auto`
+ never consolidated it.
+- **Uint32 indices for >65,535-vertex geometry.** `bridgeGeometry` always wrote
+ `Uint16Array` indices, silently wrapping values past 65,535 (corrupt GLB). It now
+ selects `Uint32Array` when the vertex count exceeds the Uint16 ceiling; the GLB
+ writer emits the matching `componentType` (5125).
+- **BYOK `apiKey` reaches Anthropic/OpenAI.** `makeKilnModel` dropped `opts.apiKey` on
+ the `anthropic` and `openai` branches (only google/openrouter passed it through), so
+ BYOK silently fell back to the provider env vars.
+
+### Changed
+- Comments in `agent/tools.ts` / `agent/run.ts` updated: the `unified` tool surface is
+ the production surface (Kiln Studio runs `KILN_TOOL_SURFACE=unified`), no longer
+ "flag-gated until a bench A/B clears it"; `current` remains the library default.
+
+### Housekeeping
+- Added the missing `LICENSE` file (MIT, already declared in `package.json`).
+- Rewrote the stale `@pixel-forge/core` module headers (`metrics.ts`, `agent/index.ts`,
+ `agent/run.ts`, `palette.ts`) to the `@kiln/engine` reality and removed dangling
+ references to files that do not exist in this repo.
+
## [0.1.1] — 2026-06-30
### Documentation
@@ -26,8 +56,8 @@ SDK never leaks into the pure core. Transcript compaction collapses to `serializ
past a threshold (the externalized model IS the state), with a soft step-cap backstop and a
`scene_layout`-first prompt so large many-asset scenes converge. ~990 lines of new tests.
-> Studio consumes this via the committed `@kiln/engine` 0.1.0 tarball (the surface landed
-> without a version bump); bump to 0.2.0 + re-`sync:engine` when a release is cut.
+> The surface landed without a version bump (Studio consumed it via the committed
+> `@kiln/engine` 0.1.0 tarball); formally versioned by the 0.2.0 release above.
## [0.1.0] — 2026-06-23
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..f2bfd501
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Matthew Kissinger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/package.json b/package.json
index d6037171..64b408ce 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@kiln/engine",
"private": true,
- "version": "0.1.1",
+ "version": "0.2.0",
"description": "Kiln 3D engine — text-to-GLB codegen agent loop, deterministic CPU render/rasterizer, primitive/CSG library, palette + instanceability grading, and pairwise ranking arena. Extracted from pixel-forge.",
"license": "MIT",
"author": "Matthew Kissinger",
diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.ts
index 49d67379..75196591 100644
--- a/src/__tests__/optimize.test.ts
+++ b/src/__tests__/optimize.test.ts
@@ -188,6 +188,18 @@ describe('optimize=auto (grade-aware, the default grade-lift lever)', () => {
expect(['A', 'B']).toContain(after.instanceability!.grade);
});
+ it('consolidates a 4-material asset (grade C floor) to grade B or better', async () => {
+ const before = await renderSceneToGLB(manyColorScene(4));
+ expect(before.instanceability!.grade).toBe('C'); // 4 materials — first C count
+
+ const after = await renderSceneToGLB(manyColorScene(4), { optimize: 'auto' });
+ expect(after.optimize).toBeDefined();
+ expect(after.optimize!.mode).toBe('palette');
+ expect(after.optimize!.materialsBefore).toBe(4);
+ expect(after.optimize!.materialsAfter).toBeLessThanOrEqual(3);
+ expect(['A', 'B']).toContain(after.instanceability!.grade);
+ });
+
it('is a byte-stable no-op on a lean asset (< PALETTE_MIN materials)', async () => {
const off = await renderSceneToGLB(manyColorScene(3), { optimize: 'off' });
const auto = await renderSceneToGLB(manyColorScene(3), { optimize: 'auto' });
diff --git a/src/__tests__/render-edges.test.ts b/src/__tests__/render-edges.test.ts
index 4d7486fc..133c8683 100644
--- a/src/__tests__/render-edges.test.ts
+++ b/src/__tests__/render-edges.test.ts
@@ -9,9 +9,11 @@
*/
import { describe, expect, test } from 'bun:test';
-import { NodeIO } from '@gltf-transform/core';
+import { Accessor, NodeIO } from '@gltf-transform/core';
+import * as THREE from 'three';
-import { executeKilnCode, renderGLB, inspectGeneratedAnimation } from '../render';
+import { boxGeo, createPart, createRoot, gameMaterial } from '../primitives';
+import { executeKilnCode, renderGLB, renderSceneToGLB, inspectGeneratedAnimation } from '../render';
// =============================================================================
// executeKilnCode guard clauses
@@ -210,6 +212,40 @@ function animate() {
});
});
+// =============================================================================
+// Index componentType selection (Uint16 vs Uint32)
+// =============================================================================
+
+describe('bridgeGeometry index componentType', () => {
+ test('a >65,535-vertex geometry roundtrips with UNSIGNED_INT indices intact', async () => {
+ const root = createRoot('BigMesh');
+ // 256x256 segments -> 257^2 = 66,049 vertices, past the Uint16 ceiling.
+ const geo = new THREE.PlaneGeometry(1, 1, 256, 256);
+ createPart('Big', geo, gameMaterial(0x8899aa), { parent: root });
+
+ const { bytes } = await renderSceneToGLB(root, { dedup: false });
+ const doc = await new NodeIO().readBinary(bytes);
+ const idx = doc.getRoot().listMeshes()[0]?.listPrimitives()[0]?.getIndices();
+ expect(idx?.getComponentType()).toBe(Accessor.ComponentType.UNSIGNED_INT);
+
+ // The top vertex index survives (a Uint16 write would wrap 66048 -> 512).
+ const arr = idx?.getArray();
+ let max = 0;
+ if (arr) for (const v of arr) max = Math.max(max, v);
+ expect(max).toBe(66049 - 1);
+ });
+
+ test('a small geometry keeps compact UNSIGNED_SHORT indices', async () => {
+ const root = createRoot('SmallMesh');
+ createPart('Small', boxGeo(1, 1, 1), gameMaterial(0x8899aa), { parent: root });
+
+ const { bytes } = await renderSceneToGLB(root, { dedup: false });
+ const doc = await new NodeIO().readBinary(bytes);
+ const idx = doc.getRoot().listMeshes()[0]?.listPrimitives()[0]?.getIndices();
+ expect(idx?.getComponentType()).toBe(Accessor.ComponentType.UNSIGNED_SHORT);
+ });
+});
+
// =============================================================================
// inspectGeneratedAnimation
// =============================================================================
diff --git a/src/agent/index.ts b/src/agent/index.ts
index 485e3592..2f72b444 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -1,11 +1,10 @@
/**
- * `@pixel-forge/core/kiln/agent` — the agnostic, tool-driven Kiln codegen
- * foundation (validated in packages/kiln-bench, folded into core 2026-06).
+ * `@kiln/engine/agent` — the agnostic, tool-driven Kiln codegen foundation
+ * (validated in the pixel-forge kiln-bench harness, folded in 2026-06).
*
- * This is an ADDITIVE surface: it does not replace the legacy emit-and-parse
- * `generate.ts` / `llm` paths. It is isolated on its own subpath export so the
- * `@strands-agents/sdk` dependency does not leak into the rest of core — import
- * from `@pixel-forge/core/kiln/agent` only when you want the agent loop.
+ * Isolated on its own subpath export so the `@strands-agents/sdk` dependency
+ * does not leak into the rest of the engine — import from `@kiln/engine/agent`
+ * only when you want the agent loop.
*
* - {@link runKilnAgent} — drive any Strands Model through the kiln tool loop
* - {@link generateKilnAsset} — model id -> tool loop -> rendered GLB (the default codegen engine)
diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.ts
index c4702a50..10863c5a 100644
--- a/src/agent/providers.test.ts
+++ b/src/agent/providers.test.ts
@@ -119,6 +119,22 @@ describe('makeKilnModel', () => {
expect(m).toBeTruthy();
});
+ test('passes a BYOK apiKey through to the anthropic and openai clients', () => {
+ const clientKey = (m: unknown): unknown =>
+ (m as { _client?: { apiKey?: unknown } })._client?.apiKey;
+ expect(
+ clientKey(
+ makeKilnModel(
+ { provider: 'anthropic', model: 'claude-opus-4-8' },
+ { apiKey: 'byok-anthropic' },
+ ),
+ ),
+ ).toBe('byok-anthropic');
+ expect(
+ clientKey(makeKilnModel({ provider: 'openai', model: 'gpt-5.5' }, { apiKey: 'byok-openai' })),
+ ).toBe('byok-openai');
+ });
+
describe('anthropic thinking control (KILN_THINKING)', () => {
const getCfg = (m: unknown): Record<string, unknown> =>
(m as { getConfig(): Record<string, unknown> }).getConfig();
diff --git a/src/agent/providers.ts b/src/agent/providers.ts
index fa17ee38..263de59f 100644
--- a/src/agent/providers.ts
+++ b/src/agent/providers.ts
@@ -146,6 +146,7 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
const thinking = resolveAnthropicThinking(desc.model, desc.thinking);
return new AnthropicModel({
modelId: desc.model,
+ ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
...(maxTokens != null ? { maxTokens } : {}),
...(thinking ? { params: thinking.params } : {}),
...(thinking?.betas ? { betas: thinking.betas } : {}),
@@ -155,6 +156,7 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
return new OpenAIModel({
api: 'chat',
modelId: desc.model,
+ ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
...(maxTokens != null ? { maxTokens } : {}),
});
case 'google':
diff --git a/src/agent/run.ts b/src/agent/run.ts
index a3879adc..4a4fd1e3 100644
--- a/src/agent/run.ts
+++ b/src/agent/run.ts
@@ -5,14 +5,13 @@
* bridge providers like OpenRouter) through a tool loop where it discovers Kiln
* primitives, validates and renders its program with the shared kiln tools, then
* submits the final code via the terminal `kiln_submit` tool. This is the
- * "interact with Kiln through tools" path — distinct from the legacy emit-and-
- * parse `generate.ts` / `llm` paths, which stay intact.
+ * "interact with Kiln through tools" path — the engine's codegen foundation.
*
* Know-how is supplied by either an inline system prompt (`getSystemPrompt`) or
* the kiln-glb SKILL.md via the Strands `AgentSkills` plugin — the task prompt
* itself should stay natural language and NOT bake in conventions.
*
- * Pure orchestration over @pixel-forge/core primitives + @strands-agents/sdk. The
+ * Pure orchestration over @kiln/engine primitives + @strands-agents/sdk. The
* caller constructs the `model` (see provider helpers) and owns any out-of-process
* resources (e.g. an MCP client passed via `extraTools`).
*/
@@ -108,7 +107,8 @@ 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/validate/render/finalize six (render+screenshot
- * collapsed, no kiln_list_primitives). Flag-gated until a bench A/B clears it. */
+ * collapsed, no kiln_list_primitives) — the surface Kiln Studio runs in prod
+ * (KILN_TOOL_SURFACE=unified); 'current' remains the library default. */
toolSurface?: KilnToolSurface;
/** Agent name (for tracing). Default 'kiln-agent'. */
agentName?: string;
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index ad79446d..4e0a11b3 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -11,11 +11,11 @@
* latter's coexistence with a full tool set is provider-dependent; a submit tool
* is unambiguous and works across every provider.
*
- * Three factories: {@link makeKilnTools} (the default `current` generate surface),
- * {@link makeKilnEditTools} (the `current` surgical-refine surface), and
- * {@link makeKilnUnifiedTools} (the buffer-based 6-tool `unified` surface, gated
- * behind KILN_TOOL_SURFACE='unified'). The first two stay byte-identical so the
- * bench baseline and production default do not move.
+ * Three factories: {@link makeKilnTools} (the library-default `current` generate
+ * surface), {@link makeKilnEditTools} (the `current` surgical-refine surface), and
+ * {@link makeKilnUnifiedTools} (the buffer-based 6-tool `unified` surface, selected
+ * via KILN_TOOL_SURFACE='unified' — what Kiln Studio runs 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';
import { z } from 'zod';
@@ -447,9 +447,9 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
// buffer; refine seeds the parent's code. `kiln_list_primitives` is dropped — the
// primitive catalog (incl. examples) lives in the cached system prompt instead.
//
-// Selected only when the flag is on; the legacy `makeKilnTools` /
-// `makeKilnEditTools` surfaces stay byte-identical for the default `current`
-// surface and the bench baseline.
+// Selected via KILN_TOOL_SURFACE='unified' — the production surface for Kiln
+// Studio. The legacy `makeKilnTools` / `makeKilnEditTools` surfaces stay
+// byte-identical for the library-default `current` surface and the bench baseline.
/**
* A mutable sink the unified tools write into. Create one per run with
diff --git a/src/metrics.ts b/src/metrics.ts
index 28d9b08a..eb87fe5f 100644
--- a/src/metrics.ts
+++ b/src/metrics.ts
@@ -2,7 +2,7 @@
* Kiln instanceability metrics + grader.
*
* A pure, deterministic, GPU-free static analysis over a baked glTF Document.
- * Lives in @pixel-forge/core so it can be computed at every natural point with
+ * Lives in @kiln/engine so it can be computed at every natural point with
* zero deploy coupling:
* - in render.ts -> render.meta for CLI / MCP / batch (never crosses the wire)
* - web-side in Kiln Studio from the persisted GLB
@@ -15,8 +15,6 @@
* NOTHING here is a hard gate. The metrics and grade are informational signals
* that help agents and humans understand how cheap an asset is to render at
* scale. They never reject, block, or fail a generation/validation/bake.
- *
- * See docs/kiln-instanceability-and-runtime-instancing-cycle.md.
*/
import type { Document } from '@gltf-transform/core';
diff --git a/src/palette.ts b/src/palette.ts
index a2a8f072..c4fda6e9 100644
--- a/src/palette.ts
+++ b/src/palette.ts
@@ -5,18 +5,18 @@
*
* PURE DATA + a text helper. NO `three`, NO node, NO gltf-transform imports — so
* it is browser-safe and can be consumed anywhere (the leaf subpath
- * `@pixel-forge/core/kiln/palette`) without dragging runtime code into a bundle.
+ * `@kiln/engine/palette`) without dragging runtime code into a bundle.
*
- * Why it lives in core: the palette is the shared contract both the authoring
- * prompt (instruct the model to build against these roles) and a later bake-time
- * shared-palette texture (Phase C) target. The slot SET + ORDER are stable so the
- * future texture is deterministic; the implementer may tune individual color /
- * metalness / roughness values without breaking that contract.
+ * Why it lives in the engine: the palette is the shared contract both the
+ * authoring prompt (instruct the model to build against these roles) and a later
+ * bake-time shared-palette texture (Phase C) target. The slot SET + ORDER are
+ * 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
- * `@pixel-forge/kiln-studio/shared` 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. See docs/kiln-material-consolidation-cycle.md.
+ * The rendered directive string is mirrored verbatim in Kiln Studio'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.
*/
/** One material role in the canonical palette. A PBR spec the directive names and
diff --git a/src/render.ts b/src/render.ts
index 6c09d5d1..69273310 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -335,10 +335,14 @@ function bridgeGeometry(
const indexAttr = geometry.getIndex();
if (indexAttr) {
+ // Uint16 holds indices up to 65535; a geometry with more vertices needs
+ // Uint32 indices or the values silently wrap (corrupt GLB). gltf-transform
+ // derives componentType (5123 vs 5125) from the typed-array class.
+ const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;
prim.setIndices(
doc
.createAccessor(meshName + '_idx')
- .setArray(new Uint16Array(indexAttr.array))
+ .setArray(new IndexArray(indexAttr.array))
.setType(TYPE_SCALAR)
.setBuffer(buf),
);
@@ -540,8 +544,10 @@ export interface RenderSceneOptions {
}
/** Minimum distinct material-value blocks before palette() generates a texture.
- * Below this it is a no-op (an asset with very few materials is already cheap). */
-const PALETTE_MIN = 5;
+ * Below this it is a no-op (an asset with very few materials is already cheap).
+ * Aligned with the instanceability rubric: grade B tops out at 3 materials, so
+ * the first grade-C count (4) must trigger `auto` consolidation. */
+const PALETTE_MIN = 4;
/** Resolve the effective optimize mode: explicit option wins, else the env, else off. */
function resolveOptimize(opt?: OptimizeMode): OptimizeMode {