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: GLB-derived bounds, rear-quarter grid arm, Gemini thinking knob, OR reasoning clamp, actionable QA-block errors (0.6.0)

Matt Kissinger50541a11de6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd626188..83b47c91 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,47 @@ for the consuming app's lockfile + tarball provenance, not public npm releases.
## [Unreleased]
+## [0.6.0] — 2026-07-12
+
+### Added
+- **`measureGlbBounds(bytes)` (H-41).** World-space AABB straight from stored GLB
+ bytes (WebIO + `getBounds`, EXT_mesh_gpu_instancing registered) so consumers that
+ only hold the artifact never need `executeKilnCode` to recover a footprint —
+ Kiln Studio's compose catalog drops its execute-model-code bbox fallback on this.
+- **Six-grid rear-quarter variant (H-33 arm).** `SIX_VIEWS_REAR_QUARTER` swaps the
+ 3/4 cell to the opposite-rear azimuth (`[-0.7, 0.5, -0.7]`, labeled `3/4 Rear`);
+ `resolveGridViews(variant)` + the `KILN_GRID_VARIANT=rear-quarter` env select it
+ as the `renderViewGrid` default per-process — no wire or tool-schema change.
+ Explicit `opts.views` always wins; unknown env values fall back to `SIX_VIEWS`.
+- **Gemini thinking + budget knob (H-43/B1).** The `google` provider now forwards
+ `KilnModelDescriptor.maxTokens` → `generationConfig.maxOutputTokens` and effort
+ keywords → `thinkingConfig.thinkingLevel` ('xhigh'/'max' collapse to 'high';
+ numbers ignored; the KILN_THINKING env stays Anthropic-only). A bare descriptor
+ still sends nothing — Gemini API defaults (65,536 output, dynamic thinking) are
+ preserved unless a consumer opts in. NOTE for consumers: registry rows that
+ carried a decorative Google `maxTokens` now BIND — set them to the intended
+ ceiling before upgrading.
+
+### Changed
+- **OpenRouter reasoning clamp (A7).** `resolveOpenRouterReasoning(thinking,
+ maxTokens?)` now bounds reasoning by the completion budget: numeric budgets cap
+ at 50% of `maxTokens` (dropped entirely when even the 1024 floor exceeds that
+ half), and 'high'/'xhigh' downgrade to 'medium' when OpenRouter's ~80%
+ translation would leave < 8,192 visible tokens (the cycle-2 step-1 MaxTokens
+ deaths: a 32K model at 'high' kept only ~6.4K for visible output). 64K/48K
+ configurations are untouched.
+- **QA-blocked render errors are actionable (H-40(3)).** `AssetQaBlockedError`'s
+ message now spells out each blocker's human message + authored `repairText`
+ (first 6, then a count) instead of bare rule codes — this string is exactly what
+ the agent reads when a mid-loop `kiln_render` is QA-blocked, and what the
+ salvage path records for QA-blocked step-cap programs.
+
+### Measured
+- **Per-render QA cost (H-40(4), `scripts/qa-cost-bench.ts`):** registry rules add
+ 1–10 ms p95 per render across all five category fixtures; Khronos validation
+ (unconditional, both modes) adds 1–4 ms p95. Two orders of magnitude under the
+ 1.5 s follow-up threshold — mid-loop QA stays on unconditionally.
+
## [0.4.0] — 2026-07-02
### Added
diff --git a/package.json b/package.json
index 04f672b4..f05fd0fa 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@kiln/engine",
"private": true,
- "version": "0.5.0",
+ "version": "0.6.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/scripts/qa-cost-bench.ts b/scripts/qa-cost-bench.ts
new file mode 100644
index 00000000..2599622b
--- /dev/null
+++ b/scripts/qa-cost-bench.ts
@@ -0,0 +1,204 @@
+/**
+ * H-40(4): per-render QA cost benchmark.
+ *
+ * Measures what the asset-quality program adds to EVERY mid-loop render
+ * (kiln_render runs the full renderSceneToGLB pipeline each call):
+ *
+ * 1. Registry-rule cost — renderGLB timed under KILN_QA_MODE=observe (all
+ * rules evaluate, nothing throws) vs KILN_QA_MODE=off (rules skipped).
+ * observe-vs-off isolates rule execution without throw-path asymmetry;
+ * enforce evaluates the identical rule set (only dispositions differ).
+ * 2. Khronos validation cost — validateFinalGlbBytes timed in isolation.
+ * NOTE: Khronos runs UNCONDITIONALLY in the render path (render.ts) —
+ * KILN_QA_MODE=off does NOT remove it, so it is measured separately.
+ *
+ * Decision rule (hardening plan A5): QA overhead > 1.5s p95 per render →
+ * file a follow-up to cache/skip Khronos on mid-loop renders; otherwise close
+ * H-40(4) as "measured, acceptable".
+ *
+ * Run: cd kiln && bun scripts/qa-cost-bench.ts
+ */
+import { performance } from 'node:perf_hooks';
+
+import { createAssetIntentV1, type AssetCategory } from '../src/contracts';
+import { renderGLB } from '../src/render';
+import { validateFinalGlbBytes } from '../src/qa/gltf';
+
+const ITERATIONS = 6;
+
+interface Fixture {
+ name: string;
+ category: AssetCategory;
+ code: string;
+}
+
+const FIXTURES: Fixture[] = [
+ {
+ name: 'chest',
+ category: 'prop',
+ code: `
+const meta = { name: 'BenchChest', category: 'prop' };
+function build() {
+ const root = createRoot('BenchChest');
+ createPart('Base', boxGeo(1, 0.4, 0.8), gameMaterial(0x8B4513), { position: [0, 0.2, 0], parent: root });
+ const lidPivot = createPivot('Lid', [0, 0.4, -0.35], root);
+ createPart('LidMesh', boxGeo(1, 0.15, 0.8), gameMaterial(0x8B4513), { position: [0, 0.075, 0.35], parent: lidPivot });
+ createPart('Lock', sphereGeo(0.05, 6, 4), gameMaterial(0xffcc00, { metalness: 0.8 }), { position: [0, 0.3, 0.4], parent: root });
+ return root;
+}
+`,
+ },
+ {
+ name: 'cart',
+ category: 'vehicle',
+ code: `
+const meta = { name: 'BenchCart', category: 'vehicle' };
+function build() {
+ const root = createRoot('BenchCart');
+ createPart('Body', boxGeo(1.6, 0.3, 0.9), gameMaterial(0x7B5B3A), { position: [0, 0.55, 0], parent: root });
+ const wheels = [[-0.55, -0.35], [-0.55, 0.35], [0.55, -0.35], [0.55, 0.35]];
+ for (let i = 0; i < wheels.length; i++) {
+ const [x, z] = wheels[i];
+ const pivot = createPivot('Joint_Wheel' + (i + 1), [x, 0.25, z], root);
+ createPart('Wheel' + (i + 1), cylinderGeo(0.25, 0.25, 0.12, 10), gameMaterial(0x333333), {
+ rotation: [90, 0, 0], parent: pivot,
+ });
+ }
+ return root;
+}
+`,
+ },
+ {
+ name: 'hut',
+ category: 'architecture',
+ code: `
+const meta = { name: 'BenchHut', category: 'architecture' };
+function build() {
+ const root = createRoot('BenchHut');
+ createPart('WallLeft', boxGeo(2, 1.6, 0.1), gameMaterial(0xB0A080), { position: [0, 0.8, -1], parent: root });
+ createPart('WallRight', boxGeo(2, 1.6, 0.1), gameMaterial(0xB0A080), { position: [0, 0.8, 1], parent: root });
+ createPart('WallBack', boxGeo(0.1, 1.6, 2), gameMaterial(0xB0A080), { position: [-1, 0.8, 0], parent: root });
+ createPart('WallFrontA', boxGeo(0.1, 1.6, 0.6), gameMaterial(0xB0A080), { position: [1, 0.8, -0.7], parent: root });
+ createPart('WallFrontB', boxGeo(0.1, 1.6, 0.6), gameMaterial(0xB0A080), { position: [1, 0.8, 0.7], parent: root });
+ createPart('Floor', boxGeo(2, 0.08, 2), gameMaterial(0x8a7a60), { position: [0, 0.04, 0], parent: root });
+ createPart('Roof', coneGeo(1.7, 0.9, 4), gameMaterial(0x6B3B2A), { position: [0, 2.05, 0], rotation: [0, 45, 0], parent: root });
+ return root;
+}
+`,
+ },
+ {
+ name: 'figure',
+ category: 'character',
+ code: `
+const meta = { name: 'BenchFigure', category: 'character' };
+function build() {
+ const root = createRoot('BenchFigure');
+ createPart('Torso', boxGeo(0.5, 0.7, 0.3), gameMaterial(0x4A6B8A), { position: [0, 1.05, 0], parent: root });
+ createPart('Head', sphereGeo(0.18, 8, 6), gameMaterial(0xD9B48F), { position: [0, 1.6, 0], parent: root });
+ const legL = createPivot('Joint_LegL', [0, 0.7, -0.15], root);
+ createPart('LegLMesh', boxGeo(0.22, 0.7, 0.18), gameMaterial(0x39424E), { position: [0, -0.35, 0], parent: legL });
+ const legR = createPivot('Joint_LegR', [0, 0.7, 0.15], root);
+ createPart('LegRMesh', boxGeo(0.22, 0.7, 0.18), gameMaterial(0x39424E), { position: [0, -0.35, 0], parent: legR });
+ const armL = createPivot('Joint_ArmL', [0, 1.32, -0.33], root);
+ createPart('ArmLMesh', boxGeo(0.18, 0.6, 0.14), gameMaterial(0x4A6B8A), { position: [0, -0.3, 0], parent: armL });
+ const armR = createPivot('Joint_ArmR', [0, 1.32, 0.33], root);
+ createPart('ArmRMesh', boxGeo(0.18, 0.6, 0.14), gameMaterial(0x4A6B8A), { position: [0, -0.3, 0], parent: armR });
+ return root;
+}
+`,
+ },
+ {
+ name: 'rocks',
+ category: 'environment',
+ code: `
+const meta = { name: 'BenchRocks', category: 'environment' };
+function build() {
+ const root = createRoot('BenchRocks');
+ createPart('RockA', sphereGeo(0.6, 7, 5), gameMaterial(0x777a70), { position: [0, 0.45, 0], parent: root });
+ createPart('RockB', sphereGeo(0.4, 6, 4), gameMaterial(0x6a6d64), { position: [0.8, 0.3, 0.3], parent: root });
+ createPart('RockC', sphereGeo(0.25, 6, 4), gameMaterial(0x82857b), { position: [-0.6, 0.2, -0.4], parent: root });
+ const trunk = createPart('Trunk', cylinderGeo(0.08, 0.1, 0.9, 6), gameMaterial(0x6B4A2F), { position: [-0.2, 0.45, 0.9], parent: root });
+ createPart('Canopy', coneGeo(0.5, 1.1, 7), gameMaterial(0x3F6B3A), { position: [-0.2, 1.4, 0.9], parent: root });
+ return root;
+}
+`,
+ },
+];
+
+function quantile(sorted: number[], q: number): number {
+ if (sorted.length === 0) return Number.NaN;
+ const pos = (sorted.length - 1) * q;
+ const lo = Math.floor(pos);
+ const hi = Math.ceil(pos);
+ return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (pos - lo);
+}
+
+async function timeRender(fixture: Fixture, iterations: number): Promise<number[]> {
+ const intent = createAssetIntentV1({ category: fixture.category });
+ const samples: number[] = [];
+ for (let i = 0; i < iterations; i++) {
+ const t0 = performance.now();
+ await renderGLB(fixture.code, { intent });
+ samples.push(performance.now() - t0);
+ }
+ return samples.sort((a, b) => a - b);
+}
+
+async function main(): Promise<void> {
+ const rows: string[] = [];
+ rows.push(
+ '| fixture | category | observe p50/p95 (ms) | off p50/p95 (ms) | rule cost p50/p95 (ms) | khronos p50/p95 (ms) |',
+ );
+ rows.push('|---|---|---|---|---|---|');
+
+ for (const fixture of FIXTURES) {
+ const intent = createAssetIntentV1({ category: fixture.category });
+
+ // Warm-up + fixture sanity: the program must complete under observe.
+ process.env['KILN_QA_MODE'] = 'observe';
+ let bytes: Uint8Array;
+ try {
+ const warm = await renderGLB(fixture.code, { intent });
+ bytes = warm.glb;
+ } catch (err) {
+ console.error(
+ `fixture ${fixture.name} (${fixture.category}) failed to render: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ rows.push(`| ${fixture.name} | ${fixture.category} | RENDER FAILED | — | — | — |`);
+ continue;
+ }
+
+ process.env['KILN_QA_MODE'] = 'observe';
+ const observe = await timeRender(fixture, ITERATIONS);
+ process.env['KILN_QA_MODE'] = 'off';
+ await timeRender(fixture, 1); // warm the off path
+ const off = await timeRender(fixture, ITERATIONS);
+ delete process.env['KILN_QA_MODE'];
+
+ // Isolated Khronos cost (runs unconditionally in the render path).
+ const khronos: number[] = [];
+ await validateFinalGlbBytes(bytes); // warm the WASM validator
+ for (let i = 0; i < ITERATIONS; i++) {
+ const t0 = performance.now();
+ await validateFinalGlbBytes(bytes);
+ khronos.push(performance.now() - t0);
+ }
+ khronos.sort((a, b) => a - b);
+
+ const fmt = (samples: number[]) =>
+ `${quantile(samples, 0.5).toFixed(0)} / ${quantile(samples, 0.95).toFixed(0)}`;
+ const ruleCostP50 = quantile(observe, 0.5) - quantile(off, 0.5);
+ const ruleCostP95 = quantile(observe, 0.95) - quantile(off, 0.95);
+ rows.push(
+ `| ${fixture.name} | ${fixture.category} | ${fmt(observe)} | ${fmt(off)} | ${ruleCostP50.toFixed(0)} / ${ruleCostP95.toFixed(0)} | ${fmt(khronos)} |`,
+ );
+ }
+
+ console.log(`\nQA cost benchmark — ${ITERATIONS} iterations/arm, bun ${Bun.version}\n`);
+ console.log(rows.join('\n'));
+ console.log(
+ '\nrule cost = observe − off (registry rules only); khronos runs unconditionally in BOTH modes.',
+ );
+}
+
+await main();
diff --git a/src/__tests__/glb-bounds.test.ts b/src/__tests__/glb-bounds.test.ts
new file mode 100644
index 00000000..8539c184
--- /dev/null
+++ b/src/__tests__/glb-bounds.test.ts
@@ -0,0 +1,54 @@
+/**
+ * H-41: `measureGlbBounds` recovers the same world AABB from stored GLB bytes
+ * that `executeKilnCode` + `measureBounds` computes from the live scene — the
+ * equivalence Kiln Studio's compose catalog relies on to drop its
+ * execute-model-code bbox fallback.
+ */
+import { describe, expect, test } from 'bun:test';
+
+import { createAssetIntentV1 } from '../contracts';
+import { executeKilnCode, measureGlbBounds, renderGLB } from '../render';
+import { measureBounds } from '../views';
+
+const OFFSET_CODE = `
+const meta = { name: 'BoundsProbe', category: 'prop' };
+function build() {
+ const root = createRoot('BoundsProbe');
+ createPart('Body', boxGeo(2, 1, 0.5), gameMaterial(0x8B4513), { position: [0.5, 0.5, -0.25], parent: root });
+ const pivot = createPivot('Joint_Arm', [1, 1, 0], root);
+ createPart('Arm', boxGeo(0.2, 1.2, 0.2), gameMaterial(0x445566), { position: [0, 0.6, 0], parent: pivot });
+ return root;
+}
+`;
+
+describe('measureGlbBounds', () => {
+ test('matches the live-scene bounds for a rendered program', async () => {
+ const intent = createAssetIntentV1({ category: 'prop' });
+ const rendered = await renderGLB(OFFSET_CODE, { intent });
+ const fromBytes = await measureGlbBounds(rendered.glb);
+ expect(fromBytes).toBeDefined();
+
+ const { root } = await executeKilnCode(OFFSET_CODE);
+ const live = measureBounds(root);
+ for (let axis = 0; axis < 3; axis++) {
+ expect(fromBytes!.min[axis]!).toBeCloseTo(live.min[axis]!, 4);
+ expect(fromBytes!.max[axis]!).toBeCloseTo(live.max[axis]!, 4);
+ }
+ });
+
+ test('returns undefined for bytes with no measurable geometry', async () => {
+ const intent = createAssetIntentV1({ category: 'prop' });
+ // Render something valid, then strip it to an empty document via a re-read
+ // is overkill — an asset whose only node is empty is not producible through
+ // renderGLB (QA blocks it), so probe the guard directly with a minimal
+ // valid-but-empty GLB written by gltf-transform.
+ const { Document, WebIO } = await import('@gltf-transform/core');
+ const doc = new Document();
+ doc.createScene('Empty');
+ const bytes = await new WebIO().writeBinary(doc);
+ expect(await measureGlbBounds(bytes)).toBeUndefined();
+ // And the happy path still stands on the same IO round-trip.
+ const rendered = await renderGLB(OFFSET_CODE, { intent });
+ expect(await measureGlbBounds(rendered.glb)).toBeDefined();
+ });
+});
diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.ts
index e7605bd8..470dd042 100644
--- a/src/agent/providers.test.ts
+++ b/src/agent/providers.test.ts
@@ -175,6 +175,30 @@ describe('makeKilnModel', () => {
expect(resolveOpenRouterReasoning('ultra')).toBeUndefined();
});
+ test('A7 clamp: numeric budgets cap at 50% of the completion budget', () => {
+ // reasoning == completion budget would guarantee zero visible text.
+ expect(resolveOpenRouterReasoning(32000, 32000)).toEqual({ max_tokens: 16000 });
+ // Already under half: untouched.
+ expect(resolveOpenRouterReasoning(8000, 64000)).toEqual({ max_tokens: 8000 });
+ // Completion budget too small to host even the 1024 floor at ≤50%: off.
+ expect(resolveOpenRouterReasoning(4096, 1500)).toBeUndefined();
+ // No completion budget known: legacy pass-through.
+ expect(resolveOpenRouterReasoning(32000)).toEqual({ max_tokens: 32000 });
+ });
+
+ test("A7 clamp: high/xhigh downgrade to medium when OpenRouter's ~80% translation would starve visible output", () => {
+ // The cycle-2 step-1 deaths: Sonnet 4.6 twin at 32K + 'high' → ~6.4K visible.
+ expect(resolveOpenRouterReasoning('high', 32000)).toEqual({ effort: 'medium' });
+ expect(resolveOpenRouterReasoning('xhigh', 16000)).toEqual({ effort: 'medium' });
+ // The 64K/48K twins keep 'high' (visible remainder ≥ 8192) — the live
+ // config that put Fable 5 / Sonnet 5 in the #1 tie group stays untouched.
+ expect(resolveOpenRouterReasoning('high', 64000)).toEqual({ effort: 'high' });
+ expect(resolveOpenRouterReasoning('high', 48000)).toEqual({ effort: 'high' });
+ // medium/low are never rewritten.
+ expect(resolveOpenRouterReasoning('medium', 16000)).toEqual({ effort: 'medium' });
+ expect(resolveOpenRouterReasoning('low', 16000)).toEqual({ effort: 'low' });
+ });
+
test('an OpenRouter-hosted Claude with thinking still constructs the Vercel bridge', () => {
const m = makeKilnModel({
provider: 'openrouter',
@@ -200,6 +224,45 @@ describe('makeKilnModel', () => {
);
});
+ describe('google thinking + budget (B1/H-43)', () => {
+ const getCfg = (m: unknown): Record<string, unknown> =>
+ (m as { getConfig(): Record<string, unknown> }).getConfig();
+
+ test('descriptor maxTokens + thinking flow into the Gemini generationConfig params', () => {
+ const cfg = getCfg(
+ makeKilnModel({
+ provider: 'google',
+ model: 'gemini-3.5-flash',
+ maxTokens: 65536,
+ thinking: 'high',
+ }),
+ );
+ expect(cfg['params']).toEqual({
+ maxOutputTokens: 65536,
+ thinkingConfig: { thinkingLevel: 'high' },
+ });
+ });
+
+ test('a bare descriptor sends no params — the pre-knob API-default behavior', () => {
+ const cfg = getCfg(makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }));
+ expect(cfg['params']).toBeUndefined();
+ });
+
+ test('xhigh/max collapse to high; numbers and unknown keywords are ignored', () => {
+ const level = (thinking: string | number) =>
+ (
+ getCfg(makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash', thinking }))[
+ 'params'
+ ] as { thinkingConfig?: { thinkingLevel?: string } } | undefined
+ )?.thinkingConfig?.thinkingLevel;
+ expect(level('xhigh')).toBe('high');
+ expect(level('max')).toBe('high');
+ expect(level('medium')).toBe('medium');
+ expect(level(8000)).toBeUndefined();
+ expect(level('ultra')).toBeUndefined();
+ });
+ });
+
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 e561b4cd..49733ecb 100644
--- a/src/agent/providers.ts
+++ b/src/agent/providers.ts
@@ -31,6 +31,17 @@ export type OpenRouterReasoning =
const OPENROUTER_EFFORTS = new Set(['xhigh', 'high', 'medium', 'low', 'minimal', 'none']);
+/**
+ * OpenRouter's documented effort→budget translation for budget-based upstreams
+ * (Anthropic et al.): xhigh/high ≈ 80% of max_tokens, medium ≈ 50%, low ≈ 20%.
+ * At 80%, a 32K-budget model keeps only ~6.4K visible tokens per turn — below
+ * what a first-turn Kiln program needs, which is how the cycle-2 OR twins died
+ * at step 1 with "maximum token limit, unrecoverable" (2026-07-11 postmortem).
+ * When the visible remainder under 'high' would fall below this floor, the
+ * effort is downgraded to 'medium' (reasoning ≤ 50% of the completion budget).
+ */
+const MIN_VISIBLE_OUTPUT_TOKENS = 8192;
+
/**
* Map the Kiln descriptor `thinking` control onto OpenRouter's reasoning setting.
* Keywords pass through ('max' — an Anthropic-vocabulary level OpenRouter's type
@@ -39,19 +50,44 @@ const OPENROUTER_EFFORTS = new Set(['xhigh', 'high', 'medium', 'low', 'minimal',
* or an unknown keyword → undefined (send nothing; the OpenRouter/upstream
* default applies — which for Claude Opus 4.8 means reasoning OFF, same as the
* native path).
+ *
+ * When `maxTokens` (the completion budget) is known, reasoning is clamped so it
+ * can never consume the whole turn: numeric budgets cap at 50% of maxTokens
+ * (or are dropped entirely when even the 1024 floor would exceed that half),
+ * and 'xhigh'/'high' downgrade to 'medium' when OpenRouter's ~80% translation
+ * would leave fewer than {@link MIN_VISIBLE_OUTPUT_TOKENS} visible tokens.
*/
export function resolveOpenRouterReasoning(
thinking?: string | number,
+ maxTokens?: number,
): OpenRouterReasoning | undefined {
if (thinking == null || thinking === '' || thinking === 0) return undefined;
+ const halfBudget =
+ maxTokens != null && Number.isFinite(maxTokens) && maxTokens > 0
+ ? Math.floor(maxTokens / 2)
+ : undefined;
if (typeof thinking === 'number') {
if (!Number.isFinite(thinking) || thinking <= 0) return undefined;
- return { max_tokens: Math.max(1024, Math.floor(thinking)) };
+ const budget = Math.max(1024, Math.floor(thinking));
+ if (halfBudget === undefined) return { max_tokens: budget };
+ // A completion budget too small to host even the 1024 reasoning floor at
+ // ≤50% means reasoning off beats a guaranteed truncated turn.
+ if (halfBudget < 1024) return undefined;
+ return { max_tokens: Math.min(budget, halfBudget) };
}
const raw = thinking.trim().toLowerCase();
- if (/^\d+$/.test(raw)) return resolveOpenRouterReasoning(Number.parseInt(raw, 10));
- const effort = raw === 'max' ? 'xhigh' : raw;
+ if (/^\d+$/.test(raw)) return resolveOpenRouterReasoning(Number.parseInt(raw, 10), maxTokens);
+ let effort = raw === 'max' ? 'xhigh' : raw;
if (!OPENROUTER_EFFORTS.has(effort)) return undefined;
+ if (
+ (effort === 'xhigh' || effort === 'high') &&
+ maxTokens != null &&
+ Number.isFinite(maxTokens) &&
+ maxTokens > 0 &&
+ maxTokens * 0.2 < MIN_VISIBLE_OUTPUT_TOKENS
+ ) {
+ effort = 'medium';
+ }
return { effort: effort as Extract<OpenRouterReasoning, { effort: string }>['effort'] };
}
@@ -109,13 +145,17 @@ export interface KilnModelDescriptor {
provider: KilnAgentProvider;
/** Concrete model id passed to the underlying SDK (e.g. 'gemini-3.5-flash'). */
model: string;
- /** Output-token budget; applied to anthropic/openai/bedrock (GoogleModel uses its own default). */
+ /** Output-token budget; applied to anthropic/openai/bedrock/google (Gemini's
+ * API default is 65,536 — omit to keep it) and to openrouter (where it also
+ * bounds the reasoning clamp in {@link resolveOpenRouterReasoning}). */
maxTokens?: number;
/**
* Reasoning/thinking control. Honored by the `anthropic` provider (shapes
- * below) and by `openrouter` (mapped onto OpenRouter's unified `reasoning`
+ * below), by `openrouter` (mapped onto OpenRouter's unified `reasoning`
* setting via {@link resolveOpenRouterReasoning} — so OpenRouter-hosted Claude
- * twins behave like the native transport). Other providers ignore it.
+ * twins behave like the native transport), and by `google` (effort keywords
+ * map to Gemini `thinkingConfig.thinkingLevel`; numbers are ignored). Other
+ * providers ignore it.
*
* - Effort keyword (`'low' | 'medium' | 'high'`, passed through verbatim) →
* `thinking: {type:'adaptive'}` + `output_config: {effort}` — the
@@ -171,6 +211,24 @@ function isAnthropicAdaptiveOnlyModel(model: string): boolean {
return /^claude-(sonnet-5|fable-5|mythos-5|opus-4-[78])(?:-|$)/.test(model);
}
+/**
+ * Map the descriptor `thinking` control onto Gemini's `thinkingConfig.thinkingLevel`
+ * vocabulary ('low' | 'medium' | 'high'). 'xhigh'/'max' collapse to 'high';
+ * numbers and unknown keywords → undefined (send nothing — Gemini's dynamic
+ * thinking default applies, which is what every Google row ran before this knob
+ * existed). Deliberately does NOT read KILN_THINKING: that env is Anthropic
+ * vocabulary and history — only an explicit per-model config reaches Gemini.
+ */
+function resolveGoogleThinkingLevel(
+ fromDesc?: string | number,
+): 'low' | 'medium' | 'high' | undefined {
+ if (fromDesc == null || typeof fromDesc === 'number') return undefined;
+ const raw = fromDesc.trim().toLowerCase();
+ if (raw === 'xhigh' || raw === 'max') return 'high';
+ if (raw === 'low' || raw === 'medium' || raw === 'high') return raw;
+ return undefined;
+}
+
function resolveAnthropicThinking(
model: string,
fromDesc?: string | number,
@@ -227,11 +285,22 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
...(maxTokens != null ? { maxTokens } : {}),
});
- case 'google':
+ case 'google': {
+ // H-43/B1: forward the descriptor budget + thinking level into the Gemini
+ // generationConfig (GoogleModel spreads `params` into the request config).
+ // Only descriptor-explicit thinking applies — the KILN_THINKING env stays
+ // Anthropic-only so a global env flip can't perturb Gemini defaults.
+ const thinkingLevel = resolveGoogleThinkingLevel(desc.thinking);
+ const googleParams = {
+ ...(maxTokens != null ? { maxOutputTokens: maxTokens } : {}),
+ ...(thinkingLevel ? { thinkingConfig: { thinkingLevel } } : {}),
+ };
return new GoogleModel({
modelId: desc.model,
apiKey: opts.apiKey ?? trimmedEnv('GEMINI_API_KEY'),
+ ...(Object.keys(googleParams).length > 0 ? { params: googleParams } : {}),
});
+ }
case 'bedrock':
return new BedrockModel({
modelId: desc.model,
@@ -260,8 +329,10 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
// The same descriptor `thinking` control the anthropic case honors, mapped
// onto OpenRouter's unified reasoning setting — so an OpenRouter-hosted
// Claude (e.g. anthropic/claude-opus-4.8) gets its thinking turned on just
- // like the native transport would.
- const reasoning = resolveOpenRouterReasoning(desc.thinking);
+ // like the native transport would. maxTokens rides along so reasoning can
+ // never start with a budget ≥ the completion budget (the cycle-2 step-1
+ // MaxTokens deaths).
+ const reasoning = resolveOpenRouterReasoning(desc.thinking, maxTokens);
return makeOpenRouterModel({
modelId: desc.model,
...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
diff --git a/src/qa/policy-env.test.ts b/src/qa/policy-env.test.ts
index 79304e72..90ef0e7d 100644
--- a/src/qa/policy-env.test.ts
+++ b/src/qa/policy-env.test.ts
@@ -59,6 +59,24 @@ describe('KILN_QA_MODE render-path integration', () => {
await expect(renderGLB(ZERO_SCALE_CODE, { intent })).rejects.toThrow(AssetQaBlockedError);
});
+ test('H-40(3): the blocked-render message carries the finding message + authored repairText', async () => {
+ // This message is exactly what the agent reads mid-loop (kiln_render returns
+ // { ok:false, error: err.message }) — bare rule codes would leave the model
+ // guessing what to fix.
+ delete process.env['KILN_QA_MODE'];
+ const intent = createAssetIntentV1({ category: 'prop' });
+ const err = await renderGLB(ZERO_SCALE_CODE, { intent }).then(
+ () => undefined,
+ (e: unknown) => e,
+ );
+ expect(err).toBeInstanceOf(AssetQaBlockedError);
+ const message = (err as AssetQaBlockedError).message;
+ expect(message).toMatch(/Asset QA blocked/);
+ expect(message).toContain('UNIVERSAL_ZERO_SCALE_RENDERABLE');
+ expect(message).toContain('has zero scale');
+ expect(message).toContain('FIX: Use a finite non-zero scale');
+ });
+
test('the same program completes under KILN_QA_MODE=observe', async () => {
process.env['KILN_QA_MODE'] = 'observe';
const intent = createAssetIntentV1({ category: 'prop' });
diff --git a/src/qa/run.ts b/src/qa/run.ts
index c3829a63..03bcef9c 100644
--- a/src/qa/run.ts
+++ b/src/qa/run.ts
@@ -210,6 +210,9 @@ export function qaBlockingEnabled(env: Record<string, string | undefined> = proc
return mode !== 'observe' && mode !== 'off';
}
+/** Blockers spelled out in full per message; the rest collapse to a count. */
+const MAX_DETAILED_BLOCKERS = 6;
+
export class AssetQaBlockedError extends Error {
readonly report: AssetQaReportV1;
readonly stage: 'scene' | 'final-glb';
@@ -223,9 +226,21 @@ export class AssetQaBlockedError extends Error {
const blockers = Object.values(report.dimensions)
.flatMap((dimension) => dimension.findings)
.filter((finding) => finding.disposition === 'block');
- super(
- `Asset QA blocked at ${stage}: ${blockers.map((finding) => finding.code).join(', ') || 'unknown blocker'}`,
- );
+ // H-40(3): this message IS what the agent reads when a mid-loop render is
+ // QA-blocked (kiln_render catches and returns { ok:false, error: message }),
+ // so each blocker carries its human message + authored repairText — bare
+ // rule codes give the model nothing to act on.
+ const detailed = blockers
+ .slice(0, MAX_DETAILED_BLOCKERS)
+ .map(
+ (finding) =>
+ `${finding.code}: ${finding.message}${finding.repairText ? ` FIX: ${finding.repairText}` : ''}`,
+ );
+ const overflow =
+ blockers.length > MAX_DETAILED_BLOCKERS
+ ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)`
+ : '';
+ super(`Asset QA blocked at ${stage}: ${detailed.join(' | ') || 'unknown blocker'}${overflow}`);
this.name = 'AssetQaBlockedError';
this.report = report;
this.stage = stage;
diff --git a/src/render.ts b/src/render.ts
index 506239bb..0b81fdca 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -11,7 +11,7 @@
*/
import * as THREE from 'three';
-import { Document, WebIO } from '@gltf-transform/core';
+import { Document, WebIO, getBounds } from '@gltf-transform/core';
import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';
import {
dedup,
@@ -103,6 +103,32 @@ export type CapturedDiagnosticV1 = CharacterCapturedDiagnosticV1 | VehicleCaptur
* travels on the Document). */
const engineIO = (): WebIO => new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+/**
+ * World-space AABB of a stored GLB, computed from its bytes alone — node
+ * transforms applied over the (spec-required) POSITION accessor bounds. No
+ * model-authored code is executed: this exists so consumers that only hold the
+ * artifact (e.g. Kiln Studio's compose catalog fallback, H-41) never need
+ * `executeKilnCode` to recover a footprint. Caveat: EXT_mesh_gpu_instancing
+ * copies are not expanded (the batch node contributes its single-copy bounds);
+ * records new enough to be instanced also persist `metrics.bbox`, so the
+ * from-bytes path is a legacy-record fallback. Returns undefined for a GLB with
+ * no measurable geometry.
+ */
+export async function measureGlbBounds(
+ bytes: Uint8Array,
+): Promise<{ min: [number, number, number]; max: [number, number, number] } | undefined> {
+ const doc = await engineIO().readBinary(bytes);
+ const root = doc.getRoot();
+ const scene = root.getDefaultScene() ?? root.listScenes()[0];
+ if (!scene) return undefined;
+ const { min, max } = getBounds(scene);
+ if (!min.every(Number.isFinite) || !max.every(Number.isFinite)) return undefined;
+ return {
+ min: [min[0]!, min[1]!, min[2]!],
+ max: [max[0]!, max[1]!, max[2]!],
+ };
+}
+
// Gltf-transform type aliases for local readability.
type GtNode = import('@gltf-transform/core').Node;
type GtMesh = import('@gltf-transform/core').Mesh;
diff --git a/src/views/__tests__/views.test.ts b/src/views/__tests__/views.test.ts
index 02c3bcd9..d7c7e23d 100644
--- a/src/views/__tests__/views.test.ts
+++ b/src/views/__tests__/views.test.ts
@@ -172,6 +172,27 @@ describe('renderViewGrid / renderCodeViewGrid', () => {
expect(result.png.length).toBeGreaterThan(100);
});
+ test('H-33: KILN_GRID_VARIANT=rear-quarter swaps the 3/4 cell; unknown values are ignored', async () => {
+ const saved = process.env['KILN_GRID_VARIANT'];
+ try {
+ process.env['KILN_GRID_VARIANT'] = 'rear-quarter';
+ const rear = await renderCodeViewGrid(BOX_CODE, { size: 32 });
+ expect(rear.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4 Rear']);
+
+ process.env['KILN_GRID_VARIANT'] = 'not-a-variant';
+ const fallback = await renderCodeViewGrid(BOX_CODE, { size: 32 });
+ expect(fallback.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+
+ // Explicit opts.views always wins over the env.
+ process.env['KILN_GRID_VARIANT'] = 'rear-quarter';
+ const explicit = await renderCodeViewGrid(BOX_CODE, { size: 32, views: SIX_VIEWS });
+ expect(explicit.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+ } finally {
+ if (saved === undefined) delete process.env['KILN_GRID_VARIANT'];
+ else process.env['KILN_GRID_VARIANT'] = saved;
+ }
+ });
+
test('snapSceneToPalette applies the general render palette before CPU previews', async () => {
const { root } = await executeKilnCode(DARK_FOLIAGE_CODE);
const snap = snapSceneToPalette(root, paletteToSnapSlots(GENERAL_RENDER_PALETTE));
diff --git a/src/views/index.ts b/src/views/index.ts
index 052de651..d3ebc2fc 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -17,7 +17,7 @@ import {
rasterizeView,
measureBounds,
hideNodeInScene,
- SIX_VIEWS,
+ resolveGridViews,
type RasterOptions,
type ViewSpec,
} from './raster';
@@ -40,8 +40,16 @@ import {
type Vec3,
} from '../palette-snap';
-export { rasterizeView, measureBounds, hideNodeInScene, SIX_VIEWS, coverage } from './raster';
-export type { RasterOptions, ViewSpec } from './raster';
+export {
+ rasterizeView,
+ measureBounds,
+ hideNodeInScene,
+ SIX_VIEWS,
+ SIX_VIEWS_REAR_QUARTER,
+ resolveGridViews,
+ coverage,
+} from './raster';
+export type { RasterOptions, ViewSpec, ViewGridVariant } from './raster';
export { encodePng } from './png';
export {
ARCHITECTURE_ROOF_ROLE_PREFIXES,
@@ -316,7 +324,11 @@ export async function renderViewGrid(
// marginal legibility gain at typical asset scales. Candidate thumbnails
// downscale separately (Studio thumbnailFor), unaffected.
const size = opts.size ?? 384;
- const views = opts.views ?? SIX_VIEWS;
+ // H-33: the default view set is env-selectable (KILN_GRID_VARIANT=rear-quarter
+ // swaps the 3/4 cell to the opposite-rear azimuth) so a bench arm can flip the
+ // grid per-process without any wire or tool-schema change. Explicit opts.views
+ // always wins; unset/unknown env keeps SIX_VIEWS.
+ const views = opts.views ?? resolveGridViews(process.env['KILN_GRID_VARIANT']);
if (opts.snapPalette?.length) snapSceneToPalette(root, opts.snapPalette);
const cols = 3;
const rows = Math.ceil(views.length / cols);
diff --git a/src/views/raster.ts b/src/views/raster.ts
index 62bb802b..8aa60eaa 100644
--- a/src/views/raster.ts
+++ b/src/views/raster.ts
@@ -36,6 +36,28 @@ export const SIX_VIEWS: ViewSpec[] = [
{ name: '3/4', dir: [0.7, 0.5, 0.7] },
];
+/**
+ * H-33 arm: the same grid with the single 3/4 swapped to the opposite-rear
+ * azimuth, so features the front-quarter cell always occludes (rear fascia,
+ * tail geometry, the back of a spoiler) get one perspective cell.
+ */
+export const SIX_VIEWS_REAR_QUARTER: ViewSpec[] = [
+ ...SIX_VIEWS.slice(0, 5),
+ { name: '3/4 Rear', dir: [-0.7, 0.5, -0.7] },
+];
+
+/** Named six-view grid variants (H-33). 'default' keeps the shipped front-quarter grid. */
+export type ViewGridVariant = 'default' | 'rear-quarter';
+
+/**
+ * Resolve a grid-variant name (typically the `KILN_GRID_VARIANT` env) to its
+ * view set. Unknown / unset names fall back to {@link SIX_VIEWS} so a stale or
+ * mistyped env can never change what the agent sees.
+ */
+export function resolveGridViews(variant?: string): ViewSpec[] {
+ return variant?.trim().toLowerCase() === 'rear-quarter' ? SIX_VIEWS_REAR_QUARTER : SIX_VIEWS;
+}
+
export interface RasterOptions {
/** Square output size in pixels per view. Default 256. */
size?: number;