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(agent): loop efficiency - cache breakpoints, cache usage fidelity, concurrency guard, 8-tool surface (#6)
Matthew Kissinger93c5e9d1397a
diff --git a/src/agent/__tests__/run-loop.test.ts b/src/agent/__tests__/run-loop.test.tsnew file mode 100644index 00000000..43d06f35--- /dev/null+++ b/src/agent/__tests__/run-loop.test.ts@@ -0,0 +1,138 @@+/**+ * runKilnAgent integration over a ScriptedModel — the real Strands Agent loop+ * (concurrent tool executor, hooks, usage accumulation) with zero network.+ *+ * Pins the loop-efficiency wiring end to end:+ * - A2-instrumentation: cache read/write token counts flow from the model's+ * metadata events into `result.usage`.+ * - M1/M2: `result.counters` carries per-model-call stats and the+ * renders-per-generation count.+ * - A2-cachepoint: a provider whose adapter does NOT consume system-prompt+ * cache points receives the PLAIN STRING system prompt (block-array shaping+ * for Anthropic/Bedrock is pinned in providers.test.ts).+ * - A3: the mutator batch guard is installed on the real run path.+ */+import { describe, expect, test } from 'bun:test';++import { runKilnAgent } from '../run';+import { ScriptedModel } from './scripted-model';++const BOX_CODE = `+const meta = { name: 'test-box', category: 'prop' };+function build() {+ const root = createRoot('Root');+ createPart('Mesh_Box', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root, position: [0, 0.5, 0] });+ return root;+}+`;++describe('runKilnAgent over a ScriptedModel (unified surface)', () => {+ test('draft -> render -> finalize: captures code, usage w/ cache counts, and M1/M2 counters', async () => {+ const model = new ScriptedModel([+ {+ toolCalls: [{ name: 'kiln_draft', input: { code: BOX_CODE } }],+ usage: {+ inputTokens: 100,+ outputTokens: 10,+ totalTokens: 110,+ cacheWriteInputTokens: 900,+ },+ },+ { toolCalls: [{ name: 'kiln_render' }] },+ { toolCalls: [{ name: 'kiln_finalize' }] },+ {+ text: 'done',+ usage: {+ inputTokens: 50,+ outputTokens: 5,+ totalTokens: 55,+ cacheReadInputTokens: 900,+ },+ },+ ]);++ const result = await runKilnAgent({+ model,+ prompt: 'a red test box',+ toolSurface: 'unified',+ gradeRefine: 'off',+ });++ expect(result.error).toBeUndefined();+ expect(result.code).toBe(BOX_CODE);+ expect(result.steps).toBe(4);+ expect(result.toolCalls).toEqual(['kiln_draft', 'kiln_render', 'kiln_finalize']);++ // A2-instrumentation: cache counts accumulated alongside the token totals.+ expect(result.usage).toEqual({+ inputTokens: 150,+ outputTokens: 15,+ cacheReadInputTokens: 900,+ cacheWriteInputTokens: 900,+ });++ // M1: one record per model call, each with the transcript length it saw.+ expect(result.counters).toBeDefined();+ expect(result.counters!.modelCalls).toHaveLength(4);+ for (const call of result.counters!.modelCalls) {+ expect(call.messages).toBeGreaterThan(0);+ }+ // The transcript grows monotonically across calls.+ const sizes = result.counters!.modelCalls.map((c) => c.messages);+ expect([...sizes].sort((a, b) => a - b)).toEqual(sizes);++ // M2: exactly one render-bearing tool result (the kiln_render six-view image;+ // draft/finalize results are JSON-only).+ expect(result.counters!.renders).toBe(1);++ // A2-cachepoint: ScriptedModel is not an Anthropic/Bedrock adapter, so the+ // system prompt must arrive as the PLAIN STRING on every model call.+ expect(model.seenSystemPrompts).toHaveLength(4);+ for (const sp of model.seenSystemPrompts) {+ expect(typeof sp).toBe('string');+ expect(sp as string).toContain('3D asset');+ }+ });++ test('A3 on the real run path: a mixed mutator batch is rejected, the model recovers', async () => {+ const model = new ScriptedModel([+ // Turn 1: illegal batch — a buffer write alongside a reader.+ { toolCalls: [{ name: 'kiln_draft', input: { code: BOX_CODE } }, { name: 'kiln_view' }] },+ // Turn 2: the model follows the guard's instruction — mutator alone.+ { toolCalls: [{ name: 'kiln_draft', input: { code: BOX_CODE } }] },+ { toolCalls: [{ name: 'kiln_finalize' }] },+ { text: 'done' },+ ]);++ const result = await runKilnAgent({+ model,+ prompt: 'a red test box',+ toolSurface: 'unified',+ gradeRefine: 'off',+ });++ expect(result.error).toBeUndefined();+ // The rejected batch never wrote the buffer; the retry did, and finalize+ // locked it in — so the run still converges on the drafted program.+ expect(result.code).toBe(BOX_CODE);+ expect(result.steps).toBe(4);+ });++ test('refine framing keeps the directive INSIDE the (cacheable) system prompt text', async () => {+ const model = new ScriptedModel([{ toolCalls: [{ name: 'kiln_finalize' }] }, { text: 'done' }]);++ await runKilnAgent({+ model,+ prompt: 'make it blue',+ toolSurface: 'unified',+ existingCode: BOX_CODE,+ gradeRefine: 'off',+ });++ const sp = model.seenSystemPrompts[0] as string;+ expect(typeof sp).toBe('string');+ // The refine directive is prepended to the same string that becomes the+ // cached TextBlock for cache-point providers.+ expect(sp.startsWith('You are MODIFYING an existing Kiln asset')).toBe(true);+ });+});diff --git a/src/agent/__tests__/scripted-model.ts b/src/agent/__tests__/scripted-model.tsnew file mode 100644index 00000000..78ced54d--- /dev/null+++ b/src/agent/__tests__/scripted-model.ts@@ -0,0 +1,81 @@+/**+ * ScriptedModel — a deterministic offline Strands `Model` for agent-loop tests.+ *+ * Plays back a fixed list of turns: each turn is either a set of tool calls+ * (with complete JSON inputs) or a final text. Events are emitted in the exact+ * shapes the SDK's `streamAggregated` consumes (verified against+ * @strands-agents/sdk 1.10.0 dist/src/models/model.js), so a REAL `Agent` runs+ * its genuine loop — hooks, concurrent tool execution, usage accumulation —+ * against it with no network and no provider SDK.+ *+ * Test helper only (lives under __tests__ so it is coverage-exempt).+ */+import { Model, type Message, type StreamOptions, type Usage } from '@strands-agents/sdk';+import type { BaseModelConfig, ModelStreamEvent } from '@strands-agents/sdk';++export interface ScriptedToolCall {+ name: string;+ input?: unknown;+ id?: string;+}++export type ScriptedTurn =+ | { toolCalls: ScriptedToolCall[]; usage?: Usage }+ | { text: string; usage?: Usage };++export class ScriptedModel extends Model {+ /** `options.systemPrompt` captured per stream() call, in order. */+ readonly seenSystemPrompts: unknown[] = [];+ private turnIndex = 0;++ constructor(private readonly turns: ScriptedTurn[]) {+ super();+ }++ override updateConfig(_config: BaseModelConfig): void {+ // scripted — nothing to configure+ }++ override getConfig(): BaseModelConfig {+ return { modelId: 'scripted-test-model' };+ }++ override async *stream(+ _messages: Message[],+ options?: StreamOptions,+ ): AsyncIterable<ModelStreamEvent> {+ this.seenSystemPrompts.push(options?.systemPrompt);+ const turn: ScriptedTurn = this.turns[this.turnIndex] ?? { text: '(script exhausted)' };+ this.turnIndex += 1;++ yield { type: 'modelMessageStartEvent', role: 'assistant' };+ if ('toolCalls' in turn) {+ let i = 0;+ for (const call of turn.toolCalls) {+ yield {+ type: 'modelContentBlockStartEvent',+ start: {+ type: 'toolUseStart',+ name: call.name,+ toolUseId: call.id ?? `scripted_${this.turnIndex}_${i}`,+ },+ };+ yield {+ type: 'modelContentBlockDeltaEvent',+ delta: { type: 'toolUseInputDelta', input: JSON.stringify(call.input ?? {}) },+ };+ yield { type: 'modelContentBlockStopEvent' };+ i += 1;+ }+ } else {+ yield { type: 'modelContentBlockStartEvent' };+ yield { type: 'modelContentBlockDeltaEvent', delta: { type: 'textDelta', text: turn.text } };+ yield { type: 'modelContentBlockStopEvent' };+ }+ if (turn.usage) yield { type: 'modelMetadataEvent', usage: turn.usage };+ yield {+ type: 'modelMessageStopEvent',+ stopReason: 'toolCalls' in turn ? 'toolUse' : 'endTurn',+ };+ }+}diff --git a/src/agent/compaction.test.ts b/src/agent/compaction.test.tsindex 0038e69a..043ee093 100644--- a/src/agent/compaction.test.ts+++ b/src/agent/compaction.test.ts@@ -22,10 +22,12 @@ import {} from '@strands-agents/sdk';import {+ installGenerationCounters,installRenderImageCompaction,pruneStaleRenderImages,STALE_RENDER_PLACEHOLDER,} from './compaction';+import { AfterToolCallEvent } from '@strands-agents/sdk';const png = () => new ImageBlock({ format: 'png', source: { bytes: new Uint8Array([137, 80]) } });@@ -220,3 +222,82 @@ describe('installRenderImageCompaction', () => {expect(pruned).toEqual([2]);});});++describe('installGenerationCounters', () => {+ type Cb = (event: unknown) => void;++ /** Fake agent that also dispatches AfterToolCallEvent (tool results). */+ function fakeAgent(messages: Message[]) {+ const hooks = new Map<unknown, Cb[]>();+ const agent = {+ messages,+ addHook(EventClass: unknown, cb: Cb) {+ const arr = hooks.get(EventClass) ?? [];+ arr.push(cb);+ hooks.set(EventClass, arr);+ return () => {+ const cur = hooks.get(EventClass) ?? [];+ hooks.set(+ EventClass,+ cur.filter((c) => c !== cb),+ );+ };+ },+ };+ const modelCall = (projectedInputTokens?: number) => {+ for (const cb of hooks.get(BeforeModelCallEvent) ?? []) {+ cb({ agent, ...(projectedInputTokens != null ? { projectedInputTokens } : {}) });+ }+ };+ const toolResult = (result: ToolResultBlock) => {+ for (const cb of hooks.get(AfterToolCallEvent) ?? []) cb({ agent, result });+ };+ return { agent, modelCall, toolResult };+ }++ const imageResult = (id: string, images = 1) => toolResultOf(renderResult(id, images));+ const plainResult = (id: string) => toolResultOf(jsonResult(id));++ test('M1: records projected input tokens + transcript length per model call', () => {+ const messages = transcript();+ const { agent, modelCall } = fakeAgent(messages);+ const { counters } = installGenerationCounters(agent as never);++ modelCall(1234);+ messages.push(new Message({ role: 'assistant', content: [new TextBlock('…')] }));+ modelCall(2345);+ modelCall(); // no projection available from the SDK++ expect(counters.modelCalls).toEqual([+ { inputTokens: 1234, messages: 10 },+ { inputTokens: 2345, messages: 11 },+ { messages: 11 },+ ]);+ });++ test('M2: counts image-bearing (render) tool results; JSON-only results do not count', () => {+ const { agent, toolResult } = fakeAgent([]);+ const { counters } = installGenerationCounters(agent as never);++ toolResult(imageResult('r1'));+ toolResult(plainResult('v1')); // e.g. a validation-style JSON result+ toolResult(imageResult('r2', 4)); // one multi-image result = ONE render+ expect(counters.renders).toBe(2);+ expect(counters.modelCalls).toEqual([]);+ });++ test('uninstall stops both counters', () => {+ const messages = transcript();+ const { agent, modelCall, toolResult } = fakeAgent(messages);+ const { counters, uninstall } = installGenerationCounters(agent as never);++ modelCall(10);+ toolResult(imageResult('r1'));+ uninstall();+ modelCall(20);+ toolResult(imageResult('r2'));++ expect(counters.modelCalls).toEqual([{ inputTokens: 10, messages: 10 }]);+ expect(counters.renders).toBe(1);+ });+});diff --git a/src/agent/compaction.ts b/src/agent/compaction.tsindex 797a5e63..fca3e3fa 100644--- a/src/agent/compaction.ts+++ b/src/agent/compaction.ts@@ -19,7 +19,13 @@* keeps the numeric history and loses only superseded pixels. Images OUTSIDE* tool results (the user's reference inputImage) are always preserved.*/-import { BeforeModelCallEvent, TextBlock, type Agent, type Message } from '@strands-agents/sdk';+import {+ AfterToolCallEvent,+ BeforeModelCallEvent,+ TextBlock,+ type Agent,+ type Message,+} from '@strands-agents/sdk';/** Placeholder text swapped in for a superseded render image. */export const STALE_RENDER_PLACEHOLDER =@@ -132,3 +138,60 @@ export function installRenderImageCompaction(}});}++// =============================================================================+// Generation-loop counters (M1 per-call input/transcript size, M2 renders)+// =============================================================================++/** M1: one record per model call, in call order. */+export interface ModelCallStat {+ /** Projected input tokens for this call (SDK `BeforeModelCallEvent.projectedInputTokens`+ * — the agent loop's own estimate; hook events carry no billed usage). Absent when+ * the SDK did not compute a projection. */+ inputTokens?: number;+ /** Transcript length (`agent.messages.length`) when this call was issued. */+ messages: number;+}++/** M1/M2 loop instrumentation collected passively via hooks. Data only. */+export interface GenerationCounters {+ /** M1: per-model-call stats, in order (includes calls later cancelled by the step cap). */+ modelCalls: ModelCallStat[];+ /** M2: render-bearing tool results produced this generation — every tool result+ * that carried at least one image (kiln_render / kiln_screenshot / inspect /+ * animation / interior views). */+ renders: number;+}++/**+ * Install passive M1/M2 counters on an agent: before every model call, record+ * the projected input tokens and transcript length; after every tool call,+ * count image-bearing (render) results. Same additive hook mechanism as+ * {@link installRenderImageCompaction} — no messages are touched, no output is+ * printed. Returns the live counters plus an uninstaller.+ */+export function installGenerationCounters(agent: Agent): {+ counters: GenerationCounters;+ uninstall: () => void;+} {+ const counters: GenerationCounters = { modelCalls: [], renders: 0 };+ const offModel = agent.addHook(BeforeModelCallEvent, (event) => {+ counters.modelCalls.push({+ ...(typeof event.projectedInputTokens === 'number'+ ? { inputTokens: event.projectedInputTokens }+ : {}),+ messages: event.agent.messages.length,+ });+ });+ const offTool = agent.addHook(AfterToolCallEvent, (event) => {+ const content = (event.result as { content?: unknown[] } | undefined)?.content;+ if (Array.isArray(content) && content.some(isImageBlock)) counters.renders += 1;+ });+ return {+ counters,+ uninstall: () => {+ offModel();+ offTool();+ },+ };+}diff --git a/src/agent/concurrency.test.ts b/src/agent/concurrency.test.tsnew file mode 100644index 00000000..c6788a68--- /dev/null+++ b/src/agent/concurrency.test.ts@@ -0,0 +1,138 @@+/**+ * A3 mutator/reader batch guard.+ *+ * Unit level: `rejectMixedMutatorBatch` / `toolNamesInBatch` are pure, so the+ * allow/deny matrix is pinned directly. Integration level: a REAL Strands+ * `Agent` (default CONCURRENT tool executor) driven by a ScriptedModel proves+ * the guard rejects a mixed batch on the genuine run path — the batch's tool+ * results come back as errors carrying the guard's message, the mutator never+ * touches the buffer — while a solo mutator and a pure-reader batch execute.+ */+import { describe, expect, test } from 'bun:test';+import { Agent, Message, ToolResultBlock, ToolUseBlock, TextBlock } from '@strands-agents/sdk';++import {+ KILN_MUTATOR_TOOLS,+ installMutatorBatchGuard,+ rejectMixedMutatorBatch,+ toolNamesInBatch,+} from './concurrency';+import { makeKilnUnifiedTools, type UnifiedSink } from './tools';+import { ScriptedModel } from './__tests__/scripted-model';++const BOX_CODE = `+const meta = { name: 'test-box', category: 'prop' };+function build() {+ const root = createRoot('Root');+ createPart('Mesh_Box', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root, position: [0, 0.5, 0] });+ return root;+}+`;++describe('rejectMixedMutatorBatch', () => {+ test('classifies exactly kiln_draft and kiln_edit as mutators', () => {+ expect([...KILN_MUTATOR_TOOLS].sort()).toEqual(['kiln_draft', 'kiln_edit']);+ });++ test('mixed mutator + reader batch is rejected with an actionable message', () => {+ const msg = rejectMixedMutatorBatch(['kiln_edit', 'kiln_render']);+ expect(msg).toBeDefined();+ expect(msg).toContain('kiln_edit');+ expect(msg).toContain('ALONE');+ expect(msg).toContain('No tools were executed');+ });++ test('two mutators together are also rejected', () => {+ expect(rejectMixedMutatorBatch(['kiln_draft', 'kiln_edit'])).toBeDefined();+ expect(rejectMixedMutatorBatch(['kiln_edit', 'kiln_edit'])).toBeDefined();+ });++ test('solo mutator is allowed', () => {+ expect(rejectMixedMutatorBatch(['kiln_draft'])).toBeUndefined();+ expect(rejectMixedMutatorBatch(['kiln_edit'])).toBeUndefined();+ });++ test('pure-reader batches are allowed', () => {+ expect(rejectMixedMutatorBatch(['kiln_view', 'kiln_render'])).toBeUndefined();+ expect(rejectMixedMutatorBatch(['kiln_render', 'kiln_inspect', 'kiln_view'])).toBeUndefined();+ expect(rejectMixedMutatorBatch([])).toBeUndefined();+ });+});++describe('toolNamesInBatch', () => {+ test('extracts toolUse names in order, ignoring text blocks', () => {+ const message = new Message({+ role: 'assistant',+ content: [+ new TextBlock('let me edit and render'),+ new ToolUseBlock({ name: 'kiln_edit', toolUseId: 'a', input: {} }),+ new ToolUseBlock({ name: 'kiln_render', toolUseId: 'b', input: {} }),+ ],+ });+ expect(toolNamesInBatch(message)).toEqual(['kiln_edit', 'kiln_render']);+ });+});++describe('installMutatorBatchGuard on a real Agent (concurrent executor)', () => {+ function toolResults(messages: readonly Message[]): ToolResultBlock[] {+ const out: ToolResultBlock[] = [];+ for (const m of messages) {+ for (const b of m.content) if (b instanceof ToolResultBlock) out.push(b);+ }+ return out;+ }++ test('a mixed kiln_draft + kiln_view batch is rejected: both calls error, buffer untouched', async () => {+ const sink: UnifiedSink = { edits: [] };+ const model = new ScriptedModel([+ { toolCalls: [{ name: 'kiln_draft', input: { code: BOX_CODE } }, { name: 'kiln_view' }] },+ { text: 'stopping after the rejection' },+ ]);+ const agent = new Agent({+ model,+ systemPrompt: 'test',+ tools: makeKilnUnifiedTools({ sink }) as never,+ });+ installMutatorBatchGuard(agent);++ await agent.invoke('build a box');++ // Neither tool ran: the draft never reached the buffer/sink.+ expect(sink.code).toBeUndefined();+ const results = toolResults(agent.messages);+ expect(results).toHaveLength(2);+ for (const r of results) {+ expect(r.status).toBe('error');+ const text = r.content+ .map((c) => ((c as { type?: string }).type === 'textBlock' ? (c as TextBlock).text : ''))+ .join(' ');+ expect(text).toContain('kiln_draft');+ expect(text).toContain('ALONE');+ }+ });++ test('a solo mutator executes, and a later pure-reader batch executes too', async () => {+ const sink: UnifiedSink = { edits: [] };+ const model = new ScriptedModel([+ { toolCalls: [{ name: 'kiln_draft', input: { code: BOX_CODE } }] },+ { toolCalls: [{ name: 'kiln_view' }, { name: 'kiln_view' }] },+ { toolCalls: [{ name: 'kiln_finalize' }] },+ { text: 'done' },+ ]);+ const agent = new Agent({+ model,+ systemPrompt: 'test',+ tools: makeKilnUnifiedTools({ sink }) as never,+ });+ installMutatorBatchGuard(agent);++ await agent.invoke('build a box');++ expect(sink.code).toBe(BOX_CODE);+ expect(sink.finalized).toBe(true);+ // Solo mutator + both readers + finalize all produced SUCCESS results.+ const results = toolResults(agent.messages);+ expect(results).toHaveLength(4);+ expect(results.every((r) => r.status === 'success')).toBe(true);+ });+});diff --git a/src/agent/concurrency.ts b/src/agent/concurrency.tsnew file mode 100644index 00000000..00564bd0--- /dev/null+++ b/src/agent/concurrency.ts@@ -0,0 +1,76 @@+/**+ * A3 — mutator/reader tool-batch concurrency guard.+ *+ * Strands executes a turn's tool calls CONCURRENTLY by default (Agent+ * `toolExecutor: 'concurrent'`), and the kiln buffer surfaces share one mutable+ * `KilnDraftBuffer`: `kiln_draft` / `kiln_edit` write `buffer.code` while every+ * other kiln tool reads it (validate-on-write, render, view, inspect, finalize,+ * ...). A batch that mixes a buffer write with anything else therefore races —+ * a reader can observe the buffer mid-turn in either the before or after state,+ * and two writes can interleave.+ *+ * Rather than forcing `toolExecutor: 'sequential'` (which would serialize the+ * harmless read-only batches too), this guard rejects only the dangerous shape:+ * a single assistant turn requesting 2+ tool calls where at least one call is a+ * buffer mutator. The whole batch gets a clear, actionable tool error telling+ * the model to issue the mutator alone; pure-reader batches and solo mutators+ * pass through untouched.+ *+ * Seam: the SDK's `BeforeToolsEvent` fires once per turn BEFORE any tool runs+ * and carries the full assistant message (every `toolUse` block of the batch);+ * setting `event.cancel` to a string makes the SDK return that string as the+ * error tool result for every call in the batch — exactly the reject-the-batch+ * contract, on the real run path.+ */+import { BeforeToolsEvent, type Agent } from '@strands-agents/sdk';++/** Kiln tools that WRITE the shared working buffer. Everything else on the kiln+ * surfaces only reads it (kiln_submit / kiln_finalize capture into the sink but+ * never change `buffer.code`). */+export const KILN_MUTATOR_TOOLS: ReadonlySet<string> = new Set(['kiln_draft', 'kiln_edit']);++/** Duck-typed view over an assistant-message content block (same discriminator+ * convention as run.ts / compaction.ts — robust across SDK class realms). */+interface ToolUseBlockLike {+ type?: string;+ name?: string;+}++/** Extract the tool names requested by an assistant message's toolUse blocks. */+export function toolNamesInBatch(message: { content: readonly unknown[] }): string[] {+ const names: string[] = [];+ for (const block of message.content) {+ const b = block as ToolUseBlockLike;+ if (b.type === 'toolUseBlock' && typeof b.name === 'string') names.push(b.name);+ }+ return names;+}++/**+ * Decide whether a tool batch must be rejected. Returns the rejection message+ * when the batch mixes a buffer mutator with any other call (including a second+ * mutator), or undefined when the batch is safe (solo calls, pure readers).+ */+export function rejectMixedMutatorBatch(names: readonly string[]): string | undefined {+ if (names.length < 2) return undefined;+ const mutators = names.filter((n) => KILN_MUTATOR_TOOLS.has(n));+ if (mutators.length === 0) return undefined;+ return (+ `kiln: rejected this tool batch — ${[...new Set(mutators)].join(' and ')} ` ++ 'modifies the shared working buffer, and the batch requested ' ++ `${names.length} tools to run concurrently (${names.join(', ')}). ` ++ 'Buffer-writing tools (kiln_draft, kiln_edit) must run ALONE. ' ++ 'Re-issue the buffer-writing call as the only tool call of the turn, then ' ++ 'make your other calls in the next turn. No tools were executed.'+ );+}++/**+ * Install the guard on an agent. Returns the unsubscribe function.+ */+export function installMutatorBatchGuard(agent: Agent): () => void {+ return agent.addHook(BeforeToolsEvent, (event) => {+ const rejection = rejectMixedMutatorBatch(toolNamesInBatch(event.message));+ if (rejection) event.cancel = rejection;+ });+}diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.tsindex 38dd95ba..f09f8090 100644--- a/src/agent/generate.test.ts+++ b/src/agent/generate.test.ts@@ -25,12 +25,30 @@ const FALSE_PROP_CODE = CANNED_CODE.replace("const meta = { name: 'TestBox', category: 'prop' };",);+// Capture the REAL './run' exports BEFORE mocking. bun's mock.module patches the+// module (and any already-imported namespace) in place, but plain function+// references captured beforehand keep pointing at the real implementations —+// so the afterAll below can restore the module for later test files+// (__tests__/run-loop.test.ts drives the real runKilnAgent) in a shared process.+const realRun = await import('./run');+const restoreRunModule = {+ runKilnAgent: realRun.runKilnAgent,+ resolveToolSurface: realRun.resolveToolSurface,+ buildAgentTools: realRun.buildAgentTools,+};+// Mutable impl the mocked runKilnAgent delegates to (set per test).let runImpl: (opts: Record<string, unknown>) => Promise<Record<string, unknown>>;mock.module('./run', () => ({runKilnAgent: (opts: Record<string, unknown>) => runImpl(opts),}));+afterAll(() => {+ // Un-leak the module mock: put the real functions back for any test file+ // that runs after this one.+ mock.module('./run', () => restoreRunModule);+});+// mock.module must precede the import of the module under test (bun runs it in// order; ESM imports would hoist above it, so the dynamic import is required).const { generateKilnAsset, DEFAULT_KILN_AGENT_MODEL } = await import('./generate');diff --git a/src/agent/hooks.test.ts b/src/agent/hooks.test.tsindex 1eecff6e..b361b4c6 100644--- a/src/agent/hooks.test.ts+++ b/src/agent/hooks.test.ts@@ -91,4 +91,51 @@ describe('MetricsCollector', () => {m.recordResultUsage({ inputTokens: 1200, outputTokens: 340 });expect(m.readMetrics().usage).toEqual({ inputTokens: 1200, outputTokens: 340 });});++ test('records cache read/write token counts from a result carrying them (A2)', () => {+ const m = new MetricsCollector();+ // Shape mirrors the Strands adapters: Anthropic maps cache_read_input_tokens /+ // cache_creation_input_tokens onto these fields; Bedrock passes them through.+ m.recordResultUsage({+ inputTokens: 900,+ outputTokens: 210,+ cacheReadInputTokens: 8000,+ cacheWriteInputTokens: 1500,+ });+ expect(m.readMetrics().usage).toEqual({+ inputTokens: 900,+ outputTokens: 210,+ cacheReadInputTokens: 8000,+ cacheWriteInputTokens: 1500,+ });+ });++ test('accumulates cache counts across invokes and tolerates results without them', () => {+ const m = new MetricsCollector();+ m.recordResultUsage({ inputTokens: 100, outputTokens: 10, cacheReadInputTokens: 500 });+ // Second invoke (e.g. the grade-refine turn) adds writes and more reads.+ m.recordResultUsage({+ inputTokens: 50,+ outputTokens: 5,+ cacheReadInputTokens: 700,+ cacheWriteInputTokens: 40,+ });+ // A provider result with no cache fields must not disturb the totals.+ m.recordResultUsage({ inputTokens: 25 });+ expect(m.readMetrics().usage).toEqual({+ inputTokens: 175,+ outputTokens: 15,+ cacheReadInputTokens: 1200,+ cacheWriteInputTokens: 40,+ });+ // Undefined / empty results still record nothing.+ m.recordResultUsage(undefined);+ m.recordResultUsage({});+ expect(m.readMetrics().usage).toEqual({+ inputTokens: 175,+ outputTokens: 15,+ cacheReadInputTokens: 1200,+ cacheWriteInputTokens: 40,+ });+ });});diff --git a/src/agent/hooks.ts b/src/agent/hooks.tsindex 020782cb..354234ad 100644--- a/src/agent/hooks.ts+++ b/src/agent/hooks.ts@@ -18,12 +18,29 @@ import {AfterModelCallEvent,} from '@strands-agents/sdk';-/** Token-usage subset we surface. */+/** Token-usage subset we surface. The cache fields mirror the Strands `Usage`+ * type (dist/src/models/streaming.d.ts): the Anthropic adapter fills them from+ * `cache_read_input_tokens` / `cache_creation_input_tokens` and the Bedrock+ * adapter passes its converse-stream `cacheReadInputTokens` /+ * `cacheWriteInputTokens` counts through under the same names. Providers+ * without prompt caching simply omit them. */export interface AgentUsage {inputTokens?: number;outputTokens?: number;+ /** Input tokens served from the provider's prompt cache (cache hits). */+ cacheReadInputTokens?: number;+ /** Input tokens written to the provider's prompt cache (cache creation). */+ cacheWriteInputTokens?: number;}+/** The AgentUsage fields recordResultUsage accumulates, in surface order. */+const USAGE_FIELDS = [+ 'inputTokens',+ 'outputTokens',+ 'cacheReadInputTokens',+ 'cacheWriteInputTokens',+] as const;+/** A live agent-loop event, emitted as the loop runs (for progress UIs). */export type KilnAgentEvent =| { type: 'tool'; tool: string; step: number }@@ -135,13 +152,15 @@ export class MetricsCollector {recordResultUsage(usage: AgentUsage | undefined): void {if (!usage) return;const next: AgentUsage = { ...this.usage };- if (typeof usage.inputTokens === 'number') {- next.inputTokens = (next.inputTokens ?? 0) + usage.inputTokens;- }- if (typeof usage.outputTokens === 'number') {- next.outputTokens = (next.outputTokens ?? 0) + usage.outputTokens;+ let recorded = false;+ for (const field of USAGE_FIELDS) {+ const value = usage[field];+ if (typeof value === 'number') {+ next[field] = (next[field] ?? 0) + value;+ recorded = true;+ }}- if (next.inputTokens !== undefined || next.outputTokens !== undefined) this.usage = next;+ if (recorded) this.usage = next;}/** Read the collected metrics (a fresh copy each call). */diff --git a/src/agent/index.ts b/src/agent/index.tsindex a711b914..b832d91c 100644--- a/src/agent/index.ts+++ b/src/agent/index.ts@@ -12,7 +12,7 @@* - {@link resolveKilnAgentModel} — model-id string -> Strands provider descriptor* - {@link makeKilnTools} — in-process tool skin over the shared registry* - {@link makeKilnEditTools} — surgical edit-tool skin for refining an existing asset- * - {@link makeKilnUnifiedTools} — buffer-based 6-tool surface (KILN_TOOL_SURFACE='unified')+ * - {@link makeKilnUnifiedTools} — buffer-based unified surface (KILN_TOOL_SURFACE='unified')* - {@link unifiedDiff} — dependency-free unified diff (the refine patch artifact)* - {@link ensureStreamStart} — the OpenRouter/Vercel-bridge stream fix* - {@link makeOpenRouterModel} — build an OpenRouter Strands model with the fix@@ -52,9 +52,22 @@ export type { UnifiedDiffOptions } from './diff';export {pruneStaleRenderImages,installRenderImageCompaction,+ installGenerationCounters,STALE_RENDER_PLACEHOLDER,} from './compaction';-export type { PruneImagesResult, RenderImageCompactionOptions } from './compaction';+export type {+ PruneImagesResult,+ RenderImageCompactionOptions,+ ModelCallStat,+ GenerationCounters,+} from './compaction';++export {+ installMutatorBatchGuard,+ rejectMixedMutatorBatch,+ toolNamesInBatch,+ KILN_MUTATOR_TOOLS,+} from './concurrency';export {assessProgramGrade,@@ -77,6 +90,8 @@ export {makeKilnModel,resolveKilnAgentModel,harnessIdToAgentModelId,+ modelConsumesSystemPromptCachePoints,+ toCachedSystemPrompt,} from './providers';export type {OpenRouterModelOptions,diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.tsindex 470dd042..e6ea5f79 100644--- a/src/agent/providers.test.ts+++ b/src/agent/providers.test.ts@@ -8,7 +8,14 @@* keys so native construction never touches the network).*/import { test, expect, describe, beforeAll, afterAll } from 'bun:test';-import { resolveKilnAgentModel, makeKilnModel, resolveOpenRouterReasoning } from './providers';+import { CachePointBlock, TextBlock } from '@strands-agents/sdk';+import {+ resolveKilnAgentModel,+ makeKilnModel,+ resolveOpenRouterReasoning,+ modelConsumesSystemPromptCachePoints,+ toCachedSystemPrompt,+} from './providers';describe('resolveKilnAgentModel', () => {test('explicit provider prefixes win and keep the model id intact', () => {@@ -334,3 +341,56 @@ describe('makeKilnModel', () => {});});});++describe('toCachedSystemPrompt (A2 portable cache breakpoint)', () => {+ const TEXT = 'You generate exportable 3D game assets as Kiln code.';++ test('Anthropic models get [TextBlock, CachePointBlock] — the adapter emits cache_control', () => {+ const model = makeKilnModel(+ { provider: 'anthropic', model: 'claude-opus-4-8' },+ { apiKey: 'test-key' },+ );+ expect(modelConsumesSystemPromptCachePoints(model)).toBe(true);+ const shaped = toCachedSystemPrompt(TEXT, model);+ expect(Array.isArray(shaped)).toBe(true);+ const blocks = shaped as unknown[];+ expect(blocks).toHaveLength(2);+ expect(blocks[0]).toBeInstanceOf(TextBlock);+ expect((blocks[0] as TextBlock).text).toBe(TEXT);+ expect(blocks[1]).toBeInstanceOf(CachePointBlock);+ expect((blocks[1] as CachePointBlock).cacheType).toBe('default');+ // The discriminators the anthropic/bedrock adapters branch on (1.10.0).+ expect((blocks[0] as { type: string }).type).toBe('textBlock');+ expect((blocks[1] as { type: string }).type).toBe('cachePointBlock');+ });++ test('Bedrock models get the block array too (converse cachePoint entry)', () => {+ const model = makeKilnModel(+ { provider: 'bedrock', model: 'global.anthropic.claude-opus-4-8' },+ { region: 'us-west-2' },+ );+ expect(modelConsumesSystemPromptCachePoints(model)).toBe(true);+ expect(Array.isArray(toCachedSystemPrompt(TEXT, model))).toBe(true);+ });++ test('Google keeps the plain string (its adapter drops cache points)', () => {+ const model = makeKilnModel(+ { provider: 'google', model: 'gemini-3.5-flash' },+ { apiKey: 'test-key' },+ );+ expect(modelConsumesSystemPromptCachePoints(model)).toBe(false);+ expect(toCachedSystemPrompt(TEXT, model)).toBe(TEXT);+ });++ test('OpenAI / OpenRouter (Vercel bridge) / unknown models keep the plain string', () => {+ const openai = makeKilnModel({ provider: 'openai', model: 'gpt-5.5' }, { apiKey: 'test-key' });+ expect(toCachedSystemPrompt(TEXT, openai)).toBe(TEXT);+ const openrouter = makeKilnModel(+ { provider: 'openrouter', model: 'x-ai/grok-4.3' },+ { apiKey: 'test-key' },+ );+ expect(toCachedSystemPrompt(TEXT, openrouter)).toBe(TEXT);+ expect(toCachedSystemPrompt(TEXT, undefined)).toBe(TEXT);+ expect(toCachedSystemPrompt(TEXT, {})).toBe(TEXT);+ });+});diff --git a/src/agent/providers.ts b/src/agent/providers.tsindex 3bc5be00..fa342bfc 100644--- a/src/agent/providers.ts+++ b/src/agent/providers.ts@@ -15,7 +15,7 @@ import { AnthropicModel } from '@strands-agents/sdk/models/anthropic';import { OpenAIModel } from '@strands-agents/sdk/models/openai';import { GoogleModel } from '@strands-agents/sdk/models/google';import { BedrockModel } from '@strands-agents/sdk/models/bedrock';-import type { Model } from '@strands-agents/sdk';+import { CachePointBlock, TextBlock, type Model, type SystemPrompt } from '@strands-agents/sdk';import { createOpenRouter } from '@openrouter/ai-sdk-provider';import type { LanguageModelV3 } from '@ai-sdk/provider';@@ -358,6 +358,40 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti}}+// =============================================================================+// A2 — portable system-prompt cache breakpoint+// =============================================================================++/**+ * Whether a Strands model's request adapter CONSUMES a block-array system prompt+ * with a cache point (verified against @strands-agents/sdk 1.10.0 dist):+ *+ * - AnthropicModel: a `cachePointBlock` after a `textBlock` becomes+ * `cache_control: {type:'ephemeral'}` on that text block (anthropic.js+ * `_formatRequest`) — the explicit prompt-caching breakpoint.+ * - BedrockModel: system blocks map through `_formatContentBlock`, emitting the+ * converse-API `{cachePoint: {type}}` system entry.+ * - GoogleModel joins the text blocks and DROPS cache points (Gemini caching is+ * implicit); OpenAI warns-and-ignores them; the Vercel bridge only forwards+ * text. Those providers get the plain string so nothing changes for them.+ */+export function modelConsumesSystemPromptCachePoints(model: unknown): boolean {+ return model instanceof AnthropicModel || model instanceof BedrockModel;+}++/**+ * Shape a system prompt for a model: providers whose adapter consumes cache+ * points (Anthropic / Bedrock, see {@link modelConsumesSystemPromptCachePoints})+ * get `[TextBlock(text), CachePointBlock]` so the WHOLE system prompt lands in+ * the provider's prompt cache; everyone else keeps the plain string. Any+ * refine/edit directive must already be prepended to `text` — it rides inside+ * the cached block, before the cache point.+ */+export function toCachedSystemPrompt(text: string, model: unknown): SystemPrompt {+ if (!modelConsumesSystemPromptCachePoints(model)) return text;+ return [new TextBlock(text), new CachePointBlock({ cacheType: 'default' })];+}+/*** Parse a model-id string into a Strands provider descriptor — the CLI / batch* entry, where only a string is available.diff --git a/src/agent/run-surface.test.ts b/src/agent/run-surface.test.tsindex 2339ea17..14a6705f 100644--- a/src/agent/run-surface.test.ts+++ b/src/agent/run-surface.test.ts@@ -23,11 +23,12 @@ function freshSinks() {const base: ToolBuildOptions = {};const names = (tools: ReturnType<typeof buildAgentTools>) => tools.map((t) => t.name);+// A1: no standalone kiln_validate on the unified surface — kiln_draft and+// kiln_edit validate the buffer inline in their results.const UNIFIED = ['kiln_draft','kiln_view','kiln_edit',- 'kiln_validate','kiln_render','kiln_inspect','kiln_screenshot_animation',@@ -54,11 +55,11 @@ const CURRENT_EDIT = [];describe('buildAgentTools', () => {- test('unified surface -> the nine buffer tools (fresh generate, empty seed)', () => {+ test('unified surface -> the eight buffer tools (fresh generate, empty seed)', () => {expect(names(buildAgentTools('unified', base, freshSinks()))).toEqual(UNIFIED);});- test('unified surface -> the same nine tools when refining (seeded buffer)', () => {+ test('unified surface -> the same eight tools when refining (seeded buffer)', () => {const opts = { ...base, existingCode: 'const meta = {};', refineMode: 'edit' as const };expect(names(buildAgentTools('unified', opts, freshSinks()))).toEqual(UNIFIED);});diff --git a/src/agent/run.ts b/src/agent/run.tsindex c4901331..0f445b11 100644--- a/src/agent/run.ts+++ b/src/agent/run.ts@@ -44,7 +44,13 @@ import {} from './surface';import { unifiedDiff } from './diff';import { MetricsCollector, type AgentUsage, type KilnAgentEvent } from './hooks';-import { installRenderImageCompaction } from './compaction';+import {+ installRenderImageCompaction,+ installGenerationCounters,+ type GenerationCounters,+} from './compaction';+import { installMutatorBatchGuard } from './concurrency';+import { toCachedSystemPrompt } from './providers';import {assessProgramGrade,buildGradeRefineMessage,@@ -116,7 +122,7 @@ export interface RunKilnAgentOptions {refineMode?: RefineMode;/** Which agent tool surface to use. Resolved at call time: this option, else* the KILN_TOOL_SURFACE env, else 'current'. The 'unified' surface is the- * buffer-based draft/view/edit/validate/render/finalize six (render+screenshot+ * buffer-based draft/view/edit/render/finalize set (render+screenshot* collapsed, no kiln_list_primitives) — the surface Kiln Studio runs in prod* (KILN_TOOL_SURFACE=unified); 'current' remains the library default. */toolSurface?: KilnToolSurface;@@ -161,8 +167,12 @@ export interface RunKilnAgentResult {toolCalls: string[];/** Number of model calls (agent-loop iterations). */steps: number;- /** Best-effort token usage. */+ /** Best-effort token usage (incl. provider prompt-cache read/write counts when+ * the adapter reports them). */usage?: AgentUsage;+ /** M1/M2 loop instrumentation: per-model-call projected input tokens ++ * transcript length, and render-bearing tool results per generation. */+ counters?: GenerationCounters;/** The last assistant text (fallback / diagnostics). */lastText?: string;/** In edit mode, the applied surgical edits in order (the patch the model produced). */@@ -222,6 +232,9 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst sink: SubmitSink = {};const editSink: EditSink = { edits: [] };const unifiedSink: UnifiedSink = { edits: [] };+ // M1/M2 counters live outside the try so every return path (success, step-cap,+ // salvage, hard error) can expose whatever was collected before the exit.+ let counters: GenerationCounters | undefined;try {const tools: Tool[] = buildAgentTools(surface,@@ -271,12 +284,24 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst agent = new Agent({model: opts.model as never,- systemPrompt,+ // A2: providers whose adapter consumes system-prompt cache points+ // (Anthropic/Bedrock) get [TextBlock, CachePointBlock] so the whole+ // system prompt — including any refine directive prepended above, which+ // stays INSIDE the cached text — lands in the provider prompt cache.+ // Other providers keep the plain string.+ systemPrompt: toCachedSystemPrompt(systemPrompt, opts.model),tools: allTools as never,...(plugins.length ? { plugins } : {}),name: opts.agentName ?? 'kiln-agent',});metrics.attach(agent);+ // A3: Strands runs a turn's tool calls concurrently; kiln_draft/kiln_edit+ // mutate the shared working buffer the other tools read. Reject any batch+ // that mixes a buffer mutator with another call (the model is told to issue+ // the mutator alone); solo mutators and pure-reader batches pass through.+ installMutatorBatchGuard(agent);+ // M1/M2: passive per-model-call + renders-per-generation counters.+ counters = installGenerationCounters(agent).counters;// Transcript compaction (default on): before every model call, strip the image// out of each superseded render tool result so only the newest render image// rides the request. Pairing-safe — messages and toolUseIds are untouched;@@ -375,6 +400,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgtoolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(counters ? { counters } : {}),error: `kiln agent exceeded ${maxSteps} model calls (step cap) — aborted to bound cost${qaNote}`,};}@@ -458,6 +484,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgtoolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(counters ? { counters } : {}),...(lastText ? { lastText } : {}),...(emitEdits ? { edits: editsTrace } : {}),...(diff ? { diff } : {}),@@ -470,6 +497,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgtoolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(counters ? { counters } : {}),};// 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/surface.ts b/src/agent/surface.tsindex ef03e680..cc6716ac 100644--- a/src/agent/surface.ts+++ b/src/agent/surface.ts@@ -20,7 +20,8 @@ import {/** Which agent tool surface drives the loop. 'current' = today's* list/validate/render/screenshot/submit (+ edit tools in edit-mode refine);- * 'unified' = the buffer-based draft/view/edit/validate/render/finalize six. */+ * 'unified' = the buffer-based draft/view/edit/render/finalize set (writes+ * validate inline; no standalone kiln_validate). */export type KilnToolSurface = 'current' | 'unified';/** How a refine applies its change: whole-program re-emission, or surgical edits. */diff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.tsindex c09dff60..54e58780 100644--- a/src/agent/tools-unified.test.ts+++ b/src/agent/tools-unified.test.ts@@ -1,9 +1,9 @@/*** Unit tests for the unified buffer surface (KilnDraftBuffer.draft +* makeKilnUnifiedTools). Mirrors tools-edit.test.ts: the buffer is pure string- * ops (tested directly) and the factory is checked for its 6-tool wiring,- * capture into the sink, the kiln_draft escape-hatch hint, and the collapsed- * kiln_render media contract.+ * ops (tested directly) and the factory is checked for its tool wiring,+ * capture into the sink, the inline validation on buffer writes (A1), the+ * kiln_draft escape-hatch hint, and the collapsed kiln_render media contract.*/import { describe, expect, test } from 'bun:test';import { ImageBlock, JsonBlock } from '@strands-agents/sdk';@@ -81,14 +81,13 @@ describe('KilnDraftBuffer', () => {});describe('makeKilnUnifiedTools', () => {- test('exposes exactly the nine unified tools in order (incl. the close-up, motion + interior views)', () => {+ test('exposes exactly the eight unified tools in order (incl. the close-up, motion + interior views)', () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ sink });expect(tools.map((t) => t.name)).toEqual(['kiln_draft','kiln_view','kiln_edit',- 'kiln_validate','kiln_render','kiln_inspect','kiln_screenshot_animation',@@ -96,10 +95,12 @@ describe('makeKilnUnifiedTools', () => {'kiln_finalize',]);// No legacy verbs leak into the unified surface (the static screenshot collapsed- // into kiln_render; only the dedicated motion + interior views are added).+ // into kiln_render; only the dedicated motion + interior views are added). A1:+ // there is no standalone kiln_validate — buffer writes validate inline.expect(tools.map((t) => t.name)).not.toContain('kiln_list_primitives');expect(tools.map((t) => t.name)).not.toContain('kiln_screenshot');expect(tools.map((t) => t.name)).not.toContain('kiln_submit');+ expect(tools.map((t) => t.name)).not.toContain('kiln_validate');expect(sink.edits).toHaveLength(0);});@@ -109,8 +110,12 @@ describe('makeKilnUnifiedTools', () => {const drafted = (await findTool(tools, 'kiln_draft').invoke({ code: BOX_CODE })) as {ok: boolean;bytes: number;+ validation: { valid: boolean; errors: string[]; warnings: string[] };};expect(drafted.ok).toBe(true);+ // A1: the draft result carries the static validation of the fresh buffer.+ expect(drafted.validation.valid).toBe(true);+ expect(drafted.validation.errors).toEqual([]);expect(sink.code).toBe(BOX_CODE); // captured even before finalizeconst viewed = (await findTool(tools, 'kiln_view').invoke({})) as {code: string;@@ -119,18 +124,43 @@ describe('makeKilnUnifiedTools', () => {expect(viewed.code).toBe(BOX_CODE);});+ test('kiln_draft of a broken program surfaces the validation errors inline (A1)', async () => {+ const sink: UnifiedSink = { edits: [] };+ const tools = makeKilnUnifiedTools({ sink });+ const drafted = (await findTool(tools, 'kiln_draft').invoke({+ code: 'function build() { return 1; }', // no meta+ })) as { ok: boolean; validation: { valid: boolean; errors: string[] } };+ expect(drafted.ok).toBe(true); // the write itself succeeded+ expect(drafted.validation.valid).toBe(false);+ expect(drafted.validation.errors.length).toBeGreaterThan(0);+ });+test('refine seed: kiln_edit updates sink.code; the shared edit trace records it', async () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink });const edited = (await findTool(tools, 'kiln_edit').invoke({oldString: 'boxGeo(1, 1, 1)',newString: 'boxGeo(2, 1, 1)',- })) as { ok: boolean };+ })) as { ok: boolean; validation: { valid: boolean; errors: string[] } };expect(edited.ok).toBe(true);+ // A1: a successful edit re-validates the edited buffer inline.+ expect(edited.validation.valid).toBe(true);expect(sink.code).toContain('boxGeo(2, 1, 1)');expect(sink.edits).toHaveLength(1); // live trace shared into the sink});+ test('a kiln_edit that breaks the program reports validation errors inline (A1)', async () => {+ const sink: UnifiedSink = { edits: [] };+ const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink });+ const edited = (await findTool(tools, 'kiln_edit').invoke({+ oldString: 'function build() {',+ newString: 'function broken() {',+ })) as { ok: boolean; validation: { valid: boolean; errors: string[] } };+ expect(edited.ok).toBe(true); // the string replace applied+ expect(edited.validation.valid).toBe(false);+ expect(edited.validation.errors.length).toBeGreaterThan(0);+ });+test('a failed kiln_edit points the model at kiln_draft as the escape hatch', async () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink });diff --git a/src/agent/tools.ts b/src/agent/tools.tsindex 98a940d6..e53c1abc 100644--- a/src/agent/tools.ts+++ b/src/agent/tools.ts@@ -13,7 +13,7 @@** Three factories: {@link makeKilnTools} (the library-default `current` generate* surface), {@link makeKilnEditTools} (the `current` surgical-refine surface), and- * {@link makeKilnUnifiedTools} (the buffer-based 6-tool `unified` surface, selected+ * {@link makeKilnUnifiedTools} (the buffer-based `unified` surface, selected* via KILN_TOOL_SURFACE='unified' — what Kiln Studio runs in prod). The first two* stay byte-identical so the bench baseline does not move.*/@@ -440,15 +440,20 @@ export function makeKilnEditTools(// =============================================================================//// One buffer-based surface that unifies the from-scratch generate path and the-// refine path behind a single working buffer. Six tools:+// refine path behind a single working buffer. Core tools://-// kiln_draft write/replace the whole buffer (authoring + capture point)+// kiln_draft write/replace the whole buffer (authoring + capture point);+// the result carries the buffer's static-validation report// kiln_view read the current buffer (anchors edits)-// kiln_edit surgical exact-string replace on the buffer-// kiln_validate static check of the buffer (no execution — the cheap loop)+// kiln_edit surgical exact-string replace on the buffer; a successful edit+// also carries the static-validation report// kiln_render execute ONCE -> metrics + the six-view image (render+screenshot)// kiln_finalize terminal: lock in the current buffer as the answer (arg-less)//+// There is NO standalone kiln_validate here (A1): every buffer write already+// runs the same static check and returns it inline, so a separate validate+// round-trip only cost a model call. The legacy `current` surfaces keep theirs.+//// The program is HELD in the buffer, so capture is unambiguous (the final buffer)// rather than "whichever copy landed in kiln_submit". Generate seeds an empty// buffer; refine seeds the parent's code. `kiln_list_primitives` is dropped — the@@ -512,7 +517,7 @@ const inspectBufferInput = z.object({});/**- * Build the unified 6-tool surface over a working buffer seeded with `seedCode`+ * Build the unified buffer surface over a working buffer seeded with `seedCode`* (empty for generate, the parent's code for refine). The buffer's live edit* trace is shared into `sink.edits`; `sink.code` tracks the latest buffer after* every draft/edit (so an un-finalized run still captures the work). `kiln_edit`@@ -538,18 +543,30 @@ export function makeKilnUnifiedTools(const animationDef = createKilnScreenshotAnimationDef(opts);const interiorDef = createKilnViewInteriorDef(opts);+ // A1: the unified surface has no standalone kiln_validate tool — every buffer+ // write (kiln_draft / a successful kiln_edit) runs the registry's static check+ // on the fresh buffer and returns it inline, so the model still sees every+ // validation error/warning without spending a tool round-trip on it.+ const validateBuffer = async () =>+ (await validateDef.run({ code: buffer.code })) as {+ valid: boolean;+ errors: string[];+ warnings: string[];+ };+const draftTool: Tool = tool({name: 'kiln_draft',description:'Write the complete Kiln program into your working buffer. This is how you author — call it first ' +'to lay down your program, and call it again any time to rewrite it wholesale. The argument `code` ' +'is the full program (meta + build(), optional animate()). For small fixes prefer kiln_edit. ' +- 'Returns { ok, bytes, lines }.',+ 'Returns { ok, bytes, lines, validation } — validation is the static check of the drafted buffer ' ++ '({ valid, errors, warnings }); fix any errors before rendering.',inputSchema: draftInput,- callback: (input) => {+ callback: async (input) => {const r = buffer.draft((input as { code: string }).code);opts.sink.code = buffer.code; // capture the live buffer even if finalize is skipped- return r as JSONValue;+ return { ...r, validation: await validateBuffer() } as JSONValue;},});@@ -569,15 +586,16 @@ export function makeKilnUnifiedTools('oldString must appear verbatim in the current code (call kiln_view first) and be unique unless ' +'replaceAll is set. Make the smallest edits that satisfy the request; do not rewrite the whole ' +'program. If an edit cannot anchor, fall back to kiln_draft to rewrite. Returns ' +- '{ ok, occurrences, newBytes } or { ok:false, error, hint }.',+ '{ ok, occurrences, newBytes, validation } (validation is the static check of the edited buffer) ' ++ 'or { ok:false, error, hint }.',inputSchema: editInput,- callback: (input) => {+ callback: async (input) => {const r = buffer.apply(input as { oldString: string; newString: string; replaceAll?: boolean },);if (r.ok) {opts.sink.code = buffer.code; // capture the live buffer even if finalize is skipped- return r as JSONValue;+ return { ...r, validation: await validateBuffer() } as JSONValue;}// Point the model at kiln_draft as the always-reliable escape hatch.const hint = r.hint@@ -587,13 +605,6 @@ export function makeKilnUnifiedTools(},});- const validateTool: Tool = tool({- name: 'kiln_validate',- description: `${validateDef.description} Operates on your current working buffer (no argument).`,- inputSchema: viewInput,- callback: async () => (await validateDef.run({ code: buffer.code })) as JSONValue,- });-const renderTool: Tool = tool({name: 'kiln_render',description: `${renderViewsDef.description} Operates on your current working buffer (no argument).`,@@ -685,7 +696,6 @@ export function makeKilnUnifiedTools(draftTool,viewTool,editTool,- validateTool,renderTool,inspectTool,animationTool,diff --git a/src/composer/agent/run.ts b/src/composer/agent/run.tsindex f6cb7fdd..985013a1 100644--- a/src/composer/agent/run.ts+++ b/src/composer/agent/run.ts@@ -17,6 +17,7 @@ import { Agent, type Message, type Tool } from '@strands-agents/sdk';import { unifiedDiff } from '../../agent/diff';import { type AgentUsage, type KilnAgentEvent, MetricsCollector } from '../../agent/hooks';+import { toCachedSystemPrompt } from '../../agent/providers';import { SceneCompactionManager } from './compaction';import { serialize } from '../dsl';import { flatGround, type GroundSampler } from '../ground';@@ -164,7 +165,11 @@ export async function runKilnComposer(const agent = new Agent({model: opts.model as never,- systemPrompt: COMPOSER_SYSTEM_PROMPT,+ // A2: same portable cache breakpoint as the asset agent — Anthropic/Bedrock+ // get [TextBlock, CachePointBlock]; other providers keep the plain string.+ // Safe here: the composer's system prompt is a static const, and the+ // SceneCompactionManager only manages `messages`, never the system prompt.+ systemPrompt: toCachedSystemPrompt(COMPOSER_SYSTEM_PROMPT, opts.model),tools: allTools as never,name: opts.agentName ?? 'kiln-composer',conversationManager: compaction,diff --git a/src/prompt.ts b/src/prompt.tsindex 32f675d4..490d8040 100644--- a/src/prompt.ts+++ b/src/prompt.ts@@ -781,9 +781,9 @@ export const KILN_EDIT_DIRECTIVE = `You are EDITING an existing Kiln asset in pl* terminal verb is kiln_finalize, not kiln_submit. Used only when* toolSurface:'unified'.*/-export const KILN_REFINE_DIRECTIVE_UNIFIED = `You are MODIFYING an existing Kiln asset, not building a new one from scratch. The user message gives you the Original Request that created the asset, its Current Code, and an Edit Request. Your working buffer is already seeded with the Current Code. Keep the asset's established character, proportions, and structure; change ONLY what the Edit Request asks for — use kiln_edit for small changes, or kiln_draft to rewrite the whole program. Re-validate and re-render the buffer with the kiln tools, then call kiln_finalize.`;+export const KILN_REFINE_DIRECTIVE_UNIFIED = `You are MODIFYING an existing Kiln asset, not building a new one from scratch. The user message gives you the Original Request that created the asset, its Current Code, and an Edit Request. Your working buffer is already seeded with the Current Code. Keep the asset's established character, proportions, and structure; change ONLY what the Edit Request asks for — use kiln_edit for small changes, or kiln_draft to rewrite the whole program. Every buffer write returns a static validation report — fix any errors it lists, re-render the buffer with kiln_render, then call kiln_finalize.`;-export const KILN_EDIT_DIRECTIVE_UNIFIED = `You are EDITING an existing Kiln asset in place, not rebuilding it. Your working buffer is already seeded with the Current Code shown in the user message. Use the kiln_edit tool to make the SMALLEST set of changes that satisfy the Edit Request: replace an exact span (oldString) with newString. Each oldString must match the current buffer verbatim - call kiln_view to read it (the text is raw, with no line-number prefixes). Keep everything the Edit Request does not mention byte-for-byte unchanged. After your edits, re-validate and re-render the buffer with the kiln tools, then call kiln_finalize. If an edit cannot be anchored after a couple of tries, call kiln_draft to rewrite the whole program instead.`;+export const KILN_EDIT_DIRECTIVE_UNIFIED = `You are EDITING an existing Kiln asset in place, not rebuilding it. Your working buffer is already seeded with the Current Code shown in the user message. Use the kiln_edit tool to make the SMALLEST set of changes that satisfy the Edit Request: replace an exact span (oldString) with newString. Each oldString must match the current buffer verbatim - call kiln_view to read it (the text is raw, with no line-number prefixes). Keep everything the Edit Request does not mention byte-for-byte unchanged. Every successful edit returns a static validation report - fix any errors it lists, re-render the buffer with kiln_render, then call kiln_finalize. If an edit cannot be anchored after a couple of tries, call kiln_draft to rewrite the whole program instead.`;export interface AssetBudget {maxTriangles?: number;diff --git a/src/views/__tests__/views.test.ts b/src/views/__tests__/views.test.tsindex d7c7e23d..f37c5ab2 100644--- a/src/views/__tests__/views.test.ts+++ b/src/views/__tests__/views.test.ts@@ -130,6 +130,88 @@ describe('rasterizeView', () => {const rgb = rasterizeView(root, [1, 0, 0], { size: 32 });expect(coverage(rgb, 32)).toBe(0);});++ test('multi-material mesh: each geometry group renders with its OWN material color', () => {+ // Two coplanar triangles facing +Z: the left one in group 0 (red material),+ // the right one in group 1 (blue material). Before the per-group fix every+ // triangle took mats[0], so the blue group rendered red.+ const positions = new Float32Array([+ // group 0 (left triangle)+ -1, -1, 0, -0.1, -1, 0, -0.55, 1, 0,+ // group 1 (right triangle)+ 0.1, -1, 0, 1, -1, 0, 0.55, 1, 0,+ ]);+ const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+ const mesh = {+ isMesh: true,+ geometry: {+ getAttribute: (name: string) =>+ name === 'position' ? { array: positions, itemSize: 3, count: 6 } : undefined,+ index: { array: new Uint16Array([0, 1, 2, 3, 4, 5]), itemSize: 1, count: 6 },+ groups: [+ { start: 0, count: 3, materialIndex: 0 },+ { start: 3, count: 3, materialIndex: 1 },+ ],+ },+ material: [{ color: { r: 1, g: 0, b: 0 } }, { color: { r: 0, g: 0, b: 1 } }],+ matrixWorld: { elements: identity },+ };+ const scene = {+ updateMatrixWorld() {},+ traverse(cb: (o: unknown) => void) {+ cb(mesh);+ },+ };++ const size = 64;+ const rgb = rasterizeView(scene, [0, 0, 1], { size });+ let redPixels = 0;+ let bluePixels = 0;+ for (let i = 0; i < size * size; i++) {+ const r = rgb[i * 3]!;+ const g = rgb[i * 3 + 1]!;+ const b = rgb[i * 3 + 2]!;+ if (r === 26 && g === 26 && b === 26) continue; // background+ if (r > 100 && b < 60) redPixels++;+ if (b > 100 && r < 60) bluePixels++;+ }+ // Both group materials must appear (the blue group no longer inherits red).+ expect(redPixels).toBeGreaterThan(50);+ expect(bluePixels).toBeGreaterThan(50);+ });++ test('multi-material mesh WITHOUT groups falls back to the first material', () => {+ const positions = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);+ const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+ const mesh = {+ isMesh: true,+ geometry: {+ getAttribute: (name: string) =>+ name === 'position' ? { array: positions, itemSize: 3, count: 3 } : undefined,+ index: null,+ },+ material: [{ color: { r: 1, g: 0, b: 0 } }, { color: { r: 0, g: 0, b: 1 } }],+ matrixWorld: { elements: identity },+ };+ const scene = {+ updateMatrixWorld() {},+ traverse(cb: (o: unknown) => void) {+ cb(mesh);+ },+ };+ const rgb = rasterizeView(scene, [0, 0, 1], { size: 32 });+ let bluePixels = 0;+ let redPixels = 0;+ for (let i = 0; i < 32 * 32; i++) {+ const r = rgb[i * 3]!;+ const b = rgb[i * 3 + 2]!;+ if (r === 26 && rgb[i * 3 + 1] === 26 && b === 26) continue;+ if (r > 100 && b < 60) redPixels++;+ if (b > 100 && r < 60) bluePixels++;+ }+ expect(redPixels).toBeGreaterThan(0);+ expect(bluePixels).toBe(0);+ });});describe('encodePng', () => {diff --git a/src/views/raster.ts b/src/views/raster.tsindex 8aa60eaa..cee1c092 100644--- a/src/views/raster.ts+++ b/src/views/raster.ts@@ -102,6 +102,9 @@ interface DuckAttribute {interface DuckGeometry {getAttribute(name: string): DuckAttribute | undefined;index: DuckAttribute | null;+ /** Three.js geometry groups: ranges of the index (or position) buffer drawn+ * with `materialIndex` when the mesh carries a material ARRAY. */+ groups?: Array<{ start: number; count: number; materialIndex?: number }>;}interface DuckMaterial {color?: { r: number; g: number; b: number };@@ -142,12 +145,26 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;if (!geo || !pos || pos.itemSize !== 3) return;const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];- // Multi-material groups are rare in kiln output; first material's color is- // a sufficient approximation for QA views.- const c = mats[0]?.color;- const color: [number, number, number] = c- ? [clamp01(c.r), clamp01(c.g), clamp01(c.b)]- : [0.7, 0.7, 0.7];+ const colorOf = (mat: DuckMaterial | undefined): [number, number, number] => {+ const c = mat?.color;+ return c ? [clamp01(c.r), clamp01(c.g), clamp01(c.b)] : [0.7, 0.7, 0.7];+ };+ // Per-group material resolution: a multi-material mesh draws each geometry+ // group (a start/count range over the index — or position — buffer) with its+ // own `materialIndex`. Colors are already per-triangle here, so resolve the+ // group covering each triangle's first buffer position; meshes without+ // groups (the common single-material case) keep the flat first material.+ const fallback = colorOf(mats[0]);+ const groups = mats.length > 1 && geo.groups?.length ? geo.groups : undefined;+ const colorAt = (bufferPos: number): [number, number, number] => {+ if (!groups) return fallback;+ for (const g of groups) {+ if (bufferPos >= g.start && bufferPos < g.start + g.count) {+ return colorOf(mats[g.materialIndex ?? 0]);+ }+ }+ return fallback;+ };const m = mesh.matrixWorld?.elements;if (!m) return;@@ -172,7 +189,7 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;if (wz > max[2]) max[2] = wz;}- const pushTri = (a: number, b: number, c2: number) => {+ const pushTri = (a: number, b: number, c2: number, color: [number, number, number]) => {const v = new Float64Array(9);v[0] = world[a * 3]!;v[1] = world[a * 3 + 1]!;@@ -186,15 +203,18 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;tris.push({ v, color });};+ // Geometry groups address the index buffer for indexed geometry and the+ // position buffer otherwise, so `i` (the triangle's first buffer slot) is+ // the group-lookup key in both branches.const index = geo.index;if (index) {const ia = index.array;for (let i = 0; i + 2 < index.count; i += 3) {- pushTri(ia[i]!, ia[i + 1]!, ia[i + 2]!);+ pushTri(ia[i]!, ia[i + 1]!, ia[i + 2]!, colorAt(i));}} else {for (let i = 0; i + 2 < pos.count; i += 3) {- pushTri(i, i + 1, i + 2);+ pushTri(i, i + 1, i + 2, colorAt(i));}}});