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(core): add openai provider with gpt-image-2 dual-model routing

Matt Kissingera74f738912d9
diff --git a/__tests__/inspect.test.ts b/__tests__/inspect.test.ts
new file mode 100644
index 00000000..2555bcf0
--- /dev/null
+++ b/__tests__/inspect.test.ts
@@ -0,0 +1,152 @@
+/**
+ * Kiln introspection tests (W3b.1)
+ *
+ * Render-only — no LLM, no network. Feeds hand-written Kiln code into
+ * `kiln.inspect()` and asserts the structured report captures everything
+ * agents need for debugging.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import { inspect } from '../inspect';
+
+const CHEST_CODE = `
+const meta = { name: 'TestChest', category: 'prop', tris: 60 };
+function build() {
+ const root = createRoot('TestChest');
+ const body = createPart('Body', boxGeo(1, 0.6, 0.6), gameMaterial(0x8b4513), {
+ position: [0, 0.3, 0], parent: root,
+ });
+ createPart('Lid', boxGeo(1, 0.2, 0.6), gameMaterial(0x6b3410), {
+ position: [0, 0.7, 0], pivot: true, parent: root,
+ });
+ return root;
+}
+function animate() {
+ return [createClip('Open', 1, [
+ rotationTrack('Joint_Lid', [
+ { time: 0, rotation: [0, 0, 0] },
+ { time: 1, rotation: [-80, 0, 0] },
+ ]),
+ ])];
+}
+`;
+
+const FLOATING_CODE = `
+const meta = { name: 'Floater' };
+function build() {
+ const root = createRoot('Floater');
+ createPart('Body', sphereGeo(0.5), gameMaterial(0x00ff00), {
+ position: [0, 5, 0], parent: root,
+ });
+ return root;
+}
+`;
+
+const BROKEN_JOINT_CODE = `
+const meta = { name: 'Broken' };
+function build() {
+ const root = createRoot('Broken');
+ createPivot('Body', [0, 0, 0], root);
+ return root;
+}
+function animate() {
+ return [createClip('bad', 1, [
+ rotationTrack('Joint_DoesNotExist', [
+ { time: 0, rotation: [0, 0, 0] },
+ { time: 1, rotation: [30, 0, 0] },
+ ]),
+ ])];
+}
+`;
+
+const EMPTY_CODE = `
+const meta = { name: 'Empty' };
+function build() {
+ return createRoot('Empty');
+}
+`;
+
+describe('kiln.inspect', () => {
+ test('reports triangles, materials and bounding box for a real chest', async () => {
+ const r = await inspect(CHEST_CODE);
+
+ expect(r.triangles).toBeGreaterThan(0);
+ expect(r.materials).toBe(2);
+ expect(r.boundingBox.size[0]).toBeGreaterThan(0);
+ expect(r.boundingBox.size[1]).toBeGreaterThan(0);
+ expect(r.boundingBox.size[2]).toBeGreaterThan(0);
+ expect(r.warnings).toEqual([]);
+ expect(r.meta.name).toBe('TestChest');
+ });
+
+ test('captures named parts with type classification', async () => {
+ const r = await inspect(CHEST_CODE);
+
+ const names = r.namedParts.map((p) => p.name);
+ expect(names).toContain('TestChest');
+ expect(names).toContain('Mesh_Body');
+ expect(names).toContain('Joint_Lid');
+
+ const joint = r.namedParts.find((p) => p.name === 'Joint_Lid');
+ expect(joint?.type).toBe('pivot');
+
+ const mesh = r.namedParts.find((p) => p.name === 'Mesh_Body');
+ expect(mesh?.type).toBe('mesh');
+ });
+
+ test('surfaces animation tracks with targetResolved flag', async () => {
+ const r = await inspect(CHEST_CODE);
+
+ expect(r.animationTracks.length).toBe(1);
+ const track = r.animationTracks[0];
+ expect(track?.clipName).toBe('Open');
+ expect(track?.targetName).toBe('Joint_Lid');
+ expect(track?.property).toBe('rotation');
+ expect(track?.targetResolved).toBe(true);
+ });
+
+ test('flags animation tracks whose target is missing from the scene', async () => {
+ const r = await inspect(BROKEN_JOINT_CODE);
+
+ expect(r.animationTracks.length).toBe(1);
+ expect(r.animationTracks[0]?.targetResolved).toBe(false);
+ expect(r.warnings.length).toBeGreaterThan(0);
+ expect(r.warnings.some((w) => w.includes('Joint_DoesNotExist'))).toBe(true);
+ });
+
+ test('lists the primitives actually used in the code', async () => {
+ const r = await inspect(CHEST_CODE);
+
+ expect(r.primitivesUsed).toContain('createRoot');
+ expect(r.primitivesUsed).toContain('createPart');
+ expect(r.primitivesUsed).toContain('boxGeo');
+ expect(r.primitivesUsed).toContain('gameMaterial');
+ expect(r.primitivesUsed).toContain('rotationTrack');
+ expect(r.primitivesUsed).toContain('createClip');
+
+ // Should not falsely detect unused primitives.
+ expect(r.primitivesUsed).not.toContain('sphereGeo');
+ expect(r.primitivesUsed).not.toContain('torusGeo');
+ });
+
+ test('bounds reflect a floating asset (debugging aid)', async () => {
+ const r = await inspect(FLOATING_CODE);
+
+ // Sphere at y=5 with r=0.5 → min y >= 4.5, max y <= 5.5
+ expect(r.boundingBox.min[1]).toBeGreaterThan(4);
+ expect(r.boundingBox.min[1]).toBeLessThan(5);
+ expect(r.boundingBox.max[1]).toBeGreaterThan(5);
+ });
+
+ test('returns zeroed bounds for a pivots-only scene', async () => {
+ const r = await inspect(EMPTY_CODE);
+
+ expect(r.triangles).toBe(0);
+ expect(r.materials).toBe(0);
+ expect(r.boundingBox.min).toEqual([0, 0, 0]);
+ expect(r.boundingBox.max).toEqual([0, 0, 0]);
+ expect(r.boundingBox.size).toEqual([0, 0, 0]);
+ expect(r.animationTracks).toEqual([]);
+ });
+});
diff --git a/index.ts b/index.ts
index b23b1419..d87e410f 100644
--- a/index.ts
+++ b/index.ts
@@ -29,6 +29,14 @@ export type {
KilnGenerateCallOptions,
} from './generate';
export { validate, validateKilnCode } from './validation';
+export { inspect } from './inspect';
+export type {
+ InspectResult,
+ InspectNamedPart,
+ InspectAnimationTrack,
+ InspectBoundingBox,
+ Vec3Tuple,
+} from './inspect';
export {
buildUserPrompt,
getSystemPrompt,
diff --git a/inspect.ts b/inspect.ts
new file mode 100644
index 00000000..f23f8ba2
--- /dev/null
+++ b/inspect.ts
@@ -0,0 +1,277 @@
+/**
+ * Kiln Scene Introspection (W3b.1)
+ *
+ * Executes generated Kiln code headlessly, walks the resulting Three.js scene,
+ * and returns a structured report agents can use to debug generation output.
+ *
+ * Typical use:
+ *
+ * ```ts
+ * const result = await kiln.inspect(code);
+ * if (result.boundingBox.min[1] > 0.1) {
+ * // Asset floats above ground - feed back to Claude.
+ * }
+ * ```
+ *
+ * Pure function: no file I/O, no WebGL, no GLB bytes.
+ */
+
+import * as THREE from 'three';
+
+import { executeKilnCode, inspectGeneratedAnimation } from './render';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export type Vec3Tuple = [number, number, number];
+
+export interface InspectNamedPart {
+ /** Three.js Object3D name (e.g. `"Joint_LeftWheel"`, `"Mesh_Barrel"`). */
+ name: string;
+ /** Rough classification derived from name + object type. */
+ type: 'pivot' | 'mesh' | 'group';
+ /** Local position (relative to parent). */
+ position: Vec3Tuple;
+}
+
+export interface InspectAnimationTrack {
+ /** Clip the track belongs to. */
+ clipName: string;
+ /** Node name the track targets (e.g. `"Joint_LeftWheel"`). */
+ targetName: string;
+ /** Which transform channel the track drives. */
+ property: 'rotation' | 'position' | 'scale';
+ /** Whether `targetName` resolves to a node in the scene graph. */
+ targetResolved: boolean;
+}
+
+export interface InspectBoundingBox {
+ min: Vec3Tuple;
+ max: Vec3Tuple;
+ size: Vec3Tuple;
+}
+
+export interface InspectResult {
+ /** Total triangle count across every mesh in the scene graph. */
+ triangles: number;
+ /** Unique material count (by reference equality). */
+ materials: number;
+ /** World-space bounding box of the full scene. */
+ boundingBox: InspectBoundingBox;
+ /** All named pivots, meshes, and groups in traversal order. */
+ namedParts: InspectNamedPart[];
+ /** Every animation channel, with resolution flags so agents can spot typos. */
+ animationTracks: InspectAnimationTrack[];
+ /** Primitive helper names referenced in the source code. */
+ primitivesUsed: string[];
+ /** Non-fatal issues (e.g. tracks targeting unknown nodes). */
+ warnings: string[];
+ /** `meta` block extracted from the code. */
+ meta: Record<string, unknown>;
+}
+
+// =============================================================================
+// Primitive detection
+// =============================================================================
+
+/**
+ * Names of every primitive helper exposed in the Kiln sandbox. Kept in sync
+ * with `buildSandboxGlobals` by hand — the catalog is tiny and any drift
+ * surfaces immediately in `listPrimitives()` tests.
+ */
+const KNOWN_PRIMITIVE_NAMES = [
+ 'createRoot',
+ 'createPivot',
+ 'createPart',
+ 'capsuleGeo',
+ 'cylinderGeo',
+ 'boxGeo',
+ 'sphereGeo',
+ 'coneGeo',
+ 'torusGeo',
+ 'planeGeo',
+ 'gameMaterial',
+ 'basicMaterial',
+ 'glassMaterial',
+ 'lambertMaterial',
+ 'rotationTrack',
+ 'positionTrack',
+ 'scaleTrack',
+ 'createClip',
+ 'idleBreathing',
+ 'bobbingAnimation',
+ 'spinAnimation',
+ 'countTriangles',
+ 'countMaterials',
+ 'getJointNames',
+ 'validateAsset',
+] as const;
+
+function detectPrimitivesUsed(code: string): string[] {
+ const seen = new Set<string>();
+ for (const name of KNOWN_PRIMITIVE_NAMES) {
+ // Match `name(` as a word boundary — avoids picking up substrings inside
+ // other identifiers.
+ const re = new RegExp(`\\b${name}\\s*\\(`);
+ if (re.test(code)) seen.add(name);
+ }
+ return Array.from(seen).sort();
+}
+
+// =============================================================================
+// Scene walk
+// =============================================================================
+
+function classifyNode(obj: THREE.Object3D): 'pivot' | 'mesh' | 'group' {
+ if (obj instanceof THREE.Mesh) return 'mesh';
+ if (obj.name.startsWith('Joint_')) return 'pivot';
+ return 'group';
+}
+
+function collectNamedParts(root: THREE.Object3D): InspectNamedPart[] {
+ const parts: InspectNamedPart[] = [];
+ root.traverse((obj) => {
+ if (!obj.name) return;
+ parts.push({
+ name: obj.name,
+ type: classifyNode(obj),
+ position: [obj.position.x, obj.position.y, obj.position.z],
+ });
+ });
+ return parts;
+}
+
+function countTris(root: THREE.Object3D): number {
+ let count = 0;
+ root.traverse((child) => {
+ if (!(child instanceof THREE.Mesh)) return;
+ const geometry = child.geometry;
+ if (!geometry) return;
+ if (geometry.index) {
+ count += geometry.index.count / 3;
+ } else {
+ const position = geometry.getAttribute('position');
+ if (position) count += position.count / 3;
+ }
+ });
+ return Math.floor(count);
+}
+
+function countUniqueMaterials(root: THREE.Object3D): number {
+ const materials = new Set<THREE.Material>();
+ root.traverse((child) => {
+ if (!(child instanceof THREE.Mesh)) return;
+ if (Array.isArray(child.material)) {
+ for (const m of child.material) materials.add(m);
+ } else if (child.material) {
+ materials.add(child.material);
+ }
+ });
+ return materials.size;
+}
+
+function computeBoundingBox(root: THREE.Object3D): InspectBoundingBox {
+ // Ensure world matrices are fresh before measuring — otherwise nested
+ // pivots can misreport bounds when positions were set after the last
+ // auto-update. executeKilnCode hands us a detached tree, so we drive
+ // updates explicitly.
+ root.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(root);
+
+ // If the scene has no geometry at all (pivots-only), Box3 stays at +Inf /
+ // -Inf. Collapse to the origin so downstream consumers get finite numbers.
+ if (!isFinite(box.min.x) || !isFinite(box.max.x)) {
+ return {
+ min: [0, 0, 0],
+ max: [0, 0, 0],
+ size: [0, 0, 0],
+ };
+ }
+
+ const size = new THREE.Vector3();
+ box.getSize(size);
+
+ return {
+ min: [box.min.x, box.min.y, box.min.z],
+ max: [box.max.x, box.max.y, box.max.z],
+ size: [size.x, size.y, size.z],
+ };
+}
+
+function collectAnimationTracks(
+ root: THREE.Object3D,
+ clips: THREE.AnimationClip[]
+): InspectAnimationTrack[] {
+ const tracks: InspectAnimationTrack[] = [];
+ if (clips.length === 0) return tracks;
+
+ const nodeNames = new Set<string>();
+ root.traverse((obj) => {
+ if (obj.name) nodeNames.add(obj.name);
+ });
+
+ for (const clip of clips) {
+ for (const track of clip.tracks) {
+ const dotIdx = track.name.lastIndexOf('.');
+ if (dotIdx === -1) continue;
+ const targetName = track.name.substring(0, dotIdx);
+ const rawProp = track.name.substring(dotIdx + 1);
+
+ // Three.js stores rotation tracks as `.quaternion` on the track name
+ // but agents think of them as `rotation`. Normalize for the report.
+ let property: 'rotation' | 'position' | 'scale';
+ if (rawProp === 'quaternion' || rawProp === 'rotation') {
+ property = 'rotation';
+ } else if (rawProp === 'position') {
+ property = 'position';
+ } else if (rawProp === 'scale') {
+ property = 'scale';
+ } else {
+ continue; // unsupported channel — surfaced via warnings instead
+ }
+
+ tracks.push({
+ clipName: clip.name,
+ targetName,
+ property,
+ targetResolved: nodeNames.has(targetName),
+ });
+ }
+ }
+
+ return tracks;
+}
+
+// =============================================================================
+// Public API
+// =============================================================================
+
+/**
+ * Execute Kiln code and return a structured inspection report.
+ *
+ * @throws {Error} if the code can't be executed (same errors as
+ * {@link executeKilnCode}).
+ */
+export async function inspect(code: string): Promise<InspectResult> {
+ const { meta, root, clips } = executeKilnCode(code);
+
+ const primitivesUsed = detectPrimitivesUsed(code);
+ const namedParts = collectNamedParts(root);
+ const triangles = countTris(root);
+ const materials = countUniqueMaterials(root);
+ const boundingBox = computeBoundingBox(root);
+ const animationTracks = collectAnimationTracks(root, clips);
+ const warnings = inspectGeneratedAnimation(root, clips);
+
+ return {
+ triangles,
+ materials,
+ boundingBox,
+ namedParts,
+ animationTracks,
+ primitivesUsed,
+ warnings,
+ meta: meta as Record<string, unknown>,
+ };
+}