Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(agent): prune superseded render images from the transcript

Matt Kissinger2716204776ff
diff --git a/src/agent/compaction.test.ts b/src/agent/compaction.test.ts
new file mode 100644
index 00000000..0038e69a
--- /dev/null
+++ b/src/agent/compaction.test.ts
@@ -0,0 +1,222 @@
+/**
+ * Generation-loop transcript compaction — stale render-image pruning.
+ *
+ * Pins the surgical contract: across a multi-render transcript only the newest
+ * image-bearing tool result keeps its image(s); every older one gets a text
+ * placeholder INSIDE the tool result (same toolUseId, same message count — the
+ * tool-use/tool-result pairing is never disturbed), the JSON metrics half of
+ * each result survives, images outside tool results (the user's reference
+ * inputImage) are untouched, and the pass is idempotent. The installer test
+ * mirrors hooks.test.ts's fake-agent pattern to pin the BeforeModelCallEvent
+ * wiring without a live model.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ BeforeModelCallEvent,
+ ImageBlock,
+ JsonBlock,
+ Message,
+ TextBlock,
+ ToolResultBlock,
+ ToolUseBlock,
+} from '@strands-agents/sdk';
+
+import {
+ installRenderImageCompaction,
+ pruneStaleRenderImages,
+ STALE_RENDER_PLACEHOLDER,
+} from './compaction';
+
+const png = () => new ImageBlock({ format: 'png', source: { bytes: new Uint8Array([137, 80]) } });
+
+const toolUse = (id: string, name = 'kiln_render'): Message =>
+ new Message({
+ role: 'assistant',
+ content: [new ToolUseBlock({ name, toolUseId: id, input: {} })],
+ });
+
+/** A render-shaped tool result: [ImageBlock xN, JsonBlock] (toCallbackResult order). */
+const renderResult = (id: string, images = 1): Message =>
+ new Message({
+ role: 'user',
+ content: [
+ new ToolResultBlock({
+ toolUseId: id,
+ status: 'success',
+ content: [...Array.from({ length: images }, png), new JsonBlock({ json: { ok: true } })],
+ }),
+ ],
+ });
+
+/** An image-free tool result (e.g. kiln_validate). */
+const jsonResult = (id: string): Message =>
+ new Message({
+ role: 'user',
+ content: [
+ new ToolResultBlock({
+ toolUseId: id,
+ status: 'success',
+ content: [new JsonBlock({ json: { valid: true } })],
+ }),
+ ],
+ });
+
+function toolResultOf(message: Message): ToolResultBlock {
+ const block = message.content[0];
+ if (!(block instanceof ToolResultBlock)) throw new Error('expected a tool result block');
+ return block;
+}
+
+const imageCount = (message: Message): number =>
+ toolResultOf(message).content.filter((c) => (c as { type?: string }).type === 'imageBlock')
+ .length;
+
+const textOf = (message: Message): string[] =>
+ toolResultOf(message)
+ .content.filter((c): c is TextBlock => (c as { type?: string }).type === 'textBlock')
+ .map((t) => t.text);
+
+/** A three-render transcript with a validate call in between. */
+function transcript(): Message[] {
+ return [
+ new Message({ role: 'user', content: [new TextBlock('build a chest')] }),
+ toolUse('r1'),
+ renderResult('r1'),
+ toolUse('v1', 'kiln_validate'),
+ jsonResult('v1'),
+ toolUse('r2'),
+ renderResult('r2'),
+ toolUse('r3'),
+ renderResult('r3'),
+ new Message({ role: 'assistant', content: [new TextBlock('looks good')] }),
+ ];
+}
+
+describe('pruneStaleRenderImages', () => {
+ test('only the latest render image survives; older results get the placeholder', () => {
+ const messages = transcript();
+ const result = pruneStaleRenderImages(messages);
+
+ expect(result).toEqual({ prunedImages: 2, prunedResults: 2 });
+ expect(imageCount(messages[2]!)).toBe(0);
+ expect(textOf(messages[2]!)).toEqual([STALE_RENDER_PLACEHOLDER]);
+ expect(imageCount(messages[6]!)).toBe(0);
+ expect(textOf(messages[6]!)).toEqual([STALE_RENDER_PLACEHOLDER]);
+ // The newest render keeps its image untouched.
+ expect(imageCount(messages[8]!)).toBe(1);
+ expect(textOf(messages[8]!)).toEqual([]);
+ });
+
+ test('tool-use/tool-result pairing is intact: no messages added/removed, ids stable', () => {
+ const messages = transcript();
+ pruneStaleRenderImages(messages);
+
+ expect(messages).toHaveLength(10);
+ // Every tool use still has its matching tool result with the same id.
+ for (const [useAt, id] of [
+ [1, 'r1'],
+ [3, 'v1'],
+ [5, 'r2'],
+ [7, 'r3'],
+ ] as const) {
+ const use = messages[useAt]!.content[0] as ToolUseBlock;
+ expect(use.toolUseId).toBe(id);
+ expect(toolResultOf(messages[useAt + 1]!).toolUseId).toBe(id);
+ }
+ // The JSON metrics half of a pruned result survives.
+ const prunedContent = toolResultOf(messages[2]!).content;
+ expect(prunedContent.some((c) => (c as { type?: string }).type === 'jsonBlock')).toBe(true);
+ });
+
+ test('is idempotent: a second pass prunes nothing and changes nothing', () => {
+ const messages = transcript();
+ pruneStaleRenderImages(messages);
+ const snapshot = JSON.stringify(messages);
+
+ const second = pruneStaleRenderImages(messages);
+
+ expect(second).toEqual({ prunedImages: 0, prunedResults: 0 });
+ expect(JSON.stringify(messages)).toBe(snapshot);
+ });
+
+ test('a multi-image result (perFrame animation) collapses to ONE placeholder', () => {
+ const messages = [toolUse('a1'), renderResult('a1', 4), toolUse('r1'), renderResult('r1')];
+ const result = pruneStaleRenderImages(messages);
+
+ expect(result).toEqual({ prunedImages: 4, prunedResults: 1 });
+ expect(imageCount(messages[1]!)).toBe(0);
+ expect(textOf(messages[1]!)).toEqual([
+ '[4 earlier render images omitted — superseded by a newer render]',
+ ]);
+ expect(imageCount(messages[3]!)).toBe(1);
+ });
+
+ test('images outside tool results (the reference inputImage) are never touched', () => {
+ const messages = [
+ new Message({ role: 'user', content: [new TextBlock('match this'), png()] }),
+ toolUse('r1'),
+ renderResult('r1'),
+ toolUse('r2'),
+ renderResult('r2'),
+ ];
+ pruneStaleRenderImages(messages);
+
+ const first = messages[0]!.content;
+ expect(first.some((c) => (c as { type?: string }).type === 'imageBlock')).toBe(true);
+ });
+
+ test('keep:2 preserves the two newest image-bearing results', () => {
+ const messages = transcript();
+ const result = pruneStaleRenderImages(messages, { keep: 2 });
+
+ expect(result).toEqual({ prunedImages: 1, prunedResults: 1 });
+ expect(imageCount(messages[2]!)).toBe(0);
+ expect(imageCount(messages[6]!)).toBe(1);
+ expect(imageCount(messages[8]!)).toBe(1);
+ });
+
+ test('no-op on a transcript with at most one image-bearing result', () => {
+ const single = [toolUse('r1'), renderResult('r1')];
+ expect(pruneStaleRenderImages(single)).toEqual({ prunedImages: 0, prunedResults: 0 });
+ expect(imageCount(single[1]!)).toBe(1);
+ expect(pruneStaleRenderImages([])).toEqual({ prunedImages: 0, prunedResults: 0 });
+ });
+});
+
+describe('installRenderImageCompaction', () => {
+ type Cb = (event: unknown) => void;
+
+ /** Minimal Agent stand-in (hooks.test.ts pattern): hook registry + dispatch. */
+ 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 modelCall = () => {
+ for (const cb of hooks.get(BeforeModelCallEvent) ?? []) cb({ agent });
+ };
+ return { agent, modelCall };
+ }
+
+ test('prunes before each model call and reports via onPrune', () => {
+ const messages = transcript();
+ const pruned: number[] = [];
+ const { agent, modelCall } = fakeAgent(messages);
+ installRenderImageCompaction(agent as never, { onPrune: (i) => pruned.push(i.prunedImages) });
+
+ modelCall();
+ expect(imageCount(messages[2]!)).toBe(0);
+ expect(imageCount(messages[8]!)).toBe(1);
+ expect(pruned).toEqual([2]);
+
+ // Second call: nothing left to prune, so onPrune stays quiet.
+ modelCall();
+ expect(pruned).toEqual([2]);
+ });
+});
diff --git a/src/agent/compaction.ts b/src/agent/compaction.ts
new file mode 100644
index 00000000..797a5e63
--- /dev/null
+++ b/src/agent/compaction.ts
@@ -0,0 +1,134 @@
+/**
+ * Generation-loop transcript compaction — stale render-image pruning.
+ *
+ * Every kiln_render / kiln_screenshot / kiln_view_interior / animation tool
+ * result carries a PNG ImageBlock the model inspects ONCE, then drags through
+ * every later model call (the single biggest input-token lever in a generation
+ * run — a six-view grid is tens of KB of image tokens per step). Unlike the
+ * composer (whose state lives in the PlacementModel, so its manager collapses
+ * the WHOLE transcript — see composer/agent/compaction.ts), the generation
+ * loop's transcript carries authoring context worth keeping. So this pruner is
+ * surgical: before each model call it strips the image blocks out of every
+ * image-bearing tool result EXCEPT the newest one(s), replacing them with a
+ * short text placeholder INSIDE the tool result.
+ *
+ * Tool-use/tool-result pairing is never touched — no messages are added or
+ * removed, no toolUseIds change; only the media inside an existing tool result
+ * is swapped for text (a TextBlock is a valid ToolResultContent). The JSON
+ * metrics half of each result (grade, tris, warnings) survives, so the model
+ * 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';
+
+/** Placeholder text swapped in for a superseded render image. */
+export const STALE_RENDER_PLACEHOLDER =
+ '[earlier render image omitted — superseded by a newer render]';
+
+/** What one prune pass did. */
+export interface PruneImagesResult {
+ /** Image blocks removed across the transcript. */
+ prunedImages: number;
+ /** Tool results that had their images swapped for the placeholder. */
+ prunedResults: number;
+}
+
+/** Duck-typed views over the SDK block classes (mirrors run.ts's lastMessageText:
+ * the discriminators are stable, and duck-typing keeps the pruner robust to the
+ * class instances the live loop holds). */
+interface BlockLike {
+ type?: string;
+ content?: unknown[];
+}
+
+function isImageBlock(block: unknown): boolean {
+ return (block as BlockLike).type === 'imageBlock';
+}
+
+function isToolResultBlock(block: unknown): block is Required<Pick<BlockLike, 'content'>> {
+ const b = block as BlockLike;
+ return b.type === 'toolResultBlock' && Array.isArray(b.content);
+}
+
+/**
+ * Strip image blocks from all but the newest `keep` image-bearing tool results
+ * (default 1 — only the latest render image stays). Mutates the tool-result
+ * content arrays in place; each pruned result gets ONE placeholder TextBlock in
+ * the position of its first image. Idempotent: already-pruned results carry no
+ * images and are skipped on the next pass.
+ */
+export function pruneStaleRenderImages(
+ messages: readonly Message[],
+ opts: { keep?: number } = {},
+): PruneImagesResult {
+ const keep = opts.keep ?? 1;
+
+ // Collect every image-bearing tool result, in transcript order.
+ const bearing: Array<{ content: unknown[] }> = [];
+ for (const message of messages) {
+ for (const block of message.content) {
+ if (isToolResultBlock(block) && block.content.some(isImageBlock)) {
+ bearing.push(block);
+ }
+ }
+ }
+
+ const cut = Math.max(0, bearing.length - Math.max(0, keep));
+ let prunedImages = 0;
+ let prunedResults = 0;
+ for (const result of bearing.slice(0, cut)) {
+ const images = result.content.filter(isImageBlock).length;
+ const placeholder =
+ images > 1
+ ? new TextBlock(`[${images} earlier render images omitted — superseded by a newer render]`)
+ : new TextBlock(STALE_RENDER_PLACEHOLDER);
+ const next: unknown[] = [];
+ let placed = false;
+ for (const item of result.content) {
+ if (isImageBlock(item)) {
+ if (!placed) {
+ next.push(placeholder);
+ placed = true;
+ }
+ continue;
+ }
+ next.push(item);
+ }
+ result.content.splice(0, result.content.length, ...next);
+ prunedImages += images;
+ prunedResults += 1;
+ }
+ return { prunedImages, prunedResults };
+}
+
+export interface RenderImageCompactionOptions {
+ /** How many newest image-bearing tool results keep their images. Default 1. */
+ keep?: number;
+ /** Notified after a pass that pruned something (best-effort; errors swallowed). */
+ onPrune?: (info: PruneImagesResult) => void;
+}
+
+/**
+ * Install the pruner on an agent: before EVERY model call, stale render images
+ * are swapped for placeholders so only the newest one rides the request. Same
+ * hook mechanism the composer's SceneCompactionManager uses, but additive — the
+ * agent's default conversation manager stays in place. Returns the unsubscribe.
+ */
+export function installRenderImageCompaction(
+ agent: Agent,
+ opts: RenderImageCompactionOptions = {},
+): () => void {
+ return agent.addHook(BeforeModelCallEvent, (event) => {
+ const result = pruneStaleRenderImages(
+ event.agent.messages,
+ opts.keep != null ? { keep: opts.keep } : {},
+ );
+ if (result.prunedImages > 0 && opts.onPrune) {
+ try {
+ opts.onPrune(result);
+ } catch {
+ // progress sinks are best-effort
+ }
+ }
+ });
+}
diff --git a/src/agent/hooks.ts b/src/agent/hooks.ts
index 73942821..020782cb 100644
--- a/src/agent/hooks.ts
+++ b/src/agent/hooks.ts
@@ -36,6 +36,14 @@ export type KilnAgentEvent =
messagesBefore: number;
placements: number;
overlaps: number;
+ }
+ | {
+ /** M1b: the finalized program graded below B for a consolidation-fixable
+ * reason, and one bounded grade-refine turn is being fed back to the model. */
+ type: 'grade_refine';
+ step: number;
+ grade: string;
+ materials: number;
};
/** The agent-loop-derived metrics this collector produces. */
@@ -120,12 +128,19 @@ export class MetricsCollector {
this.cleanups = [];
}
- /** Record token usage from the AgentResult after invoke completes. */
+ /** Record token usage from the AgentResult after an invoke completes.
+ * Accumulates across calls — a grade-refine pass is a SECOND invoke on the
+ * same agent, and `latestAgentInvocation.usage` is per-invocation, so the
+ * run's usage is the sum. Single-invoke callers are unaffected. */
recordResultUsage(usage: AgentUsage | undefined): void {
if (!usage) return;
- const next: AgentUsage = {};
- if (typeof usage.inputTokens === 'number') next.inputTokens = usage.inputTokens;
- if (typeof usage.outputTokens === 'number') next.outputTokens = usage.outputTokens;
+ 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;
+ }
if (next.inputTokens !== undefined || next.outputTokens !== undefined) this.usage = next;
}