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(kiln-studio): model-comparison hardening — drop DeepSeek, bump GLM/Kimi tokens, agent step cap
Matt Kissinger968f15dcc835
diff --git a/agent/hooks.test.ts b/agent/hooks.test.tsnew file mode 100644index 00000000..cce757e4--- /dev/null+++ b/agent/hooks.test.ts@@ -0,0 +1,87 @@+/**+ * MetricsCollector — step counting, tool-call capture, and the hard step-cap+ * runaway backstop. The collector only reads `event.cancel` / `event.toolUse.name`+ * off the hook events, so a tiny fake Agent (addHook registry + a dispatch helper)+ * exercises the loop without a live model.+ */+import { describe, expect, test } from 'bun:test';+import { BeforeToolCallEvent, BeforeModelCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';+import { MetricsCollector } from './hooks';++type Cb = (event: unknown) => void;++/** Minimal Agent stand-in: registers hooks by event class, dispatches on demand. */+function fakeAgent() {+ const hooks = new Map<unknown, Cb[]>();+ const agent = {+ 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 dispatch = (EventClass: unknown, event: unknown) => {+ for (const cb of hooks.get(EventClass) ?? []) cb(event);+ };+ /** Simulate one model call: Before (cancellable) then, if not cancelled, After. */+ const modelCall = (): { cancelled: boolean; cancelText?: string } => {+ const before: { cancel?: string | boolean } = {};+ dispatch(BeforeModelCallEvent, before);+ if (before.cancel) return { cancelled: true, cancelText: String(before.cancel) };+ dispatch(AfterModelCallEvent, {});+ return { cancelled: false };+ };+ const toolCall = (name: string) => dispatch(BeforeToolCallEvent, { toolUse: { name } });+ return { agent, modelCall, toolCall };+}++describe('MetricsCollector', () => {+ test('counts steps and tool calls', () => {+ const m = new MetricsCollector();+ const { agent, modelCall, toolCall } = fakeAgent();+ m.attach(agent as never);+ modelCall();+ toolCall('kiln_draft');+ modelCall();+ toolCall('kiln_render');+ const out = m.readMetrics();+ expect(out.steps).toBe(2);+ expect(out.toolCalls).toEqual(['kiln_draft', 'kiln_render']);+ expect(m.wasCapped()).toBe(false);+ });++ test('no cap when maxSteps is 0/undefined — loop runs freely', () => {+ const m = new MetricsCollector(undefined, 0);+ const { agent, modelCall } = fakeAgent();+ m.attach(agent as never);+ for (let i = 0; i < 50; i++) expect(modelCall().cancelled).toBe(false);+ expect(m.readMetrics().steps).toBe(50);+ expect(m.wasCapped()).toBe(false);+ });++ test('cancels the (cap+1)-th model call and flags capped', () => {+ const m = new MetricsCollector(undefined, 3);+ const { agent, modelCall } = fakeAgent();+ m.attach(agent as never);+ // First 3 calls proceed (steps 1..3); the 4th is cancelled before running.+ expect(modelCall().cancelled).toBe(false);+ expect(modelCall().cancelled).toBe(false);+ expect(modelCall().cancelled).toBe(false);+ const fourth = modelCall();+ expect(fourth.cancelled).toBe(true);+ expect(fourth.cancelText).toContain('step cap');+ expect(m.wasCapped()).toBe(true);+ // steps stays at 3 — the cancelled call never fired AfterModelCallEvent.+ expect(m.readMetrics().steps).toBe(3);+ });++ test('records token usage from the agent result', () => {+ const m = new MetricsCollector();+ m.recordResultUsage({ inputTokens: 1200, outputTokens: 340 });+ expect(m.readMetrics().usage).toEqual({ inputTokens: 1200, outputTokens: 340 });+ });+});diff --git a/agent/hooks.ts b/agent/hooks.tsindex d2986d2a..c9a0951e 100644--- a/agent/hooks.ts+++ b/agent/hooks.ts@@ -11,7 +11,7 @@* `recordResultUsage(result.metrics?.latestAgentInvocation?.usage)`, read* `readMetrics()`, then `detach()`.*/-import { type Agent, BeforeToolCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';+import { type Agent, BeforeToolCallEvent, BeforeModelCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';/** Token-usage subset we surface. */export interface AgentUsage {@@ -35,14 +35,23 @@ export class MetricsCollector {private readonly toolCalls: string[] = [];private steps = 0;private usage: AgentUsage | undefined;+ private capped = false;private cleanups: Array<() => void> = [];/*** @param onEvent - Optional live sink, fired as the loop runs (tool calls,* model calls). Errors thrown by the sink are swallowed — a broken progress* listener must never fail a generation.+ * @param maxSteps - Optional hard cap on model calls (agent-loop iterations).+ * When the loop reaches this many calls, the NEXT model call is cancelled+ * (SDK `BeforeModelCallEvent.cancel`), ending the loop with a clean stop+ * instead of an unbounded tool/edit/render loop. A pure cost backstop — set+ * well above normal runs (~10 calls); only catches runaways. 0/undefined = off.*/- constructor(private readonly onEvent?: (event: KilnAgentEvent) => void) {}+ constructor(+ private readonly onEvent?: (event: KilnAgentEvent) => void,+ private readonly maxSteps?: number,+ ) {}private emit(event: KilnAgentEvent): void {if (!this.onEvent) return;@@ -63,10 +72,27 @@ export class MetricsCollector {this.steps += 1;this.emit({ type: 'model_call', step: this.steps });});+ // Hard step cap: before a model call that would exceed maxSteps, cancel it.+ // The SDK ends the loop with stopReason 'endTurn' (no exception) — `capped`+ // lets the caller turn that bounded stop into a clear failed generation.+ const offCap = this.maxSteps && this.maxSteps > 0+ ? agent.addHook(BeforeModelCallEvent, (event) => {+ if (this.steps >= this.maxSteps!) {+ this.capped = true;+ event.cancel = `kiln: agent step cap reached (${this.maxSteps} model calls) — aborted to bound cost`;+ }+ })+ : undefined;this.cleanups.push(offTool, offModel);+ if (offCap) this.cleanups.push(offCap);return () => this.detach();}+ /** True if the loop was halted by the model-call cap (vs the model stopping). */+ wasCapped(): boolean {+ return this.capped;+ }+/** Remove all attached hooks. Idempotent. */detach(): void {for (const off of this.cleanups) {diff --git a/agent/run.ts b/agent/run.tsindex 99454bd8..5673a1dc 100644--- a/agent/run.ts+++ b/agent/run.ts@@ -160,7 +160,14 @@ function lastMessageText(message: Message | undefined): string | undefined {* on `result.error` with whatever metrics were collected beforehand.*/export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgentResult> {- const metrics = new MetricsCollector(opts.onEvent);+ // Hard agent-loop cap (runaway backstop, NOT a throttle): a stuck model could+ // otherwise loop draft/edit/render forever, re-feeding a growing transcript+ // (input tokens scale ~linearly with step count). Default 40 — ~4x the normal+ // run (~10 model calls) and clear of the slowest legit runs observed (~23); only+ // catches genuine infinite loops. Env-overridable (set 0 to disable, raise for+ // an unusually deep build).+ const maxSteps = Number(process.env['KILN_AGENT_MAX_STEPS'] ?? 40) || 0;+ const metrics = new MetricsCollector(opts.onEvent, maxSteps);const surface = resolveToolSurface(opts.toolSurface);// Edit mode is a `current`-surface concept (the unified surface always uses the// buffer factory, regardless of refineMode). Engages only when refining.@@ -280,6 +287,19 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst 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).+ 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`,+ };+ }+const collected = metrics.readMetrics();// Buffer-backed surfaces (unified or edit-mode refine) carry a surgical-edit// trace; when refining (existingCode set) also attach a unified diff from the