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.

Render service reports who it is; kiln_screenshot shares the unified view path (#121)

Matthew Kissingercddb96b5d68f
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.md
index 33d739d7..1295dee9 100644
--- a/.agents/skills/kiln-setup-workspace/SKILL.md
+++ b/.agents/skills/kiln-setup-workspace/SKILL.md
@@ -46,7 +46,7 @@ Offer to run its install. It lives in the engine installation rather than the wo
cd render-service && npm install
```
-That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.
+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure. `bun run kiln service status` in the engine checkout shows who is listening on the shared port and whether it runs current source; a renderer left over from before a pull is replaced automatically when nobody owns it, and `kiln service stop` clears one that is.
## Verify the loadout before authoring
diff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.md
index 33d739d7..1295dee9 100644
--- a/.claude/skills/kiln-setup-workspace/SKILL.md
+++ b/.claude/skills/kiln-setup-workspace/SKILL.md
@@ -46,7 +46,7 @@ Offer to run its install. It lives in the engine installation rather than the wo
cd render-service && npm install
```
-That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.
+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure. `bun run kiln service status` in the engine checkout shows who is listening on the shared port and whether it runs current source; a renderer left over from before a pull is replaced automatically when nobody owns it, and `kiln service stop` clears one that is.
## Verify the loadout before authoring
diff --git a/AGENTS.md b/AGENTS.md
index 40ccb54d..47964b4e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -38,12 +38,16 @@ two lists match.
The one name that differs is **`kiln_screenshot`, and it is merged rather than missing.** On
the in-process surface `kiln_render` returns metrics only and `kiln_screenshot` carries the
-six-view grid -- two tools, so a cheap structural check need not pay for an image. On MCP
+image grid -- two tools, so a cheap structural check need not pay for an image. On MCP
`kiln_render` is unified: it holds `media: screenshotMedia` and returns metrics, part paths
and images together, with six views when `capture` is omitted. A separate `kiln_screenshot`
there would be a second way to ask for the same grid. `src/mcp-parity.test.ts` asserts the
MCP surface does not carry it, so the merge stays deliberate; no capability is absent from
-the MCP workflow.
+the MCP workflow. The two names share one implementation, `runRenderViews`: `kiln_screenshot`
+takes the same `capture` (grid shape, framing, backdrop), routes through the render port and
+reports `viewFidelity` exactly as `kiln_render` does. It used to be a frozen CPU-only copy
+kept as the control arm of a bench that no longer exists; do not freeze it again without a
+consumer that needs the freeze.
Prefer an explicit terminal submit tool over `structuredOutputSchema` in the in-process loop: the
latter's coexistence with a full tool set is provider-dependent, while a submit tool is unambiguous
@@ -81,6 +85,21 @@ hides the seams the model is meant to find. The chosen id is part of both captur
echoed as `capture.backdrop` in every render result. `kiln_save` paints its preview on the backdrop
it is given and the manifest records it as `preview.backdrop`; a reader never guesses it.
+**One render service per machine, and the socket is its registry.** Every session finds the
+service on one shared port (8000, or `KILN_RENDER_SERVICE_PORT`); the first to need it starts
+it and the rest join. There is no lease file: `/health` reports `instance` -- pid, the owning
+session's pid, and a fingerprint of the service source -- and `src/render-service-host.ts`
+acts on that in exactly one way per case. A current service is joined whoever started it. A
+stale service (source fingerprint differs from `render-service/src` on disk) that is orphaned
+(its owner has exited) is replaced. A stale service still owned by a running session, or
+started by hand, is left alone and named, with `kiln service stop` as the way out. Something
+that is not a render service on the port is reported, never joined. An on-demand service
+watches its owner's pid and exits when it is gone, which is what makes a hard-killed host
+safe on Windows; a hand-started service has no owner and outlives sessions. The service and
+host fingerprint the source with two mirrored walks (`render-service/src/instance.mjs`,
+`renderServiceSourceFingerprint`), and `render-service-lifecycle.test.ts` fails if they drift.
+Do not add a second discovery path or a file that can outlive the process it describes.
+
**The GPU is a view producer only, never gate evidence.** `QaContext` is deliberately image-free so a
QA rule structurally cannot read a render buffer. Do not add pixels to it.
@@ -118,7 +137,7 @@ do not lower them without an explicit measured rationale. Live model tests are o
`bun run test` is `bun test src scripts`, so it does **not** reach `render-service/`, which is a
separate npm project. `bun run test:render-service` does; it needs `npm --prefix render-service ci
---ignore-scripts` once. All 49 of those tests are pure -- framing arithmetic, PNG readback packing,
+--ignore-scripts` once. All 54 of those tests are pure -- framing arithmetic, PNG readback packing,
cache identity, contract and preset validation -- so none of them needs a GPU or the native Dawn
build, which is why `--ignore-scripts` is enough. Run it whenever you change `render-service/`; CI
requires it.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fcf02f37..d0a46195 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,38 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## Unreleased: The render service knows who it is, and `kiln_screenshot` sees what `kiln_render` sees
+
+- **The shared render-service port is no longer a guess.** `/health` now carries `instance`: the
+ service's pid, the session that started it on demand, and a fingerprint of the source it runs.
+ The host reads that before joining. A current service is joined whoever started it. A service
+ running older source than `render-service/src` -- the renderer from before a `git pull`, still
+ up -- is replaced when its owning session has exited, and left alone but named when another
+ session still owns it or it was started by hand. Before this, a stale orphan was joined by
+ every session and the engine's newer request fields came back as a 400 that the sheet reported
+ as a CPU degrade with nothing saying why.
+- **An on-demand service exits when the session that started it is gone.** The host passes
+ `RENDER_SERVICE_OWNER_PID`; the service polls it and exits on its own, so a hard-killed MCP
+ server on Windows, which never runs its exit hook, no longer leaves a GPU process on port 8000
+ for the rest of the day. A hand-started service has no owner and outlives sessions as before.
+- **A session that joined a renderer which then went away starts again on the next view** instead
+ of reporting connection refused as a degrade for the rest of its life.
+- **`kiln service status | stop | prune`.** `status` prints the facts the host acts on: the URL,
+ whether the service is installed, who is listening, its owner and whether its source is current.
+ `prune` stops a stale orphan and nothing else. `stop` stops the service whoever started it, for
+ the one case the host will not decide for you. Something that is not a render service on the
+ port is reported with the variable that moves the renderer, never joined.
+- **`kiln_screenshot` on the in-process loop is the same implementation as the unified
+ `kiln_render`.** It takes the same `capture` config (grid shape, per-part framing, backdrop),
+ routes textured and metallic scenes through the render port, and reports `viewFidelity`. It
+ had been a frozen CPU-only copy kept as the control arm of a bench that no longer exists, which
+ meant `kiln generate --render gpu` could never show its model a material-faithful view.
+- **The tier-2 dogfood receipt says whether the workspace MCP server was exercised.** `toolUsage`
+ counts every tool call in the trace and classifies the run as `exercised`, `not-exercised` or
+ `unknown`, so a run that completed through the CLI alone -- an outer agent that dispatched an
+ in-session subagent, as the blind OpenCode run did -- is visible in the receipt rather than
+ only to someone reading the trace.
+
## Unreleased: Test suite holds under a loaded runner
- The test scripts and CI set a 20 s per-test budget instead of Bun's 5 s default. Tests that take
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 9d57ba2a..44d6d374 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -27608,9 +27608,6 @@ var validateInput = z4.object({
var renderInput = z4.object({
code: z4.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
-var screenshotInput = z4.object({
- code: z4.string().describe("Kiln source code to execute and render to a six-view image grid.")
-});
var backdropInput = z4.enum(BACKDROP_IDS).optional().describe("Neutral grey unless a sheet shows merging: light if the part is darker, dark if lighter.");
var legacyCaptureInput = z4.object({
preset: z4.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("Grid shape as COLSxROWS. Default 3x2. Choose fewer views for simple shapes, up to 3x3 for more angles."),
@@ -27815,30 +27812,6 @@ async function runRender(input, context) {
};
}
}
-async function runScreenshot(input, context) {
- try {
- await Promise.resolve().then(() => init_views());
- const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
- const warnings = inspectSceneStructure(root, {
- category: trustedCategory(context)
- });
- const grid = await renderGlbViewGrid(rendered.glb);
- return {
- ok: true,
- views: grid.views,
- width: grid.width,
- height: grid.height,
- pngBase64: grid.png.toString("base64"),
- warnings
- };
- } catch (err) {
- return {
- ok: false,
- error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
- warnings: []
- };
- }
-}
function screenshotMedia(output) {
const o = output;
if (!o || typeof o.pngBase64 !== "string" || o.pngBase64.length === 0)
@@ -27846,7 +27819,7 @@ function screenshotMedia(output) {
const { pngBase64: _png, ...json } = o;
return { png: new Uint8Array(Buffer.from(o.pngBase64, "base64")), json };
}
-async function runRenderViews(input, context) {
+async function runRenderViews(input, context, toolName = "kiln_render") {
try {
await Promise.resolve().then(() => init_views());
const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);
@@ -27953,7 +27926,7 @@ async function runRenderViews(input, context) {
...drawnBy.degradedReason ? { degradeReason: drawnBy.degradedReason } : {},
reasonCodes: ["IN_LOOP_BUILD_NOT_PERSISTED"]
};
- const viewEvidence = context.viewEvidenceHistory?.record("kiln_render", viewFidelity);
+ const viewEvidence = context.viewEvidenceHistory?.record(toolName, viewFidelity);
try {
context.onViewsRendered?.(drawnBy);
} catch {}
@@ -28320,6 +28293,7 @@ function createKilnEditDef(context = {}) {
}
var kilnEditDef = createKilnEditDef();
function createKilnToolRegistry(context = {}) {
+ const viewContext = withViewEvidenceHistory(context);
return [
{
name: "kiln_list_primitives",
@@ -28342,10 +28316,11 @@ function createKilnToolRegistry(context = {}) {
},
{
name: "kiln_screenshot",
- description: "Render Kiln code to a six-view image grid so you can SEE the asset: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.",
- inputSchema: screenshotInput,
- run: async (input) => guardCaptureBudget("kiln_screenshot", input, context, () => runScreenshot(screenshotInput.parse(input), context)),
- media: screenshotMedia
+ description: "Render Kiln code to an image grid so you can SEE the asset. Omit capture for six views: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. capture selects a smaller orbit sheet, per-part framing or a backdrop (neutral, dark, light). Textured or metallic materials draw through the GPU render service when one is available; otherwise a flat-shaded CPU render supports geometry review only. Read viewFidelity before judging materials. Does not write files.",
+ inputSchema: renderViewsInput,
+ run: async (input) => guardCaptureBudget("kiln_screenshot", input, viewContext, () => runRenderViews(renderViewsInput.parse(input), viewContext, "kiln_screenshot")),
+ media: screenshotMedia,
+ mediaMulti: screenshotAnimationMediaMulti
}
];
}
@@ -28564,8 +28539,11 @@ function makeKilnEditTools(opts) {
const screenshotTool = tool({
name: "kiln_screenshot",
description: `${screenshotDef.description} Omit code to screenshot the current working buffer.`,
- inputSchema: bufferCodeInput,
- callback: async (input) => toCallbackResult(screenshotDef, await screenshotDef.run({ code: input.code ?? buffer.code }), opts)
+ inputSchema: screenshotDef.inputSchema.extend(bufferCodeInput.shape),
+ callback: async (input) => toCallbackResult(screenshotDef, await screenshotDef.run({
+ ...input,
+ code: input.code ?? buffer.code
+ }), opts)
});
const animationTool = makeBufferAnimationTool(() => buffer.code, animationDef, opts);
const submitTool = tool({
diff --git a/dist/build.json b/dist/build.json
index fa67f003..c0c7f79e 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:9ffd7a8ef43c2c658249518d0d8233f439e7aa248f652b805a68a7b78b8d8d87",
+ "identity": "sha256:506725cfcbc53420e8d0f08f8517953d2ae35692e34c30d78d019c6648f520d0",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "403cfb152580c49a4001fb16143afadfe3cc52a95d7bd6e2f52aad3e42d6fbad",
+ "sourceHash": "0e84ccf501f73a2a23141b03f39ecbeaa02228869c4cb0d6e1af5ce37670212d",
"dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
@@ -31,10 +31,10 @@
"bundleHash": "sha256:7087ab40b40fdbd19a2bff3b7e050b10a4fb564acbc90c90a1d62def5df15762"
},
"agent-run": {
- "identity": "sha256:9ffd7a8ef43c2c658249518d0d8233f439e7aa248f652b805a68a7b78b8d8d87",
+ "identity": "sha256:506725cfcbc53420e8d0f08f8517953d2ae35692e34c30d78d019c6648f520d0",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "403cfb152580c49a4001fb16143afadfe3cc52a95d7bd6e2f52aad3e42d6fbad",
+ "sourceHash": "0e84ccf501f73a2a23141b03f39ecbeaa02228869c4cb0d6e1af5ce37670212d",
"dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
@@ -57,13 +57,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:977cd5abb7ae0e1615a0637fd1bd903bb48e5bbd8c4707dd5c3be7e41290948e"
+ "bundleHash": "sha256:74ee36c12609c3f72b0e17ab4d2fb4bbe45c9350d14ba646a95bcaaebfe14eea"
},
"agent-providers": {
- "identity": "sha256:9ffd7a8ef43c2c658249518d0d8233f439e7aa248f652b805a68a7b78b8d8d87",
+ "identity": "sha256:506725cfcbc53420e8d0f08f8517953d2ae35692e34c30d78d019c6648f520d0",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "403cfb152580c49a4001fb16143afadfe3cc52a95d7bd6e2f52aad3e42d6fbad",
+ "sourceHash": "0e84ccf501f73a2a23141b03f39ecbeaa02228869c4cb0d6e1af5ce37670212d",
"dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
@@ -89,10 +89,10 @@
"bundleHash": "sha256:fb2295599724eaa739ef31919eccae0ff6adece4c36b6886863eb7eeacb35650"
},
"mcp": {
- "identity": "sha256:9ffd7a8ef43c2c658249518d0d8233f439e7aa248f652b805a68a7b78b8d8d87",
+ "identity": "sha256:506725cfcbc53420e8d0f08f8517953d2ae35692e34c30d78d019c6648f520d0",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "403cfb152580c49a4001fb16143afadfe3cc52a95d7bd6e2f52aad3e42d6fbad",
+ "sourceHash": "0e84ccf501f73a2a23141b03f39ecbeaa02228869c4cb0d6e1af5ce37670212d",
"dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
@@ -115,13 +115,13 @@
},
"target": "node",
"file": "mcp-server.mjs",
- "bundleHash": "sha256:4189d4f5296c4c937b8f1df92305d98ef8c0e720bd45f92050c9043816e94f0c"
+ "bundleHash": "sha256:d7ffb2c39437a46cff62a24ddfda37e12354d5324430ba7222ed26c8a3c08e9e"
},
"cli": {
- "identity": "sha256:9ffd7a8ef43c2c658249518d0d8233f439e7aa248f652b805a68a7b78b8d8d87",
+ "identity": "sha256:506725cfcbc53420e8d0f08f8517953d2ae35692e34c30d78d019c6648f520d0",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "403cfb152580c49a4001fb16143afadfe3cc52a95d7bd6e2f52aad3e42d6fbad",
+ "sourceHash": "0e84ccf501f73a2a23141b03f39ecbeaa02228869c4cb0d6e1af5ce37670212d",
"dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
@@ -144,7 +144,7 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:dfceee6fe6c0a45abbc5db261ed85044cadae94916997de8ac5d4d6d0832a693"
+ "bundleHash": "sha256:ade6ba055c1095a57c019ff165016cfd1bdd101085d0c9a2a1e45aa68d51f950"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 7b332864..4c90ee44 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -28199,30 +28199,6 @@ async function runRender(input, context) {
};
}
}
-async function runScreenshot(input, context) {
- try {
- await Promise.resolve().then(() => init_views());
- const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
- const warnings = inspectSceneStructure(root, {
- category: trustedCategory(context)
- });
- const grid = await renderGlbViewGrid(rendered.glb);
- return {
- ok: true,
- views: grid.views,
- width: grid.width,
- height: grid.height,
- pngBase64: grid.png.toString("base64"),
- warnings
- };
- } catch (err) {
- return {
- ok: false,
- error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
- warnings: []
- };
- }
-}
function screenshotMedia(output) {
const o = output;
if (!o || typeof o.pngBase64 !== "string" || o.pngBase64.length === 0)
@@ -28230,7 +28206,7 @@ function screenshotMedia(output) {
const { pngBase64: _png, ...json } = o;
return { png: new Uint8Array(Buffer.from(o.pngBase64, "base64")), json };
}
-async function runRenderViews(input, context) {
+async function runRenderViews(input, context, toolName = "kiln_render") {
try {
await Promise.resolve().then(() => init_views());
const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);
@@ -28337,7 +28313,7 @@ async function runRenderViews(input, context) {
...drawnBy.degradedReason ? { degradeReason: drawnBy.degradedReason } : {},
reasonCodes: ["IN_LOOP_BUILD_NOT_PERSISTED"]
};
- const viewEvidence = context.viewEvidenceHistory?.record("kiln_render", viewFidelity);
+ const viewEvidence = context.viewEvidenceHistory?.record(toolName, viewFidelity);
try {
context.onViewsRendered?.(drawnBy);
} catch {}
@@ -28667,6 +28643,7 @@ function createKilnEditDef(context = {}) {
};
}
function createKilnToolRegistry(context = {}) {
+ const viewContext = withViewEvidenceHistory(context);
return [
{
name: "kiln_list_primitives",
@@ -28689,10 +28666,11 @@ function createKilnToolRegistry(context = {}) {
},
{
name: "kiln_screenshot",
- description: "Render Kiln code to a six-view image grid so you can SEE the asset: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.",
- inputSchema: screenshotInput,
- run: async (input) => guardCaptureBudget("kiln_screenshot", input, context, () => runScreenshot(screenshotInput.parse(input), context)),
- media: screenshotMedia
+ description: "Render Kiln code to an image grid so you can SEE the asset. Omit capture for six views: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. capture selects a smaller orbit sheet, per-part framing or a backdrop (neutral, dark, light). Textured or metallic materials draw through the GPU render service when one is available; otherwise a flat-shaded CPU render supports geometry review only. Read viewFidelity before judging materials. Does not write files.",
+ inputSchema: renderViewsInput,
+ run: async (input) => guardCaptureBudget("kiln_screenshot", input, viewContext, () => runRenderViews(renderViewsInput.parse(input), viewContext, "kiln_screenshot")),
+ media: screenshotMedia,
+ mediaMulti: screenshotAnimationMediaMulti
}
];
}
@@ -29052,7 +29030,7 @@ function createKilnAssetDefs(context) {
}
];
}
-var KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v5.html", DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS = 6000, viewEvidenceHistoryByContext, VIEW_EVIDENCE_GUIDANCE = " viewEvidence.current describes ONLY this request. lastFaithful is older hash-only evidence for reference, not reused pixels and not current verification.", listPrimitivesInput, validateInput, renderInput, screenshotInput, backdropInput, legacyCaptureInput, cameraVec3Input, orbitCameraError = (issue) => {
+var KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v5.html", DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS = 6000, viewEvidenceHistoryByContext, VIEW_EVIDENCE_GUIDANCE = " viewEvidence.current describes ONLY this request. lastFaithful is older hash-only evidence for reference, not reused pixels and not current verification.", listPrimitivesInput, validateInput, renderInput, backdropInput, legacyCaptureInput, cameraVec3Input, orbitCameraError = (issue) => {
if (issue.code === "unrecognized_keys" && issue.keys?.some((key) => key === "target" || key === "distance")) {
return "Orbit cameras derive target and distance from the selected subject bounds; choose subject and padding, or use an explicit camera with position and target.";
}
@@ -29090,9 +29068,6 @@ var init_registry2 = __esm(() => {
renderInput = z4.object({
code: z4.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
- screenshotInput = z4.object({
- code: z4.string().describe("Kiln source code to execute and render to a six-view image grid.")
- });
backdropInput = z4.enum(BACKDROP_IDS).optional().describe("Neutral grey unless a sheet shows merging: light if the part is darker, dark if lighter.");
legacyCaptureInput = z4.object({
preset: z4.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("Grid shape as COLSxROWS. Default 3x2. Choose fewer views for simple shapes, up to 3x3 for more angles."),
@@ -29217,9 +29192,10 @@ var init_registry2 = __esm(() => {
// src/render-service-host.ts
import { spawn as spawn2 } from "node:child_process";
-import { existsSync as existsSync2 } from "node:fs";
+import { createHash as createHash9 } from "node:crypto";
+import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync, statSync } from "node:fs";
import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
-import { join as join7 } from "node:path";
+import { join as join7, relative as relative2 } from "node:path";
function localRenderServicePort() {
const raw = Number(process.env["KILN_RENDER_SERVICE_PORT"]);
return Number.isInteger(raw) && raw > 0 && raw < 65536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;
@@ -29260,6 +29236,96 @@ async function healthy(url, timeoutMs) {
return false;
}
}
+function renderServiceSourceFingerprint(dir) {
+ const source = join7(dir, "src");
+ if (!existsSync2(source))
+ return;
+ const hash = createHash9("sha256");
+ hash.update("kiln.render-service-source.v1");
+ const visit = (path) => {
+ if (statSync(path).isDirectory()) {
+ for (const name of readdirSync(path).sort()) {
+ if (name === "node_modules")
+ continue;
+ visit(join7(path, name));
+ }
+ return;
+ }
+ const bytes = readFileSync2(path);
+ hash.update(JSON.stringify([relative2(source, path).replaceAll("\\", "/"), bytes.length]));
+ hash.update(bytes);
+ };
+ visit(source);
+ return `sha256:${hash.digest("hex")}`;
+}
+function processIsAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error.code === "EPERM";
+ }
+}
+async function inspectLocalRenderService(url, dir = renderServiceDir(), timeoutMs = 1500) {
+ let body;
+ try {
+ const res = await fetch(new URL("/health", url), {
+ signal: AbortSignal.timeout(timeoutMs),
+ cache: "no-store"
+ });
+ if (!res.ok)
+ return { kind: "foreign" };
+ body = await res.json();
+ } catch (error) {
+ if (error instanceof Error && error.name === "TimeoutError")
+ return { kind: "busy" };
+ return error.name === "SyntaxError" ? { kind: "foreign" } : { kind: "absent" };
+ }
+ if (body?.ok !== true || typeof body.rendererId !== "string")
+ return { kind: "foreign" };
+ const raw = body.instance;
+ const instance = raw && raw.version === "kiln.render-service-instance.v1" && typeof raw.pid === "number" && typeof raw.sourceFingerprint === "string" ? {
+ version: raw.version,
+ pid: raw.pid,
+ ownerPid: typeof raw.ownerPid === "number" ? raw.ownerPid : null,
+ startedAt: typeof raw.startedAt === "string" ? raw.startedAt : "",
+ sourceDir: typeof raw.sourceDir === "string" ? raw.sourceDir : "",
+ sourceFingerprint: raw.sourceFingerprint
+ } : undefined;
+ const local = renderServiceSourceFingerprint(dir);
+ const stale = instance !== undefined && local !== undefined && instance.sourceFingerprint !== local;
+ const orphaned = instance !== undefined && instance.ownerPid !== null && !processIsAlive(instance.ownerPid);
+ return {
+ kind: "service",
+ rendererId: body.rendererId,
+ ...instance ? { instance } : {},
+ stale,
+ orphaned
+ };
+}
+function describeStaleService(url, probe) {
+ if (probe.kind !== "service" || !probe.instance)
+ return `the render service on ${url} is stale`;
+ const { pid, ownerPid } = probe.instance;
+ const who = ownerPid === null ? "started by hand" : probe.orphaned ? `started by session ${ownerPid}, which has exited` : `started by session ${ownerPid}, which is still running`;
+ return `the render service on ${url} (pid ${pid}, ${who}) runs older source than the render-service directory of this installation`;
+}
+async function terminateRenderService(url, probe, waitMs = 5000) {
+ if (probe.kind !== "service" || !probe.instance)
+ return false;
+ try {
+ process.kill(probe.instance.pid);
+ } catch {
+ return false;
+ }
+ const deadline = Date.now() + waitMs;
+ while (Date.now() < deadline) {
+ if ((await inspectLocalRenderService(url, undefined, 500)).kind === "absent")
+ return true;
+ await new Promise((done) => setTimeout(done, 100));
+ }
+ return false;
+}
function nodeBinary() {
const override = process.env["KILN_RENDER_SERVICE_NODE"];
if (override)
@@ -29285,8 +29351,19 @@ function registerTeardown() {
}
async function startLocalRenderService(dir = renderServiceDir()) {
const url = localRenderServiceUrl();
- if (await healthy(url, 1500))
+ const probe = await inspectLocalRenderService(url, dir);
+ if (probe.kind === "busy")
return url;
+ if (probe.kind === "foreign")
+ throw new Error(`port ${localRenderServicePort()} is in use by something that is not a render service; ` + "set KILN_RENDER_SERVICE_PORT to move the renderer");
+ if (probe.kind === "service") {
+ if (!probe.stale)
+ return url;
+ if (!probe.orphaned)
+ throw new Error(`${describeStaleService(url, probe)}; stop it with \`kiln service stop\` and it will be started again on demand`);
+ if (!await terminateRenderService(url, probe))
+ throw new Error(`${describeStaleService(url, probe)} and could not be stopped`);
+ }
const state = localRenderServiceState(dir);
if (state !== "ready")
throw new Error(explainRenderServiceState(state, dir));
@@ -29297,6 +29374,7 @@ async function startLocalRenderService(dir = renderServiceDir()) {
env: {
...process.env,
PORT: String(localRenderServicePort()),
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
HOST: "127.0.0.1"
},
stdio: ["ignore", "ignore", "pipe"]
@@ -29326,7 +29404,7 @@ var init_render_service_host = __esm(() => {
});
// src/cli-render-mode.ts
-import { createHash as createHash9 } from "node:crypto";
+import { createHash as createHash10 } from "node:crypto";
function resolveRenderMode(value) {
if (value === "auto" || value === "cpu" || value === "gpu")
return value;
@@ -29337,7 +29415,7 @@ function makeRemoteRenderPort(url, token) {
const body = {
glb_base64: Buffer.from(req.glb).toString("base64")
};
- const inputGlbSha256 = `sha256:${createHash9("sha256").update(req.glb).digest("hex")}`;
+ const inputGlbSha256 = `sha256:${createHash10("sha256").update(req.glb).digest("hex")}`;
body["input_glb_sha256"] = inputGlbSha256;
if (req.cameras) {
body["cameras"] = req.cameras;
@@ -29379,13 +29457,31 @@ function makeRemoteRenderPort(url, token) {
}
function makeLazyRenderPort(start, token) {
let resolving;
+ const resolve = () => resolving ??= start().then((url) => ({ url, port: makeRemoteRenderPort(url, token) }), (err) => {
+ throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);
+ });
return async (req) => {
- resolving ??= start().then((url) => makeRemoteRenderPort(url, token), (err) => {
- throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);
- });
- return (await resolving)(req);
+ const { url, port } = await resolve();
+ try {
+ return await port(req);
+ } catch (error) {
+ if (error instanceof Error && error.name === "TimeoutError")
+ throw error;
+ if (await listening(url))
+ throw error;
+ resolving = undefined;
+ return (await resolve()).port(req);
+ }
};
}
+async function listening(url) {
+ try {
+ const res = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(1500) });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
async function probeCaptureIdentity(url) {
try {
const response = await fetch(new URL("/health", url), {
@@ -29408,30 +29504,11 @@ async function probeCaptureIdentity(url) {
return;
}
}
-async function probeOnce(url, timeoutMs) {
- try {
- const res = await fetch(new URL("/health", url), {
- signal: AbortSignal.timeout(timeoutMs)
- });
- if (!res.ok)
- return { kind: "absent" };
- const json = await res.json();
- if (!json.ok)
- return { kind: "absent" };
- return { kind: "ok", rendererId: json.rendererId ?? "unknown-renderer" };
- } catch (err) {
- const timedOut = err instanceof Error && err.name === "TimeoutError";
- return timedOut ? { kind: "busy" } : { kind: "absent" };
- }
-}
-async function probeRenderService(url) {
- const first = await probeOnce(url, HEALTH_PROBE_TIMEOUT_MS);
- if (first.kind === "ok")
- return first.rendererId;
- if (first.kind === "absent")
- return;
- const second = await probeOnce(url, HEALTH_PROBE_BUSY_TIMEOUT_MS);
- return second.kind === "ok" ? second.rendererId : undefined;
+async function inspectWithPatience(url, dir) {
+ const first = await inspectLocalRenderService(url, dir, HEALTH_PROBE_TIMEOUT_MS);
+ if (first.kind !== "busy")
+ return first;
+ return inspectLocalRenderService(url, dir, HEALTH_PROBE_BUSY_TIMEOUT_MS);
}
function describeRenderMode(context) {
return selected.get(context) ?? "cpu raster";
@@ -29482,11 +29559,35 @@ async function buildRenderPort(mode, portUrl, options) {
if (envUrl)
return attach(envUrl, `GPU service (${envUrl})`, explicitClientToken);
const localUrl = localRenderServiceUrl();
- const rendererId = await probeRenderService(localUrl);
- if (rendererId)
- return attach(localUrl, `GPU service (${rendererId})`, localClientToken);
+ const dir = options?.serviceDir ?? renderServiceDir();
+ const probe = await inspectWithPatience(localUrl, dir);
+ let pruned = "";
+ if (probe.kind === "service") {
+ if (!probe.stale)
+ return attach(localUrl, `GPU service (${probe.rendererId})`, localClientToken);
+ if (!probe.orphaned) {
+ const why = `${describeStaleService(localUrl, probe)}; stop it with \`kiln service stop\``;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ pruned = await terminateRenderService(localUrl, probe) ? `stopped ${describeStaleService(localUrl, probe)}` : "";
+ if (!pruned) {
+ const why = `${describeStaleService(localUrl, probe)} and could not be stopped`;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ } else if (probe.kind === "foreign") {
+ const why = `port ${localRenderServicePort()} is in use by something that is not a render service; set KILN_RENDER_SERVICE_PORT to move the renderer`;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
if (options?.autoSpawn || mode === "gpu") {
- const dir = options?.serviceDir ?? renderServiceDir();
const state = options?.start ? "ready" : localRenderServiceState(dir);
if (state === "ready") {
const start = options?.start ?? (() => startLocalRenderService(dir));
@@ -29496,7 +29597,7 @@ async function buildRenderPort(mode, portUrl, options) {
throw new Error(`no GPU render service is reachable at ${localUrl}, and ${explainRenderServiceState(state, dir)}.
` + "Set --render-port or KILN_RENDER_PORT_URL to point at one elsewhere, or use " + "--render auto to fall back to the CPU rasterizer.");
}
- selected.set(context, "cpu raster (no GPU service found)");
+ selected.set(context, pruned ? `cpu raster (${pruned}; none started for a one-shot render)` : "cpu raster (no GPU service found)");
return context;
}
var HEALTH_PROBE_TIMEOUT_MS = 1500, HEALTH_PROBE_BUSY_TIMEOUT_MS = 8000, CLI_VIEW_RENDER_TIMEOUT_MS = 20000, selected;
@@ -29507,11 +29608,11 @@ var init_cli_render_mode = __esm(() => {
});
// src/assets-node.ts
-import { createHash as createHash10, randomUUID as randomUUID4 } from "node:crypto";
-import { readFileSync as readFileSync2 } from "node:fs";
+import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";
+import { readFileSync as readFileSync3 } from "node:fs";
import { lstat as lstat3, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, realpath as realpath3, rename as rename3, rm, writeFile as writeFile4 } from "node:fs/promises";
import { homedir, platform } from "node:os";
-import { dirname as dirname4, join as join8, relative as relative2, resolve as resolve6, sep } from "node:path";
+import { dirname as dirname4, join as join8, relative as relative3, resolve as resolve6, sep } from "node:path";
async function verifyAssetRecord(record) {
for (const [name, info] of Object.entries(record.manifest.files)) {
const bytes = record.files[name];
@@ -29552,7 +29653,7 @@ class FileAssetLibrary {
const entry = await lstat3(path);
if (entry.isSymbolicLink())
throw new Error("Collection symlinks are not supported");
- const rel = relative2(canonical, await realpath3(path));
+ const rel = relative3(canonical, await realpath3(path));
if (rel === ".." || rel.startsWith(`..${sep}`))
throw new Error("Collection path escapes root");
} catch (error) {
@@ -29702,7 +29803,7 @@ function localAssetLibrary(env = process.env) {
}
const config = collectionConfigPath(env);
try {
- const text = readFileSync2(config, "utf8");
+ const text = readFileSync3(config, "utf8");
if (!text.trim())
throw new Error("Collection configuration is empty");
return localAssetLibrary({ ...env, KILN_COLLECTIONS: text });
@@ -29716,7 +29817,7 @@ function localAssetLibrary(env = process.env) {
library: defaultUserLibraryRoot(env)
});
}
-var digest4 = (bytes) => `sha256:${createHash10("sha256").update(bytes).digest("hex")}`;
+var digest4 = (bytes) => `sha256:${createHash11("sha256").update(bytes).digest("hex")}`;
var init_assets_node = __esm(() => {
init_assets();
});
@@ -30061,6 +30162,113 @@ var init_asset_cli = __esm(() => {
init_deep_link();
});
+// src/service-cli.ts
+var exports_service_cli = {};
+__export(exports_service_cli, {
+ SERVICE_USAGE: () => SERVICE_USAGE,
+ serviceMain: () => serviceMain
+});
+function describeProcess(probe) {
+ if (probe.kind !== "service")
+ return "";
+ if (!probe.instance)
+ return "unknown (this service predates instance reporting)";
+ const { pid, ownerPid } = probe.instance;
+ if (ownerPid === null)
+ return `pid ${pid}, started by hand`;
+ return `pid ${pid}, started by session ${ownerPid} (${processIsAlive(ownerPid) ? "running" : "exited"})`;
+}
+function describeSource(probe, dir) {
+ if (probe.kind !== "service")
+ return "";
+ if (!probe.instance)
+ return "unknown (this service predates instance reporting)";
+ return probe.stale ? `stale (older than ${dir})` : "current";
+}
+async function serviceMain(argv, io = { log: console.log, error: console.error }) {
+ const command = argv[0];
+ if (command === undefined || command === "--help" || command === "-h") {
+ io.log(SERVICE_USAGE);
+ return command === undefined ? 2 : 0;
+ }
+ if (command !== "status" && command !== "stop" && command !== "prune") {
+ io.error(`unknown service command: ${command}
+${SERVICE_USAGE}`);
+ return 2;
+ }
+ const url = localRenderServiceUrl();
+ const dir = renderServiceDir();
+ const state = localRenderServiceState(dir);
+ const probe = await inspectLocalRenderService(url, dir);
+ if (command === "status") {
+ io.log(`render service ${url}`);
+ io.log(`installation ${state === "ready" ? `ready (${dir})` : explainRenderServiceState(state, dir)}`);
+ switch (probe.kind) {
+ case "absent":
+ io.log("listening no");
+ break;
+ case "busy":
+ io.log("listening yes, busy rendering (did not answer in time)");
+ break;
+ case "foreign":
+ io.log(`listening something that is not a render service holds port ${localRenderServicePort()}; set KILN_RENDER_SERVICE_PORT to move the renderer`);
+ break;
+ case "service":
+ io.log(`listening yes ${probe.rendererId}`);
+ io.log(`process ${describeProcess(probe)}`);
+ io.log(`source ${describeSource(probe, dir)}`);
+ break;
+ }
+ return 0;
+ }
+ if (probe.kind === "absent") {
+ io.log(`nothing is listening on ${url}`);
+ return 0;
+ }
+ if (probe.kind === "busy") {
+ io.error(`the render service on ${url} is busy rendering and did not answer; try again`);
+ return 1;
+ }
+ if (probe.kind === "foreign") {
+ io.error(`port ${localRenderServicePort()} is in use by something that is not a render service; nothing was stopped. Set KILN_RENDER_SERVICE_PORT to move the renderer.`);
+ return 1;
+ }
+ if (!probe.instance) {
+ io.error(`the render service on ${url} predates instance reporting and does not say its pid; stop it by hand and start it again from ${dir}`);
+ return 1;
+ }
+ if (command === "prune") {
+ if (!probe.stale) {
+ io.log(`kept: the render service on ${url} (pid ${probe.instance.pid}) is current`);
+ return 0;
+ }
+ if (!probe.orphaned) {
+ io.log(`kept: ${describeStaleService(url, probe)}; \`kiln service stop\` stops it anyway`);
+ return 0;
+ }
+ }
+ const stopped = await terminateRenderService(url, probe);
+ if (!stopped) {
+ io.error(`could not stop the render service on ${url} (pid ${probe.instance.pid})`);
+ return 1;
+ }
+ io.log(command === "prune" ? `stopped: ${describeStaleService(url, probe)}` : `stopped the render service on ${url} (pid ${probe.instance.pid}); the next view that needs it starts a new one`);
+ return 0;
+}
+var SERVICE_USAGE = `
+RENDER SERVICE
+ kiln service status who is listening on the shared port, and whether it is current
+ kiln service stop stop the render service on the shared port, whoever started it
+ kiln service prune stop it only when it is an orphan running older source
+
+The port is 8000 unless KILN_RENDER_SERVICE_PORT says otherwise. A session starts the
+service on demand and stops it on exit; \`kiln service\` is for the one it will not decide
+for you: a stale service started by hand or still owned by another session.
+`;
+var init_service_cli = __esm(() => {
+ init_render_service_host();
+});
+
// src/cli.ts
init_cli_output();
import { open as open2, readFile as readFile7, writeFile as writeFile6 } from "node:fs/promises";
@@ -30089,6 +30297,7 @@ init_render_service_host();
init_program_store_node();
init_program_store();
init_asset_cli();
+init_service_cli();
var USAGE = `kiln — vision-in-the-loop 3D asset generation
USAGE
@@ -30096,6 +30305,7 @@ USAGE
kiln generate "<prompt>" [options] author a program with a model, then render
kiln source <file.js> save a source snapshot and print its programRef
kiln source <programRef> --out file.js export a revision without model transcription
+ kiln service status|stop|prune the shared GPU render service (see below)
OPTIONS
--out <path> GLB output path (default: out.glb)
@@ -30376,6 +30586,8 @@ function main(argv) {
return withProcessAlive(() => runMain(argv)).finally(stopLocalRenderService);
}
async function runMain(argv) {
+ if (argv[0] === "service")
+ return (await Promise.resolve().then(() => (init_service_cli(), exports_service_cli))).serviceMain(argv.slice(1));
if (["save", "collections", "assets", "asset", "export", "import", "view"].includes(argv[0] ?? "")) {
try {
return await (await Promise.resolve().then(() => (init_asset_cli(), exports_asset_cli))).assetMain(argv);
@@ -30392,7 +30604,7 @@ async function runMain(argv) {
return 2;
}
if (args.help || !args.command) {
- console.log(USAGE + ASSET_USAGE);
+ console.log(USAGE + ASSET_USAGE + SERVICE_USAGE);
return args.help ? 0 : 2;
}
try {
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index 10e92598..1753b1a6 100644
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -27690,9 +27690,6 @@ var validateInput = z4.object({
var renderInput = z4.object({
code: z4.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
-var screenshotInput = z4.object({
- code: z4.string().describe("Kiln source code to execute and render to a six-view image grid.")
-});
var backdropInput = z4.enum(BACKDROP_IDS).optional().describe("Neutral grey unless a sheet shows merging: light if the part is darker, dark if lighter.");
var legacyCaptureInput = z4.object({
preset: z4.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("Grid shape as COLSxROWS. Default 3x2. Choose fewer views for simple shapes, up to 3x3 for more angles."),
@@ -27897,30 +27894,6 @@ async function runRender(input, context) {
};
}
}
-async function runScreenshot(input, context) {
- try {
- await Promise.resolve().then(() => init_views());
- const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
- const warnings = inspectSceneStructure(root, {
- category: trustedCategory(context)
- });
- const grid = await renderGlbViewGrid(rendered.glb);
- return {
- ok: true,
- views: grid.views,
- width: grid.width,
- height: grid.height,
- pngBase64: grid.png.toString("base64"),
- warnings
- };
- } catch (err) {
- return {
- ok: false,
- error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
- warnings: []
- };
- }
-}
function screenshotMedia(output) {
const o = output;
if (!o || typeof o.pngBase64 !== "string" || o.pngBase64.length === 0)
@@ -27928,7 +27901,7 @@ function screenshotMedia(output) {
const { pngBase64: _png, ...json } = o;
return { png: new Uint8Array(Buffer.from(o.pngBase64, "base64")), json };
}
-async function runRenderViews(input, context) {
+async function runRenderViews(input, context, toolName = "kiln_render") {
try {
await Promise.resolve().then(() => init_views());
const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);
@@ -28035,7 +28008,7 @@ async function runRenderViews(input, context) {
...drawnBy.degradedReason ? { degradeReason: drawnBy.degradedReason } : {},
reasonCodes: ["IN_LOOP_BUILD_NOT_PERSISTED"]
};
- const viewEvidence = context.viewEvidenceHistory?.record("kiln_render", viewFidelity);
+ const viewEvidence = context.viewEvidenceHistory?.record(toolName, viewFidelity);
try {
context.onViewsRendered?.(drawnBy);
} catch {}
@@ -28402,6 +28375,7 @@ function createKilnEditDef(context = {}) {
}
var kilnEditDef = createKilnEditDef();
function createKilnToolRegistry(context = {}) {
+ const viewContext = withViewEvidenceHistory(context);
return [
{
name: "kiln_list_primitives",
@@ -28424,10 +28398,11 @@ function createKilnToolRegistry(context = {}) {
},
{
name: "kiln_screenshot",
- description: "Render Kiln code to a six-view image grid so you can SEE the asset: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.",
- inputSchema: screenshotInput,
- run: async (input) => guardCaptureBudget("kiln_screenshot", input, context, () => runScreenshot(screenshotInput.parse(input), context)),
- media: screenshotMedia
+ description: "Render Kiln code to an image grid so you can SEE the asset. Omit capture for six views: row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. If a view looks wrong, fix the code and screenshot again. capture selects a smaller orbit sheet, per-part framing or a backdrop (neutral, dark, light). Textured or metallic materials draw through the GPU render service when one is available; otherwise a flat-shaded CPU render supports geometry review only. Read viewFidelity before judging materials. Does not write files.",
+ inputSchema: renderViewsInput,
+ run: async (input) => guardCaptureBudget("kiln_screenshot", input, viewContext, () => runRenderViews(renderViewsInput.parse(input), viewContext, "kiln_screenshot")),
+ media: screenshotMedia,
+ mediaMulti: screenshotAnimationMediaMulti
}
];
}
@@ -28796,13 +28771,14 @@ function createKilnAssetDefs(context) {
}
// src/cli-render-mode.ts
-import { createHash as createHash8 } from "node:crypto";
+import { createHash as createHash9 } from "node:crypto";
// src/render-service-host.ts
import { spawn as spawn2 } from "node:child_process";
-import { existsSync as existsSync2 } from "node:fs";
+import { createHash as createHash8 } from "node:crypto";
+import { existsSync as existsSync2, readFileSync as readFileSync3, readdirSync, statSync } from "node:fs";
import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
-import { join as join3 } from "node:path";
+import { join as join3, relative as relative2 } from "node:path";
var DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000;
function localRenderServicePort() {
const raw = Number(process.env["KILN_RENDER_SERVICE_PORT"]);
@@ -28846,6 +28822,96 @@ async function healthy(url, timeoutMs) {
return false;
}
}
+function renderServiceSourceFingerprint(dir) {
+ const source = join3(dir, "src");
+ if (!existsSync2(source))
+ return;
+ const hash = createHash8("sha256");
+ hash.update("kiln.render-service-source.v1");
+ const visit = (path) => {
+ if (statSync(path).isDirectory()) {
+ for (const name of readdirSync(path).sort()) {
+ if (name === "node_modules")
+ continue;
+ visit(join3(path, name));
+ }
+ return;
+ }
+ const bytes = readFileSync3(path);
+ hash.update(JSON.stringify([relative2(source, path).replaceAll("\\", "/"), bytes.length]));
+ hash.update(bytes);
+ };
+ visit(source);
+ return `sha256:${hash.digest("hex")}`;
+}
+function processIsAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error.code === "EPERM";
+ }
+}
+async function inspectLocalRenderService(url, dir = renderServiceDir(), timeoutMs = 1500) {
+ let body;
+ try {
+ const res = await fetch(new URL("/health", url), {
+ signal: AbortSignal.timeout(timeoutMs),
+ cache: "no-store"
+ });
+ if (!res.ok)
+ return { kind: "foreign" };
+ body = await res.json();
+ } catch (error) {
+ if (error instanceof Error && error.name === "TimeoutError")
+ return { kind: "busy" };
+ return error.name === "SyntaxError" ? { kind: "foreign" } : { kind: "absent" };
+ }
+ if (body?.ok !== true || typeof body.rendererId !== "string")
+ return { kind: "foreign" };
+ const raw = body.instance;
+ const instance = raw && raw.version === "kiln.render-service-instance.v1" && typeof raw.pid === "number" && typeof raw.sourceFingerprint === "string" ? {
+ version: raw.version,
+ pid: raw.pid,
+ ownerPid: typeof raw.ownerPid === "number" ? raw.ownerPid : null,
+ startedAt: typeof raw.startedAt === "string" ? raw.startedAt : "",
+ sourceDir: typeof raw.sourceDir === "string" ? raw.sourceDir : "",
+ sourceFingerprint: raw.sourceFingerprint
+ } : undefined;
+ const local = renderServiceSourceFingerprint(dir);
+ const stale = instance !== undefined && local !== undefined && instance.sourceFingerprint !== local;
+ const orphaned = instance !== undefined && instance.ownerPid !== null && !processIsAlive(instance.ownerPid);
+ return {
+ kind: "service",
+ rendererId: body.rendererId,
+ ...instance ? { instance } : {},
+ stale,
+ orphaned
+ };
+}
+function describeStaleService(url, probe) {
+ if (probe.kind !== "service" || !probe.instance)
+ return `the render service on ${url} is stale`;
+ const { pid, ownerPid } = probe.instance;
+ const who = ownerPid === null ? "started by hand" : probe.orphaned ? `started by session ${ownerPid}, which has exited` : `started by session ${ownerPid}, which is still running`;
+ return `the render service on ${url} (pid ${pid}, ${who}) runs older source than the render-service directory of this installation`;
+}
+async function terminateRenderService(url, probe, waitMs = 5000) {
+ if (probe.kind !== "service" || !probe.instance)
+ return false;
+ try {
+ process.kill(probe.instance.pid);
+ } catch {
+ return false;
+ }
+ const deadline = Date.now() + waitMs;
+ while (Date.now() < deadline) {
+ if ((await inspectLocalRenderService(url, undefined, 500)).kind === "absent")
+ return true;
+ await new Promise((done) => setTimeout(done, 100));
+ }
+ return false;
+}
function nodeBinary() {
const override = process.env["KILN_RENDER_SERVICE_NODE"];
if (override)
@@ -28873,8 +28939,19 @@ function registerTeardown() {
}
async function startLocalRenderService(dir = renderServiceDir()) {
const url = localRenderServiceUrl();
- if (await healthy(url, 1500))
+ const probe = await inspectLocalRenderService(url, dir);
+ if (probe.kind === "busy")
return url;
+ if (probe.kind === "foreign")
+ throw new Error(`port ${localRenderServicePort()} is in use by something that is not a render service; ` + "set KILN_RENDER_SERVICE_PORT to move the renderer");
+ if (probe.kind === "service") {
+ if (!probe.stale)
+ return url;
+ if (!probe.orphaned)
+ throw new Error(`${describeStaleService(url, probe)}; stop it with \`kiln service stop\` and it will be started again on demand`);
+ if (!await terminateRenderService(url, probe))
+ throw new Error(`${describeStaleService(url, probe)} and could not be stopped`);
+ }
const state = localRenderServiceState(dir);
if (state !== "ready")
throw new Error(explainRenderServiceState(state, dir));
@@ -28885,6 +28962,7 @@ async function startLocalRenderService(dir = renderServiceDir()) {
env: {
...process.env,
PORT: String(localRenderServicePort()),
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
HOST: "127.0.0.1"
},
stdio: ["ignore", "ignore", "pipe"]
@@ -28924,7 +29002,7 @@ function makeRemoteRenderPort(url, token) {
const body = {
glb_base64: Buffer.from(req.glb).toString("base64")
};
- const inputGlbSha256 = `sha256:${createHash8("sha256").update(req.glb).digest("hex")}`;
+ const inputGlbSha256 = `sha256:${createHash9("sha256").update(req.glb).digest("hex")}`;
body["input_glb_sha256"] = inputGlbSha256;
if (req.cameras) {
body["cameras"] = req.cameras;
@@ -28966,13 +29044,31 @@ function makeRemoteRenderPort(url, token) {
}
function makeLazyRenderPort(start, token) {
let resolving;
+ const resolve = () => resolving ??= start().then((url) => ({ url, port: makeRemoteRenderPort(url, token) }), (err) => {
+ throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);
+ });
return async (req) => {
- resolving ??= start().then((url) => makeRemoteRenderPort(url, token), (err) => {
- throw new Error(`render service could not start: ${err instanceof Error ? err.message : String(err)}`);
- });
- return (await resolving)(req);
+ const { url, port } = await resolve();
+ try {
+ return await port(req);
+ } catch (error) {
+ if (error instanceof Error && error.name === "TimeoutError")
+ throw error;
+ if (await listening(url))
+ throw error;
+ resolving = undefined;
+ return (await resolve()).port(req);
+ }
};
}
+async function listening(url) {
+ try {
+ const res = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(1500) });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
async function probeCaptureIdentity(url) {
try {
const response = await fetch(new URL("/health", url), {
@@ -28995,30 +29091,11 @@ async function probeCaptureIdentity(url) {
return;
}
}
-async function probeOnce(url, timeoutMs) {
- try {
- const res = await fetch(new URL("/health", url), {
- signal: AbortSignal.timeout(timeoutMs)
- });
- if (!res.ok)
- return { kind: "absent" };
- const json = await res.json();
- if (!json.ok)
- return { kind: "absent" };
- return { kind: "ok", rendererId: json.rendererId ?? "unknown-renderer" };
- } catch (err) {
- const timedOut = err instanceof Error && err.name === "TimeoutError";
- return timedOut ? { kind: "busy" } : { kind: "absent" };
- }
-}
-async function probeRenderService(url) {
- const first = await probeOnce(url, HEALTH_PROBE_TIMEOUT_MS);
- if (first.kind === "ok")
- return first.rendererId;
- if (first.kind === "absent")
- return;
- const second = await probeOnce(url, HEALTH_PROBE_BUSY_TIMEOUT_MS);
- return second.kind === "ok" ? second.rendererId : undefined;
+async function inspectWithPatience(url, dir) {
+ const first = await inspectLocalRenderService(url, dir, HEALTH_PROBE_TIMEOUT_MS);
+ if (first.kind !== "busy")
+ return first;
+ return inspectLocalRenderService(url, dir, HEALTH_PROBE_BUSY_TIMEOUT_MS);
}
var selected = new WeakMap;
async function buildRenderPort(mode, portUrl, options) {
@@ -29053,11 +29130,35 @@ async function buildRenderPort(mode, portUrl, options) {
if (envUrl)
return attach(envUrl, `GPU service (${envUrl})`, explicitClientToken);
const localUrl = localRenderServiceUrl();
- const rendererId = await probeRenderService(localUrl);
- if (rendererId)
- return attach(localUrl, `GPU service (${rendererId})`, localClientToken);
+ const dir = options?.serviceDir ?? renderServiceDir();
+ const probe = await inspectWithPatience(localUrl, dir);
+ let pruned = "";
+ if (probe.kind === "service") {
+ if (!probe.stale)
+ return attach(localUrl, `GPU service (${probe.rendererId})`, localClientToken);
+ if (!probe.orphaned) {
+ const why = `${describeStaleService(localUrl, probe)}; stop it with \`kiln service stop\``;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ pruned = await terminateRenderService(localUrl, probe) ? `stopped ${describeStaleService(localUrl, probe)}` : "";
+ if (!pruned) {
+ const why = `${describeStaleService(localUrl, probe)} and could not be stopped`;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ } else if (probe.kind === "foreign") {
+ const why = `port ${localRenderServicePort()} is in use by something that is not a render service; set KILN_RENDER_SERVICE_PORT to move the renderer`;
+ if (mode === "gpu")
+ throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
if (options?.autoSpawn || mode === "gpu") {
- const dir = options?.serviceDir ?? renderServiceDir();
const state = options?.start ? "ready" : localRenderServiceState(dir);
if (state === "ready") {
const start = options?.start ?? (() => startLocalRenderService(dir));
@@ -29067,7 +29168,7 @@ async function buildRenderPort(mode, portUrl, options) {
throw new Error(`no GPU render service is reachable at ${localUrl}, and ${explainRenderServiceState(state, dir)}.
` + "Set --render-port or KILN_RENDER_PORT_URL to point at one elsewhere, or use " + "--render auto to fall back to the CPU rasterizer.");
}
- selected.set(context, "cpu raster (no GPU service found)");
+ selected.set(context, pruned ? `cpu raster (${pruned}; none started for a one-shot render)` : "cpu raster (no GPU service found)");
return context;
}
@@ -29342,7 +29443,7 @@ init_community_exporter();
// src/build-cache-node.ts
init_protocol();
-import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";
+import { createHash as createHash10, randomUUID as randomUUID4 } from "node:crypto";
import {
mkdir as mkdir4,
readFile as readFile4,
@@ -29356,7 +29457,7 @@ import {
import { join as join6, resolve as resolve5 } from "node:path";
var keyPattern = /^sha256:[a-f0-9]{64}$/;
var filePattern = /^[a-f0-9]{64}\.json$/;
-var digest3 = (text) => createHash9("sha256").update(text).digest("hex");
+var digest3 = (text) => createHash10("sha256").update(text).digest("hex");
class FileBuildCache {
maxBytes;
@@ -29430,11 +29531,11 @@ class FileBuildCache {
}
// src/runtime-identity.ts
-import { createHash as createHash10 } from "node:crypto";
+import { createHash as createHash11 } from "node:crypto";
import { readFile as readFile5, readdir as readdir5, realpath as realpath2, stat as stat4 } from "node:fs/promises";
import { createRequire } from "node:module";
-import { dirname as dirname2, join as join7, relative as relative2 } from "node:path";
-var digest4 = (bytes) => createHash10("sha256").update(bytes).digest("hex");
+import { dirname as dirname2, join as join7, relative as relative3 } from "node:path";
+var digest4 = (bytes) => createHash11("sha256").update(bytes).digest("hex");
var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
async function installedRuntimeIdentity(root, limits = {}) {
let bytes = 0;
@@ -29518,7 +29619,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
if (entry.isDirectory())
return tree(path, base);
if (entry.isFile())
- return [[relative2(base, path).replaceAll("\\", "/"), digest4(await read(path))]];
+ return [[relative3(base, path).replaceAll("\\", "/"), digest4(await read(path))]];
throw new Error("Dependency contains a non-file runtime input.");
}))).flat();
}
diff --git a/docs/architecture.md b/docs/architecture.md
index 701fe7d7..b8e84797 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -27,7 +27,7 @@ See [package.json](../package.json) for all exports.
## Tool surfaces
-[src/tools/registry.ts](../src/tools/registry.ts) defines the tools. `createKilnToolRegistry` preserves the original in-process baseline. `createKilnProgramToolRegistry` adds saved-source references and combines build metrics with rendered views for the current MCP surface. The two surfaces share implementations but intentionally differ in their available tools.
+[src/tools/registry.ts](../src/tools/registry.ts) defines the tools. `createKilnToolRegistry` is the in-process loop's four tools; its `kiln_screenshot` runs the same implementation as the unified `kiln_render`. `createKilnProgramToolRegistry` adds saved-source references and combines build metrics with rendered views for the current MCP surface. The two surfaces share implementations but intentionally differ in their available tools.
An embedded host can inject a `ProgramStore`. The default registry store is in memory; the stdio server and CLI use a local file store. [Program revisions](programs.md) describes the contract and lifecycle.
diff --git a/docs/clean-room.md b/docs/clean-room.md
index 092edfb7..386a937e 100644
--- a/docs/clean-room.md
+++ b/docs/clean-room.md
@@ -34,6 +34,12 @@ first authoring session. CPU views are sufficient for shape and contact, but not
The MCP server probes renderer availability when its session starts; installing the renderer
afterward requires restarting that agent session before it can use the new service.
+The MCP server is loaded by the harness process that runs in the workspace directory, and only
+by that process. An agent that hands the authoring to a subagent of its own session gives it the
+outer session's tools, not the workspace's; start a nested author as a separate harness process in
+the workspace (for OpenCode, `opencode run --dir <workspace> "<brief>"`) or it will have the CLI
+alone.
+
If paths move, use the [repair command](install.md#move-or-repair-an-installation).
Repair preserves instruction/skill copies; new evaluations require fresh workspaces,
not repaired old instructions.
diff --git a/docs/dispatch.md b/docs/dispatch.md
index 87fd4049..cff05c59 100644
--- a/docs/dispatch.md
+++ b/docs/dispatch.md
@@ -20,4 +20,6 @@ Keep the brief, supplied files, renderer, and time allowance consistent. Record
Review silhouette, construction, attachments, ground contact, and requested detail. Judge materials only from material-faithful images. A valid GLB, a high triangle count, or the model's own success message does not establish that the brief was met.
+An agent that delegates the authoring to a nested agent must start that agent as a separate harness process in the workspace directory (for OpenCode, `opencode run --dir <workspace> "<brief>"`). A subagent of the outer session inherits the outer session's tools and never loads the workspace's MCP configuration, so it is left with the CLI alone. The tier-2 driver's receipt records this as `toolUsage.workspaceMcp`: `exercised`, `not-exercised` or `unknown`.
+
Use separate workspaces for independent runs and choose concurrency within the available budget. Keep interrupted artifacts, but mark them as partial when they do not satisfy the request. See the batch-dispatch skill for collection and provenance guidance.
diff --git a/docs/dogfooding.md b/docs/dogfooding.md
index 690db88c..b02caa54 100644
--- a/docs/dogfooding.md
+++ b/docs/dogfooding.md
@@ -242,7 +242,7 @@ images were reviewed by a human after the run; the driver status alone never est
| --- | --- | --- |
| Claude Code 2.1.269 · Claude Opus 5 | Completed once; two later starts hit provider quota | Produced a weathered lighthouse after cloning, setup, a nested 86-turn author, nine revisions, and GPU review: 16,245 triangles, 38,461-byte source and 1,763,612-byte GLB. The result was detailed rather than placeholder geometry. |
| OpenCode 1.18.30 · Muse Spark 1.3 Contributor Free | Completed, pending review, 25m10s | Produced a deep-sea cartographer console after three render/edit cycles: 16,548 triangles, 10,962-byte source and 266,976-byte GLB. Its relief map, drawers, porthole and articulated plotting arms read coherently, but CPU views cannot establish its materials. |
-| OpenCode 1.18.30 · Muse Spark 1.3 Contributor Free · after the neutral-backdrop and test-budget merges (2026-09-16) | Completed, pending review, 5m42s | Cloned, ran `bun install --frozen-lockfile` and `bun run build:runtime`, found `kiln-setup-workspace` unaided, created an OpenCode workspace and verified it with a CPU crate render. It dispatched the author as an in-session `task` subagent rather than a separate `opencode run --dir` process, so the workspace MCP server was never loaded and the child worked through the CLI (`render`, `source`, `save`) with PNG readback over three review cycles. The clean room held: the child read only the workspace skills and its own retained program. Saved a brass diving helmet with a hinged faceplate, side ports, hose elbow and verdigris band: 24,152 triangles, 10,469-byte source and 377,456-byte GLB, zero tool errors; the preview is a CPU view because the render service was not installed. The nested-author sentence in the setup skill comes from this run. |
+| OpenCode 1.18.30 · Muse Spark 1.3 Contributor Free · after the neutral-backdrop and test-budget merges (2026-09-16) | Completed, pending review, 5m42s | Cloned, ran `bun install --frozen-lockfile` and `bun run build:runtime`, found `kiln-setup-workspace` unaided, created an OpenCode workspace and verified it with a CPU crate render. It dispatched the author as an in-session `task` subagent rather than a separate `opencode run --dir` process, so the workspace MCP server was never loaded and the child worked through the CLI (`render`, `source`, `save`) with PNG readback over three review cycles. The clean room held: the child read only the workspace skills and its own retained program. Saved a brass diving helmet with a hinged faceplate, side ports, hose elbow and verdigris band: 24,152 triangles, 10,469-byte source and 377,456-byte GLB, zero tool errors; the preview is a CPU view because the render service was not installed. The nested-author sentence in the setup skill comes from this run, and the receipt now records `toolUsage.workspaceMcp` so a CLI-only completion is visible without reading the trace. |
| Agy 1.2.2 · Gemini 3.8 Flash High | Completed, pending review, 27m28s | Produced a detailed polar chronometer/armillary: 72,244 triangles, 57,670-byte source and 2,365,024-byte GLB, with a material-faithful GPU view. The outer setup agent also read a cloned Kiln example and engine source before authoring; that is a clean-room protocol failure and useful contamination evidence, even though the asset succeeded. |
| Codex 0.154.0 · GPT-5.6 Luna, xhigh | Asset recovered; later provider quota | Cloned, configured a workspace, and launched a nested author that saved and exported a 16,604-triangle Ancient Tidal Observatory with a material-faithful GPU preview. The outer agent created the asset workspace beside `run-01`, exposing a driver discovery bug: the old receipt incorrectly reported no export. Whole-batch discovery and automatic local-gallery capture now cover this shape. |
| Hermes 0.21.2 · GPT-5.6 Luna, xhigh through Codex OAuth | Provider quota after 2m43s | Reached clone and workspace setup under an isolated `HERMES_HOME`; quota arrived before authoring. An earlier attempt proved that Hermes safe mode alone does not isolate its state database, so the driver now always supplies an isolated home. |
diff --git a/docs/rendering.md b/docs/rendering.md
index 1dd23758..d17c91ad 100644
--- a/docs/rendering.md
+++ b/docs/rendering.md
@@ -38,6 +38,24 @@ Either way the service listens on port 8000, where `auto` looks by default, and
claim the port wins: a service already listening is joined rather than replaced, and a session that
merely found one does not stop it on exit. Set `KILN_RENDER_SERVICE_PORT` to move it.
+**The socket is the registry.** `/health` reports the process behind the port: its pid, the session
+that started it on demand (none when started by hand) and a fingerprint of the source it runs. A
+session reads that before joining. A service running the source that is on disk is joined, whoever
+started it. One running older source -- you pulled, and a renderer from before the pull is still up --
+is replaced when nobody owns it any more, and left alone but named when another session still owns it
+or when it was started by hand, because stopping somebody's renderer mid-batch is worse than a stale
+one. An on-demand service watches the session that started it and exits when that session is gone,
+even when the session was killed without running its exit hook.
+
+```bash
+bun run kiln service status # who is listening, its owner, and whether its source is current
+bun run kiln service prune # stop it only if it is an orphan running older source
+bun run kiln service stop # stop it whoever started it; the next view that needs it starts a new one
+```
+
+`status` shows the facts the host acts on. `prune` is safe to run at any time. `stop` is for the case
+the host will not decide for you: a stale service you started by hand or that another session owns.
+
**Either way it binds loopback, and widening that costs a token.** `POST /render` takes a 48 MB GLB
and renders it on the GPU one frame at a time, so an exposed bind with no auth hands any caller on
that network both your GPU and a binary-asset parser. `HOST` widens the bind and a bind wider than
diff --git a/render-service/README.md b/render-service/README.md
index f33991d6..e57051cc 100644
--- a/render-service/README.md
+++ b/render-service/README.md
@@ -48,11 +48,29 @@ will not start, never one that quietly renders on CPU while reporting success.
| Route | Body | Returns |
|---|---|---|
-| `GET /health` | -- | `{ok, rendererId, backend, adapter, capabilities, presentationProfile, lightingPresetIds}` |
+| `GET /health` | -- | `{ok, rendererId, backend, adapter, capabilities, presentationProfile, lightingPresetIds, instance}` |
| `POST /render` (legacy) | `{glb_base64, size?=384, views?, beauty_size?, backdrop?}` | `{ok, rendererId, presentationProfile, timings, views[base64 png], beauty?}` |
| `POST /render` (camera) | `{glb_base64, cameras, width, height, lighting_preset_id?, backdrop?}` | the above plus `{backend, cameras, width, height, lightingPresetId, viewSha256, outputSetSha256, cameraReceipts}` |
| `POST /bake` | -- | 501 |
+`instance` is `{version, pid, ownerPid, startedAt, sourceDir, sourceFingerprint}`: who this process is,
+so the engine that finds it on the shared port can tell a current renderer from an orphan running
+older source (`src/instance.mjs`). `ownerPid` is the session that started it on demand, passed in as
+`RENDER_SERVICE_OWNER_PID`; the service watches that pid and exits when it is gone. A hand-started
+service has no owner and never exits on its own. `sourceFingerprint` hashes `src/` and nothing else,
+so `npm install` does not change it and an edit does.
+
+## Deploy it with the engine
+
+The engine and this service are one contract and ship from one commit. The engine sends every field
+it knows -- `backdrop`, `input_glb_sha256`, exact cameras -- and a service built before a field
+existed rejects the request with a 400, which the engine reports as a CPU degrade with the status in
+`degradeReason`. A local service is replaced or named automatically (see `instance` above); a hosted
+one is not, because the engine will not stop a process it did not start. When you update the engine
+behind `--render-port` or `KILN_RENDER_PORT_URL`, redeploy the service from the same commit, and
+compare `/health.instance.sourceFingerprint` against `bun run kiln service status` on a checkout of
+that commit if you need to prove which build is live.
+
Auth, when `RENDER_SERVICE_TOKEN` is set, is the `x-render-token` header -- **not** `Authorization`,
because serverless edge gateways routinely consume that one before it reaches the process.
diff --git a/render-service/package.json b/render-service/package.json
index 538be878..104609d1 100644
--- a/render-service/package.json
+++ b/render-service/package.json
@@ -1,22 +1,22 @@
-{
- "name": "kiln-render-service",
- "private": true,
- "version": "0.1.0",
- "type": "module",
- "description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.",
- "scripts": {
- "start": "node --import ./src/register-hooks.mjs src/server.mjs",
- "test": "node --test test/bind-policy.test.mjs test/beauty-camera.test.mjs test/display-output.test.mjs test/readback.test.mjs test/cache-identity.test.mjs test/asset-camera.test.mjs test/contract.test.mjs test/framing.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs test/gallery-presentation.test.mjs test/display-transform.test.mjs",
- "smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs",
- "conformance:display": "node --import ./src/register-hooks.mjs test/display-output-conformance.mjs",
- "conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"
- },
- "dependencies": {
- "pngjs": "^7.0.0",
- "three": "0.186.0",
- "webgpu": "0.6.1"
- },
- "allowScripts": {
- }
-}
+{
+ "name": "kiln-render-service",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.",
+ "scripts": {
+ "start": "node --import ./src/register-hooks.mjs src/server.mjs",
+ "test": "node --test test/bind-policy.test.mjs test/beauty-camera.test.mjs test/display-output.test.mjs test/readback.test.mjs test/cache-identity.test.mjs test/asset-camera.test.mjs test/contract.test.mjs test/framing.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs test/gallery-presentation.test.mjs test/display-transform.test.mjs test/instance.test.mjs",
+ "smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs",
+ "conformance:display": "node --import ./src/register-hooks.mjs test/display-output-conformance.mjs",
+ "conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"
+ },
+ "dependencies": {
+ "pngjs": "^7.0.0",
+ "three": "0.186.0",
+ "webgpu": "0.6.1"
+ },
+ "allowScripts": {
+ }
+}
diff --git a/render-service/src/health-contract.mjs b/render-service/src/health-contract.mjs
index f86de311..4b825a73 100644
--- a/render-service/src/health-contract.mjs
+++ b/render-service/src/health-contract.mjs
@@ -18,10 +18,13 @@ export const RENDER_CAPABILITIES = Object.freeze([
'auth.x-render-token',
]);
-export function buildHealthDocument(gpuState, authRequired) {
+export function buildHealthDocument(gpuState, authRequired, instance) {
return {
ok: true,
...(gpuState.captureIdentity ? { captureIdentity: gpuState.captureIdentity } : {}),
+ // Who is listening: pid, owner lease and source fingerprint, so a host can
+ // tell a current shared renderer from a stale orphan. See instance.mjs.
+ ...(instance ? { instance } : {}),
rendererId: gpuState.rendererId,
backend: gpuState.backend,
adapter: gpuState.summary,
diff --git a/render-service/src/instance.mjs b/render-service/src/instance.mjs
new file mode 100644
index 00000000..2a5b3b06
--- /dev/null
+++ b/render-service/src/instance.mjs
@@ -0,0 +1,105 @@
+/**
+ * Who this process is, for a host that has to decide whether to join it,
+ * replace it, or leave it alone.
+ *
+ * The service listens on one shared port per machine, and the host that finds
+ * something listening there has three questions it could not answer before:
+ * is it a render service at all, is it running the source that is on disk, and
+ * is anyone still using it. `/health` now carries the answers as `instance`, so
+ * the socket itself is the registry -- there is no lease file that could
+ * disagree with what is actually listening.
+ *
+ * `ownerPid` is the process that started this one on demand. It exists for two
+ * reasons. A host that finds an orphan running stale source may replace it,
+ * where it must not touch a service somebody started by hand or is still
+ * using. And on Windows a hard-killed host cannot run its exit hook, so the
+ * service watches the owner itself and exits when it is gone (see
+ * {@link startOwnerWatch}); a service started by hand has no owner and never
+ * exits on its own.
+ *
+ * The engine mirrors {@link fingerprintSourceDir} in `src/render-service-host.ts`
+ * and a test there fails if the two ever disagree on a directory.
+ */
+import { createHash } from 'node:crypto';
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+/**
+ * A digest of every file under `dir`, in sorted relative-path order, skipping
+ * `node_modules`. Path, length and bytes all enter the hash, so a rename, a
+ * truncation and an edit each change it. Deliberately NOT the capture-identity
+ * fingerprint: that one includes the installed renderer packages, the Node
+ * version and the adapter, none of which the engine can compute for itself.
+ */
+export function fingerprintSourceDir(dir) {
+ const hash = createHash('sha256');
+ hash.update('kiln.render-service-source.v1');
+ const visit = (path) => {
+ if (statSync(path).isDirectory()) {
+ for (const name of readdirSync(path).sort()) {
+ if (name === 'node_modules') continue;
+ visit(join(path, name));
+ }
+ return;
+ }
+ const bytes = readFileSync(path);
+ hash.update(JSON.stringify([relative(dir, path).replaceAll('\\', '/'), bytes.length]));
+ hash.update(bytes);
+ };
+ visit(dir);
+ return `sha256:${hash.digest('hex')}`;
+}
+
+/** The owner pid from the environment, or undefined when nothing valid was given. */
+export function parseOwnerPid(raw) {
+ const pid = Number(raw);
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
+}
+
+/** Whether `pid` is a live process. EPERM means it exists and is not ours to signal. */
+export function processIsAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error?.code === 'EPERM';
+ }
+}
+
+/**
+ * Poll the owner and call `onOrphaned` exactly once when it is gone.
+ *
+ * Injected timers and liveness so the rule is testable in milliseconds without
+ * a real process to kill. Returns the stop function.
+ */
+export function startOwnerWatch({
+ ownerPid,
+ onOrphaned,
+ isAlive = processIsAlive,
+ intervalMs = 2_000,
+ setTimer = setInterval,
+ clearTimer = clearInterval,
+}) {
+ let fired = false;
+ const handle = setTimer(() => {
+ if (fired || isAlive(ownerPid)) return;
+ fired = true;
+ clearTimer(handle);
+ onOrphaned(ownerPid);
+ }, intervalMs);
+ // Never the reason the process stays up: the listening socket is.
+ if (typeof handle?.unref === 'function') handle.unref();
+ return () => clearTimer(handle);
+}
+
+/** The `instance` block of `/health`. Frozen at boot; nothing in it is a secret. */
+export function describeInstance({ pid, ownerPid, startedAt, sourceDir, sourceFingerprint }) {
+ return Object.freeze({
+ version: 'kiln.render-service-instance.v1',
+ pid,
+ ownerPid: ownerPid ?? null,
+ startedAt,
+ sourceDir,
+ sourceFingerprint,
+ });
+}
diff --git a/render-service/src/server.mjs b/render-service/src/server.mjs
index 8481e572..d3cd4921 100644
--- a/render-service/src/server.mjs
+++ b/render-service/src/server.mjs
@@ -24,7 +24,16 @@
// bind-policy.mjs, which refuses the boot rather than warning about it.
// Renders are serialized: one GPU, one queue.
import { createServer } from 'node:http';
+import { realpathSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
import { PRESENTATION_PROFILE_ID, initRenderer, renderGlb } from './renderer.mjs';
+import {
+ describeInstance,
+ fingerprintSourceDir,
+ parseOwnerPid,
+ startOwnerWatch,
+} from './instance.mjs';
import { acquireGpu } from './gpu.mjs';
import { buildHealthDocument } from './health-contract.mjs';
import { describeBind, resolveBindPolicy } from './bind-policy.mjs';
@@ -42,6 +51,18 @@ import {
const PROCESS_STARTED_AT = performance.now();
const PORT = Number(process.env.PORT ?? 8000);
+// Who this process is, answered on /health so the host that finds it can tell a
+// current shared renderer from a stale orphan. The owner is the host that
+// started it on demand; a hand-started service has none and outlives sessions.
+const SOURCE_DIR = fileURLToPath(new URL('.', import.meta.url));
+const OWNER_PID = parseOwnerPid(process.env.RENDER_SERVICE_OWNER_PID);
+const INSTANCE = describeInstance({
+ pid: process.pid,
+ ownerPid: OWNER_PID,
+ startedAt: new Date().toISOString(),
+ sourceDir: realpathSync(dirname(SOURCE_DIR)),
+ sourceFingerprint: fingerprintSourceDir(SOURCE_DIR),
+});
const TOKEN = process.env.RENDER_SERVICE_TOKEN ?? '';
// Unset now means loopback, and a wider bind has to say so AND carry a token.
// `bind-policy.mjs` owns that rule and the reasoning; the container sets
@@ -153,7 +174,7 @@ const server = createServer(async (req, res) => {
// no commit stamp, so this is the only way a caller can tell WHICH build is
// live before depending on a feature. The pure builder is contract-tested
// without booting a GPU and advertises every registry ID explicitly.
- return done(200, buildHealthDocument(gpuState, Boolean(TOKEN)));
+ return done(200, buildHealthDocument(gpuState, Boolean(TOKEN), INSTANCE));
}
if (req.method === 'POST' && (req.url === '/render' || req.url === '/bake')) {
if (TOKEN) {
@@ -321,6 +342,19 @@ const server = createServer(async (req, res) => {
}
});
+// A host that dies without running its exit hook -- a hard kill, which is the
+// only kind Windows has -- would otherwise leave this process holding the GPU
+// on the shared port forever. Watching the owner is what makes an on-demand
+// start safe to forget about.
+if (OWNER_PID !== undefined)
+ startOwnerWatch({
+ ownerPid: OWNER_PID,
+ onOrphaned: (pid) => {
+ console.error(`owner process ${pid} is gone; exiting`);
+ process.exit(0);
+ },
+ });
+
server.listen(PORT, bind.host, () =>
console.log(
`kiln-render-service listening on ${describeBind(bind, { token: TOKEN, allowUnauthenticated: process.env.RENDER_SERVICE_ALLOW_UNAUTHENTICATED })}:${PORT}`,
diff --git a/render-service/test/instance.test.mjs b/render-service/test/instance.test.mjs
new file mode 100644
index 00000000..19ccd9a7
--- /dev/null
+++ b/render-service/test/instance.test.mjs
@@ -0,0 +1,119 @@
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve, sep } from 'node:path';
+import test from 'node:test';
+
+import { buildHealthDocument } from '../src/health-contract.mjs';
+import {
+ describeInstance,
+ fingerprintSourceDir,
+ parseOwnerPid,
+ processIsAlive,
+ startOwnerWatch,
+} from '../src/instance.mjs';
+
+// Pure, like every other test in this directory: no GPU, no socket, no Dawn.
+
+function scratch() {
+ const dir = mkdtempSync(join(tmpdir(), 'kiln-instance-'));
+ assert.ok(resolve(dir).startsWith(resolve(tmpdir()) + sep));
+ return dir;
+}
+
+test('the source fingerprint is stable, and changes with content, name and length', () => {
+ const dir = scratch();
+ try {
+ mkdirSync(join(dir, 'nested'));
+ writeFileSync(join(dir, 'server.mjs'), 'one');
+ writeFileSync(join(dir, 'nested', 'a.mjs'), 'aa');
+ const first = fingerprintSourceDir(dir);
+ assert.match(first, /^sha256:[0-9a-f]{64}$/);
+ assert.equal(fingerprintSourceDir(dir), first);
+
+ writeFileSync(join(dir, 'server.mjs'), 'two');
+ const edited = fingerprintSourceDir(dir);
+ assert.notEqual(edited, first);
+
+ // Installed packages are not source: a `node_modules` under the tree is
+ // ignored, so `npm install` does not read as an edit.
+ mkdirSync(join(dir, 'node_modules', 'x'), { recursive: true });
+ writeFileSync(join(dir, 'node_modules', 'x', 'index.js'), 'ignored');
+ assert.equal(fingerprintSourceDir(dir), edited);
+
+ writeFileSync(join(dir, 'nested', 'b.mjs'), 'aa');
+ assert.notEqual(fingerprintSourceDir(dir), edited, 'a new file changes it');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('an owner pid is a positive integer or nothing', () => {
+ assert.equal(parseOwnerPid('4242'), 4242);
+ assert.equal(parseOwnerPid(undefined), undefined);
+ assert.equal(parseOwnerPid(''), undefined);
+ assert.equal(parseOwnerPid('0'), undefined);
+ assert.equal(parseOwnerPid('-3'), undefined);
+ assert.equal(parseOwnerPid('abc'), undefined);
+});
+
+test('this process is alive; a pid nothing has is not', () => {
+ assert.equal(processIsAlive(process.pid), true);
+ // The largest pid Windows or Linux will hand out is far below this.
+ assert.equal(processIsAlive(2 ** 22 + 12345), false);
+});
+
+test('the owner watch fires once, when the owner is gone, and then stops polling', () => {
+ const timers = [];
+ let alive = true;
+ const orphaned = [];
+ const stop = startOwnerWatch({
+ ownerPid: 77,
+ isAlive: () => alive,
+ onOrphaned: (pid) => orphaned.push(pid),
+ intervalMs: 5,
+ setTimer: (fn) => {
+ const handle = { fn, cleared: false, unref: () => undefined };
+ timers.push(handle);
+ return handle;
+ },
+ clearTimer: (handle) => {
+ handle.cleared = true;
+ },
+ });
+ const tick = () => timers[0].fn();
+ tick();
+ tick();
+ assert.deepEqual(orphaned, [], 'a live owner is left alone');
+ alive = false;
+ tick();
+ tick();
+ assert.deepEqual(orphaned, [77], 'fires exactly once');
+ assert.equal(timers[0].cleared, true, 'and stops polling afterwards');
+ stop();
+});
+
+test('the health document carries the instance block when one is given', () => {
+ const gpuState = {
+ rendererId: 'dawn-test:gpu:1',
+ backend: 'test',
+ summary: { device: 'test' },
+ };
+ const instance = describeInstance({
+ pid: 123,
+ ownerPid: undefined,
+ startedAt: '2026-09-16T00:00:00.000Z',
+ sourceDir: '/srv/render-service',
+ sourceFingerprint: `sha256:${'a'.repeat(64)}`,
+ });
+ assert.deepEqual(buildHealthDocument(gpuState, false, instance).instance, {
+ version: 'kiln.render-service-instance.v1',
+ pid: 123,
+ ownerPid: null,
+ startedAt: '2026-09-16T00:00:00.000Z',
+ sourceDir: '/srv/render-service',
+ sourceFingerprint: `sha256:${'a'.repeat(64)}`,
+ });
+ // Without one the document is exactly what it was.
+ assert.equal('instance' in buildHealthDocument(gpuState, false), false);
+});
diff --git a/scripts/tier2-dogfood.mjs b/scripts/tier2-dogfood.mjs
index 87dae129..72cf30d5 100644
--- a/scripts/tier2-dogfood.mjs
+++ b/scripts/tier2-dogfood.mjs
@@ -441,6 +441,76 @@ async function evidenceFromFiles(stdoutPath, stderrPath) {
return evidence;
}
+/** The workspace MCP tools, by their unprefixed names; a harness adds its own prefix. */
+const KILN_MCP_TOOL =
+ /kiln_(?:list_primitives|validate|render|screenshot_animation|view_interior|inspect|edit|source|save|assets|present|export|import)\b/u;
+
+/**
+ * Every tool call in a trace, counted by name, and whether any of them reached the
+ * workspace MCP server. The receipt needs this because a run can succeed without
+ * it: an outer agent that dispatches an in-session subagent never loads the
+ * workspace's MCP configuration, and the child then works through the CLI alone.
+ * That is a finding about the MCP path, not a failure, and it was invisible until
+ * someone read the trace by hand.
+ *
+ * Shapes recognised: OpenCode (`{type:'tool_use', part:{tool}}`), Claude stream
+ * JSON (`{type:'tool_use', name}` inside message content), Codex JSONL
+ * (`{type:'mcp_tool_call', server, tool}` and `command_execution` items). Anything
+ * else counts as no tool calls, which the receipt reports as `unknown` rather than
+ * as `not-exercised`.
+ */
+export function toolUsageFromEvents(events) {
+ const calls = {};
+ const record = (name) => {
+ if (typeof name !== 'string' || !name) return;
+ calls[name] = (calls[name] ?? 0) + 1;
+ };
+ const visit = (node) => {
+ if (Array.isArray(node)) {
+ for (const item of node) visit(item);
+ return;
+ }
+ if (!node || typeof node !== 'object') return;
+ if (node.type === 'tool_use') {
+ record(node.name ?? node.tool ?? node.part?.tool);
+ return;
+ }
+ if (node.type === 'mcp_tool_call') {
+ record(`${node.server ?? 'mcp'}__${node.tool ?? 'unknown'}`);
+ return;
+ }
+ if (node.type === 'command_execution') {
+ record('command_execution');
+ return;
+ }
+ for (const value of Object.values(node)) if (value && typeof value === 'object') visit(value);
+ };
+ for (const event of events) visit(event);
+ const total = Object.values(calls).reduce((sum, count) => sum + count, 0);
+ const mcpCalls = Object.entries(calls)
+ .filter(([name]) => KILN_MCP_TOOL.test(name))
+ .reduce((sum, [, count]) => sum + count, 0);
+ return {
+ calls,
+ total,
+ mcpCalls,
+ workspaceMcp: total === 0 ? 'unknown' : mcpCalls > 0 ? 'exercised' : 'not-exercised',
+ };
+}
+
+async function toolUsageFromFile(stdoutPath) {
+ const events = [];
+ const stdout = createInterface({ input: createReadStream(stdoutPath), crlfDelay: Infinity });
+ for await (const line of stdout) {
+ try {
+ events.push(JSON.parse(line));
+ } catch {
+ // Prose, not an event.
+ }
+ }
+ return toolUsageFromEvents(events);
+}
+
function killProcessTree(child, signal = 'SIGTERM') {
if (!child.pid) return;
if (process.platform === 'win32') {
@@ -872,6 +942,7 @@ async function main(argv) {
signal: abort.signal,
});
const evidence = await evidenceFromFiles(stdoutPath, stderrPath);
+ const toolUsage = await toolUsageFromFile(stdoutPath);
const artifacts = discoverArtifacts(workspaceRoot).filter(
(artifact) =>
!artifactsBefore.has(`${artifact.kind}\0${artifact.path}\0${artifact.sha256}`),
@@ -909,6 +980,7 @@ async function main(argv) {
rawTraceDirectory: rawDir,
isolation: plan.invocation.isolation,
failureEvidence: evidence.slice(0, 20),
+ toolUsage,
artifactCandidates: artifacts,
localGallery: galleryCapture
? {
diff --git a/scripts/tier2-dogfood.test.mjs b/scripts/tier2-dogfood.test.mjs
index 799283a8..94c9b00d 100644
--- a/scripts/tier2-dogfood.test.mjs
+++ b/scripts/tier2-dogfood.test.mjs
@@ -15,6 +15,7 @@ import {
receiptPathReplacements,
runProcess,
sanitizeReceipt,
+ toolUsageFromEvents,
} from './tier2-dogfood.mjs';
const roots = [];
@@ -341,6 +342,57 @@ describe('Tier 2 blind dogfood driver', () => {
expect(evidenceFromTrace('', 'Reading additional input from stdin...\n')).toEqual([]);
});
+ test('the receipt says whether the workspace MCP server was exercised at all', () => {
+ // The blind OpenCode run of 2026-09-16 completed through the CLI alone: the
+ // outer agent dispatched an in-session subagent that never saw the
+ // workspace's MCP server. Nothing in the receipt said so.
+ const opencode = [
+ { type: 'tool_use', part: { type: 'tool', tool: 'bash', state: { status: 'completed' } } },
+ { type: 'tool_use', part: { type: 'tool', tool: 'read' } },
+ { type: 'tool_use', part: { type: 'tool', tool: 'bash' } },
+ { type: 'text', part: { text: 'kiln_render is a tool name in prose, not a call' } },
+ ];
+ expect(toolUsageFromEvents(opencode)).toEqual({
+ calls: { bash: 2, read: 1 },
+ total: 3,
+ mcpCalls: 0,
+ workspaceMcp: 'not-exercised',
+ });
+
+ const claude = [
+ {
+ type: 'assistant',
+ message: {
+ content: [
+ { type: 'text', text: 'rendering' },
+ { type: 'tool_use', name: 'mcp__kiln_workspace__kiln_render', input: {} },
+ { type: 'tool_use', name: 'Read', input: {} },
+ ],
+ },
+ },
+ { type: 'tool_use', part: { tool: 'kiln_workspace_kiln_save' } },
+ ];
+ expect(toolUsageFromEvents(claude)).toMatchObject({
+ total: 3,
+ mcpCalls: 2,
+ workspaceMcp: 'exercised',
+ });
+
+ const codex = [
+ { type: 'item.completed', item: { type: 'command_execution', command: 'ls' } },
+ {
+ type: 'item.completed',
+ item: { type: 'mcp_tool_call', server: 'kiln_workspace', tool: 'kiln_render' },
+ },
+ ];
+ expect(toolUsageFromEvents(codex)).toMatchObject({
+ calls: { command_execution: 1, kiln_workspace__kiln_render: 1 },
+ workspaceMcp: 'exercised',
+ });
+
+ expect(toolUsageFromEvents([{ type: 'text' }]).workspaceMcp).toBe('unknown');
+ });
+
test('a source and GLB are necessary but remain pending human quality review', () => {
expect(
classifyOutcome({
diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.md
index 33d739d7..1295dee9 100644
--- a/skills/kiln-setup-workspace/SKILL.md
+++ b/skills/kiln-setup-workspace/SKILL.md
@@ -46,7 +46,7 @@ Offer to run its install. It lives in the engine installation rather than the wo
cd render-service && npm install
```
-That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure.
+That is the whole setup. Once installed, the MCP server starts the service on the first view that needs PBR shading and stops it when the session ends, so there is no terminal to leave running and no ordering to get right -- except one: install it *before* the session that will use it, because the server checks at startup whether a renderer could run here and a session older than the install stays on CPU for its lifetime. Add `npm start` only when the service should outlive a single session, such as one GPU shared by a batch of dispatched agents; it binds loopback, and widening that with `HOST` requires `RENDER_SERVICE_TOKEN`. If the machine has no usable GPU, report that and continue on CPU views; it is a limit to state, not a setup failure. `bun run kiln service status` in the engine checkout shows who is listening on the shared port and whether it runs current source; a renderer left over from before a pull is replaced automatically when nobody owns it, and `kiln service stop` clears one that is.
## Verify the loadout before authoring
diff --git a/src/__tests__/cli-service-lifecycle.test.ts b/src/__tests__/cli-service-lifecycle.test.ts
index b732b752..1ff510be 100644
--- a/src/__tests__/cli-service-lifecycle.test.ts
+++ b/src/__tests__/cli-service-lifecycle.test.ts
@@ -15,6 +15,8 @@ import type { AddressInfo } from 'node:net';
import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
+import { writeFakeRenderService } from './helpers/fake-render-service';
+
/** A port nothing is listening on right now. */
async function freePort(): Promise<number> {
const server = createServer();
@@ -35,59 +37,6 @@ async function listening(port: number): Promise<boolean> {
}
}
-/**
- * A stand-in for render-service/: what `localRenderServiceState` needs to call
- * it ready, plus a server that answers `/health` and `/render` with one flat PNG
- * per requested view. `gpu` mode requires the GPU render to succeed, so the
- * answer has to pass the port's PNG validation; the pixels do not matter, the
- * process does.
- */
-const FAKE_SERVER = `
-import { createServer } from 'node:http';
-import { crc32, deflateSync } from 'node:zlib';
-const chunk = (type, data) => {
- const length = Buffer.alloc(4);
- length.writeUInt32BE(data.length);
- const body = Buffer.concat([Buffer.from(type), data]);
- const crc = Buffer.alloc(4);
- crc.writeUInt32BE(crc32(body));
- return Buffer.concat([length, body, crc]);
-};
-const png = (size) => {
- const ihdr = Buffer.alloc(13);
- ihdr.writeUInt32BE(size, 0);
- ihdr.writeUInt32BE(size, 4);
- ihdr[8] = 8;
- ihdr[9] = 2;
- const raw = Buffer.alloc(size * (1 + size * 3), 0x80);
- for (let y = 0; y < size; y++) raw[y * (1 + size * 3)] = 0;
- return Buffer.concat([
- Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
- chunk('IHDR', ihdr),
- chunk('IDAT', deflateSync(raw)),
- chunk('IEND', Buffer.alloc(0)),
- ]);
-};
-createServer((req, res) => {
- let body = '';
- req.on('data', (piece) => {
- body += piece;
- });
- req.on('end', () => {
- res.writeHead(200, { 'content-type': 'application/json' });
- if (req.url === '/health') {
- res.end(JSON.stringify({ ok: true, rendererId: 'fake-renderer' }));
- return;
- }
- const request = body ? JSON.parse(body) : {};
- const count = (request.views ?? request.cameras ?? []).length;
- const size = request.size ?? request.width ?? 384;
- const views = Array.from({ length: count }, () => png(size).toString('base64'));
- res.end(JSON.stringify({ ok: true, rendererId: 'fake-renderer', views }));
- });
-}).listen(Number(process.env.PORT), process.env.HOST ?? '127.0.0.1');
-`;
-
it('stops a render service the CLI started once the command settles, instead of hanging on it', async () => {
const base = resolve(import.meta.dir, '../../tmp');
await mkdir(base, { recursive: true });
@@ -102,13 +51,7 @@ it('stops a render service the CLI started once the command settles, instead of
});
expect(built.success).toBe(true);
- const service = join(directory, 'render-service');
- await mkdir(join(service, 'src'), { recursive: true });
- await mkdir(join(service, 'node_modules/webgpu'), { recursive: true });
- await mkdir(join(service, 'node_modules/three'), { recursive: true });
- await writeFile(join(service, 'package.json'), '{"name":"fake-render-service"}');
- await writeFile(join(service, 'src/register-hooks.mjs'), 'export {};');
- await writeFile(join(service, 'src/server.mjs'), FAKE_SERVER);
+ const service = await writeFakeRenderService(join(directory, 'render-service'));
const port = await freePort();
expect(await listening(port)).toBe(false);
diff --git a/src/__tests__/helpers/fake-render-service.ts b/src/__tests__/helpers/fake-render-service.ts
new file mode 100644
index 00000000..3dc1f067
--- /dev/null
+++ b/src/__tests__/helpers/fake-render-service.ts
@@ -0,0 +1,138 @@
+/**
+ * A stand-in for `render-service/`: what `localRenderServiceState` needs to
+ * call it ready, plus a server that answers `/health` like the real one and
+ * `/render` with one flat PNG per requested view. Tests that need a render
+ * service they can spawn, kill and inspect as a real process share this file,
+ * so the health contract the host reads is written down once.
+ *
+ * The PNG passes the port's validation; the pixels do not matter, the process
+ * does. `/health` reports the same `instance` block the real service does, with
+ * the source fingerprint taken from `FAKE_SOURCE_FINGERPRINT` so a test can
+ * make the process look current or stale without editing files.
+ */
+import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { join } from 'node:path';
+
+export const FAKE_RENDERER_ID = 'fake-renderer';
+
+export const FAKE_SERVER = `
+import { createServer } from 'node:http';
+import { crc32, deflateSync } from 'node:zlib';
+const chunk = (type, data) => {
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(data.length);
+ const body = Buffer.concat([Buffer.from(type), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(body));
+ return Buffer.concat([length, body, crc]);
+};
+const png = (size) => {
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(size, 0);
+ ihdr.writeUInt32BE(size, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ const raw = Buffer.alloc(size * (1 + size * 3), 0x80);
+ for (let y = 0; y < size; y++) raw[y * (1 + size * 3)] = 0;
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(raw)),
+ chunk('IEND', Buffer.alloc(0)),
+ ]);
+};
+const ownerPid = Number(process.env.RENDER_SERVICE_OWNER_PID);
+const instance = {
+ version: 'kiln.render-service-instance.v1',
+ pid: process.pid,
+ ownerPid: Number.isInteger(ownerPid) && ownerPid > 0 ? ownerPid : null,
+ startedAt: new Date().toISOString(),
+ sourceDir: process.env.FAKE_SOURCE_DIR ?? process.cwd(),
+ sourceFingerprint: process.env.FAKE_SOURCE_FINGERPRINT ?? 'sha256:' + 'f'.repeat(64),
+};
+createServer((req, res) => {
+ let body = '';
+ req.on('data', (piece) => {
+ body += piece;
+ });
+ req.on('end', () => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ if (req.url === '/health') {
+ res.end(JSON.stringify({ ok: true, rendererId: '${FAKE_RENDERER_ID}', instance }));
+ return;
+ }
+ const request = body ? JSON.parse(body) : {};
+ const count = (request.views ?? request.cameras ?? []).length;
+ const size = request.size ?? request.width ?? 384;
+ const views = Array.from({ length: count }, () => png(size).toString('base64'));
+ res.end(JSON.stringify({ ok: true, rendererId: '${FAKE_RENDERER_ID}', views }));
+ });
+}).listen(Number(process.env.PORT), process.env.HOST ?? '127.0.0.1', () => {
+ if (process.env.FAKE_ANNOUNCE) console.log('listening');
+});
+`;
+
+/** A port nothing is listening on right now. */
+export async function freePort(): Promise<number> {
+ const server = createServer();
+ await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
+ const { port } = server.address() as AddressInfo;
+ await new Promise<void>((done) => server.close(() => done()));
+ return port;
+}
+
+/** A pid that belonged to a process which has already exited. */
+export function deadPid(): number {
+ const gone = spawnSync('node', ['-e', '']);
+ if (!gone.pid) throw new Error('could not spawn a throwaway process');
+ return gone.pid;
+}
+
+/**
+ * Spawn the fake service under `dir` as a real process on `port`, resolved once
+ * it is listening. The caller owns the child and kills it in its afterEach.
+ */
+export async function spawnFakeRenderService(
+ dir: string,
+ port: number,
+ env: Record<string, string> = {},
+): Promise<ChildProcess> {
+ const child = spawn('node', [join(dir, 'src/server.mjs')], {
+ cwd: dir,
+ env: { ...process.env, PORT: String(port), HOST: '127.0.0.1', FAKE_ANNOUNCE: '1', ...env },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+ await new Promise<void>((done, fail) => {
+ child.stdout!.on('data', (chunk: Buffer) => {
+ if (chunk.toString().includes('listening')) done();
+ });
+ child.once('exit', (code) => fail(new Error(`fake service exited with ${code}`)));
+ });
+ return child;
+}
+
+/** Resolve once `child` has exited: a kill is synchronous, the exit event is not. */
+export function exited(child: ChildProcess, timeoutMs = 5_000): Promise<boolean> {
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
+ return new Promise((done) => {
+ const timer = setTimeout(() => done(false), timeoutMs);
+ child.once('exit', () => {
+ clearTimeout(timer);
+ done(true);
+ });
+ });
+}
+
+/** Lay the fake service out under `dir` so the host reads it as installed. */
+export async function writeFakeRenderService(dir: string): Promise<string> {
+ await mkdir(join(dir, 'src'), { recursive: true });
+ await mkdir(join(dir, 'node_modules/webgpu'), { recursive: true });
+ await mkdir(join(dir, 'node_modules/three'), { recursive: true });
+ await writeFile(join(dir, 'package.json'), '{"name":"fake-render-service"}');
+ await writeFile(join(dir, 'src/register-hooks.mjs'), 'export {};');
+ await writeFile(join(dir, 'src/server.mjs'), FAKE_SERVER);
+ return dir;
+}
diff --git a/src/__tests__/mcp-bundle.test.ts b/src/__tests__/mcp-bundle.test.ts
index 1fdcc1b8..cc25970d 100644
--- a/src/__tests__/mcp-bundle.test.ts
+++ b/src/__tests__/mcp-bundle.test.ts
@@ -70,11 +70,11 @@ describe('mcp server bundle', () => {
*/
it('serves the full tool surface when launched with node', async () => {
// Compare against the MCP surface, not `createKilnToolRegistry()`. Those
- // are deliberately different: the registry is the frozen four-tool bench
- // baseline whose `kiln_screenshot` is CPU-only by construction, and the MCP
- // server publishes the unified six, including the render-port-backed
- // `kiln_render`. `src/mcp-parity.test.ts` owns that distinction; this test
- // only has to prove the bundle publishes whatever the server says it does.
+ // are deliberately different: the registry is the in-process loop's four
+ // tools, and the MCP server publishes the unified surface, where one
+ // `kiln_render` carries the image. `src/mcp-parity.test.ts` owns that
+ // distinction; this test only has to prove the bundle publishes whatever
+ // the server says it does.
const expected = kilnMcpToolDefs()
.map((t) => t.name)
.sort();
diff --git a/src/__tests__/render-service-lifecycle.test.ts b/src/__tests__/render-service-lifecycle.test.ts
new file mode 100644
index 00000000..4807dfb6
--- /dev/null
+++ b/src/__tests__/render-service-lifecycle.test.ts
@@ -0,0 +1,354 @@
+/**
+ * Finding, joining, replacing and leaving alone the render service on the
+ * shared port.
+ *
+ * Before this, the host asked one question of whatever was listening on port
+ * 8000 -- "does /health say ok" -- and joined it. That was the last way a
+ * developer could reach a confusing state instead of a clean fallback: a
+ * service orphaned by a hard-killed session kept running yesterday's source
+ * after a pull, every session joined it, and the engine's new request field
+ * came back as a 400 that the sheet reported as a CPU degrade. Nothing was
+ * broken, and nothing said what was wrong.
+ *
+ * The socket is now the registry. `/health` names the process, the session
+ * that started it and a fingerprint of the source it runs, and the host acts on
+ * that in exactly one way per case:
+ *
+ * current -> join, whoever started it
+ * stale and orphaned -> replace it
+ * stale and still owned -> leave it, say who owns it and how to clear it
+ * stale and started by hand -> leave it, say how to clear it
+ * not a render service -> say the port is taken and how to move
+ */
+import type { ChildProcess } from 'node:child_process';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'bun:test';
+
+import {
+ inspectLocalRenderService,
+ renderServiceSourceFingerprint,
+ startLocalRenderService,
+ stopLocalRenderService,
+ type RenderServiceInstance,
+} from '../render-service-host';
+import { buildRenderPort, describeRenderMode, makeLazyRenderPort } from '../cli-render-mode';
+import {
+ FAKE_RENDERER_ID,
+ deadPid,
+ exited,
+ freePort,
+ spawnFakeRenderService,
+ writeFakeRenderService,
+} from './helpers/fake-render-service';
+
+const servers: Server[] = [];
+const children: ChildProcess[] = [];
+const directories: string[] = [];
+const savedPort = process.env['KILN_RENDER_SERVICE_PORT'];
+
+afterEach(async () => {
+ stopLocalRenderService();
+ for (const child of children.splice(0)) if (child.exitCode === null) child.kill();
+ await Promise.all(
+ servers.splice(0).map((s) => new Promise<void>((done) => s.close(() => done()))),
+ );
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((d) => rm(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })),
+ );
+ if (savedPort === undefined) delete process.env['KILN_RENDER_SERVICE_PORT'];
+ else process.env['KILN_RENDER_SERVICE_PORT'] = savedPort;
+});
+
+async function scratch(): Promise<string> {
+ const base = resolve(import.meta.dir, '../../tmp');
+ await mkdir(base, { recursive: true });
+ const dir = await mkdtemp(join(base, 'service-lifecycle-'));
+ directories.push(dir);
+ return dir;
+}
+
+/** An in-process stand-in whose `/health` says whatever the test needs. */
+function serve(health: unknown, status = 200): Promise<string> {
+ const server = createServer((_req, res) => {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(typeof health === 'string' ? health : JSON.stringify(health));
+ });
+ servers.push(server);
+ return new Promise((done) => {
+ server.listen(0, '127.0.0.1', () =>
+ done(`http://127.0.0.1:${(server.address() as AddressInfo).port}`),
+ );
+ });
+}
+
+function instance(overrides: Partial<RenderServiceInstance> = {}): RenderServiceInstance {
+ return {
+ version: 'kiln.render-service-instance.v1',
+ pid: process.pid,
+ ownerPid: null,
+ startedAt: '2026-09-16T00:00:00.000Z',
+ sourceDir: '/elsewhere/render-service',
+ sourceFingerprint: `sha256:${'a'.repeat(64)}`,
+ ...overrides,
+ };
+}
+
+async function health(url: string): Promise<{ ok?: boolean; instance?: RenderServiceInstance }> {
+ return (await (await fetch(new URL('/health', url))).json()) as never;
+}
+
+/** Spawn the fake service as a real process the host can kill. */
+async function spawnFake(
+ dir: string,
+ port: number,
+ env: Record<string, string>,
+): Promise<ChildProcess> {
+ const child = await spawnFakeRenderService(dir, port, env);
+ children.push(child);
+ return child;
+}
+
+describe('renderServiceSourceFingerprint', () => {
+ it('agrees with the service’s own implementation on the same directory', async () => {
+ // The service hashes its source at boot and reports it on /health; the
+ // host hashes the source on disk and compares. Two implementations of one
+ // walk, so this is the test that keeps them one.
+ const service = (await import(
+ join(import.meta.dir, '..', '..', 'render-service', 'src', 'instance.mjs')
+ )) as { fingerprintSourceDir: (dir: string) => string };
+ const dir = await scratch();
+ await mkdir(join(dir, 'src', 'nested'), { recursive: true });
+ await writeFile(join(dir, 'src', 'server.mjs'), 'export const a = 1;\n');
+ await writeFile(join(dir, 'src', 'nested', 'b.mjs'), 'export const b = 2;\n');
+ await mkdir(join(dir, 'src', 'node_modules', 'x'), { recursive: true });
+ await writeFile(join(dir, 'src', 'node_modules', 'x', 'index.js'), 'ignored');
+ expect(renderServiceSourceFingerprint(dir)).toBe(
+ service.fingerprintSourceDir(join(dir, 'src')),
+ );
+ expect(renderServiceSourceFingerprint(dir)).toMatch(/^sha256:[0-9a-f]{64}$/);
+ });
+
+ it('is undefined for an installation that does not ship the source', async () => {
+ expect(renderServiceSourceFingerprint(join(await scratch(), 'nothing'))).toBeUndefined();
+ });
+});
+
+describe('inspectLocalRenderService', () => {
+ it('reports nothing listening as absent, fast', async () => {
+ const port = await freePort();
+ const started = Date.now();
+ const probe = await inspectLocalRenderService(`http://127.0.0.1:${port}`, await scratch());
+ expect(probe).toEqual({ kind: 'absent' });
+ expect(Date.now() - started).toBeLessThan(1_500);
+ });
+
+ it('reports something that is not a render service as foreign', async () => {
+ expect(await inspectLocalRenderService(await serve('<html>'), await scratch())).toEqual({
+ kind: 'foreign',
+ });
+ expect(
+ await inspectLocalRenderService(await serve({ ok: false }, 503), await scratch()),
+ ).toEqual({ kind: 'foreign' });
+ });
+
+ it('reads a current service as current, whoever started it', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const fingerprint = renderServiceSourceFingerprint(dir)!;
+ const url = await serve({
+ ok: true,
+ rendererId: 'r',
+ instance: instance({ sourceFingerprint: fingerprint, ownerPid: null }),
+ });
+ expect(await inspectLocalRenderService(url, dir)).toMatchObject({
+ kind: 'service',
+ rendererId: 'r',
+ stale: false,
+ orphaned: false,
+ });
+ });
+
+ it('tells a stale orphan from a stale service someone still owns', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const orphan = await serve({
+ ok: true,
+ rendererId: 'r',
+ instance: instance({ ownerPid: deadPid() }),
+ });
+ expect(await inspectLocalRenderService(orphan, dir)).toMatchObject({
+ kind: 'service',
+ stale: true,
+ orphaned: true,
+ });
+ const owned = await serve({
+ ok: true,
+ rendererId: 'r',
+ instance: instance({ ownerPid: process.pid }),
+ });
+ expect(await inspectLocalRenderService(owned, dir)).toMatchObject({
+ kind: 'service',
+ stale: true,
+ orphaned: false,
+ });
+ });
+
+ it('treats a service from before instance reporting as current, not as stale', async () => {
+ // It cannot be compared, and "unknown" must not read as "old": that would
+ // turn every hosted deployment into a refused join.
+ const url = await serve({ ok: true, rendererId: 'r' });
+ expect(await inspectLocalRenderService(url, await scratch())).toMatchObject({
+ kind: 'service',
+ stale: false,
+ orphaned: false,
+ });
+ });
+});
+
+describe('startLocalRenderService on a shared port', () => {
+ it('replaces a stale orphan with a service running the source on disk', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const url = `http://127.0.0.1:${port}`;
+ const orphan = await spawnFake(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(deadPid()),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ expect((await health(url)).instance?.pid).toBe(orphan.pid!);
+
+ // The fresh process reports the fingerprint of the source it was started
+ // from, exactly as the real service does.
+ process.env['FAKE_SOURCE_FINGERPRINT'] = renderServiceSourceFingerprint(dir)!;
+ try {
+ expect(await startLocalRenderService(dir)).toBe(url);
+ } finally {
+ delete process.env['FAKE_SOURCE_FINGERPRINT'];
+ }
+ const after = (await health(url)).instance!;
+ expect(after.pid).not.toBe(orphan.pid!);
+ // The replacement is owned by this session, so it will not outlive it.
+ expect(after.ownerPid).toBe(process.pid);
+ expect(await exited(orphan)).toBe(true);
+ }, 30_000);
+
+ it('leaves a stale service that another session still owns, and says how to clear it', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const owned = await spawnFake(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ await expect(startLocalRenderService(dir)).rejects.toThrow(/older source/);
+ await expect(startLocalRenderService(dir)).rejects.toThrow(/kiln service stop/);
+ await expect(startLocalRenderService(dir)).rejects.toThrow(String(process.pid));
+ expect(owned.exitCode).toBeNull();
+ expect((await health(`http://127.0.0.1:${port}`)).ok).toBe(true);
+ }, 30_000);
+
+ it('says the port is taken, and how to move, when something else holds it', async () => {
+ const url = await serve('<html>');
+ process.env['KILN_RENDER_SERVICE_PORT'] = new URL(url).port;
+ const dir = await writeFakeRenderService(await scratch());
+ await expect(startLocalRenderService(dir)).rejects.toThrow(/not a render service/);
+ await expect(startLocalRenderService(dir)).rejects.toThrow(/KILN_RENDER_SERVICE_PORT/);
+ });
+
+ it('marks the service it starts as its own', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const url = await startLocalRenderService(dir);
+ expect((await health(url)).instance?.ownerPid).toBe(process.pid);
+ }, 30_000);
+});
+
+describe('buildRenderPort on a shared port', () => {
+ it('auto leaves a stale service another session owns alone, attaches nothing, and says why', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const owned = await spawnFake(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ const context = await buildRenderPort('auto', undefined, { serviceDir: dir });
+ // Not attached: attaching would make every CPU sheet report a degrade, and
+ // the reason belongs in the producer line where the user reads it.
+ expect(context.viewRenderPort).toBeUndefined();
+ expect(describeRenderMode(context)).toMatch(/older source/);
+ expect(describeRenderMode(context)).toMatch(/kiln service stop/);
+ expect(owned.exitCode).toBeNull();
+ // `gpu` asked for a guarantee, so it is told the same thing as an error.
+ await expect(buildRenderPort('gpu', undefined, { serviceDir: dir })).rejects.toThrow(
+ /kiln service stop/,
+ );
+ }, 30_000);
+
+ it('auto stops a stale orphan on its way past, and gpu replaces it', async () => {
+ const dir = await writeFakeRenderService(await scratch());
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const url = `http://127.0.0.1:${port}`;
+ const orphan = await spawnFake(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(deadPid()),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ const context = await buildRenderPort('auto', undefined, { serviceDir: dir });
+ expect(context.viewRenderPort).toBeUndefined();
+ expect(describeRenderMode(context)).toMatch(/stopped/);
+ expect(await exited(orphan)).toBe(true);
+ await expect(fetch(new URL('/health', url))).rejects.toThrow();
+
+ process.env['FAKE_SOURCE_FINGERPRINT'] = renderServiceSourceFingerprint(dir)!;
+ try {
+ const demanded = await buildRenderPort('gpu', undefined, { serviceDir: dir });
+ expect(demanded.viewRenderPort).toBeDefined();
+ expect(describeRenderMode(context)).not.toContain(FAKE_RENDERER_ID);
+ // The lazy port starts one on first use, owned by this process.
+ const result = await demanded.viewRenderPort!({ glb: new Uint8Array([1]), viewDirs: [] });
+ expect(result.ok).toBe(true);
+ expect((await health(url)).instance?.ownerPid).toBe(process.pid);
+ } finally {
+ delete process.env['FAKE_SOURCE_FINGERPRINT'];
+ }
+ }, 30_000);
+});
+
+describe('makeLazyRenderPort after the service goes away', () => {
+ it('starts again on the next call instead of failing every render for the rest of the session', async () => {
+ // Session A started the shared renderer and B joined it. A exits and takes
+ // the renderer with it. B's port used to hold A's URL until B restarted;
+ // every render in between was a connection refused reported as a degrade.
+ const ports: number[] = [];
+ const listeners: Server[] = [];
+ const listen = async (): Promise<string> => {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, rendererId: FAKE_RENDERER_ID, views: [] }));
+ });
+ servers.push(server);
+ listeners.push(server);
+ await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
+ ports.push((server.address() as AddressInfo).port);
+ return `http://127.0.0.1:${ports.at(-1)}`;
+ };
+ let starts = 0;
+ const port = makeLazyRenderPort(async () => {
+ starts += 1;
+ return listen();
+ });
+ const glb = new Uint8Array([1, 2, 3]);
+ expect((await port({ glb })).ok).toBe(true);
+ await new Promise<void>((done) => listeners[0]!.close(() => done()));
+
+ expect((await port({ glb })).ok).toBe(true);
+ expect(starts).toBe(2);
+ expect(ports[1]).not.toBe(ports[0]);
+ });
+});
diff --git a/src/__tests__/service-cli.test.ts b/src/__tests__/service-cli.test.ts
new file mode 100644
index 00000000..b6da397e
--- /dev/null
+++ b/src/__tests__/service-cli.test.ts
@@ -0,0 +1,172 @@
+/**
+ * `kiln service status | stop | prune` against real processes on a private port.
+ *
+ * The host acts on a stale orphan by itself; these commands are for the service
+ * it will not touch -- started by hand or owned by a session that is still
+ * running -- and for seeing the facts it acts on. So the tests spawn the fake
+ * service as a process, give it an owner or none, and check both what is
+ * printed and whether the process is still there afterwards.
+ */
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import type { ChildProcess } from 'node:child_process';
+import { mkdir, mkdtemp, rm } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'bun:test';
+
+import { serviceMain } from '../service-cli';
+import { renderServiceSourceFingerprint } from '../render-service-host';
+import {
+ deadPid,
+ freePort,
+ spawnFakeRenderService,
+ writeFakeRenderService,
+} from './helpers/fake-render-service';
+
+const children: ChildProcess[] = [];
+const servers: Server[] = [];
+const directories: string[] = [];
+const saved = {
+ port: process.env['KILN_RENDER_SERVICE_PORT'],
+ dir: process.env['KILN_RENDER_SERVICE_DIR'],
+};
+
+afterEach(async () => {
+ for (const child of children.splice(0)) if (child.exitCode === null) child.kill();
+ await Promise.all(
+ servers.splice(0).map((s) => new Promise<void>((done) => s.close(() => done()))),
+ );
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((d) => rm(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })),
+ );
+ for (const [key, value] of [
+ ['KILN_RENDER_SERVICE_PORT', saved.port],
+ ['KILN_RENDER_SERVICE_DIR', saved.dir],
+ ] as const) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+async function installation(): Promise<{ dir: string; port: number }> {
+ const base = resolve(import.meta.dir, '../../tmp');
+ await mkdir(base, { recursive: true });
+ const dir = await writeFakeRenderService(await mkdtemp(join(base, 'service-cli-')));
+ directories.push(dir);
+ const port = await freePort();
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ process.env['KILN_RENDER_SERVICE_DIR'] = dir;
+ return { dir, port };
+}
+
+async function run(argv: string[]): Promise<{ code: number; out: string; err: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const code = await serviceMain(argv, {
+ log: (line) => out.push(line),
+ error: (line) => err.push(line),
+ });
+ return { code, out: out.join('\n'), err: err.join('\n') };
+}
+
+async function alive(port: number): Promise<boolean> {
+ try {
+ return (await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1_000) }))
+ .ok;
+ } catch {
+ return false;
+ }
+}
+
+describe('kiln service', () => {
+ it('prints usage without a command and refuses one it does not know', async () => {
+ expect((await run([])).code).toBe(2);
+ expect((await run([])).out).toContain('kiln service status');
+ const unknown = await run(['restart']);
+ expect(unknown.code).toBe(2);
+ expect(unknown.err).toContain('unknown service command');
+ });
+
+ it('status says nothing is listening, and where it looked', async () => {
+ const { port } = await installation();
+ const { code, out } = await run(['status']);
+ expect(code).toBe(0);
+ expect(out).toContain(`http://127.0.0.1:${port}`);
+ expect(out).toContain('listening no');
+ expect(out).toContain('installation ready');
+ });
+
+ it('status names the process, its owner and whether its source is current', async () => {
+ const { dir, port } = await installation();
+ const child = await spawnFakeRenderService(dir, port, {
+ FAKE_SOURCE_FINGERPRINT: renderServiceSourceFingerprint(dir)!,
+ });
+ children.push(child);
+ const { out } = await run(['status']);
+ expect(out).toContain('listening yes fake-renderer');
+ expect(out).toContain(`pid ${child.pid}, started by hand`);
+ expect(out).toContain('source current');
+ }, 30_000);
+
+ it('prune keeps a current service and a stale one somebody still owns; stop stops either', async () => {
+ const { dir, port } = await installation();
+ const current = await spawnFakeRenderService(dir, port, {
+ FAKE_SOURCE_FINGERPRINT: renderServiceSourceFingerprint(dir)!,
+ });
+ children.push(current);
+ const kept = await run(['prune']);
+ expect(kept.code).toBe(0);
+ expect(kept.out).toContain('kept');
+ expect(await alive(port)).toBe(true);
+
+ const stopped = await run(['stop']);
+ expect(stopped.code).toBe(0);
+ expect(stopped.out).toContain(`pid ${current.pid}`);
+ expect(await alive(port)).toBe(false);
+
+ const owned = await spawnFakeRenderService(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ children.push(owned);
+ const keptOwned = await run(['prune']);
+ expect(keptOwned.code).toBe(0);
+ expect(keptOwned.out).toContain('kept');
+ expect(keptOwned.out).toContain(`session ${process.pid}, which is still running`);
+ expect(await alive(port)).toBe(true);
+ }, 30_000);
+
+ it('prune stops a stale orphan and says what it was', async () => {
+ const { dir, port } = await installation();
+ const orphan = await spawnFakeRenderService(dir, port, {
+ RENDER_SERVICE_OWNER_PID: String(deadPid()),
+ FAKE_SOURCE_FINGERPRINT: `sha256:${'0'.repeat(64)}`,
+ });
+ children.push(orphan);
+ const { code, out } = await run(['prune']);
+ expect(code).toBe(0);
+ expect(out).toContain('stopped');
+ expect(out).toContain('which has exited');
+ expect(await alive(port)).toBe(false);
+ }, 30_000);
+
+ it('refuses to stop something that is not a render service', async () => {
+ await installation();
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/html' });
+ res.end('<html>');
+ });
+ servers.push(server);
+ await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
+ const port = (server.address() as AddressInfo).port;
+ process.env['KILN_RENDER_SERVICE_PORT'] = String(port);
+ const { code, err } = await run(['stop']);
+ expect(code).toBe(1);
+ expect(err).toContain('not a render service');
+ expect(err).toContain('KILN_RENDER_SERVICE_PORT');
+ expect(server.listening).toBe(true);
+ });
+});
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index dd46d263..eedfb835 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -341,11 +341,16 @@ export function makeKilnEditTools(
const screenshotTool: Tool = tool({
name: 'kiln_screenshot',
description: `${screenshotDef.description} Omit code to screenshot the current working buffer.`,
- inputSchema: bufferCodeInput,
+ // The registry schema minus the required `code`, so the capture contract
+ // (grid shape, framing, backdrop) reaches the edit loop unchanged.
+ inputSchema: (screenshotDef.inputSchema as z.ZodObject).extend(bufferCodeInput.shape),
callback: async (input) =>
toCallbackResult(
screenshotDef,
- await screenshotDef.run({ code: (input as { code?: string }).code ?? buffer.code }),
+ await screenshotDef.run({
+ ...(input as Record<string, unknown>),
+ code: (input as { code?: string }).code ?? buffer.code,
+ }),
opts,
),
});
diff --git a/src/cli-render-mode.ts b/src/cli-render-mode.ts
index 79f1ec7d..b9d1f87d 100644
--- a/src/cli-render-mode.ts
+++ b/src/cli-render-mode.ts
@@ -23,11 +23,16 @@ import { createHash } from 'node:crypto';
*/
import type { PbrRenderPort, PbrRenderResult } from './composer/render-port';
import {
+ describeStaleService,
explainRenderServiceState,
+ inspectLocalRenderService,
+ localRenderServicePort,
localRenderServiceState,
localRenderServiceUrl,
renderServiceDir,
startLocalRenderService,
+ terminateRenderService,
+ type LocalRenderServiceProbe,
} from './render-service-host';
import type { KilnToolContext } from './tools/registry';
import { DEFAULT_BACKDROP_ID } from './views/background';
@@ -149,20 +154,45 @@ export function makeRemoteRenderPort(url: string, token?: string): PbrRenderPort
* stall the loop this exists to serve.
*/
export function makeLazyRenderPort(start: () => Promise<string>, token?: string): PbrRenderPort {
- let resolving: Promise<PbrRenderPort> | undefined;
- return async (req) => {
- resolving ??= start().then(
- (url) => makeRemoteRenderPort(url, token),
+ let resolving: Promise<{ url: string; port: PbrRenderPort }> | undefined;
+ const resolve = (): Promise<{ url: string; port: PbrRenderPort }> =>
+ (resolving ??= start().then(
+ (url) => ({ url, port: makeRemoteRenderPort(url, token) }),
(err: unknown) => {
throw new Error(
`render service could not start: ${err instanceof Error ? err.message : String(err)}`,
);
},
- );
- return (await resolving)(req);
+ ));
+ return async (req) => {
+ const { url, port } = await resolve();
+ try {
+ return await port(req);
+ } catch (error) {
+ // A renderer that answered before and does not answer now has gone away:
+ // the session that started it exited, or it was replaced. That is not a
+ // render failure, so it is not cached as one. Ask `/health` once rather
+ // than reading the error, because "connection refused" is spelled
+ // differently under Node and Bun; then start again -- which joins a
+ // replacement if one is already up -- and retry this request once.
+ if (error instanceof Error && error.name === 'TimeoutError') throw error;
+ if (await listening(url)) throw error;
+ resolving = undefined;
+ return (await resolve()).port(req);
+ }
};
}
+/** Whether anything at all answers `/health` there. */
+async function listening(url: string): Promise<boolean> {
+ try {
+ const res = await fetch(new URL('/health', url), { signal: AbortSignal.timeout(1_500) });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
/** Fresh attestation per capture; unknown/older/unreachable services bypass cell reuse. */
export async function probeCaptureIdentity(url: string): Promise<string | undefined> {
try {
@@ -247,6 +277,17 @@ export async function probeRenderService(url: string): Promise<string | undefine
return second.kind === 'ok' ? second.rendererId : undefined;
}
+/**
+ * The same patience as {@link probeRenderService}, answering the fuller question
+ * the host acts on: not just whether a renderer is there, but whether it runs
+ * the source on disk and whether anyone still owns it.
+ */
+async function inspectWithPatience(url: string, dir: string): Promise<LocalRenderServiceProbe> {
+ const first = await inspectLocalRenderService(url, dir, HEALTH_PROBE_TIMEOUT_MS);
+ if (first.kind !== 'busy') return first;
+ return inspectLocalRenderService(url, dir, HEALTH_PROBE_BUSY_TIMEOUT_MS);
+}
+
/** What actually got selected, for honest CLI reporting. */
const selected = new WeakMap<object, string>();
@@ -367,12 +408,44 @@ export async function buildRenderPort(
if (envUrl) return attach(envUrl, `GPU service (${envUrl})`, explicitClientToken);
const localUrl = localRenderServiceUrl();
- const rendererId = await probeRenderService(localUrl);
- if (rendererId) return attach(localUrl, `GPU service (${rendererId})`, localClientToken);
+ // `options` is optional and `gpu` reaches here without it, so every read is
+ // guarded -- this branch used to be entered only by a caller that passed one.
+ const dir = options?.serviceDir ?? renderServiceDir();
+ const probe = await inspectWithPatience(localUrl, dir);
+ let pruned = '';
+ if (probe.kind === 'service') {
+ if (!probe.stale)
+ return attach(localUrl, `GPU service (${probe.rendererId})`, localClientToken);
+ // Stale. An orphan is nobody's and runs old code, so it goes; anything
+ // still owned or hand-started is left where it is and named, because the
+ // silent alternative -- joining it and reporting its 400 as a degrade --
+ // is the confusing state this exists to remove.
+ if (!probe.orphaned) {
+ const why = `${describeStaleService(localUrl, probe)}; stop it with \`kiln service stop\``;
+ if (mode === 'gpu') throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ pruned = (await terminateRenderService(localUrl, probe))
+ ? `stopped ${describeStaleService(localUrl, probe)}`
+ : '';
+ if (!pruned) {
+ const why = `${describeStaleService(localUrl, probe)} and could not be stopped`;
+ if (mode === 'gpu') throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
+ } else if (probe.kind === 'foreign') {
+ const why = `port ${localRenderServicePort()} is in use by something that is not a render service; set KILN_RENDER_SERVICE_PORT to move the renderer`;
+ if (mode === 'gpu') throw new Error(why);
+ selected.set(context, `cpu raster (${why})`);
+ return context;
+ }
- // Nothing is listening. If this installation can start one, hand back a port
- // that will -- lazily, so a session that never renders a material never pays
- // for a GPU process, and so the start is not in front of the first connection.
+ // Nothing usable is listening. If this installation can start one, hand back
+ // a port that will -- lazily, so a session that never renders a material
+ // never pays for a GPU process, and so the start is not in front of the first
+ // connection.
//
// `gpu` implies it. That mode means "I asked for a guarantee and would rather
// know than be quietly downgraded", and refusing while a renderer this
@@ -380,9 +453,6 @@ export async function buildRenderPort(
// stays OFF for `auto`, which is a one-shot CLI sheet's default and should not
// pay a GPU process's startup to draw it.
if (options?.autoSpawn || mode === 'gpu') {
- // `options` is optional and `gpu` reaches here without it, so every read is
- // guarded -- this branch used to be entered only by a caller that passed one.
- const dir = options?.serviceDir ?? renderServiceDir();
const state = options?.start ? 'ready' : localRenderServiceState(dir);
if (state === 'ready') {
const start = options?.start ?? (() => startLocalRenderService(dir));
@@ -400,6 +470,11 @@ export async function buildRenderPort(
);
}
- selected.set(context, 'cpu raster (no GPU service found)');
+ selected.set(
+ context,
+ pruned
+ ? `cpu raster (${pruned}; none started for a one-shot render)`
+ : 'cpu raster (no GPU service found)',
+ );
return context;
}
diff --git a/src/cli.ts b/src/cli.ts
index ffeb1a10..7a021bfc 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -18,6 +18,7 @@ import type { RenderMode } from './cli-render-mode';
import { localProgramStore } from './program-store-node';
import { retainProgram, programRefPattern } from './program-store';
import { ASSET_USAGE } from './asset-cli';
+import { SERVICE_USAGE } from './service-cli';
const USAGE = `kiln — vision-in-the-loop 3D asset generation
@@ -26,6 +27,7 @@ USAGE
kiln generate "<prompt>" [options] author a program with a model, then render
kiln source <file.js> save a source snapshot and print its programRef
kiln source <programRef> --out file.js export a revision without model transcription
+ kiln service status|stop|prune the shared GPU render service (see below)
OPTIONS
--out <path> GLB output path (default: out.glb)
@@ -219,8 +221,8 @@ async function emit(code: string, args: Args, context: KilnToolContext): Promise
if (args.views) {
// The SAME def the MCP surface serves, so the CLI cannot render views through
- // a path the agent never takes — and so `--render-port` actually fires, which
- // the frozen baseline's CPU-only kiln_screenshot would silently ignore.
+ // a path the agent never takes, and `--render-port` fires exactly as it does
+ // for a host agent.
// This call already built the exact source above. Review the same artifact.
const def = createKilnProgramToolRegistry({
...context,
@@ -387,6 +389,7 @@ export function main(argv: readonly string[]): Promise<number> {
}
async function runMain(argv: readonly string[]): Promise<number> {
+ if (argv[0] === 'service') return (await import('./service-cli')).serviceMain(argv.slice(1));
if (
['save', 'collections', 'assets', 'asset', 'export', 'import', 'view'].includes(argv[0] ?? '')
) {
@@ -405,7 +408,7 @@ async function runMain(argv: readonly string[]): Promise<number> {
return 2;
}
if (args.help || !args.command) {
- console.log(USAGE + ASSET_USAGE);
+ console.log(USAGE + ASSET_USAGE + SERVICE_USAGE);
return args.help ? 0 : 2;
}
try {
diff --git a/src/composer/render-port.ts b/src/composer/render-port.ts
index c697e470..cdf41723 100644
--- a/src/composer/render-port.ts
+++ b/src/composer/render-port.ts
@@ -209,6 +209,7 @@ export interface DerivativeReviewFidelityV1 {
export type ViewEvidenceSurface =
| 'kiln_render'
+ | 'kiln_screenshot'
| 'kiln_inspect'
| 'kiln_screenshot_animation'
| 'kiln_view_interior'
diff --git a/src/mcp-parity.test.ts b/src/mcp-parity.test.ts
index 37c95658..10e83f64 100644
--- a/src/mcp-parity.test.ts
+++ b/src/mcp-parity.test.ts
@@ -82,11 +82,11 @@ describe('tool surface parity across transports', () => {
}
});
- it('the MCP surface is composed for GPU capability, not the frozen baseline', () => {
- // The baseline's kiln_screenshot never consults viewRenderPort, so shipping it
- // over MCP would mean shipping a surface the render port can never reach. This
- // pins the deliberate substitution: unified kiln_render instead of the
- // baseline's metrics-only kiln_render plus CPU-only kiln_screenshot.
+ it('the MCP surface carries one unified kiln_render, not the in-process pair', () => {
+ // In-process, `kiln_render` is metrics-only and `kiln_screenshot` carries the
+ // image (the same implementation as the unified def, under the loop's name).
+ // Over MCP one tool does both, and a second way to ask for the same grid
+ // would only cost a model a choice. This pins that composition.
expect(kilnMcpToolDefs().map((d) => d.name)).toEqual([
'kiln_list_primitives',
'kiln_validate',
diff --git a/src/render-service-host.ts b/src/render-service-host.ts
index 09e6bd6d..aa0156b4 100644
--- a/src/render-service-host.ts
+++ b/src/render-service-host.ts
@@ -21,9 +21,10 @@
* one flag and never starts anything locally.
*/
import { spawn, type ChildProcess } from 'node:child_process';
-import { existsSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
-import { join } from 'node:path';
+import { join, relative } from 'node:path';
/**
* The port a locally started service listens on -- deliberately the SAME port the
@@ -118,6 +119,178 @@ async function healthy(url: string, timeoutMs: number): Promise<boolean> {
}
}
+// -----------------------------------------------------------------------------
+// Who is listening on the shared port
+// -----------------------------------------------------------------------------
+//
+// The socket is the registry. A service reports its pid, the session that
+// started it and a fingerprint of the source it runs (`render-service/src/
+// instance.mjs`), and the host reads those instead of guessing from a port
+// number. A lease file would be a second source of truth that can outlive the
+// process it describes; `/health` cannot.
+
+/** The `instance` block of the service's `/health`. */
+export interface RenderServiceInstance {
+ version: 'kiln.render-service-instance.v1';
+ pid: number;
+ /** The session that started it on demand; null when started by hand. */
+ ownerPid: number | null;
+ startedAt: string;
+ sourceDir: string;
+ sourceFingerprint: string;
+}
+
+/**
+ * The same walk as `fingerprintSourceDir` in `render-service/src/instance.mjs`,
+ * over `<dir>/src`, so the host can compare what is on disk with what a running
+ * service reports. A test imports the service's implementation and checks the
+ * two agree on one directory; keep them in step.
+ */
+export function renderServiceSourceFingerprint(dir: string): string | undefined {
+ const source = join(dir, 'src');
+ if (!existsSync(source)) return undefined;
+ const hash = createHash('sha256');
+ hash.update('kiln.render-service-source.v1');
+ const visit = (path: string): void => {
+ if (statSync(path).isDirectory()) {
+ for (const name of readdirSync(path).sort()) {
+ if (name === 'node_modules') continue;
+ visit(join(path, name));
+ }
+ return;
+ }
+ const bytes = readFileSync(path);
+ hash.update(JSON.stringify([relative(source, path).replaceAll('\\', '/'), bytes.length]));
+ hash.update(bytes);
+ };
+ visit(source);
+ return `sha256:${hash.digest('hex')}`;
+}
+
+/** Whether `pid` is a live process. EPERM means it exists and is not ours to signal. */
+export function processIsAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as { code?: string }).code === 'EPERM';
+ }
+}
+
+export type LocalRenderServiceProbe =
+ /** Nothing accepted the connection. */
+ | { kind: 'absent' }
+ /** The socket was accepted and then went quiet: a renderer busy on another frame. */
+ | { kind: 'busy' }
+ /** Something answered, and it is not a render service. */
+ | { kind: 'foreign' }
+ | {
+ kind: 'service';
+ rendererId: string;
+ /** Absent on a service from before instance reporting. */
+ instance?: RenderServiceInstance;
+ /** Runs source that differs from `<dir>/src`. Never true when it cannot be told. */
+ stale: boolean;
+ /** Started on demand by a session that no longer exists. */
+ orphaned: boolean;
+ };
+
+/**
+ * Ask the shared port who is there. Never throws: every answer is a state the
+ * caller has a policy for.
+ */
+export async function inspectLocalRenderService(
+ url: string,
+ dir = renderServiceDir(),
+ timeoutMs = 1_500,
+): Promise<LocalRenderServiceProbe> {
+ let body: {
+ ok?: boolean;
+ rendererId?: string;
+ instance?: Partial<RenderServiceInstance>;
+ };
+ try {
+ const res = await fetch(new URL('/health', url), {
+ signal: AbortSignal.timeout(timeoutMs),
+ cache: 'no-store',
+ });
+ if (!res.ok) return { kind: 'foreign' };
+ body = (await res.json()) as typeof body;
+ } catch (error) {
+ // `AbortSignal.timeout` rejects with a TimeoutError; a refused connection
+ // is a fetch failure; a listening socket whose body is not JSON is
+ // somebody else's server on our port.
+ if (error instanceof Error && error.name === 'TimeoutError') return { kind: 'busy' };
+ return (error as { name?: string }).name === 'SyntaxError'
+ ? { kind: 'foreign' }
+ : { kind: 'absent' };
+ }
+ if (body?.ok !== true || typeof body.rendererId !== 'string') return { kind: 'foreign' };
+ const raw = body.instance;
+ const instance: RenderServiceInstance | undefined =
+ raw &&
+ raw.version === 'kiln.render-service-instance.v1' &&
+ typeof raw.pid === 'number' &&
+ typeof raw.sourceFingerprint === 'string'
+ ? {
+ version: raw.version,
+ pid: raw.pid,
+ ownerPid: typeof raw.ownerPid === 'number' ? raw.ownerPid : null,
+ startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '',
+ sourceDir: typeof raw.sourceDir === 'string' ? raw.sourceDir : '',
+ sourceFingerprint: raw.sourceFingerprint,
+ }
+ : undefined;
+ const local = renderServiceSourceFingerprint(dir);
+ const stale =
+ instance !== undefined && local !== undefined && instance.sourceFingerprint !== local;
+ const orphaned =
+ instance !== undefined && instance.ownerPid !== null && !processIsAlive(instance.ownerPid);
+ return {
+ kind: 'service',
+ rendererId: body.rendererId,
+ ...(instance ? { instance } : {}),
+ stale,
+ orphaned,
+ };
+}
+
+/** How a stale service is described to whoever has to act on it. */
+export function describeStaleService(url: string, probe: LocalRenderServiceProbe): string {
+ if (probe.kind !== 'service' || !probe.instance) return `the render service on ${url} is stale`;
+ const { pid, ownerPid } = probe.instance;
+ const who =
+ ownerPid === null
+ ? 'started by hand'
+ : probe.orphaned
+ ? `started by session ${ownerPid}, which has exited`
+ : `started by session ${ownerPid}, which is still running`;
+ return `the render service on ${url} (pid ${pid}, ${who}) runs older source than the render-service directory of this installation`;
+}
+
+/**
+ * Stop the service `probe` describes and wait for its port to come free.
+ * Returns false when it could not be stopped in time.
+ */
+export async function terminateRenderService(
+ url: string,
+ probe: LocalRenderServiceProbe,
+ waitMs = 5_000,
+): Promise<boolean> {
+ if (probe.kind !== 'service' || !probe.instance) return false;
+ try {
+ process.kill(probe.instance.pid);
+ } catch {
+ return false;
+ }
+ const deadline = Date.now() + waitMs;
+ while (Date.now() < deadline) {
+ if ((await inspectLocalRenderService(url, undefined, 500)).kind === 'absent') return true;
+ await new Promise((done) => setTimeout(done, 100));
+ }
+ return false;
+}
+
/**
* The Node binary to run the service with.
*
@@ -174,7 +347,27 @@ export async function startLocalRenderService(dir = renderServiceDir()): Promise
// this branch is also what keeps `stopLocalRenderService` honest: `child` stays
// undefined, so leaving this process never takes down a service it found. A
// batch of dispatched agents sharing one GPU depends on exactly that.
- if (await healthy(url, 1_500)) return url;
+ //
+ // Unless it runs older source than this installation ships. Then joining it
+ // is the confusing state this module exists to remove -- a 400 for a field
+ // the old build never heard of, reported as a degrade -- so an orphan is
+ // replaced and anything still owned or hand-started is named and left alone.
+ const probe = await inspectLocalRenderService(url, dir);
+ if (probe.kind === 'busy') return url;
+ if (probe.kind === 'foreign')
+ throw new Error(
+ `port ${localRenderServicePort()} is in use by something that is not a render service; ` +
+ 'set KILN_RENDER_SERVICE_PORT to move the renderer',
+ );
+ if (probe.kind === 'service') {
+ if (!probe.stale) return url;
+ if (!probe.orphaned)
+ throw new Error(
+ `${describeStaleService(url, probe)}; stop it with \`kiln service stop\` and it will be started again on demand`,
+ );
+ if (!(await terminateRenderService(url, probe)))
+ throw new Error(`${describeStaleService(url, probe)} and could not be stopped`);
+ }
const state = localRenderServiceState(dir);
if (state !== 'ready') throw new Error(explainRenderServiceState(state, dir));
@@ -186,6 +379,10 @@ export async function startLocalRenderService(dir = renderServiceDir()): Promise
env: {
...process.env,
PORT: String(localRenderServicePort()),
+ // The lease. The service watches this pid and exits when it is gone, which
+ // is what makes an on-demand start safe on a host that is hard-killed; and
+ // a later session reads it to tell an orphan from a renderer in use.
+ RENDER_SERVICE_OWNER_PID: String(process.pid),
// Loopback, where the documented manual start binds every interface. We
// are choosing on the user's behalf here, so the narrow choice is the
// right one; the Docker deployment sets its own HOST and is unaffected.
diff --git a/src/service-cli.ts b/src/service-cli.ts
new file mode 100644
index 00000000..99f2e41e
--- /dev/null
+++ b/src/service-cli.ts
@@ -0,0 +1,141 @@
+/**
+ * `kiln service`: see who is on the shared render-service port, and clear it.
+ *
+ * The host joins, replaces or refuses a service on its own (see
+ * `render-service-host.ts`); these commands exist for the one case it will not
+ * decide for you -- a stale service that somebody started by hand or that
+ * another session still owns -- and so a developer can see the same facts the
+ * host acts on instead of inferring them from a degraded sheet.
+ */
+import {
+ describeStaleService,
+ explainRenderServiceState,
+ inspectLocalRenderService,
+ localRenderServicePort,
+ localRenderServiceState,
+ localRenderServiceUrl,
+ processIsAlive,
+ renderServiceDir,
+ terminateRenderService,
+ type LocalRenderServiceProbe,
+} from './render-service-host';
+
+export const SERVICE_USAGE = `
+RENDER SERVICE
+ kiln service status who is listening on the shared port, and whether it is current
+ kiln service stop stop the render service on the shared port, whoever started it
+ kiln service prune stop it only when it is an orphan running older source
+
+The port is 8000 unless KILN_RENDER_SERVICE_PORT says otherwise. A session starts the
+service on demand and stops it on exit; \`kiln service\` is for the one it will not decide
+for you: a stale service started by hand or still owned by another session.
+`;
+
+export interface ServiceIo {
+ log: (line: string) => void;
+ error: (line: string) => void;
+}
+
+function describeProcess(probe: LocalRenderServiceProbe): string {
+ if (probe.kind !== 'service') return '';
+ if (!probe.instance) return 'unknown (this service predates instance reporting)';
+ const { pid, ownerPid } = probe.instance;
+ if (ownerPid === null) return `pid ${pid}, started by hand`;
+ return `pid ${pid}, started by session ${ownerPid} (${processIsAlive(ownerPid) ? 'running' : 'exited'})`;
+}
+
+function describeSource(probe: LocalRenderServiceProbe, dir: string): string {
+ if (probe.kind !== 'service') return '';
+ if (!probe.instance) return 'unknown (this service predates instance reporting)';
+ return probe.stale ? `stale (older than ${dir})` : 'current';
+}
+
+export async function serviceMain(
+ argv: readonly string[],
+ io: ServiceIo = { log: console.log, error: console.error },
+): Promise<number> {
+ const command = argv[0];
+ if (command === undefined || command === '--help' || command === '-h') {
+ io.log(SERVICE_USAGE);
+ return command === undefined ? 2 : 0;
+ }
+ if (command !== 'status' && command !== 'stop' && command !== 'prune') {
+ io.error(`unknown service command: ${command}\n${SERVICE_USAGE}`);
+ return 2;
+ }
+
+ const url = localRenderServiceUrl();
+ const dir = renderServiceDir();
+ const state = localRenderServiceState(dir);
+ const probe = await inspectLocalRenderService(url, dir);
+
+ if (command === 'status') {
+ io.log(`render service ${url}`);
+ io.log(
+ `installation ${state === 'ready' ? `ready (${dir})` : explainRenderServiceState(state, dir)}`,
+ );
+ switch (probe.kind) {
+ case 'absent':
+ io.log('listening no');
+ break;
+ case 'busy':
+ io.log('listening yes, busy rendering (did not answer in time)');
+ break;
+ case 'foreign':
+ io.log(
+ `listening something that is not a render service holds port ${localRenderServicePort()}; set KILN_RENDER_SERVICE_PORT to move the renderer`,
+ );
+ break;
+ case 'service':
+ io.log(`listening yes ${probe.rendererId}`);
+ io.log(`process ${describeProcess(probe)}`);
+ io.log(`source ${describeSource(probe, dir)}`);
+ break;
+ }
+ return 0;
+ }
+
+ if (probe.kind === 'absent') {
+ io.log(`nothing is listening on ${url}`);
+ return 0;
+ }
+ if (probe.kind === 'busy') {
+ io.error(`the render service on ${url} is busy rendering and did not answer; try again`);
+ return 1;
+ }
+ if (probe.kind === 'foreign') {
+ io.error(
+ `port ${localRenderServicePort()} is in use by something that is not a render service; nothing was stopped. Set KILN_RENDER_SERVICE_PORT to move the renderer.`,
+ );
+ return 1;
+ }
+ if (!probe.instance) {
+ io.error(
+ `the render service on ${url} predates instance reporting and does not say its pid; stop it by hand and start it again from ${dir}`,
+ );
+ return 1;
+ }
+
+ if (command === 'prune') {
+ if (!probe.stale) {
+ io.log(`kept: the render service on ${url} (pid ${probe.instance.pid}) is current`);
+ return 0;
+ }
+ if (!probe.orphaned) {
+ io.log(`kept: ${describeStaleService(url, probe)}; \`kiln service stop\` stops it anyway`);
+ return 0;
+ }
+ }
+
+ const stopped = await terminateRenderService(url, probe);
+ if (!stopped) {
+ io.error(`could not stop the render service on ${url} (pid ${probe.instance.pid})`);
+ return 1;
+ }
+ io.log(
+ command === 'prune'
+ ? `stopped: ${describeStaleService(url, probe)}`
+ : `stopped the render service on ${url} (pid ${probe.instance.pid}); the next view that needs it starts a new one`,
+ );
+ return 0;
+}
diff --git a/src/tools/__tests__/registry-screenshot.test.ts b/src/tools/__tests__/registry-screenshot.test.ts
index 7f6f44bb..0861f4a5 100644
--- a/src/tools/__tests__/registry-screenshot.test.ts
+++ b/src/tools/__tests__/registry-screenshot.test.ts
@@ -3,7 +3,17 @@
* transports use to attach the PNG as a real image block.
*/
import { describe, expect, test } from 'bun:test';
-import { kilnToolRegistry, type KilnScreenshotResult } from '../registry';
+import {
+ createKilnToolRegistry,
+ kilnRenderViewsDef,
+ kilnToolRegistry,
+ type KilnScreenshotResult,
+} from '../registry';
+import type { PbrRenderPort, PbrRenderRequest } from '../../composer/render-port';
+import { BACKDROPS } from '../../views/background';
+import { decodePng } from '../../views/png';
+import { encodePng } from '../../views';
+import { PAD } from '../../views/grid';
const BOX_CODE = `
const meta = { name: 'test-box', category: 'prop' };
@@ -14,8 +24,26 @@ function build() {
}
`;
+const METAL_CODE = `
+const meta = { name: 'metal-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial('#c0c0c0', { metalness: 0.6 }), { parent: root });
+ return root;
+}
+`;
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+/** Six flat per-view PNGs at the default cell size, standing in for a GPU. */
+function stubViewPngs(size = 384): Uint8Array[] {
+ return Array.from({ length: 6 }, (_, i) => {
+ const rgb = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) rgb[p * 3] = 20 + i * 30;
+ return new Uint8Array(encodePng(rgb, size, size));
+ });
+}
+
function screenshotDef() {
const def = kilnToolRegistry.find((d) => d.name === 'kiln_screenshot');
if (!def) throw new Error('kiln_screenshot missing from registry');
@@ -27,8 +55,8 @@ describe('kiln_screenshot', () => {
const out = (await screenshotDef().run({ code: BOX_CODE })) as KilnScreenshotResult;
expect(out.ok).toBe(true);
expect(out.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
- expect(out.width).toBeGreaterThan(0);
- expect(out.height).toBeGreaterThan(0);
+ expect(out.gridWidth).toBeGreaterThan(0);
+ expect(out.gridHeight).toBeGreaterThan(0);
expect(out.warnings).toEqual([]);
const png = Buffer.from(out.pngBase64!, 'base64');
expect(png.subarray(0, 8).equals(PNG_SIGNATURE)).toBe(true);
@@ -60,4 +88,53 @@ describe('kiln_screenshot', () => {
const out = await def.run({ code: 'throw new Error("boom")' });
expect(def.media!(out)).toBeUndefined();
});
+
+ /**
+ * The in-process loop's view tool was a frozen copy: CPU-only, no capture
+ * config, no backdrop, while every other surface took all three. Nothing
+ * consumed that freeze -- the bench it was a control arm for no longer exists
+ * -- so the four-tool loop now sees exactly what the MCP surface sees.
+ */
+ test('takes the same capture config as kiln_render and paints the named backdrop', async () => {
+ expect(screenshotDef().inputSchema).toBe(kilnRenderViewsDef.inputSchema);
+ const out = (await screenshotDef().run({
+ code: BOX_CODE,
+ capture: { backdrop: 'dark' },
+ })) as KilnScreenshotResult;
+ expect(out.ok).toBe(true);
+ expect(out.capture?.backdrop).toBe('dark');
+ const png = decodePng(Buffer.from(out.pngBase64!, 'base64'));
+ // A corner inside the first cell's padding is backdrop, whatever the asset is.
+ const at = ((PAD + 1) * png.width + (png.width - PAD - 2)) * 3;
+ expect([...png.rgb.subarray(at, at + 3)]).toEqual([...BACKDROPS.dark.rgb]);
+ expect(out.viewFidelity?.version).toBe('kiln.view-fidelity.v1');
+ });
+
+ test('routes a metallic scene through the injected render port, like kiln_render', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const port: PbrRenderPort = async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0', viewsPng: stubViewPngs() };
+ };
+ const def = createKilnToolRegistry({ viewRenderPort: port }).find(
+ (d) => d.name === 'kiln_screenshot',
+ )!;
+ const out = (await def.run({ code: METAL_CODE })) as KilnScreenshotResult;
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ expect(out.viewFidelity).toMatchObject({
+ materialFaithful: true,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ degraded: false,
+ });
+ // The evidence trail names the tool the model actually called.
+ expect(JSON.stringify(out.viewEvidence ?? {})).not.toContain('"kiln_render"');
+ });
+
+ test('says what it can and cannot show, instead of calling itself flat-shaded', () => {
+ const description = screenshotDef().description;
+ expect(description).not.toContain('Flat-shaded CPU render');
+ expect(description).toContain('viewFidelity');
+ expect(description).toContain('capture');
+ });
});
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index ab7a0978..e402d740 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -621,10 +621,6 @@ const renderInput = z.object({
code: z.string().describe('Kiln source code to execute and render to an in-memory GLB.'),
});
-const screenshotInput = z.object({
- code: z.string().describe('Kiln source code to execute and render to a six-view image grid.'),
-});
-
/**
* `kiln_render` (unified surface only) additionally accepts a capture config.
* Kept off the shared `renderInput` on purpose: the four-tool baseline's
@@ -1096,55 +1092,18 @@ async function runRender(
// kiln_screenshot
// =============================================================================
-export interface KilnScreenshotResult {
- ok: boolean;
- /** View names in grid order (row-major). Defaults to Front, Right, Back, Left, Top, 3/4. */
- views?: string[];
- /** Grid shape and backdrop actually rendered — echoes the capture config back, or `3x2` on neutral by default. */
- capture?: { preset: string; cols: number; cells: number; backdrop?: BackdropId };
- width?: number;
- height?: number;
- /** The 3x2 grid PNG, base64-encoded (transports with image support strip this and attach the bytes). */
- pngBase64?: string;
- warnings: string[];
- error?: string;
-}
-
/**
- * Execute Kiln code and rasterize it into the 3x2 six-view grid (pure CPU —
- * no browser, no GPU). Never throws — failures come back as { ok:false, error }.
- * The renderer is imported lazily so the views module (node:zlib) never enters
- * the browser bundle graph.
+ * `kiln_screenshot` is the unified view path under the in-process loop's name.
+ *
+ * It used to be a frozen copy: CPU-only, no capture config, no backdrop, while
+ * every other surface took all three and routed through the render port. The
+ * freeze protected a bench in which this tool was the control arm; that bench
+ * is gone, and what remained was a loop whose model could never see a
+ * material-faithful view even on a machine with a renderer. One implementation
+ * now serves both names, so a backdrop chosen on the CLI and one chosen here
+ * paint the same pixel, and `viewFidelity` tells the model which producer drew.
*/
-async function runScreenshot(
- input: z.infer<typeof screenshotInput>,
- context: KilnToolContext,
-): Promise<KilnScreenshotResult> {
- try {
- const { renderGlbViewGrid } = await import('../views');
- const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
- const warnings = inspectSceneStructure(root, {
- category: trustedCategory(context),
- });
- // No capture config here on purpose: kiln_screenshot belongs to the frozen
- // four-tool baseline, whose schemas stay byte-for-byte unchanged.
- const grid = await renderGlbViewGrid(rendered.glb);
- return {
- ok: true,
- views: grid.views,
- width: grid.width,
- height: grid.height,
- pngBase64: grid.png.toString('base64'),
- warnings,
- };
- } catch (err) {
- return {
- ok: false,
- error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
- warnings: [],
- };
- }
-}
+export type KilnScreenshotResult = KilnRenderViewsResult;
/** Shared media extractor for screenshot-shaped outputs (pngBase64 -> bytes + stripped JSON).
* Used by both `kiln_screenshot` and the unified `kilnRenderViewsDef` (both carry `pngBase64`). */
@@ -1218,6 +1177,7 @@ export interface KilnRenderViewsResult {
async function runRenderViews(
input: z.infer<typeof renderViewsInput>,
context: KilnToolContext,
+ toolName: 'kiln_render' | 'kiln_screenshot' = 'kiln_render',
): Promise<KilnRenderViewsResult> {
try {
// `CPU_RASTER_RENDERER_ID` and `resolveGridCapture` come from this SAME lazy
@@ -1383,7 +1343,7 @@ async function runRenderViews(
...(drawnBy.degradedReason ? { degradeReason: drawnBy.degradedReason } : {}),
reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED'],
};
- const viewEvidence = context.viewEvidenceHistory?.record('kiln_render', viewFidelity);
+ const viewEvidence = context.viewEvidenceHistory?.record(toolName, viewFidelity);
// A host bookkeeping hook must never be able to fail a render the model is
// waiting on.
@@ -1442,9 +1402,10 @@ async function runRenderViews(
/**
* The unified-surface render tool: render + screenshot collapsed into one.
- * Exported separately and intentionally NOT part of `kilnToolRegistry` (which
- * stays the four-tool bench baseline). Shares `screenshotMedia` so transports
- * with image support attach the PNG bytes and strip the base64 from the JSON.
+ * Exported separately and intentionally NOT part of `kilnToolRegistry`, whose
+ * `kiln_screenshot` runs this same implementation under the in-process loop's
+ * name. Shares `screenshotMedia` so transports with image support attach the
+ * PNG bytes and strip the base64 from the JSON.
*/
const KILN_RENDER_VIEWS_DESCRIPTION =
'Build the current asset and return geometry metrics, exact part paths and images. Omit capture for six orthographic views. Choose preset/cells for a smaller orbit sheet, or version kiln.capture.v1 with shots for per-part framing, local axes, perspective and separate images. +X is forward, +Y up, +Z right. Review silhouette, attachments, proportion and ground contact. GPU PBR shading supports textured or metallic materials; a flat-shaded CPU render supports geometry review. Read viewFidelity; do not judge material fidelity from CPU views. Failed builds return errors without images.' +
@@ -2064,12 +2025,10 @@ export const kilnInspectDef: KilnToolDef = createKilnInspectDef();
// and views: the loop is edit-then-look, and splitting it across two calls
// doubles the round trips for no gain.
//
-// Like `kilnRenderViewsDef`, this sits OUTSIDE `createKilnToolRegistry`. That
-// array is the frozen four-tool bench baseline and adding to it would silently
-// change what the benchmark measures. The in-process agent does not need this
-// def either -- it has a working buffer across turns and its own edit tools, so
-// `kiln_edit` is reached through `kilnMcpToolDefs()`, where the host holds the
-// program and nothing else does.
+// Like `kilnRenderViewsDef`, this sits OUTSIDE `createKilnToolRegistry`. The
+// in-process agent does not need this def -- it has a working buffer across
+// turns and its own edit tools, so `kiln_edit` is reached through
+// `kilnMcpToolDefs()`, where the host holds the program and nothing else does.
const editOperationInput = z.object({
oldString: z
@@ -2215,6 +2174,9 @@ export function createKilnEditDef(context: KilnToolContext = {}): KilnToolDef {
export const kilnEditDef: KilnToolDef = createKilnEditDef();
export function createKilnToolRegistry(context: KilnToolContext = {}): KilnToolDef[] {
+ // The view tool shares the unified implementation, which keeps a per-context
+ // evidence trail; the three text tools read the context as given.
+ const viewContext = withViewEvidenceHistory(context);
return [
{
name: 'kiln_list_primitives',
@@ -2243,17 +2205,21 @@ export function createKilnToolRegistry(context: KilnToolContext = {}): KilnToolD
{
name: 'kiln_screenshot',
description:
- 'Render Kiln code to a six-view image grid so you can SEE the asset: ' +
+ 'Render Kiln code to an image grid so you can SEE the asset. Omit capture for six views: ' +
'row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' +
'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' +
'Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. ' +
- 'If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.',
- inputSchema: screenshotInput,
+ 'If a view looks wrong, fix the code and screenshot again. capture selects a smaller orbit sheet, ' +
+ 'per-part framing or a backdrop (neutral, dark, light). Textured or metallic materials draw through the GPU ' +
+ 'render service when one is available; otherwise a flat-shaded CPU render supports geometry review only. ' +
+ 'Read viewFidelity before judging materials. Does not write files.',
+ inputSchema: renderViewsInput,
run: async (input) =>
- guardCaptureBudget('kiln_screenshot', input, context, () =>
- runScreenshot(screenshotInput.parse(input), context),
+ guardCaptureBudget('kiln_screenshot', input, viewContext, () =>
+ runRenderViews(renderViewsInput.parse(input), viewContext, 'kiln_screenshot'),
),
media: screenshotMedia,
+ mediaMulti: screenshotAnimationMediaMulti,
},
];
}