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): M1b grade-aware refine pass + step-cap salvage

Matt Kissinger848ad8abeb3a
diff --git a/src/agent/grade-refine.test.ts b/src/agent/grade-refine.test.ts
new file mode 100644
index 00000000..d4eb8f9f
--- /dev/null
+++ b/src/agent/grade-refine.test.ts
@@ -0,0 +1,174 @@
+/**
+ * M1b grade-aware refine helpers — the deterministic trigger + feedback message.
+ *
+ * `shouldGradeRefine` is the injection gate runKilnAgent consults after the
+ * model finalizes: below-B AND consolidation-fixable AND budget headroom. These
+ * tests pin every hold (mode off, missing report, already >= B, transparency-only
+ * demotion, exhausted step budget) plus the message contents the model acts on.
+ * `assessProgramGrade` is exercised against the known-good fixture program (a
+ * real CPU bake — no model, no network) and a garbage program.
+ */
+import { describe, expect, test } from 'bun:test';
+
+import type { InstanceabilityMetrics, InstanceabilityReport } from '../metrics';
+import { KNOWN_GOOD_CODE } from '../__tests__/fixtures';
+import {
+ assessProgramGrade,
+ buildGradeRefineMessage,
+ GRADE_REFINE_MIN_HEADROOM,
+ gradeRank,
+ shouldGradeRefine,
+} from './grade-refine';
+
+function report(
+ over: Partial<InstanceabilityMetrics> & { grade?: string } = {},
+): InstanceabilityReport {
+ const { grade, ...metricsOver } = over;
+ const metrics: InstanceabilityMetrics = {
+ uniqueGeometries: 5,
+ uniqueMaterials: 8,
+ drawCalls: 12,
+ textureCount: 0,
+ skinned: false,
+ transparentMaterials: 0,
+ triangles: 900,
+ ...metricsOver,
+ };
+ return {
+ grade: (grade ?? 'D') as InstanceabilityReport['grade'],
+ summary: `${grade ?? 'D'} — ${metrics.uniqueMaterials} mat / ${metrics.uniqueGeometries} geo / ${metrics.drawCalls} draws, opaque`,
+ reasons: [`${metrics.uniqueMaterials} materials`],
+ metrics,
+ };
+}
+
+describe('gradeRank', () => {
+ test('orders A best to F worst; unknown ranks worst of all', () => {
+ expect(gradeRank('A')).toBeLessThan(gradeRank('B'));
+ expect(gradeRank('B')).toBeLessThan(gradeRank('C'));
+ expect(gradeRank('C')).toBeLessThan(gradeRank('D'));
+ expect(gradeRank('D')).toBeLessThan(gradeRank('F'));
+ expect(gradeRank('?')).toBeGreaterThan(gradeRank('F'));
+ });
+});
+
+describe('shouldGradeRefine', () => {
+ const base = { mode: 'auto' as const, steps: 8, maxSteps: 40 };
+
+ test('triggers on a below-B material-sprawl grade with budget headroom', () => {
+ expect(shouldGradeRefine({ ...base, report: report({ grade: 'D', uniqueMaterials: 8 }) })).toBe(
+ true,
+ );
+ expect(shouldGradeRefine({ ...base, report: report({ grade: 'C', uniqueMaterials: 5 }) })).toBe(
+ true,
+ );
+ });
+
+ test('triggers on texture sprawl even when materials are lean', () => {
+ const r = report({ grade: 'C', uniqueMaterials: 2, textureCount: 6 });
+ expect(shouldGradeRefine({ ...base, report: r })).toBe(true);
+ });
+
+ test('never triggers at or above the B target', () => {
+ expect(shouldGradeRefine({ ...base, report: report({ grade: 'A', uniqueMaterials: 1 }) })).toBe(
+ false,
+ );
+ expect(shouldGradeRefine({ ...base, report: report({ grade: 'B', uniqueMaterials: 3 }) })).toBe(
+ false,
+ );
+ });
+
+ test('skips a transparency-only demotion (glass caps at C by design)', () => {
+ const r = report({
+ grade: 'C',
+ uniqueMaterials: 2,
+ transparentMaterials: 1,
+ textureCount: 0,
+ });
+ expect(shouldGradeRefine({ ...base, report: r })).toBe(false);
+ });
+
+ test("mode 'off' and a missing report never trigger", () => {
+ expect(shouldGradeRefine({ ...base, mode: 'off', report: report() })).toBe(false);
+ expect(shouldGradeRefine({ ...base, report: undefined })).toBe(false);
+ });
+
+ test('respects the step budget: needs MIN_HEADROOM calls under the cap', () => {
+ const r = report({ grade: 'D' });
+ const cap = 40;
+ const tooDeep = cap - GRADE_REFINE_MIN_HEADROOM + 1;
+ expect(shouldGradeRefine({ mode: 'auto', report: r, steps: tooDeep, maxSteps: cap })).toBe(
+ false,
+ );
+ const justEnough = cap - GRADE_REFINE_MIN_HEADROOM;
+ expect(shouldGradeRefine({ mode: 'auto', report: r, steps: justEnough, maxSteps: cap })).toBe(
+ true,
+ );
+ });
+
+ test('an uncapped run (maxSteps 0) has unlimited headroom', () => {
+ expect(shouldGradeRefine({ mode: 'auto', report: report(), steps: 500, maxSteps: 0 })).toBe(
+ true,
+ );
+ });
+});
+
+describe('buildGradeRefineMessage', () => {
+ test('carries grade, material count/target, offenders, and the surface verbs', () => {
+ const msg = buildGradeRefineMessage({
+ report: report({ grade: 'D', uniqueMaterials: 8 }),
+ materialLabels: ['#8b4513', '#8b4713', '#ffcc00'],
+ finalizeVerb: 'kiln_finalize',
+ editHint: 'kiln_edit for targeted swaps (or kiln_draft to rewrite)',
+ });
+ expect(msg).toContain('grades D');
+ expect(msg).toContain('you have 8');
+ expect(msg).toContain('3 or fewer');
+ expect(msg).toContain('#8b4513, #8b4713, #ffcc00');
+ expect(msg).toContain('kiln_render');
+ expect(msg).toContain('kiln_finalize');
+ expect(msg).toContain('kiln_edit');
+ // The convergence guard: one pass, no redesign.
+ expect(msg).toMatch(/ONE bounded consolidation pass/);
+ expect(msg).toMatch(/do NOT redesign/i);
+ });
+
+ test('mentions texture sprawl only when textures exceed the demotion threshold', () => {
+ const sprawl = buildGradeRefineMessage({
+ report: report({ grade: 'C', uniqueMaterials: 2, textureCount: 6 }),
+ finalizeVerb: 'kiln_submit',
+ editHint: 'rewrite the program with the consolidated materials',
+ });
+ expect(sprawl).toContain('6 textures');
+ expect(sprawl).toContain('kiln_submit');
+
+ const lean = buildGradeRefineMessage({
+ report: report({ grade: 'D', textureCount: 0 }),
+ finalizeVerb: 'kiln_submit',
+ editHint: 'rewrite the program with the consolidated materials',
+ });
+ expect(lean).not.toContain('textures');
+ });
+});
+
+describe('assessProgramGrade', () => {
+ test('grades the known-good program post-auto-consolidation', async () => {
+ const assess = await assessProgramGrade(KNOWN_GOOD_CODE);
+ expect(assess.ok).toBe(true);
+ expect(assess.report).toBeDefined();
+ // TestChest is lean (2 distinct materials after dedup) — at/above the B bar,
+ // so a real run would NOT trigger a refine turn on it.
+ expect(['A', 'B']).toContain(assess.report!.grade);
+ expect(shouldGradeRefine({ mode: 'auto', report: assess.report, steps: 5, maxSteps: 40 })).toBe(
+ false,
+ );
+ // The offender list is derived from the baked GLB's materials.
+ expect(assess.materialLabels?.length ?? 0).toBeGreaterThan(0);
+ });
+
+ test('a program that does not build comes back ok:false, never throws', async () => {
+ const assess = await assessProgramGrade('this is not a kiln program');
+ expect(assess.ok).toBe(false);
+ expect(assess.error).toBeDefined();
+ });
+});
diff --git a/src/agent/grade-refine.ts b/src/agent/grade-refine.ts
new file mode 100644
index 00000000..09321b85
--- /dev/null
+++ b/src/agent/grade-refine.ts
@@ -0,0 +1,172 @@
+/**
+ * M1b — grade-aware refine loop helpers (plan/05 §3.2).
+ *
+ * The grader (`metrics.ts`) already computes the instanceability signal on every
+ * bake; M1a made the deterministic `optimize:'auto'` consolidation the default.
+ * This module closes the remaining loop: after the agent finalizes, the run
+ * assesses the program's POST-consolidation grade (the grade the shipped GLB
+ * will actually carry), and when it lands below B for a reason the model can
+ * fix by authoring — material sprawl or texture sprawl, NOT a deliberate
+ * transparency demotion — `runKilnAgent` feeds one bounded consolidation turn
+ * back before emitting.
+ *
+ * Pure helpers: the trigger decision and the feedback message are plain
+ * functions so the injection logic is unit-testable without a live model.
+ */
+import { WebIO } from '@gltf-transform/core';
+
+import type { InstanceabilityGrade, InstanceabilityReport } from '../metrics';
+import { renderGLB } from '../render';
+
+/** Grades at or above this never trigger a refine turn. */
+export const GRADE_REFINE_TARGET: InstanceabilityGrade = 'B';
+
+/** Minimum model-call headroom under the step cap a refine round needs
+ * (edit → render → finalize, plus slack for a retry). */
+export const GRADE_REFINE_MIN_HEADROOM = 4;
+
+const GRADE_ORDER: InstanceabilityGrade[] = ['A', 'B', 'C', 'D', 'F'];
+
+/** Rank a grade for comparison: lower is better (A=0 … F=4). Unknown ranks worst. */
+export function gradeRank(grade: string): number {
+ const at = GRADE_ORDER.indexOf(grade as InstanceabilityGrade);
+ return at === -1 ? GRADE_ORDER.length : at;
+}
+
+/** Deterministic post-bake assessment of a Kiln program. */
+export interface ProgramGradeAssessment {
+ /** False when the program failed to execute/bake (error carries why). */
+ ok: boolean;
+ /** The post-`auto`-consolidation instanceability report, when computable. */
+ report?: InstanceabilityReport;
+ /** Human-readable labels for the baked GLB's distinct materials (name when
+ * set, else the sRGB base-color hex) — the "offending material list". */
+ materialLabels?: string[];
+ error?: string;
+}
+
+/** Encode one linear color channel to sRGB 0-255. */
+function srgb255(linear: number): number {
+ const v = linear <= 0.0031308 ? linear * 12.92 : 1.055 * linear ** (1 / 2.4) - 0.055;
+ return Math.max(0, Math.min(255, Math.round(v * 255)));
+}
+
+/** List distinct material labels from baked GLB bytes (best-effort; [] on parse failure). */
+async function listMaterialLabels(glb: Uint8Array): Promise<string[]> {
+ try {
+ const doc = await new WebIO().readBinary(glb);
+ const labels = new Set<string>();
+ for (const material of doc.getRoot().listMaterials()) {
+ const name = material.getName();
+ if (name) {
+ labels.add(name);
+ continue;
+ }
+ const [r, g, b] = material.getBaseColorFactor();
+ const hex = [r ?? 0, g ?? 0, b ?? 0]
+ .map((c) => srgb255(c).toString(16).padStart(2, '0'))
+ .join('');
+ labels.add(`#${hex}`);
+ }
+ return [...labels];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Render + grade a program exactly as the final bake will (grade-aware `auto`
+ * consolidation, matching `generateKilnAsset` and the Studio web-tier re-bake),
+ * so the refine trigger keys on the grade the asset actually ships with.
+ * Deterministic CPU work; never throws.
+ */
+export async function assessProgramGrade(code: string): Promise<ProgramGradeAssessment> {
+ try {
+ const render = await renderGLB(code, { optimize: 'auto' });
+ 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.
+ if (!report) return { ok: true };
+ const materialLabels = await listMaterialLabels(new Uint8Array(render.glb));
+ return { ok: true, report, ...(materialLabels.length ? { materialLabels } : {}) };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+export interface GradeRefineTrigger {
+ /** The run's gradeRefine option ('auto' triggers; anything else never does). */
+ mode: 'auto' | 'off';
+ /** Post-bake assessment report (undefined = no signal, never triggers). */
+ report: InstanceabilityReport | undefined;
+ /** Model calls used so far in this run. */
+ steps: number;
+ /** The run's hard step cap (0 = uncapped). */
+ maxSteps: number;
+}
+
+/**
+ * Decide whether to spend ONE bounded refine turn on the grade. Triggers only
+ * when every hold is clear:
+ * - gradeRefine is 'auto' and a report exists;
+ * - the grade is below B;
+ * - the cause is consolidation-fixable — material sprawl (>3 distinct) or
+ * texture sprawl (>4). A transparency-only demotion (glass caps at C by
+ * design) is a design choice, not an authoring defect: no turn is spent;
+ * - the step budget leaves at least {@link GRADE_REFINE_MIN_HEADROOM} calls.
+ */
+export function shouldGradeRefine(trigger: GradeRefineTrigger): boolean {
+ if (trigger.mode !== 'auto') return false;
+ const report = trigger.report;
+ if (!report) return false;
+ if (gradeRank(report.grade) <= gradeRank(GRADE_REFINE_TARGET)) return false;
+ const m = report.metrics;
+ if (m.uniqueMaterials <= 3 && m.textureCount <= 4) return false;
+ if (trigger.maxSteps > 0 && trigger.maxSteps - trigger.steps < GRADE_REFINE_MIN_HEADROOM) {
+ return false;
+ }
+ return true;
+}
+
+export interface GradeRefineMessageArgs {
+ report: InstanceabilityReport;
+ /** Offending material labels from {@link assessProgramGrade}. */
+ materialLabels?: string[];
+ /** Terminal verb for the active surface: kiln_finalize (unified) or kiln_submit (current). */
+ finalizeVerb: 'kiln_finalize' | 'kiln_submit';
+ /** Surface-appropriate edit instruction (e.g. 'kiln_edit (or kiln_draft to rewrite)'). */
+ editHint: string;
+}
+
+/**
+ * The concise feedback turn fed back to the model: grade, material stats, the
+ * offender list, and a tightly-bounded consolidation directive. Engineered so
+ * the model consolidates materials WITHOUT redesigning the asset.
+ */
+export function buildGradeRefineMessage(args: GradeRefineMessageArgs): string {
+ const { report } = args;
+ const m = report.metrics;
+ const lines: string[] = [
+ '[Automated grade check — not a user message.] Your finalized asset grades ' +
+ `${report.grade} for instanceability (${report.summary}). The grade keys on ` +
+ `distinct-material count: A needs 1, B needs 3 or fewer; you have ${m.uniqueMaterials}.`,
+ ];
+ if (m.textureCount > 4) {
+ lines.push(
+ `It also carries ${m.textureCount} textures (more than 4 demotes the grade — ` +
+ 'share or drop textures where parts can reuse one).',
+ );
+ }
+ if (args.materialLabels?.length) {
+ lines.push(`Distinct materials: ${args.materialLabels.join(', ')}.`);
+ }
+ lines.push(
+ 'Make ONE bounded consolidation pass now — do NOT redesign the asset:',
+ '1. Collapse near-duplicate colors/materials so parts share ONE material per color ' +
+ 'family (target 3 or fewer distinct materials). Preserve the silhouette, geometry, ' +
+ 'and overall color read.',
+ `2. Apply the smallest change that achieves it: ${args.editHint}.`,
+ `3. Call kiln_render once to confirm the material count dropped, then call ${args.finalizeVerb} again.`,
+ );
+ return lines.join('\n');
+}
diff --git a/src/agent/index.ts b/src/agent/index.ts
index 2f72b444..a711b914 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -17,6 +17,8 @@
* - {@link ensureStreamStart} — the OpenRouter/Vercel-bridge stream fix
* - {@link makeOpenRouterModel} — build an OpenRouter Strands model with the fix
* - {@link MetricsCollector} — per-loop tool/step/usage metrics via hooks
+ * - {@link installRenderImageCompaction} — prune superseded render images from the transcript
+ * - {@link assessProgramGrade} / {@link shouldGradeRefine} — M1b grade-aware refine helpers
*/
export { runKilnAgent } from './run';
export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow, KilnInputImage } from './run';
@@ -47,6 +49,27 @@ export type {
export { unifiedDiff } from './diff';
export type { UnifiedDiffOptions } from './diff';
+export {
+ pruneStaleRenderImages,
+ installRenderImageCompaction,
+ STALE_RENDER_PLACEHOLDER,
+} from './compaction';
+export type { PruneImagesResult, RenderImageCompactionOptions } from './compaction';
+
+export {
+ assessProgramGrade,
+ shouldGradeRefine,
+ buildGradeRefineMessage,
+ gradeRank,
+ GRADE_REFINE_TARGET,
+ GRADE_REFINE_MIN_HEADROOM,
+} from './grade-refine';
+export type {
+ ProgramGradeAssessment,
+ GradeRefineTrigger,
+ GradeRefineMessageArgs,
+} from './grade-refine';
+
export { ensureStreamStart } from './stream-start';
export {
diff --git a/src/agent/run.ts b/src/agent/run.ts
index 4a4fd1e3..a546016f 100644
--- a/src/agent/run.ts
+++ b/src/agent/run.ts
@@ -43,6 +43,13 @@ import {
} from './surface';
import { unifiedDiff } from './diff';
import { MetricsCollector, type AgentUsage, type KilnAgentEvent } from './hooks';
+import { installRenderImageCompaction } from './compaction';
+import {
+ assessProgramGrade,
+ buildGradeRefineMessage,
+ gradeRank,
+ shouldGradeRefine,
+} from './grade-refine';
/** How the agent learns Kiln conventions. */
export type KilnKnowhow = 'inline' | 'skill';
@@ -128,6 +135,20 @@ export interface RunKilnAgentOptions {
* the initial message becomes a [TextBlock, ImageBlock] pair and the prompt notes
* that a reference image is attached. Works for fresh gen AND refine. */
inputImage?: KilnInputImage;
+ /** Transcript image compaction. 'latest' (default) prunes each superseded render
+ * image out of its tool result before every model call (a short placeholder takes
+ * its place; the JSON metrics half survives, and tool-use/result pairing is never
+ * touched) so only the newest render image rides each request — the biggest
+ * input-token lever in a multi-render run. 'off' keeps the full image history. */
+ imageCompaction?: 'latest' | 'off';
+ /** M1b grade-aware refine (plan/05 §3.2). 'auto' (default): after the model
+ * finalizes, the program is baked + graded exactly as the final artifact will be
+ * (grade-aware `auto` consolidation); if it still grades below B for a
+ * consolidation-fixable reason (material/texture sprawl — never a transparency-only
+ * demotion) and the step budget allows, ONE bounded feedback turn asks the model to
+ * consolidate, and the refined program is kept only if its grade improves.
+ * 'off' skips the check (no extra model turn, no assessment bake). */
+ gradeRefine?: 'auto' | 'off';
}
export interface RunKilnAgentResult {
@@ -145,6 +166,10 @@ export interface RunKilnAgentResult {
edits?: EditRecord[];
/** In edit mode, a unified diff from the parent code to the final buffer. */
diff?: string;
+ /** 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`. */
+ capped?: boolean;
/** Error message if the run threw. */
error?: string;
}
@@ -234,6 +259,13 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
name: opts.agentName ?? 'kiln-agent',
});
metrics.attach(agent);
+ // 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;
+ // only media INSIDE older tool results is swapped for a text placeholder.
+ if ((opts.imageCompaction ?? 'latest') === 'latest') {
+ installRenderImageCompaction(agent);
+ }
// An image-only request still needs a textual anchor for prompt framing.
const promptText =
@@ -286,28 +318,102 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
const result = await agent.invoke(invokeArgs as never);
metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);
+ // The sink-captured program for the active surface (a REAL program, unlike
+ // the structuredOutput/lastText fallbacks below) — the only code the step-cap
+ // salvage and the grade-refine pass are allowed to act on.
+ const readSinkCode = (): string | undefined =>
+ surface === 'unified' ? unifiedSink.code : editMode ? editSink.code : sink.code;
+
// Capture: the buffer-backed surfaces (unified / edit) hold the program in
// their sink; the current generate surface captures via kiln_submit. Both
// fall back to structuredOutput then the last assistant text.
- let code = surface === 'unified' ? unifiedSink.code : editMode ? editSink.code : sink.code;
+ let code = readSinkCode();
if (!code && result.structuredOutput) {
const so = result.structuredOutput as { code?: unknown };
if (typeof so.code === 'string') code = so.code;
}
- const lastText = lastMessageText(result.lastMessage);
+ let lastText = lastMessageText(result.lastMessage);
if (!code) code = lastText;
- // If the loop was halted by the step cap, surface it as a clear failure
- // rather than trying to render a half-finished buffer (bounds cost, and the
- // gen is honestly marked failed instead of shipping a truncated asset).
+ let capped = false;
if (metrics.wasCapped()) {
- const collected = metrics.readMetrics();
- return {
- toolCalls: collected.toolCalls,
- steps: collected.steps,
- ...(collected.usage ? { usage: collected.usage } : {}),
- error: `kiln agent exceeded ${maxSteps} model calls (step cap) — aborted to bound cost`,
- };
+ // Step-cap salvage: a cap used to discard the whole run, throwing away a
+ // program the sink already held. If the captured program renders, return
+ // it flagged `capped` (an honest best effort); only a cap with nothing
+ // renderable stays a hard failure.
+ const captured = readSinkCode();
+ const salvage = captured ? await assessProgramGrade(captured) : undefined;
+ if (!salvage?.ok) {
+ const collected = metrics.readMetrics();
+ return {
+ toolCalls: collected.toolCalls,
+ steps: collected.steps,
+ ...(collected.usage ? { usage: collected.usage } : {}),
+ error: `kiln agent exceeded ${maxSteps} model calls (step cap) — aborted to bound cost`,
+ };
+ }
+ capped = true;
+ code = captured;
+ } else if ((opts.gradeRefine ?? 'auto') === 'auto') {
+ // M1b grade-aware refine (plan/05 §3.2): bake + grade the finalized program
+ // exactly as the final artifact will be graded (auto consolidation). If it
+ // still lands below B for a consolidation-fixable reason and the budget
+ // allows, feed ONE bounded feedback turn back; keep the refined program
+ // only if its grade actually improves.
+ const captured = readSinkCode();
+ if (captured && code === captured) {
+ const assess = await assessProgramGrade(captured);
+ const trigger = {
+ mode: 'auto' as const,
+ report: assess.report,
+ steps: metrics.readMetrics().steps,
+ maxSteps,
+ };
+ if (assess.ok && assess.report && shouldGradeRefine(trigger)) {
+ const report = assess.report;
+ if (opts.onEvent) {
+ try {
+ opts.onEvent({
+ type: 'grade_refine',
+ step: trigger.steps,
+ grade: report.grade,
+ materials: report.metrics.uniqueMaterials,
+ });
+ } catch {
+ // progress sinks are best-effort
+ }
+ }
+ const feedback = buildGradeRefineMessage({
+ report,
+ ...(assess.materialLabels ? { materialLabels: assess.materialLabels } : {}),
+ finalizeVerb: surface === 'unified' ? 'kiln_finalize' : 'kiln_submit',
+ editHint:
+ surface === 'unified'
+ ? 'kiln_edit for targeted swaps (or kiln_draft to rewrite)'
+ : editMode
+ ? 'kiln_edit for targeted swaps'
+ : 'rewrite the program with the consolidated materials',
+ });
+ try {
+ const refineResult = await agent.invoke(feedback);
+ metrics.recordResultUsage(refineResult.metrics?.latestAgentInvocation?.usage);
+ lastText = lastMessageText(refineResult.lastMessage) ?? lastText;
+ const refined = readSinkCode();
+ if (refined && refined !== captured) {
+ const reassess = await assessProgramGrade(refined);
+ if (
+ reassess.ok &&
+ reassess.report &&
+ gradeRank(reassess.report.grade) < gradeRank(report.grade)
+ ) {
+ code = refined;
+ }
+ }
+ } catch {
+ // the refine turn is best-effort — the original finalized program stands
+ }
+ }
+ }
}
const collected = metrics.readMetrics();
@@ -329,6 +435,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
...(lastText ? { lastText } : {}),
...(emitEdits ? { edits: editsTrace } : {}),
...(diff ? { diff } : {}),
+ ...(capped ? { capped: true } : {}),
};
} catch (err) {
const collected = metrics.readMetrics();