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(core/kiln): surgical edit-tool refine (kiln_edit buffer + unified diff)
Matt Kissinger0753be2e5de1
diff --git a/__tests__/prompt.test.ts b/__tests__/prompt.test.tsindex 07f8dd06..ed15c9ee 100644--- a/__tests__/prompt.test.ts+++ b/__tests__/prompt.test.ts@@ -16,6 +16,7 @@ import {KILN_SYSTEM_PROMPT,KILN_TSL_SYSTEM_PROMPT,KILN_BOTH_SYSTEM_PROMPT,+ KILN_REFINE_DIRECTIVE,} from '../prompt';describe('getSystemPrompt', () => {@@ -96,6 +97,66 @@ describe('buildUserPrompt', () => {expect(prompt).toContain('Create a prop: red barrel');});+ test('prepends an Original Request section (intent -> code -> edit order) when refining', () => {+ const prompt = buildUserPrompt({+ prompt: 'make the barrel taller',+ mode: 'glb',+ category: 'prop',+ existingCode: 'const meta = {};',+ originalPrompt: 'a wooden barrel',+ });+ // All three refine sections are present...+ expect(prompt).toContain('## Original Request');+ expect(prompt).toContain('## Current Code');+ expect(prompt).toContain('## Edit Request');+ // ...the original intent and the edit instruction are both carried...+ expect(prompt).toContain('a wooden barrel');+ expect(prompt).toContain('make the barrel taller');+ // ...and they appear in intent -> code -> edit order, with no fresh-gen framing.+ expect(prompt.indexOf('## Original Request')).toBeLessThan(prompt.indexOf('## Current Code'));+ expect(prompt.indexOf('## Current Code')).toBeLessThan(prompt.indexOf('## Edit Request'));+ expect(prompt).not.toContain('## Task');+ });++ test('omits the Original Request section when refining without originalPrompt', () => {+ const prompt = buildUserPrompt({+ prompt: 'add a hat',+ mode: 'glb',+ category: 'character',+ existingCode: 'const meta = {};',+ });+ expect(prompt).not.toContain('## Original Request');+ expect(prompt).toContain('## Current Code');+ expect(prompt).toContain('## Edit Request');+ });++ test('ignores originalPrompt entirely for fresh generation (no existingCode)', () => {+ const prompt = buildUserPrompt({+ prompt: 'red barrel',+ mode: 'glb',+ category: 'prop',+ originalPrompt: 'should be ignored',+ });+ expect(prompt).not.toContain('## Original Request');+ expect(prompt).not.toContain('should be ignored');+ expect(prompt).toContain('## Task');+ expect(prompt).toContain('Create a prop: red barrel');+ });++ test('omits both animation blocks when refining so the edit request governs', () => {+ // includeAnimation defaults to "on", but a refine must not force an animate()+ // function onto an asset the edit did not ask to animate (and vice versa).+ const prompt = buildUserPrompt({+ prompt: 'make the lid open',+ mode: 'glb',+ category: 'prop',+ existingCode: 'function build() { return createRoot("x"); }',+ originalPrompt: 'a treasure chest',+ });+ expect(prompt).not.toContain('## Animation Requirements');+ expect(prompt).not.toContain('## No Animation');+ });+test('emits the No Animation block when includeAnimation=false', () => {const prompt = buildUserPrompt({prompt: 'static prop',@@ -116,3 +177,12 @@ describe('buildUserPrompt', () => {expect(prompt).toContain('## Animation Requirements');});});++describe('KILN_REFINE_DIRECTIVE', () => {+ test('is a non-empty editor-framing directive that points at the refine sections', () => {+ expect(KILN_REFINE_DIRECTIVE.length).toBeGreaterThan(40);+ expect(KILN_REFINE_DIRECTIVE).toContain('MODIFYING');+ expect(KILN_REFINE_DIRECTIVE).toContain('Edit Request');+ expect(KILN_REFINE_DIRECTIVE).toContain('kiln_submit');+ });+});diff --git a/agent/diff.test.ts b/agent/diff.test.tsnew file mode 100644index 00000000..4a95b966--- /dev/null+++ b/agent/diff.test.ts@@ -0,0 +1,64 @@+/**+ * Unit tests for the dependency-free unified diff (the refine patch artifact).+ *+ * Asserts the standard `@@ -a,b +c,d @@` hunk format, the equal-input fast path,+ * pure insertions / deletions, multi-hunk grouping, and that `$`-bearing content+ * round-trips literally (no regex interpretation anywhere in the pipeline).+ */+import { test, expect } from 'bun:test';+import { unifiedDiff } from './diff';++test('returns empty string for identical input', () => {+ expect(unifiedDiff('a\nb\nc', 'a\nb\nc')).toBe('');+ expect(unifiedDiff('', '')).toBe('');+});++test('a single line change produces one hunk with context', () => {+ const before = 'l1\nl2\nl3\nl4\nl5';+ const after = 'l1\nl2\nCHANGED\nl4\nl5';+ const d = unifiedDiff(before, after);+ expect(d).toContain('@@ -1,5 +1,5 @@');+ expect(d).toContain('-l3');+ expect(d).toContain('+CHANGED');+ expect(d).toContain(' l2');+ expect(d).toContain(' l4');+});++test('emits ---/+++ headers when labels are given', () => {+ const d = unifiedDiff('x', 'y', { fromLabel: 'parent', toLabel: 'refined' });+ expect(d.startsWith('--- parent\n+++ refined\n')).toBe(true);+});++test('pure insertion: a-length is zero on the inserted hunk side', () => {+ const before = 'a\nb';+ const after = 'a\nNEW\nb';+ const d = unifiedDiff(before, after, { context: 1 });+ expect(d).toContain('+NEW');+ // before still has 2 lines of context, after has 3.+ expect(d).toMatch(/@@ -1,2 \+1,3 @@/);+});++test('pure deletion shows removed lines', () => {+ const before = 'a\nGONE\nb';+ const after = 'a\nb';+ const d = unifiedDiff(before, after, { context: 1 });+ expect(d).toContain('-GONE');+ expect(d).toMatch(/@@ -1,3 \+1,2 @@/);+});++test('two far-apart changes produce two separate hunks', () => {+ const lines = Array.from({ length: 20 }, (_, i) => `line${i}`);+ const before = lines.join('\n');+ const after = lines.map((l, i) => (i === 1 ? 'TOP' : i === 18 ? 'BOTTOM' : l)).join('\n');+ const d = unifiedDiff(before, after, { context: 2 });+ const hunks = d.split('\n').filter((l) => l.startsWith('@@'));+ expect(hunks).toHaveLength(2);+ expect(d).toContain('+TOP');+ expect(d).toContain('+BOTTOM');+});++test('content with $ tokens diffs literally', () => {+ const d = unifiedDiff('price = X', 'price = $& $1 $X');+ expect(d).toContain('-price = X');+ expect(d).toContain('+price = $& $1 $X');+});diff --git a/agent/diff.ts b/agent/diff.tsnew file mode 100644index 00000000..bed9a00b--- /dev/null+++ b/agent/diff.ts@@ -0,0 +1,140 @@+/**+ * Minimal, dependency-free unified diff for small text buffers.+ *+ * Kiln programs are a few KB, so a line-based LCS is plenty: we compute the+ * longest common subsequence of lines, backtrack into a `' '`/`'-'`/`'+'` op+ * stream, then group the ops into standard `@@ -a,b +c,d @@` hunks with a few+ * lines of surrounding context. The result records *what a surgical refine+ * changed* (parent -> final buffer) as a first-class provenance artifact, with+ * no new runtime dependency.+ */++export interface UnifiedDiffOptions {+ /** Label for the "before" file (the `---` header). Default: omit the header. */+ fromLabel?: string;+ /** Label for the "after" file (the `+++` header). Default: omit the header. */+ toLabel?: string;+ /** Lines of unchanged context to keep around each change. Default 3. */+ context?: number;+}++type Tag = ' ' | '-' | '+';+interface LocatedOp {+ tag: Tag;+ line: string;+ /** 0-based line index in the "before" file at this op. */+ a: number;+ /** 0-based line index in the "after" file at this op. */+ b: number;+}++/** LCS-backed line diff -> a flat op stream (equal / delete / insert). */+function diffLines(a: string[], b: string[]): Array<{ tag: Tag; line: string }> {+ const n = a.length;+ const m = b.length;++ // lcs[i][j] = length of the LCS of a[i..] and b[j..].+ const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));+ for (let i = n - 1; i >= 0; i--) {+ for (let j = m - 1; j >= 0; j--) {+ lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);+ }+ }++ const ops: Array<{ tag: Tag; line: string }> = [];+ let i = 0;+ let j = 0;+ while (i < n && j < m) {+ if (a[i] === b[j]) {+ ops.push({ tag: ' ', line: a[i]! });+ i++;+ j++;+ } else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) {+ ops.push({ tag: '-', line: a[i]! });+ i++;+ } else {+ ops.push({ tag: '+', line: b[j]! });+ j++;+ }+ }+ while (i < n) ops.push({ tag: '-', line: a[i++]! });+ while (j < m) ops.push({ tag: '+', line: b[j++]! });+ return ops;+}++/**+ * Compute a unified diff between two strings. Returns `''` when they are equal.+ * Output is a standard unified diff (optionally with `---`/`+++` headers).+ */+export function unifiedDiff(before: string, after: string, opts: UnifiedDiffOptions = {}): string {+ if (before === after) return '';+ const context = Math.max(0, opts.context ?? 3);+ const a = before.split('\n');+ const b = after.split('\n');++ // Annotate each op with its source line numbers as we walk the stream.+ let ai = 0;+ let bi = 0;+ const located: LocatedOp[] = diffLines(a, b).map((op) => {+ const rec: LocatedOp = { tag: op.tag, line: op.line, a: ai, b: bi };+ if (op.tag === ' ') {+ ai++;+ bi++;+ } else if (op.tag === '-') {+ ai++;+ } else {+ bi++;+ }+ return rec;+ });++ const changeIdx = located.map((o, k) => (o.tag === ' ' ? -1 : k)).filter((k) => k >= 0);+ if (changeIdx.length === 0) return '';++ // Group changes whose context windows touch into single hunks.+ const groups: Array<[number, number]> = [];+ let gStart = Math.max(0, changeIdx[0]! - context);+ let gEnd = Math.min(located.length - 1, changeIdx[0]! + context);+ for (let k = 1; k < changeIdx.length; k++) {+ const ci = changeIdx[k]!;+ if (ci - context <= gEnd + 1) {+ gEnd = Math.min(located.length - 1, ci + context);+ } else {+ groups.push([gStart, gEnd]);+ gStart = Math.max(0, ci - context);+ gEnd = Math.min(located.length - 1, ci + context);+ }+ }+ groups.push([gStart, gEnd]);++ const out: string[] = [];+ if (opts.fromLabel || opts.toLabel) {+ out.push(`--- ${opts.fromLabel ?? 'a'}`);+ out.push(`+++ ${opts.toLabel ?? 'b'}`);+ }++ for (const [s, e] of groups) {+ const slice = located.slice(s, e + 1);+ const first = slice[0]!;+ let aLen = 0;+ let bLen = 0;+ for (const o of slice) {+ if (o.tag === ' ') {+ aLen++;+ bLen++;+ } else if (o.tag === '-') {+ aLen++;+ } else {+ bLen++;+ }+ }+ // 1-based start lines; when a side contributes no lines, git uses the+ // 0-based position of the insertion point.+ const aStart = aLen > 0 ? first.a + 1 : first.a;+ const bStart = bLen > 0 ? first.b + 1 : first.b;+ out.push(`@@ -${aStart},${aLen} +${bStart},${bLen} @@`);+ for (const o of slice) out.push(`${o.tag}${o.line}`);+ }++ return out.join('\n');+}diff --git a/agent/index.ts b/agent/index.tsindex 0e9c4e36..c789bfa8 100644--- a/agent/index.ts+++ b/agent/index.ts@@ -9,15 +9,20 @@** - {@link runKilnAgent} — drive any Strands Model through the kiln tool loop* - {@link makeKilnTools} — in-process tool skin over the shared registry+ * - {@link makeKilnEditTools} — surgical edit-tool skin for refining an existing asset+ * - {@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* - {@link MetricsCollector} — per-loop tool/step/usage metrics via hooks*/export { runKilnAgent } from './run';-export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow } from './run';+export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow, RefineMode } from './run';-export { makeKilnTools, KILN_SUBMIT_TOOL_NAME } from './tools';-export type { SubmitSink } from './tools';+export { makeKilnTools, makeKilnEditTools, KilnEditBuffer, KILN_SUBMIT_TOOL_NAME } from './tools';+export type { SubmitSink, EditSink, EditRecord, EditResult } from './tools';++export { unifiedDiff } from './diff';+export type { UnifiedDiffOptions } from './diff';export { ensureStreamStart } from './stream-start';diff --git a/agent/run.ts b/agent/run.tsindex 6c91da6a..f284e106 100644--- a/agent/run.ts+++ b/agent/run.ts@@ -19,14 +19,18 @@import { Agent, type Plugin, type Tool, type Message } from '@strands-agents/sdk';import { AgentSkills } from '@strands-agents/sdk/vended-plugins/skills';-import { getSystemPrompt, buildUserPrompt } from '../prompt';+import { getSystemPrompt, buildUserPrompt, KILN_REFINE_DIRECTIVE, KILN_EDIT_DIRECTIVE } from '../prompt';import type { AssetCategory } from '../prompt';-import { makeKilnTools, type SubmitSink } from './tools';+import { makeKilnTools, makeKilnEditTools, type SubmitSink, type EditSink, type EditRecord } from './tools';+import { unifiedDiff } from './diff';import { MetricsCollector, type AgentUsage } from './hooks';/** How the agent learns Kiln conventions. */export type KilnKnowhow = 'inline' | 'skill';+/** How a refine applies its change: whole-program re-emission, or surgical edits. */+export type RefineMode = 'rewrite' | 'edit';+export interface RunKilnAgentOptions {/** A constructed Strands `Model` instance (provider-agnostic). */model: unknown;@@ -42,6 +46,18 @@ export interface RunKilnAgentOptions {extraTools?: unknown[];/** Ask the model for an animate() function too. Default false (static). */includeAnimation?: boolean;+ /** Existing Kiln program to refine. When set, the run is framed as an edit:+ * `prompt` becomes the Edit Request and `KILN_REFINE_DIRECTIVE` is prepended to+ * the system prompt, so the model edits this code rather than starting over. */+ existingCode?: string;+ /** The asset's original generation prompt, surfaced as "## Original Request" when+ * refining (existingCode set) so the model sees the asset's intent, not just code. */+ originalPrompt?: string;+ /** How a refine applies its change. 'rewrite' (default) re-emits the whole program via+ * kiln_submit; 'edit' seeds a working buffer with `existingCode` and exposes surgical+ * kiln_edit/kiln_view tools so the model patches it in place. Only takes effect when+ * `existingCode` is set (a fresh generation always rewrites). */+ refineMode?: RefineMode;/** Agent name (for tracing). Default 'kiln-agent'. */agentName?: string;}@@ -57,6 +73,10 @@ export interface RunKilnAgentResult {usage?: AgentUsage;/** The last assistant text (fallback / diagnostics). */lastText?: string;+ /** In edit mode, the applied surgical edits in order (the patch the model produced). */+ edits?: EditRecord[];+ /** In edit mode, a unified diff from the parent code to the final buffer. */+ diff?: string;/** Error message if the run threw. */error?: string;}@@ -80,9 +100,14 @@ function lastMessageText(message: Message | undefined): string | undefined {*/export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgentResult> {const metrics = new MetricsCollector();+ // Edit mode only engages when refining (existingCode set) AND explicitly chosen.+ const editMode = Boolean(opts.existingCode) && opts.refineMode === 'edit';const sink: SubmitSink = {};+ const editSink: EditSink = { edits: [] };try {- const tools: Tool[] = makeKilnTools(sink);+ const tools: Tool[] = editMode+ ? makeKilnEditTools({ seedCode: opts.existingCode!, sink: editSink })+ : makeKilnTools(sink);const allTools: unknown[] = opts.extraTools ? [...tools, ...opts.extraTools] : tools;const plugins: Plugin[] = [];@@ -99,6 +124,13 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgsystemPrompt = getSystemPrompt('glb');}+ // Refine framing: edit an existing asset on top of the unchanged conventions.+ // Edit mode swaps in the surgical-edit directive (it supersedes the refine one).+ if (opts.existingCode) {+ const directive = editMode ? KILN_EDIT_DIRECTIVE : KILN_REFINE_DIRECTIVE;+ systemPrompt = `${directive}\n\n${systemPrompt}`;+ }+const agent = new Agent({model: opts.model as never,systemPrompt,@@ -114,6 +146,8 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgmode: 'glb',category: opts.category ?? 'prop',includeAnimation: opts.includeAnimation ?? false,+ ...(opts.existingCode ? { existingCode: opts.existingCode } : {}),+ ...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),}) +'\n\nWhen finished, call the kiln_submit tool exactly once with your final, ' +'complete Kiln program.';@@ -121,7 +155,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst result = await agent.invoke(userPrompt);metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);- let code = sink.code;+ let code = editMode ? editSink.code : sink.code;if (!code && result.structuredOutput) {const so = result.structuredOutput as { code?: unknown };if (typeof so.code === 'string') code = so.code;@@ -130,12 +164,21 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgif (!code) code = lastText;const collected = metrics.readMetrics();+ // In edit mode, attach the patch the model produced: the applied edits + a+ // unified diff from the parent code to the final buffer (robust to a rewrite+ // fallback, since it diffs the actual submitted code).+ const diff =+ editMode && code && opts.existingCode+ ? unifiedDiff(opts.existingCode, code, { fromLabel: 'parent', toLabel: 'refined' })+ : undefined;return {...(code ? { code } : {}),toolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),...(lastText ? { lastText } : {}),+ ...(editMode ? { edits: editSink.edits } : {}),+ ...(diff ? { diff } : {}),};} catch (err) {const collected = metrics.readMetrics();diff --git a/agent/tools-edit.test.ts b/agent/tools-edit.test.tsnew file mode 100644index 00000000..1a5c618f--- /dev/null+++ b/agent/tools-edit.test.ts@@ -0,0 +1,106 @@+/**+ * Unit tests for the surgical edit-tool skin (KilnEditBuffer + makeKilnEditTools).+ *+ * The buffer is the whole edit contract - pure string ops, no Strands / THREE -+ * so it is tested directly. The tool factory is checked for its wiring (the six+ * tools and their names, plus the shared edit trace). The run-level gating (edit+ * mode only when refining) is exercised by the studio mock-adapter tests.+ */+import { test, expect } from 'bun:test';+import { KilnEditBuffer, makeKilnEditTools, type EditSink } from './tools';++const SEED = `const meta = { name: 'crate' };+function build() {+ const root = createRoot();+ const body = createPart('Body', boxGeo(1, 1, 1), gameMaterial('#8a5a2b'));+ root.add(body);+ return root;+}`;++test('apply replaces a unique span and records the edit', () => {+ const buf = new KilnEditBuffer(SEED);+ const r = buf.apply({ oldString: 'boxGeo(1, 1, 1)', newString: 'boxGeo(2, 1, 1)' });+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.occurrences).toBe(1);+ expect(r.newBytes).toBe(buf.code.length);+ }+ expect(buf.code).toContain('boxGeo(2, 1, 1)');+ expect(buf.code).not.toContain('boxGeo(1, 1, 1)');+ expect(buf.edits).toHaveLength(1);+ expect(buf.edits[0]).toEqual({+ oldString: 'boxGeo(1, 1, 1)',+ newString: 'boxGeo(2, 1, 1)',+ replaceAll: false,+ occurrences: 1,+ });+});++test('apply errors (no mutation) when oldString is not found', () => {+ const buf = new KilnEditBuffer(SEED);+ const r = buf.apply({ oldString: 'sphereGeo(3)', newString: 'boxGeo(3,3,3)' });+ expect(r.ok).toBe(false);+ if (!r.ok) {+ expect(r.error).toContain('not found');+ expect(r.hint).toBeDefined();+ }+ expect(buf.code).toBe(SEED);+ expect(buf.edits).toHaveLength(0);+});++test('apply errors on an ambiguous (multi-match) oldString unless replaceAll', () => {+ const src = 'a = 1;\nb = 1;\nc = 1;';+ const buf = new KilnEditBuffer(src);+ const r = buf.apply({ oldString: '1', newString: '2' });+ expect(r.ok).toBe(false);+ if (!r.ok) {+ expect(r.occurrences).toBe(3);+ expect(r.error).toContain('3 times');+ }+ expect(buf.code).toBe(src); // unchanged++ const r2 = buf.apply({ oldString: '1', newString: '2', replaceAll: true });+ expect(r2.ok).toBe(true);+ if (r2.ok) expect(r2.occurrences).toBe(3);+ expect(buf.code).toBe('a = 2;\nb = 2;\nc = 2;');+ expect(buf.edits[0]?.replaceAll).toBe(true);+});++test('apply rejects an identical or empty oldString', () => {+ const buf = new KilnEditBuffer(SEED);+ expect(buf.apply({ oldString: 'createRoot()', newString: 'createRoot()' }).ok).toBe(false);+ expect(buf.apply({ oldString: '', newString: 'x' }).ok).toBe(false);+ expect(buf.code).toBe(SEED);+});++test('apply treats newString literally - no $ / $& substitution', () => {+ const buf = new KilnEditBuffer('label = PRICE;');+ const r = buf.apply({ oldString: 'PRICE', newString: '$5 for $& and $1' });+ expect(r.ok).toBe(true);+ expect(buf.code).toBe('label = $5 for $& and $1;');+});++test('view returns the raw buffer and a line count that tracks edits', () => {+ const buf = new KilnEditBuffer(SEED);+ const v = buf.view();+ expect(v.code).toBe(SEED);+ expect(v.lines).toBe(SEED.split('\n').length);+ buf.apply({ oldString: ' return root;\n', newString: ' root.add(createPart("Lid", boxGeo(1,1,1)));\n return root;\n' });+ expect(buf.view().lines).toBe(buf.code.split('\n').length);+});++test('makeKilnEditTools exposes the six edit-mode tools and wires the edit trace', () => {+ const sink: EditSink = { edits: [] };+ const tools = makeKilnEditTools({ seedCode: SEED, sink });+ expect(tools.map((t) => t.name)).toEqual([+ 'kiln_list_primitives',+ 'kiln_view',+ 'kiln_edit',+ 'kiln_validate',+ 'kiln_render',+ 'kiln_submit',+ ]);+ // The sink's edit trace is the buffer's live array (shared reference).+ expect(Array.isArray(sink.edits)).toBe(true);+ expect(sink.edits).toHaveLength(0);+});diff --git a/agent/tools.ts b/agent/tools.tsindex 0488e1b4..cc280a8d 100644--- a/agent/tools.ts+++ b/agent/tools.ts@@ -67,3 +67,224 @@ export function makeKilnTools(sink: SubmitSink): Tool[] {});return [...kilnTools, submitTool];}++// =============================================================================+// Edit-mode tool skin (surgical refine)+// =============================================================================+//+// An alternative to whole-program re-emission for REFINING an existing asset.+// Instead of re-typing the full program through `kiln_submit`, the model edits a+// working buffer seeded with the parent's code via `kiln_edit` (exact-string+// replace, like Claude Code's Edit tool). Unchanged code is guaranteed byte-for-+// byte stable, and the sequence of edits becomes a first-class diff artifact.+//+// Used only when refining in edit mode (existingCode set + refineMode='edit');+// the from-scratch generate path keeps `makeKilnTools` unchanged.++/** One applied `kiln_edit` call, recorded for provenance / the diff trace. */+export interface EditRecord {+ oldString: string;+ newString: string;+ replaceAll: boolean;+ /** How many occurrences this edit actually replaced. */+ occurrences: number;+}++/** Result of a single `kiln_edit` application (never thrown - returned to the model). */+export type EditResult =+ | { ok: true; occurrences: number; newBytes: number }+ | { ok: false; error: string; occurrences?: number; hint?: string };++/**+ * A mutable sink the edit tools write into. Create one per run with `edits: []`,+ * pass it to {@link makeKilnEditTools}, and after invoke read `.code` (the final+ * working buffer) and `.edits` (the applied edit trace).+ */+export interface EditSink {+ code?: string;+ edits: EditRecord[];+}++/**+ * The in-memory working copy of the asset being refined. Pure string ops - no+ * Strands / THREE involvement - so it is trivially unit-testable on its own.+ */+export class KilnEditBuffer {+ private buf: string;+ readonly edits: EditRecord[] = [];++ constructor(seedCode: string) {+ this.buf = seedCode;+ }++ /** The current working code. */+ get code(): string {+ return this.buf;+ }++ /** Current line count. */+ get lineCount(): number {+ return this.buf.split('\n').length;+ }++ /** Read the current buffer (raw text - exactly what `apply` matches against). */+ view(): { code: string; lines: number } {+ return { code: this.buf, lines: this.lineCount };+ }++ /** Apply one exact-string replacement. Mirrors the Edit tool's contract. */+ apply(input: { oldString: string; newString: string; replaceAll?: boolean }): EditResult {+ const { oldString, newString } = input;+ const replaceAll = input.replaceAll ?? false;++ if (oldString.length === 0) {+ return { ok: false, error: 'oldString must not be empty.' };+ }+ if (oldString === newString) {+ return { ok: false, error: 'oldString and newString are identical - there is nothing to change.' };+ }++ const occurrences = this.buf.split(oldString).length - 1;+ if (occurrences === 0) {+ return {+ ok: false,+ error: 'oldString was not found in the current code.',+ hint: 'Call kiln_view and copy an exact span (including whitespace and indentation) to edit.',+ };+ }+ if (occurrences > 1 && !replaceAll) {+ return {+ ok: false,+ occurrences,+ error: `oldString matched ${occurrences} times, so the edit is ambiguous.`,+ hint: 'Add surrounding context to make oldString unique, or set replaceAll:true to change every occurrence.',+ };+ }++ // Replace WITHOUT going through String.prototype.replace(string, string):+ // that interprets `$&` / `$1` etc. in newString. Index/splice and split/join+ // are literal.+ if (replaceAll) {+ this.buf = this.buf.split(oldString).join(newString);+ } else {+ const at = this.buf.indexOf(oldString);+ this.buf = this.buf.slice(0, at) + newString + this.buf.slice(at + oldString.length);+ }++ const applied = replaceAll ? occurrences : 1;+ this.edits.push({ oldString, newString, replaceAll, occurrences: applied });+ return { ok: true, occurrences: applied, newBytes: this.buf.length };+ }+}++const viewInput = z.object({});++const editInput = z.object({+ oldString: z+ .string()+ .describe(+ 'The exact text to replace, copied verbatim from the current code (no line-number prefixes). ' ++ 'Must be unique in the buffer unless replaceAll is true.',+ ),+ newString: z.string().describe('The replacement text. Must differ from oldString.'),+ replaceAll: z+ .boolean()+ .optional()+ .describe('Replace every occurrence instead of requiring a unique match. Default false.'),+});++const bufferCodeInput = z.object({+ code: z+ .string()+ .optional()+ .describe('Kiln source to check. Omit to use the current working buffer (your edited code).'),+});++const submitEditInput = z.object({+ code: z+ .string()+ .optional()+ .describe(+ 'The complete final program. Omit to submit the current working buffer (your applied edits) - ' ++ 'recommended. Pass a full program only to replace the buffer wholesale.',+ ),+});++/**+ * Build the edit-mode tool list for a refine run: list_primitives (as-is),+ * `kiln_view` + `kiln_edit` over a working buffer seeded with `seedCode`, plus+ * `kiln_validate` / `kiln_render` / `kiln_submit` that default to the buffer+ * when their `code` arg is omitted. The buffer's live edit trace is shared into+ * `sink.edits`; `sink.code` tracks the latest buffer (so an un-submitted run+ * still captures the edits).+ */+export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): Tool[] {+ const buffer = new KilnEditBuffer(opts.seedCode);+ opts.sink.edits = buffer.edits; // share the live trace++ const find = (name: string): (typeof kilnToolRegistry)[number] => {+ const def = kilnToolRegistry.find((d) => d.name === name);+ if (!def) throw new Error(`makeKilnEditTools: missing registry tool ${name}`);+ return def;+ };+ const validateDef = find('kiln_validate');+ const renderDef = find('kiln_render');++ const listTool = toStrandsTool(find('kiln_list_primitives'));++ const viewTool: Tool = tool({+ name: 'kiln_view',+ description:+ 'Read the current working code (the asset you are editing). Returns the full raw source and ' ++ 'its line count. kiln_edit matches against exactly this text - copy spans from here.',+ inputSchema: viewInput,+ callback: () => buffer.view() as JSONValue,+ });++ const editTool: Tool = tool({+ name: 'kiln_edit',+ description:+ 'Make a surgical change to the working code: replace an exact span (oldString) with newString. ' ++ '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. Returns { ok, occurrences, newBytes } or { ok:false, error, hint }.',+ inputSchema: editInput,+ callback: (input) => {+ const r = buffer.apply(input);+ if (r.ok) opts.sink.code = buffer.code; // capture the live buffer even if submit is skipped+ return r as JSONValue;+ },+ });++ const validateTool: Tool = tool({+ name: 'kiln_validate',+ description: `${validateDef.description} Omit code to validate the current working buffer.`,+ inputSchema: bufferCodeInput,+ callback: async (input) =>+ (await validateDef.run({ code: (input as { code?: string }).code ?? buffer.code })) as JSONValue,+ });++ const renderTool: Tool = tool({+ name: 'kiln_render',+ description: `${renderDef.description} Omit code to render the current working buffer.`,+ inputSchema: bufferCodeInput,+ callback: async (input) =>+ (await renderDef.run({ code: (input as { code?: string }).code ?? buffer.code })) as JSONValue,+ });++ const submitTool: Tool = tool({+ name: KILN_SUBMIT_TOOL_NAME,+ description:+ 'Submit your FINAL edited Kiln program. Call this exactly once after your edits validate and ' ++ 'render. Omit code to submit the current working buffer (recommended); pass a complete program ' ++ 'only to replace the buffer wholesale (the rewrite escape hatch).',+ inputSchema: submitEditInput,+ callback: (input) => {+ const code = (input as { code?: string }).code ?? buffer.code;+ opts.sink.code = code;+ return { ok: true, recorded: true, bytes: code.length, edits: buffer.edits.length } as JSONValue;+ },+ });++ return [listTool, viewTool, editTool, validateTool, renderTool, submitTool];+}diff --git a/prompt.ts b/prompt.tsindex 1e866293..ff7e8760 100644--- a/prompt.ts+++ b/prompt.ts@@ -589,6 +589,25 @@ export function getSystemPrompt(mode: RenderMode): string {return KILN_SYSTEM_PROMPT;}+/**+ * Prepended to the system prompt when refining an existing asset (existingCode set).+ * Frames the model as an editor working on top of the unchanged Kiln conventions, so+ * it preserves the asset's character and changes only what the Edit Request asks. The+ * task-level know-how (primitives, orientation, attachment) still comes from+ * `getSystemPrompt`; this is an additive directive, not a replacement.+ */+export const KILN_REFINE_DIRECTIVE = `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. Keep the asset's established character, proportions, and structure; change ONLY what the Edit Request asks for. Re-validate and re-render the edited program with the kiln tools, then submit it with kiln_submit.`;++/**+ * Prepended to the system prompt when refining in EDIT mode (existingCode set and the+ * caller chose surgical edits). Supersedes {@link KILN_REFINE_DIRECTIVE}: it carries the+ * same modify-not-rebuild framing plus the edit-tool mechanics. The model works on a live+ * working buffer seeded with the Current Code and changes it in place with `kiln_edit`,+ * rather than re-emitting the whole program. The full-rewrite path stays available as an+ * escape hatch (submit a complete program) so edit mode is never strictly worse.+ */+export const KILN_EDIT_DIRECTIVE = `You are EDITING an existing Kiln asset in place, not rebuilding it. A working buffer holds 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_submit (omit its code argument to submit the working buffer). If an edit cannot be anchored after a couple of tries, you may submit a complete corrected program instead.`;+export interface AssetBudget {maxTriangles?: number;maxMaterials?: number;@@ -602,6 +621,10 @@ export interface KilnGenerateRequest {budget?: AssetBudget;includeAnimation?: boolean;existingCode?: string;+ /** The asset's original generation prompt. When refining (existingCode set) it+ * is rendered as a "## Original Request" section ahead of the code so the model+ * knows the asset's intent, not just its source. Ignored for fresh generation. */+ originalPrompt?: string;referenceImageUrl?: string;}@@ -628,23 +651,34 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {// Main requestif (request.existingCode) {- parts.push(`## Current Code\n\n\`\`\`typescript\n${request.existingCode}\n\`\`\`\n\n## Edit Request\n\n${request.prompt}`);+ // Refine framing: Original Request (intent) -> Current Code (source) -> Edit Request.+ const editSections: string[] = [];+ if (request.originalPrompt) {+ editSections.push(`## Original Request\n\n${request.originalPrompt}`);+ }+ editSections.push(`## Current Code\n\n\`\`\`typescript\n${request.existingCode}\n\`\`\``);+ editSections.push(`## Edit Request\n\n${request.prompt}`);+ parts.push(editSections.join('\n\n'));} else {parts.push(`## Task\n\nCreate a ${request.category}: ${request.prompt}`);}- // Animation instructions- if (request.includeAnimation !== false) {- parts.push(`+ // Animation instructions — only for fresh generation. When editing existing code+ // the Edit Request governs whether animation changes, so forcing either block+ // would fight the instruction (e.g. "add a spin" vs a "## No Animation" directive).+ if (!request.existingCode) {+ if (request.includeAnimation !== false) {+ parts.push(`## Animation RequirementsInclude an animate() function that returns an array of AnimationClips.Use createPivot() for parts that need animation, then animate them with rotationTrack/positionTrack.Track names MUST match pivot names exactly (e.g., createPivot("Lid",...) -> rotationTrack("Joint_Lid",...)).Make animations loop seamlessly (end keyframe = start keyframe values).`);- } else {- parts.push(`+ } else {+ parts.push(`## No AnimationDo NOT include an animate() function. Only create the static geometry in build().`);+ }}parts.push('\n\nGenerate the complete code.');