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: preserve agent capture and optimize OpenRouter routing (#26)
Matthew Kissingere3a0aa54ead4
diff --git a/src/agent/__tests__/run-loop.test.ts b/src/agent/__tests__/run-loop.test.tsindex 43d06f35..fa8ee2cd 100644--- a/src/agent/__tests__/run-loop.test.ts+++ b/src/agent/__tests__/run-loop.test.ts@@ -38,7 +38,7 @@ describe('runKilnAgent over a ScriptedModel (unified surface)', () => {cacheWriteInputTokens: 900,},},- { toolCalls: [{ name: 'kiln_render' }] },+ { toolCalls: [{ name: 'kiln_render', input: { capture: { preset: '2x2' } } }] },{ toolCalls: [{ name: 'kiln_finalize' }] },{text: 'done',@@ -62,6 +62,7 @@ describe('runKilnAgent over a ScriptedModel (unified surface)', () => {expect(result.code).toBe(BOX_CODE);expect(result.steps).toBe(4);expect(result.toolCalls).toEqual(['kiln_draft', 'kiln_render', 'kiln_finalize']);+ expect(result.captureSelection).toEqual({ capture: { preset: '2x2' } });// A2-instrumentation: cache counts accumulated alongside the token totals.expect(result.usage).toEqual({diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.tsindex a2833c27..a3691174 100644--- a/src/agent/providers.test.ts+++ b/src/agent/providers.test.ts@@ -453,7 +453,43 @@ describe('OpenRouter-Anthropic prompt caching (cache_control)', () => {{ provider: 'openrouter', model: 'x-ai/grok-4.3', maxTokens: 64000, thinking: 'high' },{ apiKey: 'test-key' },);- expect(settingsOf(reasoning)).toEqual({ reasoning: { effort: 'high' } });+ expect(settingsOf(reasoning)).toEqual({+ reasoning: { effort: 'high' },+ provider: { sort: 'throughput' },+ });+ });++ test('all OpenRouter author calls prefer throughput without changing the requested model', async () => {+ const model = makeKilnModel(+ { provider: 'openrouter', model: 'deepseek/deepseek-v4-flash-latest' },+ { apiKey: 'test-key' },+ );+ expect(settingsOf(model)['provider']).toEqual({ sort: 'throughput' });++ const provider = (model as unknown as { _provider: { doStream(o: unknown): Promise<unknown> } })+ ._provider;+ const realFetch = globalThis.fetch;+ let body: Record<string, unknown> | undefined;+ globalThis.fetch = (async (_url: unknown, init: { body: string }) => {+ body = JSON.parse(init.body) as Record<string, unknown>;+ return new Response('data: [DONE]\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ });+ }) as unknown as typeof fetch;+ try {+ const result = (await provider.doStream({+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],+ })) as { stream: ReadableStream<unknown> };+ const reader = result.stream.getReader();+ while (!(await reader.read()).done) {+ // drain+ }+ } finally {+ globalThis.fetch = realFetch;+ }+ expect(body?.['model']).toBe('deepseek/deepseek-v4-flash-latest');+ expect(body?.['provider']).toEqual({ sort: 'throughput' });});test('the two caching mechanisms stay separate: cache_control is not a system cache point', () => {diff --git a/src/agent/providers.ts b/src/agent/providers.tsindex fe735fa3..422feabf 100644--- a/src/agent/providers.ts+++ b/src/agent/providers.ts@@ -119,6 +119,10 @@ export interface OpenRouterModelOptions {* drops cache-point blocks outright (@strands-agents/sdk vercel.js), which is* exactly why the OpenRouter fix lives here in request settings instead. */promptCache?: boolean;+ /** OpenRouter provider routing. `throughput` preserves the requested model and+ * all generation parameters while avoiding the router's price-first default,+ * which is a poor fit for a serial interactive tool loop. */+ providerSort?: 'price' | 'throughput' | 'latency';}/**@@ -131,6 +135,7 @@ export function makeOpenRouterModel(opts: OpenRouterModelOptions): Model {openrouter.chat(opts.modelId, {...(opts.reasoning ? { reasoning: opts.reasoning } : {}),...(opts.promptCache ? { cache_control: { type: 'ephemeral' } } : {}),+ ...(opts.providerSort ? { provider: { sort: opts.providerSort } } : {}),}) as LanguageModelV3,);if (opts.splitToolResultImages) provider = splitToolResultImages(provider);@@ -358,6 +363,10 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti...(opts.apiKey ? { apiKey: opts.apiKey } : {}),...(maxTokens != null ? { maxTokens } : {}),...(reasoning ? { reasoning } : {}),+ // OpenRouter's default is price-first routing. Kiln's calls are serial+ // and user-facing, so choose the same model's highest-throughput healthy+ // endpoint. Reasoning, tools, prompts, and completion limits are unchanged.+ providerSort: 'throughput',// Together's Inkling hosting rejects images embedded in a tool-result// message (verified live 2026-07-19) — see split-tool-result-images.ts....(desc.model === 'thinkingmachines/inkling' ? { splitToolResultImages: true } : {}),diff --git a/src/agent/run.ts b/src/agent/run.tsindex 00bb6241..7ae66e70 100644--- a/src/agent/run.ts+++ b/src/agent/run.ts@@ -38,6 +38,7 @@ import {import type { AssetCategory, AssetStyle } from '../prompt';import type { AssetIntentV1 } from '../contracts';import type { KilnToolContext } from '../tools/registry';+import type { CaptureConfig } from '../views/capture';import type { SubmitSink, EditSink, UnifiedSink, EditRecord, KilnRenderCandidate } from './tools';import {resolveToolSurface,@@ -198,6 +199,10 @@ export interface RunKilnAgentResult {edits?: EditRecord[];/** In edit mode, a unified diff from the parent code to the final buffer. */diff?: string;+ /** Layout selected by the most recent successful unified `kiln_render`.+ * Presence means a render succeeded; an empty object means the standard 3x2+ * grid, while `capture` carries a custom grid/camera selection. */+ captureSelection?: { capture?: CaptureConfig };/** True when the run hit the step cap but the sink held a program that renders —* the code is the salvaged best effort instead of a discarded run. A cap with* nothing renderable is still an `error`. */@@ -346,10 +351,12 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst reviewNote =surface === 'unified'- ? '\n\nBefore finalizing, call kiln_render once and look at the six views: correct ' +- 'facing in Front, a clean silhouette in Right, symmetry in Top, and no floating or ' +- 'detached parts in the 3/4 view. Fix anything that looks wrong (kiln_edit or ' +- 'kiln_draft), then call kiln_finalize exactly once.'+ ? '\n\nBefore finalizing, call kiln_render and inspect the view sheet: correct facing in ' ++ 'Front, a clean silhouette in Right, symmetry in Top, and no floating or detached ' ++ 'parts in the 3/4 view. Keep the default 3x2 when it communicates the asset well; ' ++ 'otherwise choose the smallest useful grid and bounded per-cell cameras. The last ' ++ 'successful layout becomes the final presentation sheet. Fix anything that looks ' ++ 'wrong (kiln_edit or kiln_draft), then call kiln_finalize exactly once.': '\n\nBefore submitting, call kiln_screenshot once on your final code and check ' +'the six views: correct facing in Front, a clean silhouette in Right, symmetry in ' +'Top, and no floating or detached parts in the 3/4 view. Fix anything that looks ' +@@ -518,6 +525,9 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg...(lastText ? { lastText } : {}),...(emitEdits ? { edits: editsTrace } : {}),...(diff ? { diff } : {}),+ ...(unifiedSink.rendered+ ? { captureSelection: unifiedSink.capture ? { capture: unifiedSink.capture } : {} }+ : {}),...(capped ? { capped: true, salvaged: 'step-cap' as const } : {}),};} catch (err) {@@ -528,6 +538,9 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgsteps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),...(counters ? { counters } : {}),+ ...(unifiedSink.rendered+ ? { captureSelection: unifiedSink.capture ? { capture: unifiedSink.capture } : {} }+ : {}),};// Salvage-on-error (H-10): a thrown error used to discard a program the// sink already held — and MaxTokensError, the canonical throw here, isdiff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.tsindex 9b8785db..b8fcc23a 100644--- a/src/agent/tools-unified.test.ts+++ b/src/agent/tools-unified.test.ts@@ -196,10 +196,16 @@ describe('makeKilnUnifiedTools', () => {capture?: { preset?: string; cols?: number; cells?: number };};expect(json.capture).toEqual({ preset: '1x1', cols: 1, cells: 1 });+ expect(sink.rendered).toBe(true);+ expect(sink.capture).toEqual({ preset: '1x1' });++ await render.invoke({});+ expect(sink.rendered).toBe(true);+ expect(sink.capture).toBeUndefined(); // a later successful default render wins});test('kiln_render on a broken buffer is image-free (plain JSON error)', async () => {- const sink: UnifiedSink = { edits: [] };+ const sink: UnifiedSink = { edits: [], capture: { preset: '2x2' } };const tools = makeKilnUnifiedTools({ seedCode: 'not a kiln program (', sink });const out = (await findTool(tools, 'kiln_render').invoke({})) as {ok: boolean;@@ -208,6 +214,8 @@ describe('makeKilnUnifiedTools', () => {expect(Array.isArray(out)).toBe(false);expect(out.ok).toBe(false);expect(out.error).toBeDefined();+ expect(sink.rendered).toBeUndefined();+ expect(sink.capture).toEqual({ preset: '2x2' }); // failed renders never replace the last good layout});test('kiln_render emits a render candidate (buffer code + six-view png) via onCandidate', async () => {diff --git a/src/agent/tools.ts b/src/agent/tools.tsindex f3be992d..138df396 100644--- a/src/agent/tools.ts+++ b/src/agent/tools.ts@@ -19,6 +19,7 @@*/import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strands-agents/sdk';import { z } from 'zod';+import type { CaptureConfig } from '../views/capture';import {createKilnToolRegistry,@@ -531,6 +532,12 @@ export interface UnifiedSink {code?: string;edits: EditRecord[];finalized?: boolean;+ /** True after at least one successful unified render. This distinguishes a+ * successful default-layout render from a run that never produced a view. */+ rendered?: boolean;+ /** Capture requested by the most recent successful unified render. Undefined+ * means that render used the standard 3x2 layout. */+ capture?: CaptureConfig;}/**@@ -654,6 +661,13 @@ export function makeKilnUnifiedTools(code: buffer.code,...(i.capture !== undefined ? { capture: i.capture } : {}),});+ const rendered = out as { ok?: boolean };+ if (rendered.ok) {+ // Preserve only a validated, successful render request. A later default+ // render deliberately clears an earlier custom layout.+ opts.sink.rendered = true;+ opts.sink.capture = i.capture as CaptureConfig | undefined;+ }// Out-of-band: surface a SUCCESSFUL render as a live candidate (the working// buffer + the six-view image the agent just saw). Best-effort; a build// failure is image-free and not a candidate. Never changes the agent's view.