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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(kiln-bench): model-agnostic Kiln text-to-3D benchmark + Strands agent fold into core
Matt Kissinger6a656307267e
diff --git a/agent/hooks.ts b/agent/hooks.tsnew file mode 100644index 00000000..36609a2a--- /dev/null+++ b/agent/hooks.ts@@ -0,0 +1,76 @@+/**+ * Agent-loop metrics via Strands lifecycle hooks.+ *+ * A `MetricsCollector` attaches to an Agent and records:+ * - toolCalls[] — every tool the model called, in order (BeforeToolCallEvent)+ * - steps — number of model calls (AfterModelCallEvent count)+ * - usage — best-effort token usage, filled from the AgentResult after+ * invoke via `recordResultUsage()` (hook events carry no usage)+ *+ * Usage: construct, `attach(agent)`, run `agent.invoke(...)`, call+ * `recordResultUsage(result.metrics?.latestAgentInvocation?.usage)`, read+ * `readMetrics()`, then `detach()`.+ */+import { type Agent, BeforeToolCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';++/** Token-usage subset we surface. */+export interface AgentUsage {+ inputTokens?: number;+ outputTokens?: number;+}++/** The agent-loop-derived metrics this collector produces. */+export interface CollectedMetrics {+ toolCalls: string[];+ steps: number;+ usage?: AgentUsage;+}++export class MetricsCollector {+ private readonly toolCalls: string[] = [];+ private steps = 0;+ private usage: AgentUsage | undefined;+ private cleanups: Array<() => void> = [];++ /** Attach hooks; returns a cleanup function (also tracked for `detach()`). */+ attach(agent: Agent): () => void {+ const offTool = agent.addHook(BeforeToolCallEvent, (event) => {+ this.toolCalls.push(event.toolUse.name);+ });+ const offModel = agent.addHook(AfterModelCallEvent, () => {+ this.steps += 1;+ });+ this.cleanups.push(offTool, offModel);+ return () => this.detach();+ }++ /** Remove all attached hooks. Idempotent. */+ detach(): void {+ for (const off of this.cleanups) {+ try {+ off();+ } catch {+ // best-effort cleanup+ }+ }+ this.cleanups = [];+ }++ /** Record token usage from the AgentResult after invoke completes. */+ recordResultUsage(usage: AgentUsage | undefined): void {+ if (!usage) return;+ const next: AgentUsage = {};+ if (typeof usage.inputTokens === 'number') next.inputTokens = usage.inputTokens;+ if (typeof usage.outputTokens === 'number') next.outputTokens = usage.outputTokens;+ if (next.inputTokens !== undefined || next.outputTokens !== undefined) this.usage = next;+ }++ /** Read the collected metrics (a fresh copy each call). */+ readMetrics(): CollectedMetrics {+ return {+ toolCalls: [...this.toolCalls],+ steps: this.steps,+ ...(this.usage ? { usage: { ...this.usage } } : {}),+ };+ }+}diff --git a/agent/index.ts b/agent/index.tsnew file mode 100644index 00000000..0e9c4e36--- /dev/null+++ b/agent/index.ts@@ -0,0 +1,28 @@+/**+ * `@pixel-forge/core/kiln/agent` — the agnostic, tool-driven Kiln codegen+ * foundation (validated in packages/kiln-bench, folded into core 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.+ *+ * - {@link runKilnAgent} — drive any Strands Model through the kiln tool loop+ * - {@link makeKilnTools} — in-process tool skin over the shared registry+ * - {@link ensureStreamStart} — the OpenRouter/Vercel-bridge stream fix+ * - {@link makeOpenRouterModel} — build an OpenRouter Strands model with the fix+ * - {@link MetricsCollector} — per-loop tool/step/usage metrics via hooks+ */+export { runKilnAgent } from './run';+export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow } from './run';++export { makeKilnTools, KILN_SUBMIT_TOOL_NAME } from './tools';+export type { SubmitSink } from './tools';++export { ensureStreamStart } from './stream-start';++export { makeOpenRouterModel } from './providers';+export type { OpenRouterModelOptions } from './providers';++export { MetricsCollector } from './hooks';+export type { CollectedMetrics, AgentUsage } from './hooks';diff --git a/agent/providers.ts b/agent/providers.tsnew file mode 100644index 00000000..cbf1b086--- /dev/null+++ b/agent/providers.ts@@ -0,0 +1,38 @@+/**+ * Model construction helpers for the agnostic Kiln agent.+ *+ * Native Strands providers (Anthropic/OpenAI/Google/Bedrock) are constructed by+ * the caller directly from `@strands-agents/sdk/models/*`. OpenRouter has no+ * native Strands provider, so we reach it through the Vercel AI SDK bridge+ * (`VercelModel`) wrapping a `LanguageModelV3` from `@openrouter/ai-sdk-provider`+ * — with {@link ensureStreamStart} restoring the spec-required leading+ * `stream-start` part the OpenRouter provider omits (see stream-start.ts).+ */+import { VercelModel } from '@strands-agents/sdk/models/vercel';+import type { Model } from '@strands-agents/sdk';+import { createOpenRouter } from '@openrouter/ai-sdk-provider';+import type { LanguageModelV3 } from '@ai-sdk/provider';++import { ensureStreamStart } from './stream-start';++export interface OpenRouterModelOptions {+ /** OpenRouter model id, e.g. 'x-ai/grok-4.3'. */+ modelId: string;+ /** API key. Falls back to OPENROUTER_API_KEY. */+ apiKey?: string;+ /** Max output tokens. */+ maxTokens?: number;+}++/**+ * Build a Strands `Model` for an OpenRouter model id, with the stream-start fix+ * applied so the Strands agent loop completes correctly.+ */+export function makeOpenRouterModel(opts: OpenRouterModelOptions): Model {+ const openrouter = createOpenRouter({ apiKey: opts.apiKey ?? process.env['OPENROUTER_API_KEY'] });+ const provider = ensureStreamStart(openrouter.chat(opts.modelId) as LanguageModelV3);+ return new VercelModel({+ provider,+ ...(opts.maxTokens != null ? { maxTokens: opts.maxTokens } : {}),+ });+}diff --git a/agent/run.ts b/agent/run.tsnew file mode 100644index 00000000..6c91da6a--- /dev/null+++ b/agent/run.ts@@ -0,0 +1,151 @@+/**+ * `runKilnAgent` — the agnostic, tool-driven Kiln codegen foundation.+ *+ * Drives any Strands `Model` (Anthropic / OpenAI / Google / Bedrock / Vercel-+ * 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.+ *+ * 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+ * 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 { AgentSkills } from '@strands-agents/sdk/vended-plugins/skills';++import { getSystemPrompt, buildUserPrompt } from '../prompt';+import type { AssetCategory } from '../prompt';+import { makeKilnTools, type SubmitSink } from './tools';+import { MetricsCollector, type AgentUsage } from './hooks';++/** How the agent learns Kiln conventions. */+export type KilnKnowhow = 'inline' | 'skill';++export interface RunKilnAgentOptions {+ /** A constructed Strands `Model` instance (provider-agnostic). */+ model: unknown;+ /** Natural-language description of the asset to build. */+ prompt: string;+ /** Asset category (drives prompt framing). Default 'prop'. */+ category?: AssetCategory;+ /** Know-how source: inline system prompt (default) or the kiln-glb skill. */+ knowhow?: KilnKnowhow;+ /** Absolute path to a SKILL.md dir, required when knowhow='skill'. */+ skillDir?: string;+ /** Extra tools to expose (e.g. a Strands McpClient for the MCP transport). */+ extraTools?: unknown[];+ /** Ask the model for an animate() function too. Default false (static). */+ includeAnimation?: boolean;+ /** Agent name (for tracing). Default 'kiln-agent'. */+ agentName?: string;+}++export interface RunKilnAgentResult {+ /** The final Kiln program, if the agent produced one. */+ code?: string;+ /** Every tool the model called, in order. */+ toolCalls: string[];+ /** Number of model calls (agent-loop iterations). */+ steps: number;+ /** Best-effort token usage. */+ usage?: AgentUsage;+ /** The last assistant text (fallback / diagnostics). */+ lastText?: string;+ /** Error message if the run threw. */+ error?: string;+}++function lastMessageText(message: Message | undefined): string | undefined {+ if (!message) return undefined;+ const parts: string[] = [];+ for (const block of message.content) {+ if ((block as { type?: string }).type === 'textBlock') {+ const t = (block as { text?: string }).text;+ if (typeof t === 'string') parts.push(t);+ }+ }+ const joined = parts.join('\n').trim();+ return joined.length ? joined : undefined;+}++/**+ * Run one Kiln codegen session end-to-end. Never throws — failures are returned+ * on `result.error` with whatever metrics were collected beforehand.+ */+export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgentResult> {+ const metrics = new MetricsCollector();+ const sink: SubmitSink = {};+ try {+ const tools: Tool[] = makeKilnTools(sink);+ const allTools: unknown[] = opts.extraTools ? [...tools, ...opts.extraTools] : tools;++ const plugins: Plugin[] = [];+ let systemPrompt: string;+ if (opts.knowhow === 'skill') {+ if (!opts.skillDir) throw new Error('runKilnAgent: knowhow="skill" requires skillDir');+ plugins.push(new AgentSkills({ skills: [opts.skillDir] }));+ systemPrompt =+ 'You generate exportable 3D game assets as Kiln code. Use the available ' ++ 'skill(s) to learn the Kiln primitives and conventions, write the program, ' ++ 'validate and render it with the kiln tools, then call kiln_submit with the ' ++ 'final code.';+ } else {+ systemPrompt = getSystemPrompt('glb');+ }++ const agent = new Agent({+ model: opts.model as never,+ systemPrompt,+ tools: allTools as never,+ ...(plugins.length ? { plugins } : {}),+ name: opts.agentName ?? 'kiln-agent',+ });+ metrics.attach(agent);++ const userPrompt =+ buildUserPrompt({+ prompt: opts.prompt,+ mode: 'glb',+ category: opts.category ?? 'prop',+ includeAnimation: opts.includeAnimation ?? false,+ }) ++ '\n\nWhen finished, call the kiln_submit tool exactly once with your final, ' ++ 'complete Kiln program.';++ const result = await agent.invoke(userPrompt);+ metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);++ let code = sink.code;+ if (!code && result.structuredOutput) {+ const so = result.structuredOutput as { code?: unknown };+ if (typeof so.code === 'string') code = so.code;+ }+ const lastText = lastMessageText(result.lastMessage);+ if (!code) code = lastText;++ const collected = metrics.readMetrics();+ return {+ ...(code ? { code } : {}),+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ ...(lastText ? { lastText } : {}),+ };+ } catch (err) {+ const collected = metrics.readMetrics();+ return {+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ error: err instanceof Error ? err.message : String(err),+ };+ } finally {+ metrics.detach();+ }+}diff --git a/agent/stream-start.test.ts b/agent/stream-start.test.tsnew file mode 100644index 00000000..fc30ecde--- /dev/null+++ b/agent/stream-start.test.ts@@ -0,0 +1,68 @@+/**+ * Regression tests for `ensureStreamStart` — the OpenRouter/Vercel-bridge fix.+ *+ * Build a fake LanguageModelV3 whose doStream emits a chosen sequence of parts,+ * drain the wrapped stream, and assert `stream-start` leads exactly once. No+ * network. Mirrors the live OpenRouter doStream, which omits `stream-start` and+ * thus made Strands throw "Stream ended without completing a message".+ */+import { test, expect } from 'bun:test';+import { ensureStreamStart } from './stream-start';++function fakeModel(+ parts: Array<{ type: string; [k: string]: unknown }>,+ extra: Record<string, unknown> = {},+) {+ return {+ specificationVersion: 'v3',+ provider: 'fake',+ modelId: 'fake/m',+ ...extra,+ doStream: async (_opts: unknown) => ({+ stream: new ReadableStream({+ start(ctrl) {+ for (const p of parts) ctrl.enqueue(p);+ ctrl.close();+ },+ }),+ }),+ } as never;+}++async function drain(model: { doStream: (o: unknown) => Promise<{ stream: ReadableStream }> }): Promise<string[]> {+ const { stream } = await model.doStream({});+ const reader = stream.getReader();+ const types: string[] = [];+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ types.push((value as { type: string }).type);+ }+ return types;+}++test('injects a leading stream-start when the provider omits it (OpenRouter shape)', async () => {+ const wrapped = ensureStreamStart(+ fakeModel([{ type: 'response-metadata' }, { type: 'tool-call' }, { type: 'finish' }]),+ );+ const types = await drain(wrapped as never);+ expect(types[0]).toBe('stream-start');+ expect(types).toEqual(['stream-start', 'response-metadata', 'tool-call', 'finish']);+ expect(types.filter((t) => t === 'stream-start').length).toBe(1);+});++test('is a no-op when the provider already emits stream-start', async () => {+ const wrapped = ensureStreamStart(fakeModel([{ type: 'stream-start', warnings: [] }, { type: 'finish' }]));+ expect(await drain(wrapped as never)).toEqual(['stream-start', 'finish']);+});++test('injects stream-start even for an empty stream', async () => {+ const wrapped = ensureStreamStart(fakeModel([]));+ expect(await drain(wrapped as never)).toEqual(['stream-start']);+});++test('passes through non-doStream properties', () => {+ const wrapped = ensureStreamStart(fakeModel([], { modelId: 'fake/keep' }));+ expect((wrapped as unknown as { specificationVersion: string }).specificationVersion).toBe('v3');+ expect((wrapped as unknown as { modelId: string }).modelId).toBe('fake/keep');+});diff --git a/agent/stream-start.ts b/agent/stream-start.tsnew file mode 100644index 00000000..dc2069d5--- /dev/null+++ b/agent/stream-start.ts@@ -0,0 +1,58 @@+/**+ * `ensureStreamStart` — guarantee a leading `stream-start` part on a+ * LanguageModelV3 stream.+ *+ * WHY THIS EXISTS: Strands' `VercelModel` only emits its `modelMessageStartEvent`+ * (which sets the internal `messageRole`) when it sees a `stream-start` stream+ * part, and its base model loop only stores the final message `if (messageRole)`.+ * The AI-SDK V3 spec lists `stream-start` as the leading part, but some providers+ * — notably `@openrouter/ai-sdk-provider` (2.9.0) — omit it, leading instead with+ * `response-metadata`. The result: `messageRole` is never set, the terminal+ * `modelMessageStopEvent` is dropped, and the loop throws+ * `ModelError: Stream ended without completing a message`. Native Strands+ * providers (Anthropic/OpenAI/Google) emit `stream-start`, so only the+ * Vercel-bridge providers (OpenRouter and friends) are affected.+ *+ * This proxy pipes `doStream`'s stream through a TransformStream that prepends a+ * spec-conformant `{ type: 'stream-start', warnings: [] }` part if the provider+ * doesn't already open with one. It is a no-op for conformant providers.+ *+ * Confirmed against the live OpenRouter `doStream` (no `stream-start`) and proven+ * end-to-end through a Strands Agent tool loop. Covered by stream-start.test.ts.+ */+import type {+ LanguageModelV3,+ LanguageModelV3CallOptions,+ LanguageModelV3StreamPart,+} from '@ai-sdk/provider';++/**+ * Wrap a `LanguageModelV3` so its `doStream` output always begins with a+ * `stream-start` part. All other properties/methods pass through unchanged.+ */+export function ensureStreamStart(model: LanguageModelV3): LanguageModelV3 {+ const origDoStream = model.doStream.bind(model);+ return new Proxy(model, {+ get(target, prop, receiver) {+ if (prop === 'doStream') {+ return async (options: LanguageModelV3CallOptions) => {+ const result = await origDoStream(options);+ let injected = false;+ const guard = new TransformStream<LanguageModelV3StreamPart, LanguageModelV3StreamPart>({+ transform(chunk, ctrl) {+ if (!injected && chunk.type !== 'stream-start') ctrl.enqueue({ type: 'stream-start', warnings: [] });+ injected = true;+ ctrl.enqueue(chunk);+ },+ flush(ctrl) {+ if (!injected) ctrl.enqueue({ type: 'stream-start', warnings: [] });+ },+ });+ return { ...result, stream: result.stream.pipeThrough(guard) };+ };+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}diff --git a/agent/tools.ts b/agent/tools.tsnew file mode 100644index 00000000..0488e1b4--- /dev/null+++ b/agent/tools.ts@@ -0,0 +1,69 @@+/**+ * In-process Kiln tool skin for the agnostic Strands agent foundation.+ *+ * Adapts the shared `kilnToolRegistry` (kiln/tools/registry) into Strands+ * `tool()` instances that run in the same Node realm as the agent loop, plus a+ * terminal `kiln_submit` tool the agent calls once to record its final program.+ * The registry is the single source of truth for tool names/descriptions/schemas,+ * so any other transport (e.g. an MCP skin) stays byte-for-byte consistent.+ *+ * An explicit submit tool is preferred over `structuredOutputSchema` because the+ * latter's coexistence with a full tool set is provider-dependent; a submit tool+ * is unambiguous and works across every provider.+ */+import { tool, type Tool, type JSONValue } from '@strands-agents/sdk';+import { z } from 'zod';++import { kilnToolRegistry } from '../tools/registry';++/** Name of the terminal tool the agent calls to record its final program. */+export const KILN_SUBMIT_TOOL_NAME = 'kiln_submit';++/**+ * A mutable sink the `kiln_submit` tool writes the final code into. Create one+ * per run, pass it to {@link makeKilnTools}, and read `.code` after invoke.+ */+export interface SubmitSink {+ code?: string;+}++const submitInput = z.object({+ code: z+ .string()+ .describe(+ 'The complete, final Kiln program (defines `meta` + `build()`, optional `animate()`). ' ++ 'Call this exactly once when you are done to record your answer.',+ ),+});++function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {+ return tool({+ name: def.name,+ description: def.description,+ inputSchema: def.inputSchema as z.ZodType,+ callback: async (input) => (await def.run(input)) as JSONValue,+ });+}++/**+ * Build the in-process tool list for an agent: the kiln registry tools+ * (list_primitives / validate / render) plus the terminal `kiln_submit` tool.+ *+ * @param sink - Receives the submitted final code. Read `sink.code` after invoke.+ */+export function makeKilnTools(sink: SubmitSink): Tool[] {+ const kilnTools = kilnToolRegistry.map(toStrandsTool);+ const submitTool: Tool = tool({+ name: KILN_SUBMIT_TOOL_NAME,+ description:+ 'Submit your FINAL Kiln program. Call this exactly once, after you have ' ++ 'validated and rendered your code, to record the answer. The argument ' ++ '`code` must be the complete program (meta + build(), optional animate()).',+ inputSchema: submitInput,+ callback: (input) => {+ sink.code = input.code;+ return { ok: true, recorded: true, bytes: input.code.length };+ },+ });+ return [...kilnTools, submitTool];+}diff --git a/index.ts b/index.tsindex 29b4d9a0..ad7bc8f5 100644--- a/index.ts+++ b/index.ts@@ -129,6 +129,12 @@ export type { GearOptions, BladeOptions } from './gears';export { loadTexture, pbrMaterial } from './textures';export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';+// -----------------------------------------------------------------------------+// Shared tool registry (kiln/tools) — Kiln Bench capability surface+// -----------------------------------------------------------------------------+export { kilnToolRegistry } from './tools/registry';+export type { KilnToolDef, KilnRenderMetrics } from './tools/registry';+// -----------------------------------------------------------------------------// LOD chain generator (kiln/lod)// -----------------------------------------------------------------------------diff --git a/tools/registry.ts b/tools/registry.tsnew file mode 100644index 00000000..7dfba0d0--- /dev/null+++ b/tools/registry.ts@@ -0,0 +1,198 @@+/**+ * Kiln Tool Registry — shared capability surface for agents.+ *+ * Three model-facing tools, each a thin wrapper over the existing kiln core+ * functions. This registry is the single source of truth for both the+ * in-process-tool capability skin and the MCP capability skin in the Kiln+ * Bench spike: both adapters iterate `kilnToolRegistry` so the tool names,+ * descriptions, and behavior stay identical across mechanisms.+ *+ * Pure metrics only — `kiln_render` never writes files and never throws.+ */++import { z } from 'zod';+import * as THREE from 'three';++import { validate } from '../validation';+import { executeKilnCode, inspectSceneStructure, renderSceneToGLB } from '../render';+import { listPrimitives, type PrimitiveSpec } from '../list-primitives';++// =============================================================================+// Tool definition contract+// =============================================================================++export interface KilnToolDef {+ /** Stable tool name exposed to the model (in-process and over MCP). */+ name: string;+ /** Model-facing description, consistent with the kiln-glb SKILL.md language. */+ description: string;+ /** Zod schema for the tool input. */+ inputSchema: z.ZodType;+ /** Execute the tool. Returns JSON-serializable output. */+ run(input: unknown): Promise<unknown>;+}++// =============================================================================+// Schemas+// =============================================================================++const listPrimitivesInput = z.object({+ category: z+ .string()+ .optional()+ .describe(+ 'Optional category filter: geometry, material, structure, animation, utility, instancing, csg, arrays, mesh-ops, curves, uv, textures.'+ ),+});++const validateInput = z.object({+ code: z.string().describe('Kiln source code (defines `meta` + `build()`, optional `animate()`).'),+});++const renderInput = z.object({+ code: z.string().describe('Kiln source code to execute and render to an in-memory GLB.'),+});++// =============================================================================+// kiln_list_primitives+// =============================================================================++function runListPrimitives(input: z.infer<typeof listPrimitivesInput>): {+ primitives: PrimitiveSpec[];+ text: string;+} {+ const all = listPrimitives();+ const category = input.category?.trim().toLowerCase();+ const primitives = category+ ? all.filter((p) => p.category.toLowerCase() === category)+ : all;++ const text = primitives+ .map((p) => `${p.signature} -> ${p.returns}\n ${p.description}\n e.g. ${p.example}`)+ .join('\n\n');++ return { primitives, text };+}++// =============================================================================+// kiln_validate+// =============================================================================++function runValidate(input: z.infer<typeof validateInput>): {+ valid: boolean;+ errors: string[];+ warnings: string[];+} {+ const result = validate(input.code);+ return {+ valid: result.valid,+ errors: result.errors,+ warnings: result.warnings.map((w) => (w.fixHint ? `${w.message} (${w.fixHint})` : w.message)),+ };+}++// =============================================================================+// kiln_render+// =============================================================================++export interface KilnRenderMetrics {+ ok: boolean;+ tris?: number;+ meshes?: number;+ materials?: number;+ bbox?: { min: number[]; max: number[]; size: number[] };+ warnings: string[];+ error?: string;+}++/**+ * Execute Kiln code, render it to an in-memory GLB, and report metrics.+ * Never writes files; never throws — failures come back as { ok:false, error }.+ */+async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRenderMetrics> {+ try {+ const { root, clips } = await executeKilnCode(input.code);++ // Structural advisories (floating parts / stray planes at origin).+ const structuralWarnings = inspectSceneStructure(root);++ // Mesh + material counts via duck-typing (sandbox THREE is a different+ // realm than this module's THREE — `instanceof` would always be false).+ let meshes = 0;+ const materialSet = new Set<unknown>();+ root.traverse((node: THREE.Object3D) => {+ const n = node as { isMesh?: boolean; material?: unknown };+ if (n.isMesh) {+ meshes += 1;+ const mat = n.material;+ if (Array.isArray(mat)) {+ for (const m of mat) materialSet.add(m);+ } else if (mat) {+ materialSet.add(mat);+ }+ }+ });++ // World-space bounding box.+ const box = new THREE.Box3().setFromObject(root);+ let bbox: KilnRenderMetrics['bbox'];+ if (!box.isEmpty()) {+ const size = new THREE.Vector3();+ box.getSize(size);+ bbox = {+ 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],+ };+ }++ // Render to GLB bytes for the triangle count. Output is discarded — pure+ // metrics, no files written.+ const rendered = await renderSceneToGLB(root, { clips });++ const warnings = [...structuralWarnings, ...rendered.warnings];++ return {+ ok: true,+ tris: rendered.tris,+ meshes,+ materials: materialSet.size,+ bbox,+ warnings,+ };+ } catch (err) {+ return {+ ok: false,+ error: err instanceof Error ? err.message : String(err),+ warnings: [],+ };+ }+}++// =============================================================================+// Registry+// =============================================================================++export const kilnToolRegistry: KilnToolDef[] = [+ {+ name: 'kiln_list_primitives',+ description:+ 'List the Kiln sandbox primitives available to generated 3D code: geometry helpers (boxGeo, cylinderXGeo, capsuleGeo, ...), materials (gameMaterial, glassMaterial, ...), structure (createRoot, createPart, createPivot), animation, CSG, arrays, UV, and textures. Call this before writing Kiln code to discover exact signatures and idiomatic usage. Optionally filter by category.',+ inputSchema: listPrimitivesInput,+ run: async (input) => runListPrimitives(listPrimitivesInput.parse(input)),+ },+ {+ name: 'kiln_validate',+ description:+ 'Statically validate Kiln source code before rendering. Checks for the required `meta` const and `build()` function, `value:` keyframe typos, infinite loops, recursive build() calls, syntax errors, and triangle-budget advisories. Returns { valid, errors, warnings }. Run this to catch mistakes cheaply before kiln_render.',+ inputSchema: validateInput,+ run: async (input) => runValidate(validateInput.parse(input)),+ },+ {+ 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.',+ inputSchema: renderInput,+ run: async (input) => runRender(renderInput.parse(input)),+ },+];