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(kiln): reference-image input on the agent loop + substrate hardening

Matt Kissinger4f998aa9c111
diff --git a/__tests__/__snapshots__/prompt-api.test.ts.snap b/__tests__/__snapshots__/prompt-api.test.ts.snap
index 5c77a463..0114bcbc 100644
--- a/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -5,10 +5,13 @@ exports[`system prompt embeds the generated catalog api section snapshot (review
createRoot(name: string) // Creates the root Object3D for an asset. Call first in build().
createPivot(name: string, position?: [x, y, z], parent?: Object3D)
// Creates an empty pivot node for skeletal animation. Name is auto-prefixed with \`Joint_\`.
-createPart(name, geometry, material, opts?: { position, rotation, scale, pivot, parent })
- // Creates a mesh, optionally wrapped in a pivot, and attaches it to \`opts.parent\`.
+createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })
+ // Creates a mesh, optionally wrapped in a pivot, and attaches it to \`opts.parent\`. \`rotation\`
+ // is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57]
+ // is a no-op.
// NOTE: AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent }
- // instead.
+ // instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces
+ // ~zero rotation.
beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })
// Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun
// barrels, skid struts, cables, and scaffolding.
@@ -117,9 +120,10 @@ cloneGeometry(geo: BufferGeometry)
// Returns the same geometry reference. Use it as a signal that you are intentionally sharing
// geometry across multiple parts; gltf-transform dedupes on export.
cloneMaterial(mat: Material) // Shared material reference. See cloneGeometry.
-createInstance(name, source, opts?: { position, rotation, scale, parent })
+createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })
// Creates a new mesh reusing an existing part's geometry + material at a new transform.
- // Cheapest way to replicate wheels / bolts / fence posts / windows.
+ // Cheapest way to replicate wheels / bolts / fence posts / windows. \`rotation\` is in DEGREES,
+ // like createPart.
// Arrays (replicate a source part)
arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)
diff --git a/__tests__/validation-hardened.test.ts b/__tests__/validation-hardened.test.ts
index 09d38d63..414ab88a 100644
--- a/__tests__/validation-hardened.test.ts
+++ b/__tests__/validation-hardened.test.ts
@@ -261,3 +261,72 @@ function build() { return createRoot('X'); }
expect(r.errors).toEqual(r.issues.map((i) => i.message));
});
});
+
+describe('kiln validation — rotation units lint (ROTATION_RADIANS_SUSPECTED)', () => {
+ const wrap = (body: string) => `
+const meta = { name: 'X' };
+function build() {
+ const root = createRoot('X');
+ ${body}
+ return root;
+}`;
+
+ const radianWarnings = (code: string) =>
+ validate(code).warnings.filter((w) => w.code === 'ROTATION_RADIANS_SUSPECTED');
+
+ test('flags a numeric radian triple with the degree equivalent', () => {
+ const w = radianWarnings(
+ wrap(`createPart('Grip', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`)
+ );
+ expect(w.length).toBe(1);
+ expect(w[0]!.message).toContain('[0, 0, 0.785]');
+ expect(w[0]!.message).toContain('[0, 0, 45]');
+ expect(w[0]!.line).toBeDefined();
+ // Advisory only — the program is still valid.
+ expect(validate(wrap(`createPart('G', boxGeo(1,1,1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`)).valid).toBe(true);
+ });
+
+ test('flags Math.PI expressions (the -Math.PI/2 fin case)', () => {
+ const w = radianWarnings(
+ wrap(`createPart('Fin', wingGeo({ span: 3 }), gameMaterial(0x445522), { rotation: [-Math.PI / 2, 0, 0], parent: root });`)
+ );
+ expect(w.length).toBe(1);
+ expect(w[0]!.message).toContain('RADIANS');
+ });
+
+ test('does NOT flag the rad-to-deg conversion idiom (a * 180 / Math.PI)', () => {
+ const w = radianWarnings(
+ wrap(`const a = 0.5;
+ createPart('Blade', boxGeo(0.06, 1.7, 0.27), gameMaterial(0x111111), { rotation: [a * 180 / Math.PI, 0, 0], parent: root });`)
+ );
+ expect(w).toEqual([]);
+ });
+
+ test('does NOT flag degree-style values', () => {
+ const cases = ['[0, 0, 90]', '[0, 0, -15]', '[0, 0, 28.6]', '[0, 45, 0.5]', '[0, 0, 0]', '[0, 0, 1]'];
+ for (const rot of cases) {
+ const w = radianWarnings(
+ wrap(`createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: ${rot}, parent: root });`)
+ );
+ expect(w).toEqual([]);
+ }
+ });
+
+ test('stays quiet on dynamic expressions it cannot read', () => {
+ const w = radianWarnings(
+ wrap(`const tilt = 17;
+ createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, tilt], parent: root });`)
+ );
+ expect(w).toEqual([]);
+ });
+
+ test('covers createInstance and ignores unrelated rotation keys', () => {
+ const w = radianWarnings(
+ wrap(`const src = createPart('W', cylinderZGeo(0.5, 0.5, 0.3), gameMaterial(0x222222), { parent: root });
+ createInstance('W2', src, { position: [1, 0, 0], rotation: [0, 1.57, 0], parent: root });
+ rotationTrack('Joint_X', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 0, 0.5] }]);`)
+ );
+ expect(w.length).toBe(1);
+ expect(w[0]!.message).toContain('createInstance');
+ });
+});
diff --git a/agent/generate.ts b/agent/generate.ts
index 6e4978a5..b26bde5c 100644
--- a/agent/generate.ts
+++ b/agent/generate.ts
@@ -16,7 +16,7 @@
*/
import { renderGLB, type KilnCodeMeta } from '../render';
import type { AssetCategory, AssetStyle } from '../prompt';
-import { runKilnAgent, type RefineMode, type KilnKnowhow } from './run';
+import { runKilnAgent, type RefineMode, type KilnKnowhow, type KilnInputImage } from './run';
import {
makeKilnModel,
resolveKilnAgentModel,
@@ -65,6 +65,8 @@ export interface GenerateKilnAssetOptions {
* FRESH generation (ignored on refine). ~5-15k input tokens/run, mostly
* absorbed by prompt caching when reused across a batch. */
exemplarCode?: string;
+ /** Optional reference image fed to the model as multimodal context (fresh gen + refine). */
+ inputImage?: KilnInputImage;
}
export interface GenerateKilnAssetResult {
@@ -109,6 +111,8 @@ export async function generateKilnCodeAgent(opts: {
includeAnimation?: boolean;
existingCode?: string;
originalPrompt?: string;
+ /** Optional reference image fed to the model as multimodal context. */
+ inputImage?: KilnInputImage;
/** Strands model id; defaults like {@link generateKilnAsset}. */
model?: string;
}): Promise<{
@@ -135,6 +139,7 @@ export async function generateKilnCodeAgent(opts: {
...(opts.style ? { style: opts.style } : {}),
...(opts.existingCode ? { existingCode: opts.existingCode } : {}),
...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),
+ ...(opts.inputImage ? { inputImage: opts.inputImage } : {}),
});
if (agent.error || !agent.code) {
@@ -181,6 +186,7 @@ export async function generateKilnAsset(
...(opts.existingCode && opts.refineMode ? { refineMode: opts.refineMode } : {}),
...(opts.agentName ? { agentName: opts.agentName } : {}),
...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),
+ ...(opts.inputImage ? { inputImage: opts.inputImage } : {}),
});
if (agent.error || !agent.code) {
diff --git a/agent/index.ts b/agent/index.ts
index 988d21e6..a24d5d69 100644
--- a/agent/index.ts
+++ b/agent/index.ts
@@ -19,7 +19,7 @@
* - {@link MetricsCollector} — per-loop tool/step/usage metrics via hooks
*/
export { runKilnAgent } from './run';
-export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow, RefineMode } from './run';
+export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow, RefineMode, KilnInputImage } from './run';
export { generateKilnAsset, generateKilnCodeAgent, DEFAULT_KILN_AGENT_MODEL } from './generate';
export type { GenerateKilnAssetOptions, GenerateKilnAssetResult } from './generate';
diff --git a/agent/providers.test.ts b/agent/providers.test.ts
index 62c7656f..875a98a6 100644
--- a/agent/providers.test.ts
+++ b/agent/providers.test.ts
@@ -79,4 +79,54 @@ describe('makeKilnModel', () => {
const m = makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }, { apiKey: 'byok-override' });
expect(m).toBeTruthy();
});
+
+ describe('anthropic thinking control (KILN_THINKING)', () => {
+ const getCfg = (m: unknown): Record<string, unknown> =>
+ (m as { getConfig(): Record<string, unknown> }).getConfig();
+
+ test('sends nothing by default — the API default (adaptive on Fable 5), the verified config', () => {
+ const cfg = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5' }));
+ expect(cfg['params']).toBeUndefined();
+ expect(cfg['betas']).toBeUndefined();
+ });
+
+ test('effort keyword maps to the adaptive shape (Fable 5 family), no beta header', () => {
+ const cfg = getCfg(
+ makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5', thinking: 'high' }),
+ );
+ expect(cfg['params']).toEqual({ thinking: { type: 'adaptive' }, output_config: { effort: 'high' } });
+ expect(cfg['betas']).toBeUndefined();
+ });
+
+ test('numeric budget maps to the legacy enabled shape + interleaved beta (pre-adaptive models)', () => {
+ const cfg = getCfg(
+ makeKilnModel({ provider: 'anthropic', model: 'claude-opus-4-8', thinking: 8000 }),
+ );
+ expect(cfg['params']).toEqual({ thinking: { type: 'enabled', budget_tokens: 8000 } });
+ expect(cfg['betas']).toEqual(['interleaved-thinking-2025-05-14']);
+ });
+
+ test('env keyword/number applies (numbers floored to 1024); descriptor 0 forces default; google ignores it', () => {
+ const prev = process.env['KILN_THINKING'];
+ try {
+ process.env['KILN_THINKING'] = 'medium';
+ const adaptive = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5' }));
+ expect(adaptive['params']).toEqual({ thinking: { type: 'adaptive' }, output_config: { effort: 'medium' } });
+
+ process.env['KILN_THINKING'] = '512';
+ const floored = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-opus-4-8' }));
+ expect(floored['params']).toEqual({ thinking: { type: 'enabled', budget_tokens: 1024 } });
+
+ const off = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5', thinking: 0 }));
+ expect(off['params']).toBeUndefined();
+
+ // Non-anthropic providers must not grow a thinking param from the env.
+ const google = getCfg(makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }));
+ expect(google['params']).toBeUndefined();
+ } finally {
+ if (prev === undefined) delete process.env['KILN_THINKING'];
+ else process.env['KILN_THINKING'] = prev;
+ }
+ });
+ });
});
diff --git a/agent/providers.ts b/agent/providers.ts
index cf03e1e9..66b36db2 100644
--- a/agent/providers.ts
+++ b/agent/providers.ts
@@ -62,6 +62,23 @@ export interface KilnModelDescriptor {
model: string;
/** Output-token budget; applied to anthropic/openai/bedrock (GoogleModel uses its own default). */
maxTokens?: number;
+ /**
+ * Anthropic thinking control (anthropic provider only; others ignore it).
+ *
+ * - Effort keyword (`'low' | 'medium' | 'high'`, passed through verbatim) →
+ * `thinking: {type:'adaptive'}` + `output_config: {effort}` — the
+ * Fable-5-family shape. These models think adaptively BY DEFAULT (verified
+ * live: reasoning blocks interleave with kiln tool calls on a plain
+ * request); the keyword only tunes how hard.
+ * - Number → legacy `thinking: {type:'enabled', budget_tokens}` plus the
+ * interleaved-thinking beta, for pre-adaptive Claude models. Fable 5
+ * REJECTS this shape with a 400 (verified live 2026-06-11).
+ *
+ * Unset falls back to the `KILN_THINKING` env (read at call time); 0 / ''
+ * forces default behavior even when the env is set. Default: send nothing —
+ * the API default, which on Fable 5 is adaptive thinking at default effort.
+ */
+ thinking?: string | number;
}
export interface MakeKilnModelOptions {
@@ -76,6 +93,32 @@ const trimmedEnv = (k: string): string | undefined => {
return v && v.trim() ? v.trim() : undefined;
};
+/**
+ * Resolve the Anthropic thinking control: per-call descriptor wins, else the
+ * `KILN_THINKING` env. Effort keywords map to the adaptive shape (Fable 5
+ * family); numbers map to the legacy enabled+budget shape (floored to the API
+ * minimum of 1024, interleaved beta added). Unset / 0 / '' → undefined, i.e.
+ * send nothing and take the API default.
+ */
+function resolveAnthropicThinking(
+ fromDesc?: string | number,
+): { params: Record<string, unknown>; betas?: string[] } | undefined {
+ const raw = fromDesc ?? trimmedEnv('KILN_THINKING');
+ if (raw == null || raw === '' || raw === 0) return undefined;
+ const asNum =
+ typeof raw === 'number' ? raw : /^\d+$/.test(String(raw).trim()) ? Number.parseInt(String(raw).trim(), 10) : undefined;
+ if (asNum !== undefined) {
+ if (!Number.isFinite(asNum) || asNum <= 0) return undefined;
+ return {
+ params: { thinking: { type: 'enabled', budget_tokens: Math.max(1024, Math.floor(asNum)) } },
+ betas: ['interleaved-thinking-2025-05-14'],
+ };
+ }
+ const effort = String(raw).trim().toLowerCase();
+ if (!/^[a-z]+$/.test(effort)) return undefined;
+ return { params: { thinking: { type: 'adaptive' }, output_config: { effort } } };
+}
+
/**
* Construct a Strands `Model` from a provider+model descriptor — the agnostic
* factory the whole Kiln agent path builds on. Native providers (Anthropic /
@@ -86,8 +129,15 @@ const trimmedEnv = (k: string): string | undefined => {
export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOptions = {}): Model {
const maxTokens = desc.maxTokens;
switch (desc.provider) {
- case 'anthropic':
- return new AnthropicModel({ modelId: desc.model, ...(maxTokens != null ? { maxTokens } : {}) });
+ case 'anthropic': {
+ const thinking = resolveAnthropicThinking(desc.thinking);
+ return new AnthropicModel({
+ modelId: desc.model,
+ ...(maxTokens != null ? { maxTokens } : {}),
+ ...(thinking ? { params: thinking.params } : {}),
+ ...(thinking?.betas ? { betas: thinking.betas } : {}),
+ });
+ }
case 'openai':
return new OpenAIModel({ api: 'chat', modelId: desc.model, ...(maxTokens != null ? { maxTokens } : {}) });
case 'google':
diff --git a/agent/run.ts b/agent/run.ts
index d9668c28..9c4b58cc 100644
--- a/agent/run.ts
+++ b/agent/run.ts
@@ -16,7 +16,7 @@
* caller constructs the `model` (see provider helpers) and owns any out-of-process
* resources (e.g. an MCP client passed via `extraTools`).
*/
-import { Agent, type Plugin, type Tool, type Message } from '@strands-agents/sdk';
+import { Agent, TextBlock, ImageBlock, type Plugin, type Tool, type Message } from '@strands-agents/sdk';
import { AgentSkills } from '@strands-agents/sdk/vended-plugins/skills';
import { getSystemPrompt, buildUserPrompt, KILN_REFINE_DIRECTIVE, KILN_EDIT_DIRECTIVE } from '../prompt';
@@ -31,6 +31,24 @@ export type KilnKnowhow = 'inline' | 'skill';
/** How a refine applies its change: whole-program re-emission, or surgical edits. */
export type RefineMode = 'rewrite' | 'edit';
+/** A user-supplied reference image fed to the agent as multimodal context.
+ * `base64` is the raw image bytes base64-encoded (JSON/wire-safe); `mime` is the
+ * source content-type (e.g. 'image/png'). Gemini 3.5 Flash consumes it via the
+ * same Strands ImageBlock path the agent already uses for kiln_screenshot. */
+export interface KilnInputImage {
+ base64: string;
+ mime: string;
+}
+
+/** Map an input-image MIME to a Strands ImageFormat (defaults to png). */
+function imageFormatFromMime(mime: string): 'png' | 'jpeg' | 'gif' | 'webp' {
+ const m = mime.toLowerCase();
+ if (m.includes('jpeg') || m.includes('jpg')) return 'jpeg';
+ if (m.includes('gif')) return 'gif';
+ if (m.includes('webp')) return 'webp';
+ return 'png';
+}
+
export interface RunKilnAgentOptions {
/** A constructed Strands `Model` instance (provider-agnostic). */
model: unknown;
@@ -73,6 +91,10 @@ export interface RunKilnAgentOptions {
* rendered as "## Reference Asset" in the user prompt (ignored when
* existingCode is set). ~5-15k input tokens/run; cached on most providers. */
exemplarCode?: string;
+ /** Optional reference image fed to the model alongside the text prompt. When set,
+ * the initial message becomes a [TextBlock, ImageBlock] pair and the prompt notes
+ * that a reference image is attached. Works for fresh gen AND refine. */
+ inputImage?: KilnInputImage;
}
export interface RunKilnAgentResult {
@@ -153,9 +175,20 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
});
metrics.attach(agent);
+ // An image-only request still needs a textual anchor for prompt framing.
+ const promptText =
+ opts.prompt?.trim() || (opts.inputImage ? 'Build a 3D game asset that matches the attached reference image.' : opts.prompt);
+
+ const reviewNote =
+ '\n\nBefore submitting, call kiln_screenshot once on your final code and check ' +
+ 'the six views: correct facing in Front, a clean silhouette in Right, symmetry in ' +
+ 'Top, and no floating or detached parts in the 3/4 view. Fix anything that looks ' +
+ 'wrong, then call the kiln_submit tool exactly once with your final, complete ' +
+ 'Kiln program.';
+
const userPrompt =
buildUserPrompt({
- prompt: opts.prompt,
+ prompt: promptText,
mode: 'glb',
category: opts.category ?? 'prop',
includeAnimation: opts.includeAnimation ?? false,
@@ -164,13 +197,25 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),
...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),
}) +
- '\n\nBefore submitting, call kiln_screenshot once on your final code and check ' +
- 'the six views: correct facing in Front, a clean silhouette in Right, symmetry in ' +
- 'Top, and no floating or detached parts in the 3/4 view. Fix anything that looks ' +
- 'wrong, then call the kiln_submit tool exactly once with your final, complete ' +
- 'Kiln program.';
+ (opts.inputImage
+ ? '\n\nA reference image of the desired asset is attached. Match its overall form, ' +
+ 'proportions, and silhouette; treat the text above as the intent and any specific changes.'
+ : '') +
+ reviewNote;
+
+ // With a reference image, send a [text, image] content-block pair (the same
+ // ImageBlock path kiln_screenshot uses); otherwise a plain string prompt.
+ const invokeArgs = opts.inputImage
+ ? [
+ new TextBlock(userPrompt),
+ new ImageBlock({
+ format: imageFormatFromMime(opts.inputImage.mime),
+ source: { bytes: new Uint8Array(Buffer.from(opts.inputImage.base64, 'base64')) },
+ }),
+ ]
+ : userPrompt;
- const result = await agent.invoke(userPrompt);
+ const result = await agent.invoke(invokeArgs as never);
metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);
let code = editMode ? editSink.code : sink.code;
diff --git a/list-primitives.ts b/list-primitives.ts
index 3b8c5df3..4bd292ec 100644
--- a/list-primitives.ts
+++ b/list-primitives.ts
@@ -69,15 +69,15 @@ const PRIMITIVES: PrimitiveSpec[] = [
{
name: 'createPart',
signature:
- 'createPart(name, geometry, material, opts?: { position, rotation, scale, pivot, parent })',
+ 'createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })',
returns: 'THREE.Object3D (mesh or wrapping pivot)',
category: 'structure',
description:
- 'Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`.',
+ 'Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.',
example:
- "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], parent: root });",
+ "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
promptNotes:
- 'AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead.',
+ 'AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation.',
},
{
name: 'beamBetween',
@@ -498,11 +498,11 @@ const PRIMITIVES: PrimitiveSpec[] = [
{
name: 'createInstance',
signature:
- 'createInstance(name, source, opts?: { position, rotation, scale, parent })',
+ 'createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })',
returns: 'THREE.Object3D',
category: 'instancing',
description:
- 'Creates a new mesh reusing an existing part\'s geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows.',
+ 'Creates a new mesh reusing an existing part\'s geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.',
example:
"const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });\ncreateInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });",
},
diff --git a/prompt.ts b/prompt.ts
index a0b27847..83d35ccc 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -211,7 +211,11 @@ export const KILN_RULES = `<rules>
- NO "export" statements - just define meta, build, animate
- Output ONLY valid JavaScript code (no TypeScript types)
- NEVER call .add() on createPart result - it auto-adds to parent
+- createPart/createInstance rotation is in DEGREES, not radians. rotation: [0,0,90] is a quarter turn; rotation: [0,0,0.785] is invisible. Never pass Math.PI-based values to the rotation option (direct THREE properties like group.rotation.z stay radians)
- Z-FIGHTING PREVENTION: No two mesh faces may be coplanar or near-coplanar. All decorative geometry (decals, markings, edge strips, reinforcements, trim) must be fully outside the parent mesh - never intersecting or flush. Offset at least 0.01 from the nearest surface. If a box is 0.6 wide (edges at x=+-0.3), place edge trim at x=+-0.31, NOT x=+-0.29. Minimum 0.01 thickness for flat parts.
+- ROOFS AND TENTS: the two gable slopes MIRROR each other (+angle / -angle) and their top edges meet at the ridge. Every slope must extend PAST its wall line so the eave hangs below the wall top with real overhang - a panel that stops flush at the wall reads as a lid propped on the box. A panel perpendicular to its roof plane is wrong: its thin axis must align with the roof NORMAL, not the slope direction.
+- CLOSED CIRCLES: barrels, drums, and towers built from staves/planks must close the full circumference - each stave TANGENT to the circle (rotate by its own angle), never radial fins with gaps. Do not carve groove detail with many thin CSG cutters (booleans blow up on thin blades); use lathe facets or thin proud surface strips instead.
+- GROUND: only intentionally below-grade parts (earth mounds, footings, piles, keels/rudders) may dip below Y=0. Functional surface parts - wheels, tails, missiles, furniture, equipment - must stay at or above it; if a tilted assembly buries one end, raise or re-pivot it.
</rules>`;
export const KILN_ANIMATION_FORMAT = `<critical-animation-format>
@@ -228,13 +232,21 @@ export const KILN_VISUAL_QA = `<visual-qa>
Before kiln_submit, call kiln_screenshot and check each view deliberately:
- Front (camera on +X): the nose/muzzle/face should point AT you. If you see
a side profile here, the asset is built sideways — rebuild along +X.
+ Wheels/discs read edge-on here and as circles from the side — a circle seen
+ from the front means the disc faces the wrong axis.
- Right (+Z): the long profile. Check silhouette: proportions, ground contact
- at the bottom edge, nothing important missing.
+ at the bottom edge, nothing important missing. Roof slopes must DRAPE — the
+ eave line drops below the wall top with visible overhang; a roofline flush
+ with the walls reads as a flap propped open. Nothing functional should hang
+ below the ground line (cross-check kiln_render bbox.min[1]: below -0.05 is
+ only OK for intentional earthworks, piles, or keels).
- Back / Left: symmetry with their opposites; no missing or one-sided parts.
- Top (+Y): left/right symmetry; wings/axles/rails centered on the body.
- 3/4: part CONTACT. Look for gaps where parts should touch (struts, ladder
rails, wing roots, attachments). A visible gap means a floating part — fix
- the position or call snapTo(part, host), then screenshot again.
+ the position or call snapTo(part, host), then screenshot again. Cylindrical
+ stave assemblies (barrels, drums) must look CLOSED — daylight through the
+ wall means staves are rotated radial instead of tangent.
If any view looks wrong, fix the code and re-screenshot before submitting.
</visual-qa>`;
@@ -564,6 +576,8 @@ createPivot(name, [x,y,z], parent) - creates Joint_name pivot, returns it
createPart(name, geo, mat, {position, rotation, scale, parent, pivot}) - AUTO-ADDS to parent!
NEVER: root.add(createPart(...)) // WRONG!
ALWAYS: createPart("Name", geo, mat, { parent: root }) // RIGHT!
+ rotation is DEGREES, not radians: [0,0,90] = quarter turn; [0,0,1.57] does nothing.
+ (Same for createInstance. Only direct THREE access like obj.rotation.z uses radians.)
boxGeo, sphereGeo, cylinderGeo, coneGeo, capsuleGeo, torusGeo, planeGeo
gameMaterial(0xcolor, {metalness, roughness, emissive, flatShading})
diff --git a/tools/registry.ts b/tools/registry.ts
index 261181a6..5821f694 100644
--- a/tools/registry.ts
+++ b/tools/registry.ts
@@ -113,6 +113,10 @@ export interface KilnRenderMetrics {
meshes?: number;
materials?: number;
bbox?: { min: number[]; max: number[]; size: number[] };
+ /** Mesh touching the lowest world point — ground-contact attribution. When
+ * bbox.min[1] dips below 0, this names the buried part so the agent can
+ * judge intent (earthworks/keels are fine; wheels/tails/missiles are not). */
+ lowestPart?: { name: string; y: number };
warnings: string[];
error?: string;
}
@@ -132,6 +136,7 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender
// realm than this module's THREE — `instanceof` would always be false).
let meshes = 0;
const materialSet = new Set<unknown>();
+ let lowestPart: KilnRenderMetrics['lowestPart'];
root.traverse((node: THREE.Object3D) => {
const n = node as { isMesh?: boolean; material?: unknown };
if (n.isMesh) {
@@ -142,6 +147,11 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender
} else if (mat) {
materialSet.add(mat);
}
+ // Ground-contact attribution: which mesh touches the lowest point.
+ const mb = new THREE.Box3().setFromObject(node);
+ if (!mb.isEmpty() && (!lowestPart || mb.min.y < lowestPart.y)) {
+ lowestPart = { name: node.name || '(unnamed mesh)', y: mb.min.y };
+ }
}
});
@@ -170,6 +180,7 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender
meshes,
materials: materialSet.size,
bbox,
+ lowestPart,
warnings,
};
} catch (err) {
@@ -256,7 +267,7 @@ export const kilnToolRegistry: KilnToolDef[] = [
{
name: 'kiln_render',
description:
- 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, and the world-space bounding box. Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',
+ 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, the world-space bounding box, and lowestPart (the mesh touching the lowest point — anything below Y=0 must be intentionally below-grade like earthworks or keels, never wheels/tails/equipment). Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',
inputSchema: renderInput,
run: async (input) => runRender(renderInput.parse(input)),
},
diff --git a/validation.ts b/validation.ts
index c9785343..79e7b877 100644
--- a/validation.ts
+++ b/validation.ts
@@ -313,6 +313,19 @@ export function validate(
}
}
+ // Rotation-units advisory: createPart/createInstance rotation is DEGREES,
+ // but models steeped in raw THREE habitually write radians — which silently
+ // flatten to ~0°. Caught live 2026-06-11 (AC-47 prop blades all vertical).
+ for (const smell of analyzeRotationUnits(ast, normalized)) {
+ warnings.push({
+ code: 'ROTATION_RADIANS_SUSPECTED',
+ message: `${smell.fn} rotation ${smell.rendered} looks like RADIANS — the rotation option is DEGREES${smell.suggestion ? `; did you mean ${smell.suggestion}?` : ''}`,
+ fixHint:
+ 'createPart/createInstance rotation is degrees ([0,0,90] = quarter turn). Convert: deg = rad * 180 / Math.PI. Direct THREE properties (obj.rotation.z) stay radians.',
+ line: smell.line,
+ });
+ }
+
return toResult(issues, warnings);
}
@@ -347,6 +360,159 @@ function lineOfIndex(code: string, idx: number): number {
return line;
}
+// -----------------------------------------------------------------------------
+// Rotation-units lint — createPart/createInstance rotation is DEGREES
+// -----------------------------------------------------------------------------
+
+interface RotationSmell {
+ fn: string;
+ /** The rotation array as written in source (truncated). */
+ rendered: string;
+ /** Degree equivalent, when the array is a pure numeric literal triple. */
+ suggestion?: string;
+ line?: number;
+}
+
+const ROTATION_OPTION_FNS = new Set(['createPart', 'createInstance']);
+
+/**
+ * Find `rotation: [...]` options on createPart/createInstance calls that look
+ * like radians. Two signals:
+ * - `Math.PI` anywhere in an element (unless the element divides by Math.PI —
+ * the `x * 180 / Math.PI` rad→deg conversion idiom, which IS degrees).
+ * - Pure numeric triples where every non-zero |v| < 6.3 and at least one is
+ * a non-integer: a degrees author writes 90 / 45 / -15 / 28.6, a radians
+ * author writes 0.3 / 0.785 / 1.57 / 4.49.
+ * Anything dynamic (identifiers, calls) stays quiet — warnings must not cry
+ * wolf on code the heuristic can't read.
+ */
+function analyzeRotationUnits(ast: acorn.Program, source: string): RotationSmell[] {
+ const smells: RotationSmell[] = [];
+ walk.simple(ast, {
+ CallExpression(node) {
+ if (node.callee.type !== 'Identifier' || !ROTATION_OPTION_FNS.has(node.callee.name)) return;
+ const fn = node.callee.name;
+ for (const arg of node.arguments) {
+ if (arg.type !== 'ObjectExpression') continue;
+ for (const prop of arg.properties) {
+ if (prop.type !== 'Property' || prop.computed) continue;
+ const key =
+ prop.key.type === 'Identifier'
+ ? prop.key.name
+ : prop.key.type === 'Literal'
+ ? String(prop.key.value)
+ : '';
+ if (key !== 'rotation' || prop.value.type !== 'ArrayExpression') continue;
+ const smell = classifyRotationArray(prop.value, fn, source);
+ if (smell) smells.push(smell);
+ }
+ }
+ },
+ });
+ return smells;
+}
+
+function classifyRotationArray(
+ arr: acorn.ArrayExpression,
+ fn: string,
+ source: string
+): RotationSmell | null {
+ const rendered = () => {
+ const text = source.slice(arr.start, arr.end).replace(/\s+/g, ' ');
+ return text.length > 64 ? `${text.slice(0, 61)}...` : text;
+ };
+
+ // Signal 1: Math.PI in any element = radians thinking, unless every PI use
+ // is the rad→deg conversion idiom (`... / Math.PI`).
+ let sawPI = false;
+ let onlyConversions = true;
+ for (const el of arr.elements) {
+ if (!el || el.type === 'SpreadElement') continue;
+ if (containsMathPI(el)) {
+ sawPI = true;
+ if (!dividesByMathPI(el)) onlyConversions = false;
+ }
+ }
+ if (sawPI) {
+ if (onlyConversions) return null;
+ return { fn, rendered: rendered(), line: arr.loc?.start.line };
+ }
+
+ // Signal 2: pure numeric literal triples with radian-scale magnitudes.
+ const nums: number[] = [];
+ for (const el of arr.elements) {
+ if (!el || el.type === 'SpreadElement') return null;
+ const n = literalNumber(el);
+ if (n === undefined) return null; // dynamic expression — stay quiet
+ nums.push(n);
+ }
+ const nonZero = nums.filter((n) => n !== 0);
+ if (nonZero.length === 0) return null;
+ if (!nonZero.every((n) => Math.abs(n) < 6.3)) return null;
+ if (!nonZero.some((n) => !Number.isInteger(n))) return null;
+ const deg = nums.map((n) => (n === 0 ? 0 : Math.round((n * 180) / Math.PI)));
+ return {
+ fn,
+ rendered: rendered(),
+ suggestion: `[${deg.join(', ')}]`,
+ line: arr.loc?.start.line,
+ };
+}
+
+/** Literal number, including the `-x` unary form. */
+function literalNumber(el: acorn.Expression): number | undefined {
+ if (el.type === 'Literal' && typeof el.value === 'number') return el.value;
+ if (el.type === 'UnaryExpression' && el.operator === '-') {
+ const inner = literalNumber(el.argument);
+ return inner === undefined ? undefined : -inner;
+ }
+ return undefined;
+}
+
+/** Deep scan for a `Math.PI` member expression anywhere in the subtree. */
+function containsMathPI(node: unknown): boolean {
+ if (!node || typeof node !== 'object') return false;
+ const n = node as Record<string, unknown> & { type?: string };
+ if (n.type === 'MemberExpression') {
+ const obj = n['object'] as { type?: string; name?: string } | undefined;
+ const prop = n['property'] as { type?: string; name?: string } | undefined;
+ if (
+ obj?.type === 'Identifier' &&
+ obj.name === 'Math' &&
+ prop?.type === 'Identifier' &&
+ prop.name === 'PI'
+ ) {
+ return true;
+ }
+ }
+ for (const key of Object.keys(n)) {
+ if (key === 'loc' || key === 'start' || key === 'end') continue;
+ const v = n[key];
+ if (Array.isArray(v)) {
+ for (const item of v) if (containsMathPI(item)) return true;
+ } else if (v && typeof v === 'object' && (v as { type?: string }).type) {
+ if (containsMathPI(v)) return true;
+ }
+ }
+ return false;
+}
+
+/** Is this expression a division whose divisor contains Math.PI (rad→deg)? */
+function dividesByMathPI(node: unknown): boolean {
+ if (!node || typeof node !== 'object') return false;
+ const n = node as {
+ type?: string;
+ operator?: string;
+ left?: unknown;
+ right?: unknown;
+ argument?: unknown;
+ };
+ if (n.type === 'BinaryExpression' && n.operator === '/' && containsMathPI(n.right)) return true;
+ if (n.type === 'BinaryExpression') return dividesByMathPI(n.left) || dividesByMathPI(n.right);
+ if (n.type === 'UnaryExpression') return dividesByMathPI(n.argument);
+ return false;
+}
+
// -----------------------------------------------------------------------------
// Top-level shape
// -----------------------------------------------------------------------------