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: add remote evaluator execution boundary (#35)
Matthew Kissingere481da460b15
diff --git a/src/__tests__/inspect.test.ts b/src/__tests__/inspect.test.tsindex 2555bcf0..9c7e3d1b 100644--- a/src/__tests__/inspect.test.ts+++ b/src/__tests__/inspect.test.ts@@ -47,7 +47,8 @@ const BROKEN_JOINT_CODE = `const meta = { name: 'Broken' };function build() {const root = createRoot('Broken');- createPivot('Body', [0, 0, 0], root);+ const body = createPivot('Body', [0, 0, 0], root);+ createPart('Mesh', boxGeo(1, 1, 1), gameMaterial('#888888'), { parent: body });return root;}function animate() {@@ -106,11 +107,10 @@ describe('kiln.inspect', () => {expect(track?.targetResolved).toBe(true);});- test('flags animation tracks whose target is missing from the scene', async () => {+ test('reports an evaluator warning when an unresolved track is omitted from final GLB', async () => {const r = await inspect(BROKEN_JOINT_CODE);- expect(r.animationTracks.length).toBe(1);- expect(r.animationTracks[0]?.targetResolved).toBe(false);+ expect(r.animationTracks.length).toBe(0);expect(r.warnings.length).toBeGreaterThan(0);expect(r.warnings.some((w) => w.includes('Joint_DoesNotExist'))).toBe(true);});@@ -139,14 +139,7 @@ describe('kiln.inspect', () => {expect(r.boundingBox.max[1]).toBeGreaterThan(5);});- test('returns zeroed bounds for a pivots-only scene', async () => {- const r = await inspect(EMPTY_CODE);-- expect(r.triangles).toBe(0);- expect(r.materials).toBe(0);- expect(r.boundingBox.min).toEqual([0, 0, 0]);- expect(r.boundingBox.max).toEqual([0, 0, 0]);- expect(r.boundingBox.size).toEqual([0, 0, 0]);- expect(r.animationTracks).toEqual([]);+ test('fails closed when evaluator QA blocks a pivots-only scene', async () => {+ await expect(inspect(EMPTY_CODE)).rejects.toMatchObject({ stage: 'scene' });});});diff --git a/src/agent/generate.ts b/src/agent/generate.tsindex 05a9d5b6..ab36cdaa 100644--- a/src/agent/generate.ts+++ b/src/agent/generate.ts@@ -14,7 +14,12 @@* non-agent `kiln` module must import it lazily (dynamic `import()`), so the* `@strands-agents/sdk` dependency never enters the browser/editor bundle graph.*/-import { renderGLB, type KilnCodeMeta, type RenderResult } from '../render';+import type { KilnCodeMeta, RenderResult } from '../render';+import {+ resolveEvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorPortV1,+} from '../evaluator';import type { PbrRenderPort, ViewFidelityV1 } from '../composer/render-port';import {CaptureConfigError,@@ -102,6 +107,10 @@ export interface GenerateKilnAssetOptions {exemplarCode?: string;/** Optional reference image fed to the model as multimodal context (fresh gen + refine). */inputImage?: KilnInputImage;+ /** Generated-source execution boundary. Production must inject the port and+ * select `evaluator-required`; trusted local/test remains compatible. */+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;}export interface GenerateKilnAssetResult {@@ -179,6 +188,8 @@ export async function generateKilnCodeAgent(opts: {inputImage?: KilnInputImage;/** Strands model id; defaults like {@link generateKilnAsset}. */model?: string;+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;}): Promise<{success: boolean;code?: string;@@ -206,6 +217,8 @@ export async function generateKilnCodeAgent(opts: {...(opts.existingCode ? { existingCode: opts.existingCode } : {}),...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),...(opts.inputImage ? { inputImage: opts.inputImage } : {}),+ ...(opts.evaluatorPort ? { evaluatorPort: opts.evaluatorPort } : {}),+ ...(opts.evaluatorProfile ? { evaluatorProfile: opts.evaluatorProfile } : {}),});if (agent.error || !agent.code) {@@ -438,6 +451,8 @@ export async function generateKilnAsset(...(opts.agentName ? { agentName: opts.agentName } : {}),...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),...(opts.inputImage ? { inputImage: opts.inputImage } : {}),+ ...(opts.evaluatorPort ? { evaluatorPort: opts.evaluatorPort } : {}),+ ...(opts.evaluatorProfile ? { evaluatorProfile: opts.evaluatorProfile } : {}),});// A salvaged run carries BOTH code and the original error (H-10) — only a@@ -448,7 +463,10 @@ export async function generateKilnAsset(// Grade-aware consolidation by default: lifts material-sprawl heroes from// grade C/D/F to A/B, byte-stable on already-lean assets (M1a, plan/05 §3.1).- const render = await renderGLB(agent.code, { optimize: 'auto', intent });+ const render = await resolveEvaluatorPortV1(+ opts.evaluatorPort,+ opts.evaluatorProfile ?? 'trusted-local',+ ).render(agent.code, { optimize: 'auto', intent });// Best-effort views artifact: what the vision loop / review UIs show.// Never fails the run — a rasterizer error just drops the sidecar.diff --git a/src/agent/grade-refine.ts b/src/agent/grade-refine.tsindex ef2c2041..36712a17 100644--- a/src/agent/grade-refine.ts+++ b/src/agent/grade-refine.ts@@ -18,7 +18,11 @@ import { WebIO } from '@gltf-transform/core';import type { AssetCategory, AssetIntentV1 } from '../contracts';import type { InstanceabilityGrade, InstanceabilityReport } from '../metrics';import { AssetQaBlockedError } from '../qa/run';-import { renderGLB } from '../render';+import {+ resolveEvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorPortV1,+} from '../evaluator';/** Grades at or above this never trigger a refine turn. */export const GRADE_REFINE_TARGET: InstanceabilityGrade = 'B';@@ -89,10 +93,19 @@ async function listMaterialLabels(glb: Uint8Array): Promise<string[]> {*/export async function assessProgramGrade(code: string,- opts: { intent?: AssetIntentV1; category?: AssetCategory } = {},+ opts: {+ intent?: AssetIntentV1;+ category?: AssetCategory;+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;+ } = {},): Promise<ProgramGradeAssessment> {try {- const render = await renderGLB(code, { optimize: 'auto', ...opts });+ const { evaluatorPort, evaluatorProfile, ...renderOptions } = opts;+ const render = await resolveEvaluatorPortV1(+ evaluatorPort,+ evaluatorProfile ?? 'trusted-local',+ ).render(code, { optimize: 'auto', ...renderOptions });const report = render.meta.instanceability;// Metrics computation failing is non-fatal everywhere else — same here: the// program is valid, there is just no grade signal to act on.diff --git a/src/agent/run.ts b/src/agent/run.tsindex 00caa641..c2896bfa 100644--- a/src/agent/run.ts+++ b/src/agent/run.ts@@ -105,6 +105,8 @@ export interface RunKilnAgentOptions| 'onViewsRendered'| 'renderObservationPort'| 'generationCallBudget'+ | 'evaluatorPort'+ | 'evaluatorProfile'> {/** A constructed Strands `Model` instance (provider-agnostic). */model: unknown;@@ -258,6 +260,8 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst gradeAssessmentOptions = {category: trustedCategory,...(opts.intent ? { intent: opts.intent } : {}),+ ...(opts.evaluatorPort ? { evaluatorPort: opts.evaluatorPort } : {}),+ ...(opts.evaluatorProfile ? { evaluatorProfile: opts.evaluatorProfile } : {}),};// Edit mode is a `current`-surface concept (the unified surface always uses the// buffer factory, regardless of refineMode). Engages only when refining.diff --git a/src/agent/surface.ts b/src/agent/surface.tsindex 664869ae..61559f01 100644--- a/src/agent/surface.ts+++ b/src/agent/surface.ts@@ -84,6 +84,8 @@ export function buildAgentTools(...(opts.onViewsRendered ? { onViewsRendered: opts.onViewsRendered } : {}),...(opts.renderObservationPort ? { renderObservationPort: opts.renderObservationPort } : {}),...(opts.generationCallBudget ? { generationCallBudget: opts.generationCallBudget } : {}),+ ...(opts.evaluatorPort ? { evaluatorPort: opts.evaluatorPort } : {}),+ ...(opts.evaluatorProfile ? { evaluatorProfile: opts.evaluatorProfile } : {}),};if (surface === 'unified') {return makeKilnUnifiedTools({diff --git a/src/evaluator/handler.test.ts b/src/evaluator/handler.test.tsnew file mode 100644index 00000000..67027f9c--- /dev/null+++ b/src/evaluator/handler.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test } from 'bun:test';++import type { RenderResult } from '../render';+import {+ createEvaluatorRequestV1,+ decodeEvaluatorResultV1,+ evaluateEvaluatorRequestV1,+} from './index';++const GLB = Buffer.from('glTF strict evaluator fixture');+const HASH = `sha256:${new Bun.CryptoHasher('sha256').update(GLB).digest('hex')}` as const;+const RENDER: RenderResult = {+ glb: GLB,+ artifactGlbSha256: HASH,+ tris: 1,+ meta: {},+ warnings: [],+ integrationManifest: {+ schemaVersion: 'kiln.integration-manifest.v1',+ analyzerVersion: 1,+ artifactSha256: HASH.slice(7),+ units: 'm',+ axes: { forward: '+X', up: '+Y', right: '+Z' },+ bounds: { min: [0, 0, 0], max: [1, 1, 1], size: [1, 1, 1], center: [0.5, 0.5, 0.5] },+ pivot: { convention: 'author-origin', position: [0, 0, 0] },+ ground: { groundY: 0, contactTolerance: 0.02, minY: 0, offsetToGround: 0, grounded: true },+ defaultScene: { index: 0, name: 'Scene' },+ renderMetrics: {+ triangles: 1,+ drawCalls: 1,+ uniqueGeometries: 1,+ uniqueMaterials: 1,+ textureCount: 0,+ transparentMaterials: 0,+ skinned: false,+ },+ structuralQa: {+ hasDefaultScene: true,+ finiteBounds: true,+ validatorErrors: 0,+ validatorWarnings: 0,+ },+ visualQa: 'not_assessed',+ },+};++describe('transport-neutral evaluator handler', () => {+ test('reuses the strict protocol and canonical result encoding', async () => {+ const built = createEvaluatorRequestV1({ requestId: 'http-1', code: 'fixture' });+ const resultJson = await evaluateEvaluatorRequestV1(built.json, {+ render: async () => RENDER,+ });+ expect(decodeEvaluatorResultV1(resultJson, 1024, 'http-1')).toMatchObject({+ ok: true,+ requestId: 'http-1',+ render: { artifactGlbSha256: HASH },+ });+ });++ test('sanitizes execution failures and refuses oversized encoded output', async () => {+ const built = createEvaluatorRequestV1({ requestId: 'http-2', code: 'private source marker' });+ const failed = await evaluateEvaluatorRequestV1(built.json, {+ render: async () => {+ throw new Error('private source marker and /secret/path');+ },+ });+ expect(failed).not.toContain('private source marker');+ expect(failed).not.toContain('/secret/path');+ expect(decodeEvaluatorResultV1(failed, 1024, 'http-2')).toMatchObject({+ ok: false,+ error: { code: 'EXECUTION_REJECTED' },+ });+ await expect(+ evaluateEvaluatorRequestV1(+ built.json,+ { render: async () => RENDER },+ {+ maxResponseBytes: 32,+ },+ ),+ ).rejects.toMatchObject({ code: 'OUTPUT_LIMIT_EXCEEDED' });+ });++ test('bounds the transport-neutral execution deadline', async () => {+ const built = createEvaluatorRequestV1({ requestId: 'http-deadline', code: 'fixture' });+ const failed = await evaluateEvaluatorRequestV1(+ built.json,+ { render: () => new Promise(() => {}) },+ { deadlineMs: 5 },+ );+ expect(decodeEvaluatorResultV1(failed, 1024, 'http-deadline')).toMatchObject({+ ok: false,+ error: { code: 'DEADLINE_EXCEEDED' },+ });+ });+});diff --git a/src/evaluator/handler.ts b/src/evaluator/handler.tsnew file mode 100644index 00000000..ed663b10--- /dev/null+++ b/src/evaluator/handler.ts@@ -0,0 +1,111 @@+import type { RenderGlbOptions, RenderResult } from '../render';+import { renderGLBInProcess } from '../render';+import { AssetQaBlockedError } from '../qa/run';+import {+ decodeEvaluatorRequestV1,+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,+ DEFAULT_EVALUATOR_DEADLINE_MS,+ encodeRenderResultV1,+ evaluatorOutcomeMessage,+ EVALUATOR_RESULT_VERSION,+ EvaluatorPortError,+ type EvaluatorOutcomeCode,+ type EvaluatorRequestV1,+ type WireEvaluatorResultV1,+} from './protocol';++export interface EvaluatorHandlerDependenciesV1 {+ render?(code: string, options: RenderGlbOptions): Promise<RenderResult>;+}++export interface EvaluatorHandlerControlsV1 {+ maxResponseBytes?: number;+ deadlineMs?: number;+}++function failure(+ requestId: string,+ code: EvaluatorOutcomeCode,+ qa?: Extract<WireEvaluatorResultV1, { ok: false }>['error']['qa'],+): Extract<WireEvaluatorResultV1, { ok: false }> {+ return {+ version: EVALUATOR_RESULT_VERSION,+ requestId,+ ok: false,+ error: {+ code,+ message: evaluatorOutcomeMessage(code),+ ...(qa ? { qa } : {}),+ },+ };+}++function boundedMaxResponseBytes(value: number | undefined): number {+ const resolved = value ?? DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > 96 * 1024 * 1024) {+ throw new EvaluatorPortError('INPUT_INVALID');+ }+ return resolved;+}++function boundedDeadlineMs(value: number | undefined): number {+ const resolved = value ?? DEFAULT_EVALUATOR_DEADLINE_MS;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > 120_000) {+ throw new EvaluatorPortError('INPUT_INVALID');+ }+ return resolved;+}++/**+ * Transport-neutral evaluator core shared by the fd3 worker and a host-owned+ * HTTP/AgentCore entrypoint. It accepts and emits only canonical v1 JSON. No+ * network, environment, path, resolver, or AWS capability enters this seam.+ */+export async function evaluateEvaluatorRequestV1(+ requestJson: string,+ dependencies: EvaluatorHandlerDependenciesV1 = {},+ controls: EvaluatorHandlerControlsV1 = {},+): Promise<string> {+ const maxResponseBytes = boundedMaxResponseBytes(controls.maxResponseBytes);+ const deadlineMs = boundedDeadlineMs(controls.deadlineMs);+ let request: EvaluatorRequestV1;+ try {+ request = decodeEvaluatorRequestV1(requestJson);+ } catch {+ return JSON.stringify(failure('invalid', 'INPUT_INVALID'));+ }+ let wire: WireEvaluatorResultV1;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const render = await Promise.race([+ (dependencies.render ?? renderGLBInProcess)(request.code, request.options),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new EvaluatorPortError('DEADLINE_EXCEEDED')), deadlineMs);+ }),+ ]);+ if (render.glb.byteLength > request.limits.maxGlbBytes) {+ wire = failure(request.requestId, 'OUTPUT_LIMIT_EXCEEDED');+ } else {+ wire = encodeRenderResultV1(request.requestId, render);+ }+ } catch (error) {+ if (error instanceof AssetQaBlockedError) {+ wire = failure(request.requestId, 'QA_BLOCKED', {+ report: error.report,+ stage: error.stage,+ ...(error.gltfValidation ? { gltfValidation: error.gltfValidation } : {}),+ });+ } else if (error instanceof EvaluatorPortError && error.code === 'DEADLINE_EXCEEDED') {+ wire = failure(request.requestId, 'DEADLINE_EXCEEDED');+ } else {+ wire = failure(request.requestId, 'EXECUTION_REJECTED');+ }+ } finally {+ clearTimeout(timer);+ }+ const json = JSON.stringify(wire);+ if (Buffer.byteLength(json, 'utf8') > maxResponseBytes) {+ throw new EvaluatorPortError('OUTPUT_LIMIT_EXCEEDED');+ }+ return json;+}diff --git a/src/evaluator/index.ts b/src/evaluator/index.tsindex 36b5b1dd..fb35353c 100644--- a/src/evaluator/index.ts+++ b/src/evaluator/index.ts@@ -1,13 +1,36 @@export {EVALUATOR_REQUEST_VERSION,EVALUATOR_RESULT_VERSION,+ createEvaluatorPortV1,+ createEvaluatorRequestV1,+ decodeEvaluatorRequestV1,+ decodeEvaluatorResultV1,+ encodeRenderResultV1,evaluatorOutcomeMessage,+ EvaluatorPortError,+ resolveEvaluatorPortV1,+ trustedInProcessEvaluatorPortV1,MAX_EVALUATOR_CODE_BYTES,MAX_EVALUATOR_REQUEST_BYTES,+ DEFAULT_EVALUATOR_DEADLINE_MS,+ DEFAULT_EVALUATOR_MAX_GLB_BYTES,+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,+ type CreateEvaluatorRequestV1Input,type EvaluatorOutcomeCode,type EvaluatorRequestV1,type EvaluatorResultV1,+ type EvaluatorPortCallControlsV1,+ type EvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorTransportControlsV1,+ type EvaluatorTransportV1,+ type WireEvaluatorResultV1,} from './protocol';+export {+ evaluateEvaluatorRequestV1,+ type EvaluatorHandlerControlsV1,+ type EvaluatorHandlerDependenciesV1,+} from './handler';export {EvaluatorSubprocessError,renderGLBViaSubprocess,diff --git a/src/evaluator/port.test.ts b/src/evaluator/port.test.tsnew file mode 100644index 00000000..12fa9487--- /dev/null+++ b/src/evaluator/port.test.ts@@ -0,0 +1,19 @@+import { expect, test } from 'bun:test';++import { resolveEvaluatorPortV1 } from './index';++test('production profile requires an injected evaluator with no fallback', async () => {+ expect(() => resolveEvaluatorPortV1(undefined, 'evaluator-required')).toThrow(+ 'Evaluator port is required',+ );+ const calls: string[] = [];+ const injected = {+ render: async (code: string) => {+ calls.push(code);+ return {} as never;+ },+ };+ expect(resolveEvaluatorPortV1(injected, 'evaluator-required')).toBe(injected);+ await resolveEvaluatorPortV1(injected, 'evaluator-required').render('source');+ expect(calls).toEqual(['source']);+});diff --git a/src/evaluator/production-boundary.test.ts b/src/evaluator/production-boundary.test.tsnew file mode 100644index 00000000..f7c416de--- /dev/null+++ b/src/evaluator/production-boundary.test.ts@@ -0,0 +1,95 @@+import { describe, expect, spyOn, test } from 'bun:test';++import * as renderModule from '../render';+import { renderGLBInProcess } from '../render';+import { inspect } from '../inspect';+import {+ createKilnRenderViewsDef,+ createKilnScreenshotAnimationDef,+ type KilnRenderViewsResult,+ type KilnScreenshotAnimationResult,+} from '../tools/registry';+import { rasterizeComposedScene, renderCodeViewGrid } from '../views';+import type { EvaluatorPortV1 } from './protocol';++const ANIMATED = `+const meta = { name: 'remote-boundary', category: 'prop' };+function build() {+ const root = createRoot('Root');+ const pivot = createPivot('Arm', [0, 0, 0], root);+ createPart('Blade', boxGeo(1, 1, 1), gameMaterial('#888888'), { parent: pivot });+ return root;+}+function animate() {+ return [createClip('move', 1, [rotationTrack('Joint_Arm', [+ { time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 90, 0] }+ ])])];+}`;++describe('production evaluator boundary', () => {+ test('all source-taking review helpers consume injected evaluator GLB without local execution', async () => {+ const fixture = await renderGLBInProcess(ANIMATED);+ let calls = 0;+ const evaluatorPort: EvaluatorPortV1 = {+ async render() {+ calls++;+ return fixture;+ },+ };+ const execute = spyOn(renderModule, 'executeKilnCode');+ try {+ const context = { evaluatorPort, evaluatorProfile: 'evaluator-required' as const };+ const rendered = (await createKilnRenderViewsDef(context).run({+ code: ANIMATED,+ })) as KilnRenderViewsResult;+ const animation = (await createKilnScreenshotAnimationDef(context).run({+ code: ANIMATED,+ clip: 'move',+ })) as KilnScreenshotAnimationResult;+ const grid = await renderCodeViewGrid(ANIMATED, { ...context, size: 32 });+ const report = await inspect(ANIMATED, context);+ const scene = await rasterizeComposedScene(+ [{ code: ANIMATED, pos: [0, 0, 0], rotYDeg: 0, scale: 1 }],+ { ...context, size: 32 },+ );++ expect(rendered.ok).toBe(true);+ expect(animation.ok).toBe(true);+ expect(grid.png.byteLength).toBeGreaterThan(100);+ expect(report.triangles).toBeGreaterThan(0);+ expect(scene.png.byteLength).toBeGreaterThan(100);+ expect(calls).toBe(5);+ expect(execute).not.toHaveBeenCalled();+ } finally {+ execute.mockRestore();+ }+ });++ test('required production profile has no trusted-local fallback', async () => {+ const execute = spyOn(renderModule, 'executeKilnCode');+ try {+ const result = (await createKilnRenderViewsDef({+ evaluatorProfile: 'evaluator-required',+ }).run({ code: ANIMATED })) as KilnRenderViewsResult;+ expect(result).toMatchObject({ ok: false, error: 'Evaluator port is required.' });+ expect(execute).not.toHaveBeenCalled();+ } finally {+ execute.mockRestore();+ }+ });++ test('composed-scene exact GLB mode never evaluates source', async () => {+ const fixture = await renderGLBInProcess(ANIMATED);+ const execute = spyOn(renderModule, 'executeKilnCode');+ try {+ const scene = await rasterizeComposedScene(+ [{ glb: fixture.glb, pos: [0, 0, 0], rotYDeg: 0, scale: 1 }],+ { evaluatorProfile: 'evaluator-required', size: 32 },+ );+ expect(scene.png.byteLength).toBeGreaterThan(100);+ expect(execute).not.toHaveBeenCalled();+ } finally {+ execute.mockRestore();+ }+ });+});diff --git a/src/evaluator/protocol.test.ts b/src/evaluator/protocol.test.tsindex bd2bc4b5..ab0906dc 100644--- a/src/evaluator/protocol.test.ts+++ b/src/evaluator/protocol.test.ts@@ -1,5 +1,11 @@import { describe, expect, test } from 'bun:test';+import { renderGLBInProcess } from '../render';+import { AssetQaBlockedError } from '../qa/run';+import { createAssetIntentV1 } from '../contracts';+import { createAssetQaReportV1 } from '../qa/types';import {+ createEvaluatorPortV1,+ createEvaluatorRequestV1,decodeEvaluatorRequestV1,decodeEvaluatorResultV1,encodeRenderResultV1,@@ -15,6 +21,13 @@ const request = {options: { optimize: 'off' as const },limits: { maxGlbBytes: 1024 },};+const BOX_CODE = `+const meta={name:'Box'};+function build(){+ const root=createRoot('Box');+ createPart('Body', boxGeo(1,1,1), gameMaterial('#777777'), {parent:root});+ return root;+}`;describe('evaluator protocol v1', () => {test('accepts the exact versioned request shape', () => {@@ -87,4 +100,101 @@ describe('evaluator protocol v1', () => {'invalid evaluator result',);});++ test('rejects malformed or unbound QA evidence from a remote worker', () => {+ const malformed = {+ version: EVALUATOR_RESULT_VERSION,+ requestId: 'render-1',+ ok: false,+ error: {+ code: 'QA_BLOCKED',+ message: 'Generated asset did not pass quality checks.',+ qa: { report: { disposition: 'block', source: 'untrusted' }, stage: 'scene' },+ },+ };+ expect(() => decodeEvaluatorResultV1(JSON.stringify(malformed), 1024, 'render-1')).toThrow(+ 'invalid evaluator result',+ );+ expect(() =>+ decodeEvaluatorResultV1(+ JSON.stringify({+ ...malformed,+ error: {+ code: 'EXECUTION_REJECTED',+ message: 'Generated asset execution was rejected.',+ qa: malformed.error.qa,+ },+ }),+ 1024,+ 'render-1',+ ),+ ).toThrow('invalid evaluator result');+ });++ test('builds exact transport-neutral requests and rejects host capabilities', () => {+ const built = createEvaluatorRequestV1({+ requestId: 'remote-42',+ code: BOX_CODE,+ options: { optimize: 'auto' },+ maxGlbBytes: 2048,+ });+ expect(JSON.parse(built.json)).toEqual(built.request);+ expect(built.request).toMatchObject({+ version: 'kiln.evaluator.request.v1',+ requestId: 'remote-42',+ operation: 'execute-export-glb',+ limits: { maxGlbBytes: 2048 },+ });+ expect(() =>+ createEvaluatorRequestV1({+ requestId: 'remote-43',+ code: BOX_CODE,+ options: { textureResolver: (async () => undefined) as never },+ }),+ ).toThrow('host resolver');+ });++ test('binds the response to the caller request id and enforces transport caps', async () => {+ const direct = await renderGLBInProcess(BOX_CODE);+ const port = createEvaluatorPortV1(async (requestJson) => {+ const request = decodeEvaluatorRequestV1(requestJson);+ return JSON.stringify(encodeRenderResultV1(`${request.requestId}-wrong`, direct));+ });+ await expect(port.render(BOX_CODE)).rejects.toMatchObject({ code: 'PROTOCOL_ERROR' });++ const oversized = createEvaluatorPortV1(async () => 'x'.repeat(2049), {+ maxResponseBytes: 2048,+ });+ await expect(oversized.render(BOX_CODE)).rejects.toMatchObject({+ code: 'OUTPUT_LIMIT_EXCEEDED',+ });++ const stalled = createEvaluatorPortV1(() => new Promise(() => {}), { deadlineMs: 10 });+ await expect(stalled.render(BOX_CODE)).rejects.toMatchObject({ code: 'DEADLINE_EXCEEDED' });+ });++ test('preserves bounded QA evidence for the existing repair loop', async () => {+ const direct = await renderGLBInProcess(BOX_CODE);+ const report = createAssetQaReportV1(createAssetIntentV1({ category: 'prop' }));+ const port = createEvaluatorPortV1(async (requestJson) => {+ const decoded = decodeEvaluatorRequestV1(requestJson);+ return JSON.stringify({+ version: EVALUATOR_RESULT_VERSION,+ requestId: decoded.requestId,+ ok: false,+ error: {+ code: 'QA_BLOCKED',+ message: 'Generated asset did not pass quality checks.',+ qa: { report, stage: 'scene' },+ },+ });+ });+ try {+ await port.render(BOX_CODE);+ throw new Error(`expected QA block for ${direct.artifactGlbSha256}`);+ } catch (error) {+ expect(error).toBeInstanceOf(AssetQaBlockedError);+ expect((error as AssetQaBlockedError).report).toEqual(report);+ }+ });});diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.tsindex 0f0d21b3..5e5a53fd 100644--- a/src/evaluator/protocol.ts+++ b/src/evaluator/protocol.ts@@ -2,12 +2,15 @@ import { createHash } from 'node:crypto';import { isAssetCategory, validateAssetIntentV1, type AssetIntentV1 } from '../contracts';import type { RenderGlbOptions, RenderResult } from '../render';import type { KhronosGltfValidationReport } from '../qa/gltf';-import type { AssetQaReportV1 } from '../qa/types';+import { isQaFinding, QA_DIMENSIONS, type AssetQaReportV1 } from '../qa/types';export const EVALUATOR_REQUEST_VERSION = 'kiln.evaluator.request.v1' as const;export const EVALUATOR_RESULT_VERSION = 'kiln.evaluator.result.v1' as const;export const MAX_EVALUATOR_CODE_BYTES = 512 * 1024;export const MAX_EVALUATOR_REQUEST_BYTES = 1024 * 1024;+export const DEFAULT_EVALUATOR_DEADLINE_MS = 60_000;+export const DEFAULT_EVALUATOR_MAX_GLB_BYTES = 16 * 1024 * 1024;+export const DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;export type EvaluatorOutcomeCode =| 'INPUT_INVALID'@@ -43,6 +46,60 @@ export interface EvaluatorRequestV1 {limits: { maxGlbBytes: number };}+export interface CreateEvaluatorRequestV1Input {+ requestId: string;+ code: string;+ options?: RenderGlbOptions;+ maxGlbBytes?: number;+}++export interface EvaluatorTransportControlsV1 {+ deadlineMs: number;+ maxResponseBytes: number;+}++export type EvaluatorTransportV1 = (+ requestJson: string,+ controls: Readonly<EvaluatorTransportControlsV1>,+) => Promise<string>;++export interface EvaluatorPortCallControlsV1 {+ deadlineMs?: number;+ maxGlbBytes?: number;+ maxResponseBytes?: number;+}++export interface EvaluatorPortV1 {+ render(+ code: string,+ options?: RenderGlbOptions,+ controls?: EvaluatorPortCallControlsV1,+ ): Promise<RenderResult>;+}++export type EvaluatorExecutionProfileV1 = 'trusted-local' | 'evaluator-required';++export function resolveEvaluatorPortV1(+ port: EvaluatorPortV1 | undefined,+ profile: EvaluatorExecutionProfileV1,+): EvaluatorPortV1 {+ if (port) return port;+ if (profile === 'evaluator-required') {+ throw new EvaluatorPortError('ISOLATION_UNAVAILABLE', 'Evaluator port is required.');+ }+ return trustedInProcessEvaluatorPortV1;+}++export class EvaluatorPortError extends Error {+ constructor(+ readonly code: EvaluatorOutcomeCode,+ message = evaluatorOutcomeMessage(code),+ ) {+ super(message);+ this.name = 'EvaluatorPortError';+ }+}+interface WireDiagnosticView {[key: string]: unknown;pngBase64: string;@@ -99,6 +156,99 @@ function validInteger(value: unknown, min: number, max: number): value is numberreturn Number.isInteger(value) && Number(value) >= min && Number(value) <= max;}+function validQaReport(value: unknown): value is AssetQaReportV1 {+ const dimensions = isRecord(value) && isRecord(value.dimensions) ? value.dimensions : undefined;+ if (+ !isRecord(value) ||+ !hasExactKeys(value, ['schemaVersion', 'category', 'qaProfile', 'disposition', 'dimensions']) ||+ value.schemaVersion !== 1 ||+ !isAssetCategory(value.category) ||+ typeof value.qaProfile !== 'string' ||+ value.qaProfile.length < 1 ||+ value.qaProfile.length > 128 ||+ !['pass', 'warn', 'block', 'notEvaluated', 'legacy-unassessed'].includes(+ String(value.disposition),+ ) ||+ !dimensions ||+ !hasExactKeys(dimensions, QA_DIMENSIONS) ||+ !QA_DIMENSIONS.every((dimension) => dimension in dimensions)+ ) {+ return false;+ }+ return QA_DIMENSIONS.every((dimension) => {+ const result = dimensions[dimension];+ return (+ isRecord(result) &&+ hasExactKeys(result, ['status', 'findings', 'metrics']) &&+ ['pass', 'warn', 'block', 'notEvaluated'].includes(String(result.status)) &&+ Array.isArray(result.findings) &&+ result.findings.length <= 1_000 &&+ result.findings.every(isQaFinding) &&+ (result.metrics === undefined || isRecord(result.metrics))+ );+ });+}++function validGltfValidation(value: unknown): value is KhronosGltfValidationReport {+ const issues = isRecord(value) && isRecord(value.issues) ? value.issues : undefined;+ if (!issues || !Array.isArray(issues.messages)) {+ return false;+ }+ return (+ ['numErrors', 'numWarnings', 'numInfos', 'numHints'].every((key) =>+ validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER),+ ) &&+ issues.messages.length <= 1_000 &&+ issues.messages.every(+ (issue) =>+ isRecord(issue) &&+ typeof issue.code === 'string' &&+ typeof issue.message === 'string' &&+ typeof issue.severity === 'number' &&+ Number.isFinite(issue.severity),+ )+ );+}++function boundedControl(value: number | undefined, fallback: number, max: number): number {+ const resolved = value ?? fallback;+ if (!validInteger(resolved, 1, max)) {+ throw new EvaluatorPortError('INPUT_INVALID');+ }+ return resolved;+}++export function createEvaluatorRequestV1(input: CreateEvaluatorRequestV1Input): {+ request: EvaluatorRequestV1;+ json: string;+} {+ if (input.options?.textureResolver) {+ throw new EvaluatorPortError(+ 'INPUT_INVALID',+ 'Evaluator requests do not accept a host resolver capability.',+ );+ }+ const maxGlbBytes = boundedControl(+ input.maxGlbBytes,+ DEFAULT_EVALUATOR_MAX_GLB_BYTES,+ 64 * 1024 * 1024,+ );+ const { textureResolver: _, ...options } = input.options ?? {};+ const request: EvaluatorRequestV1 = {+ version: EVALUATOR_REQUEST_VERSION,+ requestId: input.requestId,+ operation: 'execute-export-glb',+ code: input.code,+ options,+ limits: { maxGlbBytes },+ };+ const json = JSON.stringify(request);+ // Reuse the strict decoder as the single authority for ids, source, options,+ // prototype-key rejection, and request budgets.+ const decoded = decodeEvaluatorRequestV1(json);+ return { request: decoded, json };+}+function parseOptions(value: unknown): Omit<RenderGlbOptions, 'textureResolver'> {if (!isRecord(value) || !hasExactKeys(value, ['optimize', 'instance', 'intent', 'category'])) {return fail('request');@@ -184,7 +334,11 @@ function isSha256(value: unknown): value is `sha256:${string}` {return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);}-export function decodeEvaluatorResultV1(json: string, maxGlbBytes: number): EvaluatorResultV1 {+export function decodeEvaluatorResultV1(+ json: string,+ maxGlbBytes: number,+ expectedRequestId?: string,+): EvaluatorResultV1 {let value: unknown;try {value = JSON.parse(json);@@ -200,6 +354,7 @@ export function decodeEvaluatorResultV1(json: string, maxGlbBytes: number): Eval) {return fail('result');}+ if (expectedRequestId !== undefined && value.requestId !== expectedRequestId) fail('result');if (!value.ok) {if (value.render !== undefined) return fail('result');if (!isRecord(value.error) || !hasExactKeys(value.error, ['code', 'message', 'qa'])) {@@ -222,6 +377,21 @@ export function decodeEvaluatorResultV1(json: string, maxGlbBytes: number): Eval) {return fail('result');}+ if (value.error.qa !== undefined) {+ if (+ value.error.code !== 'QA_BLOCKED' ||+ !isRecord(value.error.qa) ||+ !hasExactKeys(value.error.qa, ['report', 'stage', 'gltfValidation']) ||+ !validQaReport(value.error.qa.report) ||+ !['scene', 'final-glb'].includes(String(value.error.qa.stage)) ||+ (value.error.qa.gltfValidation !== undefined &&+ !validGltfValidation(value.error.qa.gltfValidation))+ ) {+ return fail('result');+ }+ } else if (value.error.code === 'QA_BLOCKED') {+ return fail('result');+ }return value as unknown as Extract<EvaluatorResultV1, { ok: false }>;}if (value.error !== undefined || !isRecord(value.render)) fail('result');@@ -276,3 +446,80 @@ export function decodeEvaluatorResultV1(json: string, maxGlbBytes: number): Eval} as unknown as RenderResult,};}++export function createEvaluatorPortV1(+ transport: EvaluatorTransportV1,+ defaults: EvaluatorPortCallControlsV1 = {},+): EvaluatorPortV1 {+ let sequence = 0;+ return {+ async render(code, options = {}, controls = {}) {+ const deadlineMs = boundedControl(+ controls.deadlineMs ?? defaults.deadlineMs,+ DEFAULT_EVALUATOR_DEADLINE_MS,+ 120_000,+ );+ const maxGlbBytes = boundedControl(+ controls.maxGlbBytes ?? defaults.maxGlbBytes,+ DEFAULT_EVALUATOR_MAX_GLB_BYTES,+ 64 * 1024 * 1024,+ );+ const maxResponseBytes = boundedControl(+ controls.maxResponseBytes ?? defaults.maxResponseBytes,+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,+ 96 * 1024 * 1024,+ );+ const requestId = `eval-${++sequence}`;+ const built = createEvaluatorRequestV1({ requestId, code, options, maxGlbBytes });+ let timer: ReturnType<typeof setTimeout> | undefined;+ let response: string;+ try {+ response = await Promise.race([+ transport(built.json, { deadlineMs, maxResponseBytes }),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new EvaluatorPortError('DEADLINE_EXCEEDED')),+ deadlineMs,+ );+ }),+ ]);+ } catch (error) {+ if (error instanceof EvaluatorPortError) throw error;+ throw new EvaluatorPortError('WORKER_FAILED');+ } finally {+ clearTimeout(timer);+ }+ if (typeof response !== 'string') throw new EvaluatorPortError('PROTOCOL_ERROR');+ if (Buffer.byteLength(response, 'utf8') > maxResponseBytes) {+ throw new EvaluatorPortError('OUTPUT_LIMIT_EXCEEDED');+ }+ let result: EvaluatorResultV1;+ try {+ result = decodeEvaluatorResultV1(response, maxGlbBytes, requestId);+ } catch {+ throw new EvaluatorPortError('PROTOCOL_ERROR');+ }+ if (!result.ok) {+ if (result.error.code === 'QA_BLOCKED' && result.error.qa) {+ const { AssetQaBlockedError } = await import('../qa/run');+ throw new AssetQaBlockedError(+ result.error.qa.report,+ result.error.qa.stage,+ result.error.qa.gltfValidation,+ );+ }+ throw new EvaluatorPortError(result.error.code);+ }+ return result.render;+ },+ };+}++/** Explicit trusted/test compatibility port. Production hosts must inject a+ * transport-backed port and select `evaluator-required`; there is no fallback. */+export const trustedInProcessEvaluatorPortV1: EvaluatorPortV1 = {+ async render(code, options = {}) {+ const { renderGLBInProcess } = await import('../render');+ return renderGLBInProcess(code, options);+ },+};diff --git a/src/evaluator/worker.ts b/src/evaluator/worker.tsindex 6538a296..7230c4ce 100644--- a/src/evaluator/worker.ts+++ b/src/evaluator/worker.ts@@ -1,15 +1,6 @@import { writeFileSync } from 'node:fs';-import { AssetQaBlockedError } from '../qa/run';-import { renderGLBInProcess } from '../render';-import {- decodeEvaluatorRequestV1,- encodeRenderResultV1,- evaluatorOutcomeMessage,- EVALUATOR_RESULT_VERSION,- MAX_EVALUATOR_REQUEST_BYTES,- type EvaluatorOutcomeCode,- type WireEvaluatorResultV1,-} from './protocol';+import { evaluateEvaluatorRequestV1 } from './handler';+import { MAX_EVALUATOR_REQUEST_BYTES } from './protocol';async function readBoundedInput(): Promise<string> {const chunks: Buffer[] = [];@@ -23,57 +14,13 @@ async function readBoundedInput(): Promise<string> {return Buffer.concat(chunks).toString('utf8');}-function sanitizedFailure(requestId: string, error: unknown): WireEvaluatorResultV1 {- if (error instanceof AssetQaBlockedError) {- return {- version: EVALUATOR_RESULT_VERSION,- requestId,- ok: false,- error: {- code: 'QA_BLOCKED',- message: evaluatorOutcomeMessage('QA_BLOCKED'),- qa: {- report: error.report,- stage: error.stage,- ...(error.gltfValidation ? { gltfValidation: error.gltfValidation } : {}),- },- },- };- }- const code: EvaluatorOutcomeCode =- error instanceof Error && error.message.includes('exceeds its configured output limit')- ? 'OUTPUT_LIMIT_EXCEEDED'- : 'EXECUTION_REJECTED';- return {- version: EVALUATOR_RESULT_VERSION,- requestId,- ok: false,- error: {- code,- message: evaluatorOutcomeMessage(code),- },- };-}--let output: WireEvaluatorResultV1;try {- const request = decodeEvaluatorRequestV1(await readBoundedInput());- try {- const render = await renderGLBInProcess(request.code, request.options);- if (render.glb.byteLength > request.limits.maxGlbBytes) {- throw new Error('GLB exceeds its configured output limit');- }- output = encodeRenderResultV1(request.requestId, render);- } catch (error) {- output = sanitizedFailure(request.requestId, error);- }+ writeFileSync(3, await evaluateEvaluatorRequestV1(await readBoundedInput()), {+ encoding: 'utf8',+ });} catch {- output = {- version: EVALUATOR_RESULT_VERSION,- requestId: 'invalid',- ok: false,- error: { code: 'INPUT_INVALID', message: evaluatorOutcomeMessage('INPUT_INVALID') },- };+ // Input overflow happens before the handler can classify a request. Passing+ // an invalid empty request through the same handler keeps the result shape+ // canonical and sanitized.+ writeFileSync(3, await evaluateEvaluatorRequestV1(''), { encoding: 'utf8' });}--writeFileSync(3, JSON.stringify(output), { encoding: 'utf8' });diff --git a/src/inspect.ts b/src/inspect.tsindex c8b7e73b..4d6fd68c 100644--- a/src/inspect.ts+++ b/src/inspect.ts@@ -18,8 +18,14 @@import * as THREE from 'three';-import { executeKilnCode, inspectGeneratedAnimation } from './render';+import { inspectGeneratedAnimation } from './render';import { listPrimitives } from './list-primitives';+import {+ resolveEvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorPortV1,+} from './evaluator';+import { loadGlbReviewScene } from './views/glb';// =============================================================================// Types@@ -101,10 +107,14 @@ function detectPrimitivesUsed(code: string): string[] {function classifyNode(obj: THREE.Object3D): 'pivot' | 'mesh' | 'group' {// Duck-typed `.isMesh` instead of `instanceof` — sandbox-created meshes- // (from `new Function(...)` in executeKilnCode) belong to a different+ // Loaded GLB scene objects may belong to a different// module realm than this file's THREE import, so `instanceof` returns// false. See `kiln-cross-module-three.md` memory + render.ts comment.- if ((obj as { isMesh?: boolean }).isMesh) return 'mesh';+ if (+ (obj as { isMesh?: boolean }).isMesh ||+ (obj.userData as { kilnGlbMeshNode?: boolean }).kilnGlbMeshNode+ )+ return 'mesh';if (obj.name.startsWith('Joint_')) return 'pivot';return 'group';}@@ -156,14 +166,14 @@ function countUniqueMaterials(root: THREE.Object3D): number {function computeBoundingBox(root: THREE.Object3D): InspectBoundingBox {// Ensure world matrices are fresh before measuring — otherwise nested// pivots can misreport bounds when positions were set after the last- // auto-update. executeKilnCode hands us a detached tree, so we drive+ // auto-update. The GLB loader hands us a detached tree, so we drive// updates explicitly.root.updateMatrixWorld(true);const box = new THREE.Box3().setFromObject(root);// If the scene has no geometry at all (pivots-only), Box3 stays at +Inf /// -Inf. Collapse to the origin so downstream consumers get finite numbers.- if (!isFinite(box.min.x) || !isFinite(box.max.x)) {+ if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return {min: [0, 0, 0],max: [0, 0, 0],@@ -232,11 +242,20 @@ function collectAnimationTracks(/*** Execute Kiln code and return a structured inspection report.*- * @throws {Error} if the code can't be executed (same errors as- * {@link executeKilnCode}).+ * @throws {Error} if the evaluator rejects the code or the returned GLB.*/-export async function inspect(code: string): Promise<InspectResult> {- const { meta, root, clips } = await executeKilnCode(code);+export async function inspect(+ code: string,+ options: {+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;+ } = {},+): Promise<InspectResult> {+ const rendered = await resolveEvaluatorPortV1(+ options.evaluatorPort,+ options.evaluatorProfile ?? 'trusted-local',+ ).render(code);+ const { root, clips } = await loadGlbReviewScene(rendered.glb);const primitivesUsed = detectPrimitivesUsed(code);const namedParts = collectNamedParts(root);@@ -244,7 +263,7 @@ export async function inspect(code: string): Promise<InspectResult> {const materials = countUniqueMaterials(root);const boundingBox = computeBoundingBox(root);const animationTracks = collectAnimationTracks(root, clips);- const warnings = inspectGeneratedAnimation(root, clips);+ const warnings = [...rendered.warnings, ...inspectGeneratedAnimation(root, clips)];return {triangles,@@ -254,6 +273,6 @@ export async function inspect(code: string): Promise<InspectResult> {animationTracks,primitivesUsed,warnings,- meta: meta as Record<string, unknown>,+ meta: rendered.meta as Record<string, unknown>,};}diff --git a/src/tools/__tests__/registry-derivative-views.test.ts b/src/tools/__tests__/registry-derivative-views.test.tsindex 079a07ba..57d78e1b 100644--- a/src/tools/__tests__/registry-derivative-views.test.ts+++ b/src/tools/__tests__/registry-derivative-views.test.ts@@ -22,7 +22,7 @@ function build() {return root;}function animate() {- return [createClip('move', 1, [rotationTrack('Arm', [+ return [createClip('move', 1, [rotationTrack('Joint_Arm', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 90, 0] }])])];}`;@@ -45,7 +45,7 @@ function solidPng(size: number): Uint8Array {}describe('derivative review surfaces', () => {- test('animation executes source once and binds every GPU frame receipt to its derivative GLB', async () => {+ test('animation evaluates once and never re-executes source while binding derivative receipts', async () => {const requests: PbrRenderRequest[] = [];const port: PbrRenderPort = async (request) => {requests.push(request);diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 80bf1428..653da1c1 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -21,7 +21,7 @@ import { z } from 'zod';import * as THREE from 'three';import { validate } from '../validation';-import { executeKilnCode, inspectSceneStructure, renderSceneToGLB } from '../render';+import { inspectSceneStructure, renderSceneToGLB, type RenderResult } from '../render';import { listPrimitives, type PrimitiveSpec } from '../list-primitives';import type { AssetCategory, AssetIntentV1 } from '../contracts';import type { AssetQaReportV1 } from '../qa';@@ -34,6 +34,8 @@ import type {ViewEvidenceHistoryV1,} from '../composer/render-port';import type { ViewGridResult } from '../views';+import type { EvaluatorExecutionProfileV1, EvaluatorPortV1 } from '../evaluator';+import { resolveEvaluatorPortV1 } from '../evaluator';import { sceneNeedsPbrShading } from '../material-resources';import type { GenerationCallBudget } from '../agent/call-budget';import {@@ -132,6 +134,11 @@ export interface KilnToolContext {generationCallBudget?: GenerationCallBudget;/** Shared bounded hash-only evidence ledger for one agent/tool session. */viewEvidenceHistory?: ViewEvidenceHistoryStore;+ /** Host-owned generated-source execution boundary. Production selects+ * `evaluator-required`; trusted local/test callers may retain the explicit+ * compatibility profile. */+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;}/** JSON-safe value accepted from a host visual observer. */@@ -205,6 +212,28 @@ function trustedCategory(context: KilnToolContext): AssetCategory | undefined {return context.intent?.category ?? context.category;}+async function evaluateGeneratedSource(+ code: string,+ context: KilnToolContext,+ optimize: 'off' | 'auto' = 'off',+): Promise<RenderResult> {+ return resolveEvaluatorPortV1(+ context.evaluatorPort,+ context.evaluatorProfile ?? 'trusted-local',+ ).render(code, {+ optimize,+ ...(trustedCategory(context) ? { category: trustedCategory(context) } : {}),+ ...(context.intent ? { intent: context.intent } : {}),+ });+}++async function loadEvaluatedReviewScene(code: string, context: KilnToolContext) {+ const rendered = await evaluateGeneratedSource(code, context);+ const { loadGlbReviewScene } = await import('../views');+ const scene = await loadGlbReviewScene(rendered.glb);+ return { rendered, ...scene };+}+const viewEvidenceHistoryByContext = new WeakMap<KilnToolContext, ViewEvidenceHistoryStore>();const VIEW_EVIDENCE_GUIDANCE =' viewEvidence.current describes ONLY this request. lastFaithful is older hash-only evidence for reference, not reused pixels and not current verification.';@@ -601,22 +630,15 @@ async function runRender(context: KilnToolContext,): Promise<KilnRenderMetrics> {try {- const { root, clips } = await executeKilnCode(input.code);+ const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);const category = trustedCategory(context);// Structural advisories (floating parts / stray planes at origin).const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);- // Render to GLB bytes for the triangle count. Output is discarded — pure- // metrics, no files written.- const rendered = await renderSceneToGLB(root, {- clips,- ...(category ? { category } : {}),- ...(context.intent ? { intent: context.intent } : {}),- });-const warnings = [...structuralWarnings, ...rendered.warnings];+ const instanceability = rendered.meta.instanceability;return {ok: true,@@ -625,16 +647,16 @@ async function runRender(materials: metrics.materials,bbox: metrics.bbox,lowestPart: metrics.lowestPart,- ...(rendered.instanceability+ ...(instanceability? {instanceability: {- grade: rendered.instanceability.grade,- summary: rendered.instanceability.summary,+ grade: instanceability.grade,+ summary: instanceability.summary,},}: {}),warnings,- qaReport: rendered.qaReport,+ qaReport: rendered.meta.qaReport as AssetQaReportV1 | undefined,};} catch (err) {return {@@ -674,12 +696,12 @@ async function runScreenshot(context: KilnToolContext,): Promise<KilnScreenshotResult> {try {- const { renderViewGrid } = await import('../views');- const { root } = await executeKilnCode(input.code);+ const { renderGlbViewGrid } = await import('../views');+ const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });// No capture config here on purpose: kiln_screenshot belongs to the frozen// four-tool baseline, whose schemas stay byte-for-byte unchanged.- const grid = await renderViewGrid(root);+ const grid = await renderGlbViewGrid(rendered.glb);return {ok: true,views: grid.views,@@ -757,26 +779,25 @@ async function runRenderViews(// put a `node:fs` edge — evaluated on import, not on call — into this// module's graph, which is exactly what the lazy `../views` import at the top// of this file exists to prevent.- const { renderViewGrid, CPU_RASTER_RENDERER_ID, resolveGridCapture } = await import('../views');- const { root, clips } = await executeKilnCode(input.code);+ const { renderGlbViewGrid, CPU_RASTER_RENDERER_ID, resolveGridCapture } = await import(+ '../views'+ );+ const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);const category = trustedCategory(context);const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);- // Single execution, two consumers — both read-only on `root`.- const rendered = await renderSceneToGLB(root, {- clips,- ...(category ? { category } : {}),- ...(context.intent ? { intent: context.intent } : {}),- });-// Route to the GPU only when a flat-shaded raster would misrepresent the// scene. A prop made of untextured `gameMaterial` looks the same either way,// so sending it costs a round trip and a warm GPU to draw a picture the CPU// already draws correctly. `renderSceneToGLB` above ALREADY produced the// bytes the port needs — this reuses them rather than paying a second bake.- const neededPbr = sceneNeedsPbrShading(root);+ const neededPbr =+ sceneNeedsPbrShading(root) ||+ (rendered.materialMetrics?.texturedMaterials ?? 0) > 0 ||+ (rendered.materialMetrics?.materialExtensionCount ?? 0) > 0 ||+ reasonCodes.length > 0;let grid: ViewGridResult | undefined;let drawnBy: InLoopViewRender | undefined;let materialFaithful = false;@@ -790,7 +811,7 @@ async function runRenderViews(const { captureViewsViaPort } = await import('../agent/generate');const ported = await captureViewsViaPort(context.viewRenderPort,- rendered.bytes,+ rendered.glb,resolveInLoopViewRenderTimeoutMs(context, 'in-loop-grid'),input.capture,);@@ -822,7 +843,7 @@ async function runRenderViews(// not need PBR, every host with no port, and every port call that did not// come back. It is never skipped as an optimisation — it is the fallback.if (!grid) {- grid = await renderViewGrid(root, input.capture ? { capture: input.capture } : {});+ grid = await renderGlbViewGrid(rendered.glb, input.capture ? { capture: input.capture } : {});}drawnBy ??= context.viewRenderPort? { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr }@@ -838,8 +859,8 @@ async function runRenderViews(// Copy into an ArrayBuffer-backed view: render bytes are typed as// `Uint8Array<ArrayBufferLike>`, while Web Crypto deliberately rejects a// possible SharedArrayBuffer at its boundary.- const hashInput = new Uint8Array(rendered.bytes.byteLength);- hashInput.set(rendered.bytes);+ const hashInput = new Uint8Array(rendered.glb.byteLength);+ hashInput.set(rendered.glb);const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', hashInput));const inputGlbSha256 = `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0'))@@ -874,11 +895,11 @@ async function runRenderViews(materials: metrics.materials,bbox: metrics.bbox,lowestPart: metrics.lowestPart,- ...(rendered.instanceability+ ...(rendered.meta.instanceability? {instanceability: {- grade: rendered.instanceability.grade,- summary: rendered.instanceability.summary,+ grade: rendered.meta.instanceability.grade,+ summary: rendered.meta.instanceability.summary,},}: {}),@@ -890,7 +911,7 @@ async function runRenderViews(viewFidelity,...(viewEvidence ? { viewEvidence } : {}),warnings,- qaReport: rendered.qaReport,+ qaReport: rendered.meta.qaReport as AssetQaReportV1 | undefined,};} catch (err) {return {@@ -983,7 +1004,7 @@ async function runScreenshotAnimation(): Promise<KilnScreenshotAnimationResult> {try {const { renderClipAnimation } = await import('../views');- const { root, clips } = await executeKilnCode(input.code);+ const { root, clips } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });const r = await renderClipAnimation(root, clips, {clip: input.clip,@@ -1132,7 +1153,7 @@ async function runViewInterior(): Promise<KilnViewInteriorResult> {try {const { renderInteriorGrid } = await import('../views');- const { root } = await executeKilnCode(input.code);+ const { root } = await loadEvaluatedReviewScene(input.code, context);// No default name. An explicit nodeName stays an exact-name override; with// none, the grid resolves the roof from its semantic role (and only then// falls back to historical "Roof" naming) — so a correctly-roled roof named@@ -1305,7 +1326,7 @@ async function runInspect(): Promise<KilnInspectResult> {try {const { prepareInspectView } = await import('../views/inspect');- const { root } = await executeKilnCode(input.code);+ const { root } = await loadEvaluatedReviewScene(input.code, context);const r = prepareInspectView(root, {...(input.part !== undefined ? { part: input.part } : {}),...(input.view !== undefined ? { view: input.view } : {}),diff --git a/src/views/__tests__/glb.test.ts b/src/views/__tests__/glb.test.tsindex 788a4f5a..beaef56d 100644--- a/src/views/__tests__/glb.test.ts+++ b/src/views/__tests__/glb.test.ts@@ -8,6 +8,7 @@ import {GLB_GEOMETRY_FLAT_REASON,geometryFlatTextureReasonCode,loadGlbGeometryFlatScene,+ loadGlbReviewScene,measureBounds,renderGlbViewGrid,} from '..';@@ -131,4 +132,18 @@ describe('GLB-native geometry-flat view input', () => {GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,);});++ test('review scene retains embedded texture bytes for derivative re-export', async () => {+ const source = triangleDocument({ texture: true });+ const expected = source.getRoot().listTextures()[0]!.getImage()!;+ const loaded = await loadGlbReviewScene(await io().writeBinary(source));+ let encoded: Uint8Array | undefined;+ loaded.root.traverse((node) => {+ const map = (node as { material?: { map?: { userData?: Record<string, unknown> } } }).material+ ?.map;+ const record = map?.userData?.encoded as { bytes?: Uint8Array } | undefined;+ if (record?.bytes) encoded = record.bytes;+ });+ expect(encoded).toEqual(expected);+ });});diff --git a/src/views/glb.ts b/src/views/glb.tsindex f0d246d0..4d8c9cbe 100644--- a/src/views/glb.ts+++ b/src/views/glb.ts@@ -1,12 +1,34 @@/** GLB-native input adapter for the deterministic CPU geometry-flat renderer. */-import { Primitive, WebIO, type Accessor, type Material } from '@gltf-transform/core';+import {+ Primitive,+ WebIO,+ type Accessor,+ type Material,+ type Texture as GltfTexture,+} from '@gltf-transform/core';import {EXTMeshGPUInstancing,KHRMaterialsVariants,KHRTextureBasisu,} from '@gltf-transform/extensions';-import { Matrix4, Quaternion, Vector3 } from 'three';+import {+ BufferAttribute,+ BufferGeometry,+ Group,+ Matrix4,+ Mesh,+ MeshStandardMaterial,+ NoColorSpace,+ SRGBColorSpace,+ Texture,+ type Object3D,+ AnimationClip,+ QuaternionKeyframeTrack,+ VectorKeyframeTrack,+ Quaternion,+ Vector3,+} from 'three';export const GLB_GEOMETRY_FLAT_REASON = {TEXTURE_SAMPLING_UNSUPPORTED: 'GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED',@@ -53,6 +75,11 @@ interface FlatMaterial {color: { r: number; g: number; b: number };opacity: number;doubleSided: boolean;+ metalness: number;+ roughness: number;+ alphaMode: 'OPAQUE' | 'MASK' | 'BLEND';+ alphaCutoff: number;+ emissive: [number, number, number];}interface FlatMesh {@@ -78,6 +105,11 @@ export interface LoadedGlbGeometryFlatScene {instanceCount: number;}+export interface LoadedGlbReviewScene extends LoadedGlbGeometryFlatScene {+ root: Object3D;+ clips: AnimationClip[];+}+const glbIO = (): WebIO =>new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRMaterialsVariants, KHRTextureBasisu]);@@ -136,7 +168,16 @@ function triangleIndices(function flatMaterial(material: Material | null): FlatMaterial {if (!material) {- return { color: { r: 0.7, g: 0.7, b: 0.7 }, opacity: 1, doubleSided: false };+ return {+ color: { r: 0.7, g: 0.7, b: 0.7 },+ opacity: 1,+ doubleSided: false,+ metalness: 0,+ roughness: 1,+ alphaMode: 'OPAQUE',+ alphaCutoff: 0.5,+ emissive: [0, 0, 0],+ };}const [r, g, b, factorAlpha] = material.getBaseColorFactor();const alphaMode = material.getAlphaMode();@@ -150,9 +191,38 @@ function flatMaterial(material: Material | null): FlatMaterial {color: { r, g, b },opacity,doubleSided: material.getDoubleSided(),+ metalness: material.getMetallicFactor(),+ roughness: material.getRoughnessFactor(),+ alphaMode,+ alphaCutoff: material.getAlphaCutoff(),+ emissive: material.getEmissiveFactor(),};}+function preserveTexture(+ source: GltfTexture | null,+ usage: 'color' | 'data',+ cache: Map<GltfTexture, Map<'color' | 'data', Texture>>,+): Texture | null {+ if (!source) return null;+ const encoded = source.getImage();+ const mime = source.getMimeType();+ if (!encoded || !mime) return null;+ let byUsage = cache.get(source);+ if (!byUsage) {+ byUsage = new Map();+ cache.set(source, byUsage);+ }+ const existing = byUsage.get(usage);+ if (existing) return existing;+ const texture = new Texture();+ texture.name = source.getName();+ texture.colorSpace = usage === 'color' ? SRGBColorSpace : NoColorSpace;+ texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };+ byUsage.set(usage, texture);+ return texture;+}+function noteMaterialTextures(material: Material | null,reasons: Set<GlbGeometryFlatReasonCode>,@@ -310,3 +380,191 @@ export async function loadGlbGeometryFlatScene(instanceCount,};}++function localInstanceMatrices(node: import('@gltf-transform/core').Node): Matrix4[] {+ const extension = node.getExtension('EXT_mesh_gpu_instancing') as {+ getAttribute(name: string): Accessor | null;+ listAttributes(): Accessor[];+ } | null;+ if (!extension) return [new Matrix4()];+ const attributes = extension.listAttributes();+ if (attributes.length === 0) {+ throw new GlbGeometryFlatError('GLB_FLAT_INVALID_INSTANCING', 'Invalid empty instancing data.');+ }+ const count = attributes[0]!.getCount();+ if (attributes.some((attribute) => attribute.getCount() !== count)) {+ throw new GlbGeometryFlatError('GLB_FLAT_INVALID_INSTANCING', 'Mismatched instancing data.');+ }+ const translations = extension.getAttribute('TRANSLATION');+ const rotations = extension.getAttribute('ROTATION');+ const scales = extension.getAttribute('SCALE');+ const translation: number[] = [];+ const rotation: number[] = [];+ const scale: number[] = [];+ return Array.from({ length: count }, (_, index) => {+ translations?.getElement(index, translation);+ rotations?.getElement(index, rotation);+ scales?.getElement(index, scale);+ return new Matrix4().compose(+ new Vector3(+ ...(translations ? (translation.slice(0, 3) as [number, number, number]) : [0, 0, 0]),+ ),+ new Quaternion(+ ...(rotations ? (rotation.slice(0, 4) as [number, number, number, number]) : [0, 0, 0, 1]),+ ).normalize(),+ new Vector3(...(scales ? (scale.slice(0, 3) as [number, number, number]) : [1, 1, 1])),+ );+ });+}++/** Load exact GLB bytes into a named, transformable review scene. This is the+ * production replacement for re-executing generated source in animation,+ * interior, inspect, and composed-scene review tools. Textures are deliberately+ * not sampled by the CPU scene; the same reason codes remain explicit. */+export async function loadGlbReviewScene(bytes: Uint8Array): Promise<LoadedGlbReviewScene> {+ let document: import('@gltf-transform/core').Document;+ try {+ document = await glbIO().readBinary(Uint8Array.from(bytes));+ } catch {+ throw new GlbGeometryFlatError('GLB_FLAT_PARSE_FAILED', 'Could not parse final GLB bytes.');+ }+ const sourceScene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];+ if (!sourceScene) throw new GlbGeometryFlatError('GLB_FLAT_NO_SCENE', 'Final GLB has no scene.');+ const reasons = new Set<GlbGeometryFlatReasonCode>();+ const root = new Group();+ root.name = sourceScene.getName() || 'Scene';+ const nodeMap = new Map<import('@gltf-transform/core').Node, Object3D>();+ const textureCache = new Map<GltfTexture, Map<'color' | 'data', Texture>>();+ let meshCount = 0;+ let instanceCount = 0;++ const buildNode = (source: import('@gltf-transform/core').Node): Object3D => {+ const existing = nodeMap.get(source);+ if (existing) return existing;+ const target = new Group();+ target.name = source.getName();+ target.position.fromArray(source.getTranslation());+ target.quaternion.fromArray(source.getRotation());+ target.scale.fromArray(source.getScale());+ target.userData = { ...source.getExtras() };+ nodeMap.set(source, target);+ const sourceMesh = source.getMesh();+ if (sourceMesh) {+ target.userData.kilnGlbMeshNode = true;+ if (source.getSkin()) reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);+ const matrices = localInstanceMatrices(source);+ instanceCount += matrices.length;+ for (const [primitiveIndex, primitive] of sourceMesh.listPrimitives().entries()) {+ if (primitive.listTargets().length)+ reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);+ const position = primitive.getAttribute('POSITION');+ if (position?.getElementSize() !== 3) continue;+ const indices = triangleIndices(primitive, position.getCount());+ if (!indices) {+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);+ continue;+ }+ const material = primitive.getMaterial();+ noteMaterialTextures(material, reasons);+ const flat = flatMaterial(material);+ const geometry = new BufferGeometry();+ geometry.setAttribute(+ 'position',+ new BufferAttribute(Float32Array.from(decodedAccessor(position)), 3),+ );+ geometry.setIndex(new BufferAttribute(indices, 1));+ const threeMaterial = new MeshStandardMaterial({+ opacity: flat.opacity,+ transparent: flat.alphaMode === 'BLEND',+ alphaTest: flat.alphaMode === 'MASK' ? flat.alphaCutoff : 0,+ side: flat.doubleSided ? 2 : 0,+ metalness: flat.metalness,+ roughness: flat.roughness,+ });+ threeMaterial.color.setRGB(flat.color.r, flat.color.g, flat.color.b);+ threeMaterial.emissive.fromArray(flat.emissive);+ if (material) {+ threeMaterial.map = preserveTexture(+ material.getBaseColorTexture(),+ 'color',+ textureCache,+ );+ threeMaterial.normalMap = preserveTexture(+ material.getNormalTexture(),+ 'data',+ textureCache,+ );+ threeMaterial.normalScale.setScalar(material.getNormalScale());+ const metallicRoughness = preserveTexture(+ material.getMetallicRoughnessTexture(),+ 'data',+ textureCache,+ );+ threeMaterial.metalnessMap = metallicRoughness;+ threeMaterial.roughnessMap = metallicRoughness;+ threeMaterial.emissiveMap = preserveTexture(+ material.getEmissiveTexture(),+ 'color',+ textureCache,+ );+ threeMaterial.aoMap = preserveTexture(+ material.getOcclusionTexture(),+ 'data',+ textureCache,+ );+ threeMaterial.aoMapIntensity = material.getOcclusionStrength();+ }+ for (const [index, matrix] of matrices.entries()) {+ const mesh = new Mesh(geometry, threeMaterial);+ const baseName = sourceMesh.getName() || source.getName() || 'Mesh';+ mesh.name = `${baseName}:primitive-${primitiveIndex}${+ matrices.length === 1 ? '' : `:instance-${index}`+ }`;+ mesh.matrixAutoUpdate = false;+ mesh.matrix.copy(matrix);+ target.add(mesh);+ meshCount++;+ }+ }+ }+ for (const child of source.listChildren()) target.add(buildNode(child));+ return target;+ };+ for (const child of sourceScene.listChildren()) root.add(buildNode(child));+ root.updateMatrixWorld(true);+ if (meshCount === 0)+ throw new GlbGeometryFlatError(+ 'GLB_FLAT_NO_RENDERABLE_GEOMETRY',+ 'Final GLB contains no renderable geometry.',+ );++ const clips = document+ .getRoot()+ .listAnimations()+ .map(+ (animation) =>+ new AnimationClip(+ animation.getName(),+ -1,+ animation.listChannels().flatMap((channel) => {+ const node = channel.getTargetNode();+ const path = channel.getTargetPath();+ const sampler = channel.getSampler();+ const input = sampler?.getInput()?.getArray();+ const output = sampler?.getOutput()?.getArray();+ const property =+ path === 'translation' ? 'position' : path === 'rotation' ? 'quaternion' : path;+ if (!node || !property || property === 'weights' || !input || !output) return [];+ const Track = path === 'rotation' ? QuaternionKeyframeTrack : VectorKeyframeTrack;+ return [new Track(`${node.getName()}.${property}`, input, output)];+ }),+ ),+ );+ return {+ root,+ clips,+ reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),+ meshCount,+ instanceCount,+ };+}diff --git a/src/views/index.ts b/src/views/index.tsindex 8a5eccc9..1f3fb1cd 100644--- a/src/views/index.ts+++ b/src/views/index.ts@@ -43,6 +43,11 @@ import {type Vec3,} from '../palette-snap';import { loadGlbGeometryFlatScene, type GlbGeometryFlatReasonCode } from './glb';+import {+ resolveEvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorPortV1,+} from '../evaluator';export {rasterizeView,@@ -88,12 +93,14 @@ export {GlbGeometryFlatError,geometryFlatTextureReasonCode,loadGlbGeometryFlatScene,+ loadGlbReviewScene,} from './glb';export type {GlbGeometryFlatErrorCode,GlbGeometryFlatReasonCode,GlbGeometryFlatRoot,LoadedGlbGeometryFlatScene,+ LoadedGlbReviewScene,} from './glb';export {ARCHITECTURE_ROOF_ROLE_PREFIXES,@@ -442,13 +449,21 @@ function expandFrameBounds(}/** Execute a Kiln program and render its scene into the 3x2 grid. */+export interface CodeViewGridOptions extends ViewGridOptions {+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;+}+export async function renderCodeViewGrid(code: string,- opts: ViewGridOptions = {},+ opts: CodeViewGridOptions = {},): Promise<ViewGridResult> {- const { executeKilnCode } = await import('../render');- const { root } = await executeKilnCode(code);- return renderViewGrid(root, opts);+ const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;+ const rendered = await resolveEvaluatorPortV1(+ evaluatorPort,+ evaluatorProfile ?? 'trusted-local',+ ).render(code);+ return renderGlbViewGrid(rendered.glb, viewOptions);}// =============================================================================diff --git a/src/views/scene-raster.ts b/src/views/scene-raster.tsindex fb244d3e..1959f97b 100644--- a/src/views/scene-raster.ts+++ b/src/views/scene-raster.ts@@ -15,7 +15,12 @@*/import * as THREE from 'three';-import { executeKilnCode } from '../render';+import {+ resolveEvaluatorPortV1,+ type EvaluatorExecutionProfileV1,+ type EvaluatorPortV1,+} from '../evaluator';+import { loadGlbReviewScene } from './glb';import { encodePng } from './png';import { rasterizeView, type ViewSpec } from './raster';@@ -24,16 +29,25 @@ const PAD = 4;const PAD_COLOR: readonly [number, number, number] = [10, 11, 13];/** One placed asset: its Kiln program + the world transform to instance it at. */-export interface ComposedPart {- /** The asset's Kiln source (defines `meta` + `build()`). */- code: string;+export type ComposedPart = {/** World position [x, y, z] (kiln frame: +X forward, +Y up, +Z right). */pos: [number, number, number];/** Y-rotation in degrees. */rotYDeg: number;/** Uniform scale. */scale: number;-}+} & (+ | {+ /** Exact previously-evaluated GLB bytes. Preferred for production composition. */+ glb: Uint8Array;+ code?: never;+ }+ | {+ /** Trusted-local compatibility or source routed through `evaluatorPort`. */+ code: string;+ glb?: never;+ }+);/** Three canonical scene angles (kiln frame): a hero 3/4, the reverse 3/4, and a* top-down — enough to read spacing, facing, groupings, and overlaps at a glance. */@@ -59,18 +73,35 @@ export interface ComposedSceneRasterResult {*/export async function rasterizeComposedScene(parts: ComposedPart[],- opts: { views?: ViewSpec[]; size?: number } = {},+ opts: {+ views?: ViewSpec[];+ size?: number;+ evaluatorPort?: EvaluatorPortV1;+ evaluatorProfile?: EvaluatorExecutionProfileV1;+ } = {},): Promise<ComposedSceneRasterResult> {const views = opts.views?.length ? opts.views : SCENE_VIEWS;const size = opts.size ?? 320;const group = new THREE.Group();- const baseByCode = new Map<string, THREE.Object3D>();+ const baseByInput = new Map<string | Uint8Array, THREE.Object3D>();for (const part of parts) {- let base = baseByCode.get(part.code);+ if ((part.code === undefined) === (part.glb === undefined)) {+ throw new TypeError('Composed part must provide exactly one of code or glb.');+ }+ const key = part.glb ?? part.code!;+ let base = baseByInput.get(key);if (!base) {- base = (await executeKilnCode(part.code)).root;- baseByCode.set(part.code, base);+ const glb = part.glb+ ? Uint8Array.from(part.glb)+ : (+ await resolveEvaluatorPortV1(+ opts.evaluatorPort,+ opts.evaluatorProfile ?? 'trusted-local',+ ).render(part.code!)+ ).glb;+ base = (await loadGlbReviewScene(glb)).root;+ baseByInput.set(key, base);}const inst = base.clone(true);inst.position.set(part.pos[0], part.pos[1], part.pos[2]);