Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(mcp): add opt-in kiln_export_to for host-rooted file export (#207) (#239)
Matthew Kissingerd5d059da1289
diff --git a/AGENTS.md b/AGENTS.mdindex d652ce8c..d1fa8658 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -69,11 +69,11 @@ The stdio executable is a thin entry: `src/mcp-server.ts` bundles the protocol lengine-loading problem is a tool result naming the next step, never a dead server.`createKilnProgramToolRegistry` supplies the fifteen base MCP tools. The packaged local host-also injects `kiln_project`, `kiln_material` and `kiln_review` (eighteen); embeddings-advertise these only when the host services exist, never as tools that always fail.+also injects `kiln_project`, `kiln_material` and `kiln_review` (eighteen; `KILN_EXPORT_ROOT`+adds `kiln_export_to`); embeddings advertise these only when the host services exist.`createKilnNativeToolRegistry` uses the same definitions and adds `kiln_finish`: eleven tools-by default, sixteen with an injected `assetLibrary` (the five delivery tools). A configured-skill-resource reader adds `kiln_skill_resource` to either native set.+by default, sixteen with an injected `assetLibrary` (the five delivery tools; an `exportRoot`+adds `kiln_export_to`). A skill-resource reader adds `kiln_skill_resource` to either set.Both skins use unified `kiln_render`: metrics, part paths, QA, images and fidelity share oneevaluation. `kiln_validate` is the image-free syntax check. Review results are compact bydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2334c2ca..986db4d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -138,6 +138,17 @@ does not publish a package.of the policy hash, so changing it refuses earlier reviewed artifacts. Tool input andsource cannot weaken it, and Discovery capabilities show it as host-declared. Bindingswithout the key are unchanged.+- Write exported files from MCP into a host-configured folder ([#207](https://github.com/instruktlabs/kiln/issues/207)).+ When the MCP server's environment sets `KILN_EXPORT_ROOT` (an existing absolute+ directory outside every collection and `.kiln/`), it also advertises `kiln_export_to`,+ which writes one saved revision's GLB, and for the default runtime profile its+ metadata sidecar, at a root-relative path. `profile: "editable"` writes the exact saved+ GLB and `target: "three"` the three.js runtime GLB, byte-identical to CLI `export`.+ Paths are relative, forward-slash and portable; links in the path and existing files+ are refused, and the receipt is the CLI `--json` receipt with root-relative paths.+ Without the variable the tool list is unchanged (eighteen tools), and `kiln_export`+ stays read-only with the same schema. Native registries add it to the delivery tools+ when an `exportRoot` writer is injected.## 1.3.1 (2026-10-17)diff --git a/ROADMAP.md b/ROADMAP.mdindex f79b8644..e2e67c44 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -108,7 +108,7 @@ They are potential new scope, not prerequisites for the published scene.| Hide-node capture | `kiln.capture.v2` || Intentional open shells | `markOpenShell`; measured overlap failures still apply || LOD authoring/review | `defineLod`, `MSFT_lod`, LOD0 default views and per-level inspection; verify destination support |-| MCP render file destination | Unadopted; CLI file output and MCP media/receipts remain supported |+| MCP export file destination | Adopted (opt-in `KILN_EXPORT_ROOT`, `kiln_export_to`); render file output remains unadopted: delivery starts from a saved revision |Projects remain optional for standalone authoring.diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex ace61eac..377f33b2 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -38774,7 +38774,8 @@ var init_runtime_three = __esm(() => {// src/asset-export.tsvar exports_asset_export = {};__export(exports_asset_export, {- exportAssetGlb: () => exportAssetGlb+ exportAssetGlb: () => exportAssetGlb,+ validateMetadataFileName: () => validateMetadataFileName});async function sha2562(bytes) {const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));@@ -40417,6 +40418,44 @@ var init_asset_widget = __esm(() => {init_widget_transfer();});+// src/export-root.ts+function rootRelativeSegments(path) {+ if (path.length > MAX_PATH_CHARS)+ throw new Error(`Export path must be at most ${MAX_PATH_CHARS} characters.`);+ if (path.includes("\\"))+ throw new Error("Export path must use forward slashes, for example models/door.glb.");+ if (path.startsWith("/") || /^[A-Za-z]:/.test(path))+ throw new Error("Export path must be relative to the export root, for example models/door.glb.");+ const segments = path.split("/");+ if (segments.length > MAX_SEGMENTS)+ throw new Error(`Export path must have at most ${MAX_SEGMENTS} segments.`);+ for (const segment of segments) {+ if (segment === "..")+ throw new Error('Export path must stay inside the export root; ".." is not allowed.');+ if (!PORTABLE_SEGMENT.test(segment) || segment.endsWith("."))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is not portable: use ASCII letters, digits, ".", "_" or "-", starting with a letter or digit.`);+ if (DEVICE_NAME.test(segment))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is a Windows device name; choose another name.`);+ }+ return segments;+}+function validateExportPath(path) {+ if (!path.toLowerCase().endsWith(".glb"))+ throw new Error("Export path must name a .glb file, for example models/door.glb.");+ const segments = rootRelativeSegments(path);+ const metadataFileName = `${segments.at(-1).slice(0, -4)}.kiln-metadata.json`;+ return {+ path,+ metadataPath: [...segments.slice(0, -1), metadataFileName].join("/"),+ metadataFileName+ };+}+var MAX_PATH_CHARS = 240, MAX_SEGMENTS = 8, PORTABLE_SEGMENT, DEVICE_NAME;+var init_export_root = __esm(() => {+ PORTABLE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+ DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;+});+// src/agent/run.tsimport {Agent,@@ -48635,6 +48674,7 @@ function createKilnNativeToolRegistry(suppliedContext, completion) {"kiln_save","kiln_assets","kiln_export",+ "kiln_export_to","kiln_import","kiln_present"]);@@ -48841,6 +48881,11 @@ function createKilnAssetDefs(context, presentation = "grouped") {const profileExportInput = exportInput.extend({profile: z24.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")});+ const exportToInput = exportInput.extend({+ path: z24.string().max(240).describe("Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."),+ profile: z24.enum(["runtime", "editable"]).default("runtime").describe("runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only."),+ target: z24.enum(["three"]).optional().describe("Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).")+ });const importInput = z24.object({...selector,sourceCollection: selector.collection@@ -49017,6 +49062,7 @@ function createKilnAssetDefs(context, presentation = "grouped") {};}},+ ...context.exportRoot && context.assetLibrary ? [createKilnExportToDef(context.exportRoot, exportToInput, library, listCall)] : [],{name: "kiln_import",description: "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",@@ -49031,6 +49077,61 @@ function createKilnAssetDefs(context, presentation = "grouped") {}];}+function createKilnExportToDef(writer, inputSchema, library, listCall) {+ return {+ name: "kiln_export_to",+ description: "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ inputSchema,+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false+ },+ run: async (raw) => {+ const input = inputSchema.parse(raw);+ if (input.target !== undefined && input.profile !== "runtime")+ throw new Error("target requires profile runtime");+ await Promise.resolve().then(() => init_export_root());+ const destination = validateExportPath(input.path);+ await Promise.resolve().then(() => init_asset_export());+ if (input.profile === "runtime")+ validateMetadataFileName(destination.metadataFileName);+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId, listCall(input.collection));+ const files = [];+ if (input.profile === "runtime") {+ const output = await exportAssetGlb(record, {+ profile: "runtime",+ metadataFileName: destination.metadataFileName,+ ...input.target ? { target: input.target } : {}+ });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ files.push({ kind: "glb", path: destination.path, data: output.glb }, { kind: "metadata", path: destination.metadataPath, data: output.metadata.bytes });+ } else+ files.push({ kind: "glb", path: destination.path, data: record.files["asset.glb"] });+ await writer.writeNew([...files].reverse());+ await Promise.resolve().then(() => init_draw_diagnostics());+ const digest = async (data) => `sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(data))), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ return {+ ok: true,+ collection: input.collection,+ assetId: input.assetId,+ revisionId: input.revisionId,+ profile: input.profile,+ ...input.target ? { target: input.target } : {},+ format: "glb",+ drawDiagnostics: await inspectDrawDiagnostics(files[0].data),+ files: await Promise.all(files.map(async ({ kind, path, data }) => ({+ kind,+ path,+ bytes: data.byteLength,+ sha256: await digest(data)+ })))+ };+ }+ };+}// src/agent/tools.tsinit_requirements_context();diff --git a/dist/build.json b/dist/build.jsonindex a7c4fefa..7cedf3ca 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -40,10 +40,10 @@"bundleHash": "sha256:2839cd6aaee99ebea2e55a4f07aa079340b7d281572a7a801484ff489c15624e"},"agent-run": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:42141e716a65089730c4873a08f084b39d5bf30a4f9bf56fff38c7091726a833"+ "bundleHash": "sha256:05a2480c113f2980638b7c4f2111758b014e8258ca8aa5ac6a6ddd9c0b28b37d"},"agent-providers": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -151,13 +151,13 @@},"target": "node","file": "mcp-server.mjs",- "bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"+ "bundleHash": "sha256:4dcb8c72dd106e0dfa3261020168285444cbb51c50445a46ea3fe6aa77a3f194"},"cli": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:52450ca9223e2aee91e8e2b82a6e4db30034b4b1342bf9b67ec347d67423fb90"+ "bundleHash": "sha256:faeb1d9eab67c6ab7fe0f492c737eb0ef665927ec989375b05d6a539ba72877b"},"engine": {- "identity": "sha256:45172d48ae16758e917f14c7e0f59061af76b5a6afd4520913f4dd55cdbdbfd0",+ "identity": "sha256:e7296c49785ed77365a2ee2f79c8c712c5f040502082e793788a4b5e2d317de9","engineVersion": "1.3.1","toolchain": "[email protected]",- "sourceHash": "d5c701c5d24812cd0a0f4764633b22cb4333b08c625ef07e39f135111886a798",+ "sourceHash": "96c193c914898bd8040bed13e5497a361e285c00eb950c85d5c6b980f133ed83","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:2ec7ee5d2e9ca0dab37c7258f6e1b2b7c6928be2a088871bc2ae7fe8d15117f3"+ "bundleHash": "sha256:fa5f8d6dc7df3ebeffccca53c68f713fe9933ea4e038a9c5f65ac2b01e4ebd1e"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex ad3e454e..4cb31f37 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -43056,7 +43056,8 @@ var init_runtime_three = __esm(() => {var exports_asset_export = {};__export(exports_asset_export, {createKtx2Encoder: () => createKtx2Encoder2,- exportAssetGlb: () => exportAssetGlb+ exportAssetGlb: () => exportAssetGlb,+ validateMetadataFileName: () => validateMetadataFileName});async function sha2562(bytes) {const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));@@ -52050,6 +52051,44 @@ var init_asset_widget = __esm(() => {init_widget_transfer();});+// src/export-root.ts+function rootRelativeSegments(path) {+ if (path.length > MAX_PATH_CHARS)+ throw new Error(`Export path must be at most ${MAX_PATH_CHARS} characters.`);+ if (path.includes("\\"))+ throw new Error("Export path must use forward slashes, for example models/door.glb.");+ if (path.startsWith("/") || /^[A-Za-z]:/.test(path))+ throw new Error("Export path must be relative to the export root, for example models/door.glb.");+ const segments = path.split("/");+ if (segments.length > MAX_SEGMENTS)+ throw new Error(`Export path must have at most ${MAX_SEGMENTS} segments.`);+ for (const segment of segments) {+ if (segment === "..")+ throw new Error('Export path must stay inside the export root; ".." is not allowed.');+ if (!PORTABLE_SEGMENT.test(segment) || segment.endsWith("."))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is not portable: use ASCII letters, digits, ".", "_" or "-", starting with a letter or digit.`);+ if (DEVICE_NAME.test(segment))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is a Windows device name; choose another name.`);+ }+ return segments;+}+function validateExportPath(path) {+ if (!path.toLowerCase().endsWith(".glb"))+ throw new Error("Export path must name a .glb file, for example models/door.glb.");+ const segments = rootRelativeSegments(path);+ const metadataFileName = `${segments.at(-1).slice(0, -4)}.kiln-metadata.json`;+ return {+ path,+ metadataPath: [...segments.slice(0, -1), metadataFileName].join("/"),+ metadataFileName+ };+}+var MAX_PATH_CHARS = 240, MAX_SEGMENTS = 8, PORTABLE_SEGMENT, DEVICE_NAME;+var init_export_root = __esm(() => {+ PORTABLE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+ DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;+});+// src/tools/registry.tsimport { z as z25 } from "zod";import * as THREE58 from "three";@@ -53333,6 +53372,11 @@ function createKilnAssetDefs(context, presentation = "grouped") {const profileExportInput = exportInput.extend({profile: z25.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")});+ const exportToInput = exportInput.extend({+ path: z25.string().max(240).describe("Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."),+ profile: z25.enum(["runtime", "editable"]).default("runtime").describe("runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only."),+ target: z25.enum(["three"]).optional().describe("Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).")+ });const importInput = z25.object({...selector,sourceCollection: selector.collection@@ -53509,6 +53553,7 @@ function createKilnAssetDefs(context, presentation = "grouped") {};}},+ ...context.exportRoot && context.assetLibrary ? [createKilnExportToDef(context.exportRoot, exportToInput, library, listCall)] : [],{name: "kiln_import",description: "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",@@ -53523,6 +53568,61 @@ function createKilnAssetDefs(context, presentation = "grouped") {}];}+function createKilnExportToDef(writer, inputSchema, library, listCall) {+ return {+ name: "kiln_export_to",+ description: "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ inputSchema,+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false+ },+ run: async (raw) => {+ const input = inputSchema.parse(raw);+ if (input.target !== undefined && input.profile !== "runtime")+ throw new Error("target requires profile runtime");+ await Promise.resolve().then(() => init_export_root());+ const destination = validateExportPath(input.path);+ await Promise.resolve().then(() => init_asset_export());+ if (input.profile === "runtime")+ validateMetadataFileName(destination.metadataFileName);+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId, listCall(input.collection));+ const files = [];+ if (input.profile === "runtime") {+ const output = await exportAssetGlb(record, {+ profile: "runtime",+ metadataFileName: destination.metadataFileName,+ ...input.target ? { target: input.target } : {}+ });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ files.push({ kind: "glb", path: destination.path, data: output.glb }, { kind: "metadata", path: destination.metadataPath, data: output.metadata.bytes });+ } else+ files.push({ kind: "glb", path: destination.path, data: record.files["asset.glb"] });+ await writer.writeNew([...files].reverse());+ await Promise.resolve().then(() => init_draw_diagnostics());+ const digest = async (data) => `sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(data))), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ return {+ ok: true,+ collection: input.collection,+ assetId: input.assetId,+ revisionId: input.revisionId,+ profile: input.profile,+ ...input.target ? { target: input.target } : {},+ format: "glb",+ drawDiagnostics: await inspectDrawDiagnostics(files[0].data),+ files: await Promise.all(files.map(async ({ kind, path, data }) => ({+ kind,+ path,+ bytes: data.byteLength,+ sha256: await digest(data)+ })))+ };+ }+ };+}var 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.", validateInput, renderInput, renderViewsInput, reviewDetailOptions = (context) => ({retainedReport: () => {const operation = context.liveReview?.currentOperation?.();diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 9cac97e7..4263a64c 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -9798,7 +9798,8 @@ var init_runtime_three = __esm(() => {// src/asset-export.tsvar exports_asset_export = {};__export(exports_asset_export, {- exportAssetGlb: () => exportAssetGlb+ exportAssetGlb: () => exportAssetGlb,+ validateMetadataFileName: () => validateMetadataFileName});async function sha2562(bytes) {const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));@@ -10112,6 +10113,44 @@ var init_assets_resources = __esm(() => {};});+// src/export-root.ts+function rootRelativeSegments(path) {+ if (path.length > MAX_PATH_CHARS)+ throw new Error(`Export path must be at most ${MAX_PATH_CHARS} characters.`);+ if (path.includes("\\"))+ throw new Error("Export path must use forward slashes, for example models/door.glb.");+ if (path.startsWith("/") || /^[A-Za-z]:/.test(path))+ throw new Error("Export path must be relative to the export root, for example models/door.glb.");+ const segments = path.split("/");+ if (segments.length > MAX_SEGMENTS)+ throw new Error(`Export path must have at most ${MAX_SEGMENTS} segments.`);+ for (const segment of segments) {+ if (segment === "..")+ throw new Error('Export path must stay inside the export root; ".." is not allowed.');+ if (!PORTABLE_SEGMENT.test(segment) || segment.endsWith("."))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is not portable: use ASCII letters, digits, ".", "_" or "-", starting with a letter or digit.`);+ if (DEVICE_NAME.test(segment))+ throw new Error(`Export path segment ${JSON.stringify(segment)} is a Windows device name; choose another name.`);+ }+ return segments;+}+function validateExportPath(path) {+ if (!path.toLowerCase().endsWith(".glb"))+ throw new Error("Export path must name a .glb file, for example models/door.glb.");+ const segments = rootRelativeSegments(path);+ const metadataFileName = `${segments.at(-1).slice(0, -4)}.kiln-metadata.json`;+ return {+ path,+ metadataPath: [...segments.slice(0, -1), metadataFileName].join("/"),+ metadataFileName+ };+}+var MAX_PATH_CHARS = 240, MAX_SEGMENTS = 8, PORTABLE_SEGMENT, DEVICE_NAME;+var init_export_root = __esm(() => {+ PORTABLE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+ DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;+});+// src/evaluator/solid-diagnostic.tsfunction validSolidFailureDetails(value) {if (!record5(value) || !keys(value, ["total", "truncated", "meshes"]) || !count2(value.total) || value.total < 1 || !Array.isArray(value.meshes) || value.meshes.length !== Math.min(value.total, MAX_SOLID_FAILURE_MESHES) || value.truncated !== value.total > value.meshes.length)@@ -10148,7 +10187,7 @@ var init_solid_diagnostic = __esm(() => {});// src/qa/registry.ts-import { createHash as createHash8 } from "node:crypto";+import { createHash as createHash9 } from "node:crypto";function canonicalCalibrationReportEvidence(report) {return JSON.stringify({schemaVersion: report.schemaVersion,@@ -10181,7 +10220,7 @@ function canonicalCalibrationReportEvidence(report) {});}function calibrationReportEvidenceSha256(report) {- return createHash8("sha256").update(canonicalCalibrationReportEvidence(report)).digest("hex");+ return createHash9("sha256").update(canonicalCalibrationReportEvidence(report)).digest("hex");}function conformancePromotionAuthorization(fixtureSetId, fixturePath, evidenceSha256, owner = KILN_ENGINE_QA_OWNER, frozenAt = "2026-07-09T00:00:00.000Z", authorizedMode = "enforce", rendererId = LEGACY_CPU_RASTER_RENDERER_ID) {return {@@ -20905,12 +20944,12 @@ var init_requirements = __esm(() => {});// src/requirements-identity.ts-import { createHash as createHash9 } from "node:crypto";-function canonical(value) {+import { createHash as createHash10 } from "node:crypto";+function canonical2(value) {if (Array.isArray(value))- return `[${value.map(canonical).join(",")}]`;+ return `[${value.map(canonical2).join(",")}]`;if (value !== null && typeof value === "object") {- return `{${Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(",")}}`;+ return `{${Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonical2(entry)}`).join(",")}}`;}return JSON.stringify(value);}@@ -20925,7 +20964,7 @@ function assetRequirementsPolicyHash(input) {..."value" in value ? { value: value.value } : {}});const effective = Object.fromEntries(Object.entries(requirements.requirements).filter(([, value]) => value !== undefined).map(([key, value]) => [key, withoutReason(value)]));- return createHash9("sha256").update(canonical({+ return createHash10("sha256").update(canonical2({kind: requirements.kind,schemaVersion: requirements.schemaVersion,frame,@@ -20954,13 +20993,13 @@ var init_requirements_json = __esm(() => {});// src/requirements-context.ts-import { createHash as createHash10 } from "node:crypto";+import { createHash as createHash11 } from "node:crypto";import { z as z7 } from "zod";-function canonical2(value) {+function canonical3(value) {if (Array.isArray(value))- return `[${value.map(canonical2).join(",")}]`;+ return `[${value.map(canonical3).join(",")}]`;if (value !== null && typeof value === "object")- return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, v]) => `${JSON.stringify(key)}:${canonical2(v)}`).join(",")}}`;+ return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, v]) => `${JSON.stringify(key)}:${canonical3(v)}`).join(",")}}`;return JSON.stringify(value);}function contextHash(requirements, kind) {@@ -20974,7 +21013,7 @@ function contextHash(requirements, kind) {...requirements.scope && includes(requirements.scope.state) ? { scope: statement(requirements.scope) } : {},requirements: Object.fromEntries(Object.entries(requirements.requirements).filter(([, value]) => value && includes(value.state)).map(([key, value]) => [key, statement(value)]))};- return `sha256:${createHash10("sha256").update(`kiln.requirements-${kind}.v1`).update(canonical2(semantic)).digest("hex")}`;+ return `sha256:${createHash11("sha256").update(`kiln.requirements-${kind}.v1`).update(canonical3(semantic)).digest("hex")}`;}function validateRequirementsBinding(input) {const parsed = RequirementsBindingSchema.safeParse(input);@@ -21000,12 +21039,12 @@ function validateRequirementsContext(input) {if (Object.keys(raw).some((key) => !["kind", "requirements", "binding", "policyHash", "adviceHash"].includes(key)))throw new TypeError("Invalid requirements context fields.");const expected = resolveRequirementsContext(raw.binding);- if (canonical2(raw) !== canonical2(expected))+ if (canonical3(raw) !== canonical3(expected))throw new TypeError("Requirements context does not match its binding.");return expected;}function requirementsContextsEqual(left, right) {- return canonical2(left) === canonical2(right);+ return canonical3(left) === canonical3(right);}function createRequirementsCheckpoint(programRef, binding) {return CheckpointSchema.parse({ kind: "kiln.requirements-checkpoint.v1", programRef, binding });@@ -21360,7 +21399,7 @@ function validateRequirementsQaReport(input, context) {evaluatedDimensions: evaluated,metrics});- if (canonical3(expected) !== canonical3(result))+ if (canonical4(expected) !== canonical4(result))return fail();} else {const blocked = findings.some((finding) => finding.disposition === "block");@@ -21369,7 +21408,7 @@ function validateRequirementsQaReport(input, context) {}return result;}-var REQUIREMENTS_QA_DIMENSIONS, record8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), canonical3 = (value) => Array.isArray(value) ? `[${value.map(canonical3).join(",")}]` : record8(value) ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical3(value[key])}`).join(",")}}` : JSON.stringify(value);+var REQUIREMENTS_QA_DIMENSIONS, record8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), canonical4 = (value) => Array.isArray(value) ? `[${value.map(canonical4).join(",")}]` : record8(value) ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical4(value[key])}`).join(",")}}` : JSON.stringify(value);var init_requirements_report = __esm(() => {init_requirements_applicability();init_types();@@ -32691,7 +32730,7 @@ var init_kit = __esm(() => {});// src/texture-bake.ts-import { createHash as createHash11 } from "node:crypto";+import { createHash as createHash12 } from "node:crypto";import * as THREE50 from "three";function readPixels(texture) {const image = texture.image;@@ -32791,7 +32830,7 @@ async function bakeSceneTextures(root, warnings) {if (encoded) {const delivery = readValidatedAtlasDelivery(entry.texture);if (delivery) {- if (delivery.id !== atlasRef.id || delivery.finalMime !== encoded.mime || delivery.finalImageSha256 !== `sha256:${createHash11("sha256").update(encoded.bytes).digest("hex")}`)+ if (delivery.id !== atlasRef.id || delivery.finalMime !== encoded.mime || delivery.finalImageSha256 !== `sha256:${createHash12("sha256").update(encoded.bytes).digest("hex")}`)throw stale();} else {const sharp = (await import("sharp")).default;@@ -32802,10 +32841,10 @@ async function bakeSceneTextures(root, warnings) {if (metadata.width !== atlasRecord.spec.width || metadata.height !== atlasRecord.spec.height)throw stale();const decoded = await image.ensureAlpha().raw().toBuffer();- if (`sha256:${createHash11("sha256").update(decoded).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)+ if (`sha256:${createHash12("sha256").update(decoded).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)throw stale();}- } else if (raw.width !== atlasRecord.spec.width || raw.height !== atlasRecord.spec.height || raw.channels !== 4 || `sha256:${createHash11("sha256").update(raw.data).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)+ } else if (raw.width !== atlasRecord.spec.width || raw.height !== atlasRecord.spec.height || raw.channels !== 4 || `sha256:${createHash12("sha256").update(raw.data).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)throw stale();}let bytes;@@ -32830,8 +32869,8 @@ async function bakeSceneTextures(root, warnings) {height: raw.height,hasAlpha: hasTranslucentPixel(raw)};- const sha1 = createHash11("sha1").update(bytes).digest("hex");- const imageSha256 = `sha256:${createHash11("sha256").update(bytes).digest("hex")}`;+ const sha1 = createHash12("sha1").update(bytes).digest("hex");+ const imageSha256 = `sha256:${createHash12("sha256").update(bytes).digest("hex")}`;baked.push({schemaVersion: 1,texture: name,@@ -35506,7 +35545,7 @@ __export(exports_capture_cache, {captureCpuCell: () => captureCpuCell,createCachedRenderPort: () => createCachedRenderPort});-import { createHash as createHash12 } from "node:crypto";+import { createHash as createHash13 } from "node:crypto";function clone(entry) {const result = structuredClone(entry);if (result.kind === "cpu")@@ -35562,11 +35601,11 @@ class MemoryCaptureCache {return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };}}-function canonical4(value) {+function canonical5(value) {if (Array.isArray(value))- return value.map(canonical4);+ return value.map(canonical5);if (value && typeof value === "object")- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, canonical4(v)]));+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, canonical5(v)]));if (typeof value === "number" && !Number.isFinite(value))throw new Error("Non-finite capture identity");if (value === undefined || value === null || ["string", "number", "boolean"].includes(typeof value))@@ -35711,7 +35750,7 @@ async function captureCpuCell(cache, identity, produce) {await cache.put(key, { kind: "cpu", result }).catch(() => {});return { ...result, png: Buffer.from(result.png), captureCache: { hit: false } };}-var text4 = (value) => JSON.stringify(canonical4(value)), digest4 = (value) => `sha256:${createHash12("sha256").update(value).digest("hex")}`;+var text4 = (value) => JSON.stringify(canonical5(value)), digest4 = (value) => `sha256:${createHash13("sha256").update(value).digest("hex")}`;var init_capture_cache = __esm(() => {init_render_port();init_png();@@ -39186,7 +39225,7 @@ var init_render = __esm(() => {});// src/evaluator/protocol.ts-import { createHash as createHash13 } from "node:crypto";+import { createHash as createHash14 } from "node:crypto";function evaluatorOutcomeMessage(code) {return EVALUATOR_OUTCOME_MESSAGES[code];}@@ -39339,7 +39378,7 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {fail9("result");if (!isSha256(value.render.artifactGlbSha256))fail9("result");- const actualHash = `sha256:${createHash13("sha256").update(glb).digest("hex")}`;+ const actualHash = `sha256:${createHash14("sha256").update(glb).digest("hex")}`;if (actualHash !== value.render.artifactGlbSha256)fail9("result");const diagnosticViews = value.render.diagnosticViews;@@ -42442,27 +42481,201 @@ async function buildRenderPort(mode, portUrl, options) {return context;}-// src/live-review-node.ts-init_assets();-import { AsyncLocalStorage } from "node:async_hooks";+// src/export-root-node.ts+import { lstat as lstat5, realpath as realpath4, stat as stat2 } from "node:fs/promises";+import { isAbsolute, join as join9, relative as relative4, resolve as resolve5, sep as sep3 } from "node:path";+import { platform as platform2 } from "node:os";++// src/cli-output.tsimport { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";import {+ chmod,+ lstat as lstat4,link as link2,mkdir as mkdir3,- lstat as lstat4,- readdir as readdir3,+ open,readFile as readFile3,+ realpath as realpath3,rename as rename2,- rm as rm3,+ stat,unlink,- writeFile as writeFile3,- realpath as realpath3+ writeFile as writeFile3+} from "node:fs/promises";+import { basename, dirname as dirname5, join as join8, resolve as resolve4 } from "node:path";+async function prepareDestination(path) {+ await mkdir3(dirname5(path), { recursive: true });+ return path;+}+async function writeNewDestinationsAtomic(outputs) {+ const paths = outputs.map(({ path }) => {+ const absolute = resolve4(path);+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;+ });+ if (new Set(paths).size !== paths.length)+ throw new Error("Export destinations must be distinct");+ const staged = [];+ try {+ for (const { path, data } of outputs) {+ await prepareDestination(path);+ const temporary = join8(dirname5(path), `.kiln-write-${randomUUID3()}.tmp`);+ const file = await open(temporary, "wx");+ staged.push({ path, temporary, published: false });+ try {+ await writeFile3(file, data);+ } finally {+ await file.close();+ }+ }+ for (const output of staged) {+ try {+ await link2(output.temporary, output.path);+ } catch (error) {+ if (error.code !== "EEXIST")+ throw error;+ throw Object.assign(new Error(`${output.path} already exists and is never replaced; choose a new output path or remove the file.`), { code: "EEXIST" });+ }+ output.published = true;+ }+ } catch (error) {+ for (const output of staged.filter((item) => item.published).reverse()) {+ try {+ const [destination, temporary] = await Promise.all([+ lstat4(output.path),+ lstat4(output.temporary)+ ]);+ if (destination.dev === temporary.dev && destination.ino === temporary.ino)+ await unlink(output.path);+ } catch {}+ }+ throw error;+ } finally {+ await Promise.all(staged.map(({ temporary }) => unlink(temporary).catch(() => {})));+ }+}++// src/export-root-node.ts+init_export_root();+var windowsDrivePath2 = /^[A-Za-z]:[\\/]/;+var windowsSharePath2 = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;+var RESTART = "Correct KILN_EXPORT_ROOT and restart the MCP session.";+function inside(parent, child) {+ const rel = relative4(parent, child);+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute(rel);+}+async function canonical(path) {+ try {+ return await realpath4(path);+ } catch (error) {+ if (error.code === "ENOENT")+ return resolve5(path);+ throw error;+ }+}+async function resolveExportRoot(value, options) {+ const operatingSystem = options.operatingSystem ?? platform2();+ if (operatingSystem === "win32" && !windowsDrivePath2.test(value) && !windowsSharePath2.test(value)) {+ const gitBash = /^\/([A-Za-z])(?:\/|$)/.exec(value);+ if (gitBash)+ throw new Error(`KILN_EXPORT_ROOT is a Git Bash path (/${gitBash[1]}/...); Windows would resolve it against the current drive. Write it as ${gitBash[1].toUpperCase()}:/... or a UNC share. ${RESTART}`);+ throw new Error(`KILN_EXPORT_ROOT must be an absolute directory: a Windows drive (C:/...) or UNC share. ${RESTART}`);+ }+ if (!isAbsolute(value))+ throw new Error(`KILN_EXPORT_ROOT must be an absolute directory. ${RESTART}`);+ let entry;+ try {+ entry = await stat2(value);+ } catch (error) {+ if (error.code === "ENOENT")+ throw new Error(`KILN_EXPORT_ROOT does not exist; create the directory or ${RESTART[0].toLowerCase()}${RESTART.slice(1)}`);+ throw new Error(`KILN_EXPORT_ROOT could not be read (${error.code ?? "error"}). ${RESTART}`);+ }+ if (!entry.isDirectory())+ throw new Error(`KILN_EXPORT_ROOT is not a directory. ${RESTART}`);+ const root = await realpath4(value);+ for (const collection of options.collectionRoots) {+ const directory = await canonical(collection);+ if (inside(directory, root) || inside(root, directory))+ throw new Error(`KILN_EXPORT_ROOT overlaps a collection directory; saved revisions never change. Choose a directory outside every collection and .kiln/. ${RESTART}`);+ }+ if (options.workspaceRoot !== undefined) {+ const state = await canonical(join9(options.workspaceRoot, ".kiln"));+ if (inside(state, root) || inside(root, state))+ throw new Error(`KILN_EXPORT_ROOT overlaps the workspace .kiln/ directory. Choose a directory outside every collection and .kiln/. ${RESTART}`);+ }+ return root;+}+function createExportRootWriter(root) {+ return {+ async writeNew(files) {+ const targets = files.map(({ path, data }) => ({+ path,+ segments: rootRelativeSegments(path),+ absolute: join9(root, ...rootRelativeSegments(path)),+ data+ }));+ for (const target of targets) {+ let deepest = root;+ for (const [index, segment] of target.segments.slice(0, -1).entries()) {+ const next = join9(deepest, segment);+ let entry;+ try {+ entry = await lstat5(next);+ } catch (error) {+ if (error.code === "ENOENT")+ break;+ throw error;+ }+ const shown = target.segments.slice(0, index + 1).join("/");+ if (entry.isSymbolicLink())+ throw new Error(`${shown} in the export root is a symlink or junction; links are not followed. Choose a path through ordinary directories.`);+ if (!entry.isDirectory())+ throw new Error(`${shown} in the export root is a file, not a directory.`);+ deepest = next;+ }+ if (!inside(root, await realpath4(deepest)))+ throw new Error(`${target.path} resolves outside the export root.`);+ }+ try {+ await writeNewDestinationsAtomic(targets.map(({ absolute, data }) => ({ path: absolute, data })));+ } catch (error) {+ const failure = error;+ if (failure.code === "EEXIST") {+ const existing = targets.find(({ absolute }) => failure.message.startsWith(absolute));+ throw new Error(`${existing?.path ?? "An export file"} already exists in the export root and is never replaced; choose a new path or remove the file.`);+ }+ throw new Error(`Could not write ${targets.map(({ path }) => path).join(" and ")} in the export root (${failure.code ?? failure.message.split(root).join("<export root>")}).`);+ }+ }+ };+}+async function exportRootWriterFromEnv(env, options) {+ const value = env["KILN_EXPORT_ROOT"];+ if (!value)+ return;+ return createExportRootWriter(await resolveExportRoot(value, options));+}++// src/live-review-node.ts+init_assets();+import { AsyncLocalStorage } from "node:async_hooks";+import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";+import {+ link as link3,+ mkdir as mkdir4,+ lstat as lstat6,+ readdir as readdir3,+ readFile as readFile4,+ rename as rename3,+ rm as rm3,+ unlink as unlink2,+ writeFile as writeFile4,+ realpath as realpath5} from "node:fs/promises";-import { join as join8, resolve as resolve4, relative as relative4, sep as sep3 } from "node:path";+import { join as join10, resolve as resolve6, relative as relative5, sep as sep4 } from "node:path";import { z as z4 } from "zod";var operationPattern = /^op_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;var filePattern = /^(asset\.glb|source\.kiln\.js|evaluation\.json|capture-\d{1,2}\.png)$/;-var hash3 = (value) => `sha256:${createHash7("sha256").update(value).digest("hex")}`;+var hash3 = (value) => `sha256:${createHash8("sha256").update(value).digest("hex")}`;var metadataLimit = 256 * 1024;var evaluationLimit = 2 * 1024 * 1024;var staleMs = 120000;@@ -42661,7 +42874,7 @@ function dead(pid) {class FileLiveReview {directory;- sessionId = randomUUID3();+ sessionId = randomUUID4();workspace;current = new AsyncLocalStorage;queue = new Map;@@ -42676,8 +42889,8 @@ class FileLiveReview {storedSizes = new WeakMap;unreportedIssues = [];constructor(workspace, options = {}) {- this.workspace = resolve4(workspace);- this.directory = join8(this.workspace, ".kiln", "review");+ this.workspace = resolve6(workspace);+ this.directory = join10(this.workspace, ".kiln", "review");this.maxOperations = options.maxOperations ?? 200;this.maxBytes = options.maxBytes ?? 256 * 1024 * 1024;this.maxQueuedBytes = options.maxQueuedBytes ?? 128 * 1024 * 1024;@@ -42700,44 +42913,44 @@ class FileLiveReview {path(operationId, file) {if (!operationPattern.test(operationId))throw new Error("Invalid operation ID");- return join8(this.directory, operationId, ...file ? [file] : []);+ return join10(this.directory, operationId, ...file ? [file] : []);}async root(create = false) {if (create)- await mkdir3(this.workspace, { recursive: true });- const canonical = await realpath3(this.workspace);+ await mkdir4(this.workspace, { recursive: true });+ const canonical = await realpath5(this.workspace);let path = this.workspace;for (const part of [".kiln", "review"]) {- path = join8(path, part);+ path = join10(path, part);if (create)- await mkdir3(path).catch((error) => {+ await mkdir4(path).catch((error) => {if (!collision(error))throw error;});- const info = await lstat4(path);+ const info = await lstat6(path);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live directory");- const rel = relative4(canonical, await realpath3(path));- if (rel === ".." || rel.startsWith(`..${sep3}`))+ const rel = relative5(canonical, await realpath5(path));+ if (rel === ".." || rel.startsWith(`..${sep4}`))throw new Error("Live directory escapes workspace");}}async boundedFile(path, limit) {- const info = await lstat4(path);+ const info = await lstat6(path);if (!info.isFile() || info.isSymbolicLink() || info.size > limit)throw new Error("Invalid live file");- const data = new Uint8Array(await readFile3(path));+ const data = new Uint8Array(await readFile4(path));if (data.length !== info.size || data.length > limit)throw new Error("Live file changed while reading");return data;}async atomic(path, bytes) {- const temporary = `${path}.${randomUUID3()}.tmp`;+ const temporary = `${path}.${randomUUID4()}.tmp`;try {- await writeFile3(temporary, bytes, { flag: "wx", mode: 384 });- await rename2(temporary, path);+ await writeFile4(temporary, bytes, { flag: "wx", mode: 384 });+ await rename3(temporary, path);} finally {- await unlink(temporary).catch((error) => {+ await unlink2(temporary).catch((error) => {if (!missing(error))throw error;});@@ -42745,18 +42958,18 @@ class FileLiveReview {}async locked(run) {await this.root(true);- const token = randomUUID3();- const directory = join8(this.directory, ".locks");- await mkdir3(directory).catch((error) => {+ const token = randomUUID4();+ const directory = join10(this.directory, ".locks");+ await mkdir4(directory).catch((error) => {if (!collision(error))throw error;});- const info = await lstat4(directory);+ const info = await lstat6(directory);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live lock directory");- const candidate = join8(directory, `.candidate-${process.pid}-${token}.tmp`);+ const candidate = join10(directory, `.candidate-${process.pid}-${token}.tmp`);const owner = JSON.stringify({ pid: process.pid, token });- await writeFile3(candidate, owner, { flag: "wx", mode: 384 });+ await writeFile4(candidate, owner, { flag: "wx", mode: 384 });const generations = async () => (await readdir3(directory)).filter((name) => /^[0-9]{16}\.lock$/.test(name)).sort();const deadline = Date.now() + 3000;let acquired;@@ -42771,8 +42984,8 @@ class FileLiveReview {throw new Error("Live lock generation exhausted");if (latest) {try {- const prior = z4.object({ pid: z4.number().int().positive(), token: z4.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join8(directory, latest), 1024))));- const released = await lstat4(join8(directory, `${latest}.released`)).then((entry) => {+ const prior = z4.object({ pid: z4.number().int().positive(), token: z4.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, latest), 1024))));+ const released = await lstat6(join10(directory, `${latest}.released`)).then((entry) => {if (!entry.isFile() || entry.isSymbolicLink() || entry.size !== 0)throw new Error("Invalid lock release");return true;@@ -42793,9 +43006,9 @@ class FileLiveReview {}const name = `${String(sequence).padStart(16, "0")}.lock`;try {- await link2(candidate, join8(directory, name));+ await link3(candidate, join10(directory, name));if ((await generations()).at(-1) !== name) {- await unlink(join8(directory, name));+ await unlink2(join10(directory, name));continue;}acquired = name;@@ -42805,8 +43018,8 @@ class FileLiveReview {}}for (const name of (await generations()).slice(0, -3)) {- await unlink(join8(directory, name));- await unlink(join8(directory, `${name}.released`)).catch((error) => {+ await unlink2(join10(directory, name));+ await unlink2(join10(directory, `${name}.released`)).catch((error) => {if (!missing(error))throw error;});@@ -42814,18 +43027,18 @@ class FileLiveReview {for (const name of await readdir3(directory)) {const match = /^\.candidate-([0-9]+)-[a-f0-9-]+\.tmp$/.exec(name);if (match && dead(Number(match[1])))- await unlink(join8(directory, name)).catch(() => {});+ await unlink2(join10(directory, name)).catch(() => {});}await this.limits(true);return await run();} finally {if (acquired)- await writeFile3(join8(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });- await unlink(candidate).catch(() => {});+ await writeFile4(join10(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });+ await unlink2(candidate).catch(() => {});}}async limits(create = false) {- const path = join8(this.directory, "limits.json");+ const path = join10(this.directory, "limits.json");try {const value = JSON.parse(new TextDecoder().decode(await this.boundedFile(path, 1024)));const parsed = z4.object({@@ -42899,7 +43112,7 @@ class FileLiveReview {try {await this.locked(async () => {const previous = await this.health();- await this.atomic(join8(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));+ await this.atomic(join10(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));});this.unreportedIssues = this.unreportedIssues.filter((value) => !issues.includes(value));} catch {}@@ -42938,7 +43151,7 @@ class FileLiveReview {heartbeatAt: now,operation: {version: "kiln.live.v1",- operationId: `op_${randomUUID3()}`,+ operationId: `op_${randomUUID4()}`,revision: 0,tool: String(tool).slice(0, 120) || "unknown",transport: this.transport,@@ -43059,10 +43272,10 @@ class FileLiveReview {async record(operationId) {await this.root();const directory = this.path(operationId);- const info = await lstat4(directory);+ const info = await lstat6(directory);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live directory");- const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join8(directory, "record.json"), metadataLimit)));+ const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, "record.json"), metadataLimit)));const state = stateSchema.parse(jsonValue(raw, metadataLimit));if (state.operation.operationId !== operationId)throw new Error("Invalid live identity");@@ -43081,7 +43294,7 @@ class FileLiveReview {throw new Error("Invalid artifact descriptor");if (state.operation.captures.some((file) => !/^capture-\d{1,2}\.png$/.test(file.name)))throw new Error("Invalid capture descriptor");- state.operation.pinned = await lstat4(join8(directory, "pinned")).then((s) => {+ state.operation.pinned = await lstat6(join10(directory, "pinned")).then((s) => {if (!s.isFile() || s.isSymbolicLink())throw new Error("Invalid live pin");return true;@@ -43103,7 +43316,7 @@ class FileLiveReview {for (const entry of await readdir3(directory, { withFileTypes: true })) {if (!entry.isFile() || entry.isSymbolicLink())throw new Error("Invalid live directory entry");- bytes += (await lstat4(join8(directory, entry.name))).size;+ bytes += (await lstat6(join10(directory, entry.name))).size;}this.storedSizes.set(state, bytes);return state;@@ -43154,7 +43367,7 @@ class FileLiveReview {}async health() {try {- return z4.array(z4.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join8(this.directory, "health.json"), 16384))));+ return z4.array(z4.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(this.directory, "health.json"), 16384))));} catch (error) {if (missing(error))return [];@@ -43171,7 +43384,7 @@ class FileLiveReview {for (const file of await readdir3(this.path(id), { withFileTypes: true })) {if (allowed.has(file.name) || !file.isFile() || file.isSymbolicLink())continue;- await unlink(this.path(id, file.name));+ await unlink2(this.path(id, file.name));changed = true;this.report("Removed unpublished live payloads left by an interrupted storage transaction.");}@@ -43214,20 +43427,20 @@ class FileLiveReview {return;}const directory = this.path(state.operation.operationId);- await mkdir3(directory).catch((error) => {+ await mkdir4(directory).catch((error) => {if (!collision(error))throw error;});- if ((await lstat4(directory)).isSymbolicLink())+ if ((await lstat6(directory)).isSymbolicLink())throw new Error("Unsafe live directory");for (const [name, data] of Object.entries(blobs))- await this.atomic(join8(directory, name), data);- await this.atomic(join8(directory, "record.json"), JSON.stringify(state));+ await this.atomic(join10(directory, name), data);+ await this.atomic(join10(directory, "record.json"), JSON.stringify(state));await this.cleanupRecord(await this.record(state.operation.operationId));}async remove(operationId) {const directory = this.path(operationId);- const info = await lstat4(directory);+ const info = await lstat6(directory);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live directory");await rm3(directory, { recursive: true, force: true });@@ -43281,7 +43494,7 @@ class FileLiveReview {throw new Error("Pinned evidence exceeds the shared byte budget");await this.atomic(path, "pinned");} else- await unlink(path);+ await unlink2(path);});}}@@ -43292,9 +43505,9 @@ init_isolation();init_render();// src/program-store-node.ts-import { link as link3, lstat as lstat5, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, stat, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";-import { randomUUID as randomUUID4 } from "node:crypto";-import { join as join9 } from "node:path";+import { link as link4, lstat as lstat7, mkdir as mkdir5, readFile as readFile5, readdir as readdir4, stat as stat3, unlink as unlink3, writeFile as writeFile5 } from "node:fs/promises";+import { randomUUID as randomUUID5 } from "node:crypto";+import { join as join11 } from "node:path";// src/program-store.tsvar MAX_PROGRAM_BYTES = 1024 * 1024;@@ -43396,7 +43609,7 @@ class FileProgramStore {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat(join9(this.directory, entry.name))).size;+ bytes += (await stat3(join11(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -43414,12 +43627,12 @@ class FileProgramStore {const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;if (canonical === undefined)throw this.notFound(ref);- const path = join9(this.directory, `${canonical.slice(7)}.js`);+ const path = join11(this.directory, `${canonical.slice(7)}.js`);let code;try {- if ((await stat(path)).size > MAX_PROGRAM_BYTES)+ if ((await stat3(path)).size > MAX_PROGRAM_BYTES)throw new Error("Stored program exceeds the 1 MiB source limit.");- code = await readFile4(path, "utf8");+ code = await readFile5(path, "utf8");} catch (error) {if (error.code === "ENOENT")throw this.notFound(ref);@@ -43433,12 +43646,12 @@ class FileProgramStore {return programNotFound(ref, "This program store has no such reference; it was issued by another store (KILN_PROGRAM_STORE selects which) or its store was removed.");}async readHandle(handle) {- const path = join9(this.directory, "refs", `${handle}.ref`);+ const path = join11(this.directory, "refs", `${handle}.ref`);try {- const info = await lstat5(path);+ const info = await lstat7(path);if (!info.isFile() || info.size !== 71)throw new Error(`Program handle integrity check failed: ${handle}`);- const canonical = await readFile4(path, "utf8");+ const canonical = await readFile5(path, "utf8");if (!canonicalProgramRefPattern.test(canonical) || !canonical.slice(7).startsWith(handle.slice(2)))throw new Error(`Program handle integrity check failed: ${handle}`);return canonical;@@ -43452,19 +43665,19 @@ class FileProgramStore {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join9(this.directory, "refs");- await mkdir4(directory, { recursive: true });+ const directory = join11(this.directory, "refs");+ await mkdir5(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);if (owner === ref)return handle;if (owner !== undefined)continue;- const temporary = join9(directory, `.write-${randomUUID4()}`);- await writeFile4(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join11(directory, `.write-${randomUUID5()}`);+ await writeFile5(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link3(temporary, join9(directory, `${handle}.ref`));+ await link4(temporary, join11(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -43473,27 +43686,27 @@ class FileProgramStore {return handle;}} finally {- await unlink2(temporary);+ await unlink3(temporary);}}throw new Error("Unable to register an immutable program handle.");}async put(code) {const ref = await programReference(code);- await mkdir4(this.directory, { recursive: true });- const target = join9(this.directory, `${ref.slice(7)}.js`);- const temporary = join9(this.directory, `.write-${randomUUID4()}`);- await writeFile4(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });+ await mkdir5(this.directory, { recursive: true });+ const target = join11(this.directory, `${ref.slice(7)}.js`);+ const temporary = join11(this.directory, `.write-${randomUUID5()}`);+ await writeFile5(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link3(temporary, target);+ await link4(temporary, target);} catch (error) {if (error.code !== "EEXIST")throw error;await this.get(ref);}} finally {- await unlink2(temporary);+ await unlink3(temporary);}return ref;}@@ -43506,7 +43719,7 @@ function localProgramStore(env = process.env) {init_protocol();init_requirements_context();init_requirements_report();-import { createHash as createHash14 } from "node:crypto";+import { createHash as createHash15 } from "node:crypto";import * as acorn2 from "acorn";import * as walk5 from "acorn-walk";function sourceHasAmbientInputs(code) {@@ -43592,15 +43805,15 @@ class MemoryBuildCache {return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };}}-function canonical5(value) {+function canonical6(value) {if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean")return value;if (typeof value === "number" && Number.isFinite(value))return value;if (Array.isArray(value))- return value.map(canonical5);+ return value.map(canonical6);if (typeof value === "object")- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => [key, canonical5(v)]));+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => [key, canonical6(v)]));throw new Error("Build input contains a non-data dependency.");}function validateBuildRequirements(result, expected, exact) {@@ -43636,7 +43849,7 @@ function createCachedEvaluatorPort(evaluator, options) {const { signal: _signal, ...dataControls } = controls ?? {};const snapshotControls = structuredClone(dataControls);controls = { ...snapshotControls, ...signal ? { signal } : {} };- serialized = JSON.stringify(canonical5({+ serialized = JSON.stringify(canonical6({version: "kiln.build-requirements.v1",identity,code,@@ -43652,7 +43865,7 @@ function createCachedEvaluatorPort(evaluator, options) {} catch {return evaluator.render(code, renderOptions, controls);}- const key = `sha256:${createHash14("sha256").update(serialized).digest("hex")}`;+ const key = `sha256:${createHash15("sha256").update(serialized).digest("hex")}`;const cached = await options.cache.get(key).catch(() => {return;});@@ -43702,43 +43915,43 @@ init_community_exporter();// src/build-cache-node.tsinit_protocol();-import { createHash as createHash15, randomUUID as randomUUID5 } from "node:crypto";+import { createHash as createHash16, randomUUID as randomUUID6 } from "node:crypto";import {- mkdir as mkdir5,- readFile as readFile5,+ mkdir as mkdir6,+ readFile as readFile6,readdir as readdir5,- rename as rename3,- stat as stat2,- unlink as unlink3,+ rename as rename4,+ stat as stat4,+ unlink as unlink4,utimes,- writeFile as writeFile5+ writeFile as writeFile6} from "node:fs/promises";-import { join as join10, resolve as resolve5 } from "node:path";+import { join as join12, resolve as resolve7 } from "node:path";var keyPattern = /^sha256:[a-f0-9]{64}$/;var filePattern2 = /^[a-f0-9]{64}\.json$/;-var digest5 = (text) => createHash15("sha256").update(text).digest("hex");+var digest5 = (text) => createHash16("sha256").update(text).digest("hex");class FileBuildCache {maxBytes;directory;constructor(directory, maxBytes = 128 * 1024 * 1024) {this.maxBytes = maxBytes;- this.directory = resolve5(directory);+ this.directory = resolve7(directory);if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)throw new Error("File build cache size must be 0..1 GiB.");}path(key) {if (!keyPattern.test(key))throw new Error("Invalid build cache key.");- return join10(this.directory, `${key.slice(7)}.json`);+ return join12(this.directory, `${key.slice(7)}.json`);}async get(key) {const path = this.path(key);try {- const entry = await stat2(path);+ const entry = await stat4(path);if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)return;- const envelope = JSON.parse(await readFile5(path, "utf8"));+ const envelope = JSON.parse(await readFile6(path, "utf8"));if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest5(envelope.payload))return;const decoded = decodeEvaluatorResultV2(envelope.payload, 64 * 1024 * 1024);@@ -43757,13 +43970,13 @@ class FileBuildCache {const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest5(payload) });if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))return;- await mkdir5(this.directory, { recursive: true });- const temporary = join10(this.directory, `.write-${randomUUID5()}`);- await writeFile5(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });+ await mkdir6(this.directory, { recursive: true });+ const temporary = join12(this.directory, `.write-${randomUUID6()}`);+ await writeFile6(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });try {- await rename3(temporary, path);+ await rename4(temporary, path);} finally {- await unlink3(temporary).catch(() => {});+ await unlink4(temporary).catch(() => {});}await this.trim();}@@ -43772,9 +43985,9 @@ class FileBuildCache {for (const name of await readdir5(this.directory)) {if (!filePattern2.test(name))continue;- const path = join10(this.directory, name);+ const path = join12(this.directory, name);try {- const item = await stat2(path);+ const item = await stat4(path);entries.push({ path, size: item.size, used: item.mtimeMs });} catch {}}@@ -43783,18 +43996,18 @@ class FileBuildCache {for (const entry of entries) {if (bytes <= this.maxBytes)break;- await unlink3(entry.path).catch(() => {});+ await unlink4(entry.path).catch(() => {});bytes -= entry.size;}}}// src/runtime-identity.ts-import { createHash as createHash16 } from "node:crypto";-import { lstat as lstat6, readFile as readFile6, readdir as readdir6, realpath as realpath4, stat as stat3 } from "node:fs/promises";+import { createHash as createHash17 } from "node:crypto";+import { lstat as lstat8, readFile as readFile7, readdir as readdir6, realpath as realpath6, stat as stat5 } from "node:fs/promises";import { createRequire as createRequire2 } from "node:module";-import { dirname as dirname5, join as join11, relative as relative5 } from "node:path";-var digest6 = (bytes) => createHash16("sha256").update(bytes).digest("hex");+import { dirname as dirname6, join as join13, relative as relative6 } from "node:path";+var digest6 = (bytes) => createHash17("sha256").update(bytes).digest("hex");var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;async function installedRuntimeIdentity(root, limits = {}) {let bytes = 0;@@ -43802,7 +44015,7 @@ async function installedRuntimeIdentity(root, limits = {}) {const absentPackages = [];const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;const maxFiles = limits.maxFiles ?? 40000;- const manifest = async (directory) => JSON.parse(await readFile6(join11(directory, "package.json"), "utf8"));+ const manifest = async (directory) => JSON.parse(await readFile7(join13(directory, "package.json"), "utf8"));let readers = 0;const waiting = [];const read = async (path) => {@@ -43811,11 +44024,11 @@ async function installedRuntimeIdentity(root, limits = {}) {elsereaders++;try {- const info = await stat3(path);+ const info = await stat5(path);if (++files > maxFiles || bytes + info.size > maxBytes)throw new Error("Installed runtime fingerprint exceeds its scan budget.");bytes += info.size;- return await readFile6(path);+ return await readFile7(path);} finally {const next = waiting.shift();if (next)@@ -43828,17 +44041,17 @@ async function installedRuntimeIdentity(root, limits = {}) {const pkg = await manifest(root);if (pkg.name !== "@instruktlabs/kiln")throw new Error("Not a Kiln installation.");- const build = JSON.parse(await readFile6(join11(root, "dist", "build.json"), "utf8"));+ const build = JSON.parse(await readFile7(join13(root, "dist", "build.json"), "utf8"));const worker = build.entries?.worker;if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))throw new Error("No valid packaged worker identity.");- const workerHash = `sha256:${digest6(await read(join11(root, "dist", worker.file)))}`;+ const workerHash = `sha256:${digest6(await read(join13(root, "dist", worker.file)))}`;if (worker.bundleHash !== workerHash)throw new Error("Packaged worker differs from its build manifest.");const records = [];const visited = new Map;async function resolvePackage(parent, name) {- const require2 = createRequire2(join11(parent, "package.json"));+ const require2 = createRequire2(join13(parent, "package.json"));let found;try {found = require2.resolve(`${name}/package.json`);@@ -43847,9 +44060,9 @@ async function installedRuntimeIdentity(root, limits = {}) {found = require2.resolve(name);} catch {for (const modules of require2.resolve.paths(name) ?? []) {- const candidate = join11(modules, name);+ const candidate = join13(modules, name);try {- await lstat6(candidate);+ await lstat8(candidate);} catch (error) {if (error.code === "ENOENT")continue;@@ -43857,18 +44070,18 @@ async function installedRuntimeIdentity(root, limits = {}) {}if ((await manifest(candidate)).name !== name)throw new Error(`Cannot identify installed dependency ${name}.`);- return await realpath4(candidate);+ return await realpath6(candidate);}return;}}- let directory = dirname5(found);+ let directory = dirname6(found);for (;; ) {try {if ((await manifest(directory)).name === name)- return await realpath4(directory);+ return await realpath6(directory);} catch {}- const next = dirname5(directory);+ const next = dirname6(directory);if (next === directory)throw new Error(`Cannot identify installed dependency ${name}.`);directory = next;@@ -43879,18 +44092,18 @@ async function installedRuntimeIdentity(root, limits = {}) {return (await Promise.all(entries.map(async (entry) => {if (entry.name === "node_modules" || entry.name === ".git")return [];- const path = join11(directory, entry.name);+ const path = join13(directory, entry.name);if (entry.isSymbolicLink())throw new Error("Dependency contains an untracked internal symlink.");if (entry.isDirectory())return tree(path, base);if (entry.isFile())- return [[relative5(base, path).replaceAll("\\", "/"), digest6(await read(path))]];+ return [[relative6(base, path).replaceAll("\\", "/"), digest6(await read(path))]];throw new Error("Dependency contains a non-file runtime input.");}))).flat();}async function visit(directory, path) {- const canonical = await realpath4(directory);+ const canonical = await realpath6(directory);const previous = visited.get(canonical);if (previous) {records.push([path, `same-package:${previous}`]);@@ -43956,20 +44169,20 @@ async function installedRuntimeIdentity(root, limits = {}) {}// src/local-runtime.ts-import { readFile as readFile7, stat as stat4 } from "node:fs/promises";-import { dirname as dirname6, isAbsolute, join as join14, resolve as resolve7 } from "node:path";+import { readFile as readFile8, stat as stat6 } from "node:fs/promises";+import { dirname as dirname7, isAbsolute as isAbsolute2, join as join16, resolve as resolve9 } from "node:path";import { fileURLToPath as fileURLToPath5 } from "node:url";import { Console } from "node:console";init_material_resources();// src/workspace-node.tsimport { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";-import { join as join13 } from "node:path";+import { join as join15 } from "node:path";// src/projects-node.ts-import { createHash as createHash17, randomUUID as randomUUID6 } from "node:crypto";-import { link as link4, lstat as lstat7, mkdir as mkdir6, open, readdir as readdir7, realpath as realpath5, unlink as unlink4 } from "node:fs/promises";-import { join as join12, relative as relative6, resolve as resolve6, sep as sep4 } from "node:path";+import { createHash as createHash18, randomUUID as randomUUID7 } from "node:crypto";+import { link as link5, lstat as lstat9, mkdir as mkdir7, open as open2, readdir as readdir7, realpath as realpath7, unlink as unlink5 } from "node:fs/promises";+import { join as join14, relative as relative7, resolve as resolve8, sep as sep5 } from "node:path";init_projects();var missing2 = (error) => error.code === "ENOENT";var exists = (error) => error.code === "EEXIST";@@ -43983,7 +44196,7 @@ function sequenceOf(revisionId) {}function digest7(record) {const { revisionId: _, ...payload } = record;- return createHash17("sha256").update(JSON.stringify(payload)).digest("hex");+ return createHash18("sha256").update(JSON.stringify(payload)).digest("hex");}class FileProjectStore {@@ -43992,30 +44205,30 @@ class FileProjectStore {constructor(workspace) {if (!workspace.trim())throw new Error("A workspace directory is required");- this.workspace = resolve6(workspace);- this.directory = join12(this.workspace, ".kiln", "projects");+ this.workspace = resolve8(workspace);+ this.directory = join14(this.workspace, ".kiln", "projects");}async path(projectId, create = false) {if (projectId !== undefined)projectIdSchema.parse(projectId);if (create)- await mkdir6(this.workspace, { recursive: true });- const canonical = await realpath5(this.workspace);+ await mkdir7(this.workspace, { recursive: true });+ const canonical = await realpath7(this.workspace);let path = this.workspace;for (const part of [".kiln", "projects", ...projectId ? [projectId, "revisions"] : []]) {- path = join12(path, part);+ path = join14(path, part);if (create)- await mkdir6(path).catch((error) => {+ await mkdir7(path).catch((error) => {if (!exists(error))throw error;});- const info = await lstat7(path);+ const info = await lstat9(path);if (info.isSymbolicLink())throw new Error("Project symlinks are not supported");if (!info.isDirectory())throw new Error("Invalid project directory");- const rel = relative6(canonical, await realpath5(path));- if (rel === ".." || rel.startsWith(`..${sep4}`))+ const rel = relative7(canonical, await realpath7(path));+ if (rel === ".." || rel.startsWith(`..${sep5}`))throw new Error("Project path escapes workspace");}return path;@@ -44035,11 +44248,11 @@ class FileProjectStore {return latest;}async load(projectId, directory, sequence) {- const path = join12(directory, filename(sequence));- const info = await lstat7(path);+ const path = join14(directory, filename(sequence));+ const info = await lstat9(path);if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROJECT_BYTES)throw new Error("Invalid or oversized project revision file");- const handle = await open(path, "r");+ const handle = await open2(path, "r");let bytes;try {const opened = await handle.stat();@@ -44118,8 +44331,8 @@ class FileProjectStore {for (const revision of new Set(record.reviews.map((review) => review.projectRevisionId)))await this.read(record.projectId, revision);const directory = await this.path(record.projectId, true);- const temporary = join12(directory, `.write-${randomUUID6()}`);- const handle = await open(temporary, "wx", 384);+ const temporary = join14(directory, `.write-${randomUUID7()}`);+ const handle = await open2(temporary, "wx", 384);try {try {await handle.writeFile(bytes);@@ -44128,7 +44341,7 @@ class FileProjectStore {await handle.close();}try {- await link4(temporary, join12(directory, filename(sequenceOf(record.revisionId))));+ await link5(temporary, join14(directory, filename(sequenceOf(record.revisionId))));} catch (error) {if (!exists(error))throw error;@@ -44138,7 +44351,7 @@ class FileProjectStore {throw new ProjectConflictError(record.projectId, expectedRevision, current.revisionId);}} finally {- await unlink4(temporary);+ await unlink5(temporary);}return record;}@@ -44158,7 +44371,7 @@ class FileProjectStore {return record;}async create(draft) {- const { projectId = `p_${randomUUID6().replaceAll("-", "")}`, ...data } = projectDraftSchema.parse(draft);+ const { projectId = `p_${randomUUID7().replaceAll("-", "")}`, ...data } = projectDraftSchema.parse(draft);return this.publish(this.record(projectId, 1, data));}async update(projectId, expectedRevision, patch) {@@ -44213,7 +44426,7 @@ class FileWorkspace {this.root = root;this.defaultProjectId = defaultProjectId;this.projects = new FileProjectStore(root);- this.materials = new FileMaterialLibrary(join13(root, ".kiln", "materials"));+ this.materials = new FileMaterialLibrary(join15(root, ".kiln", "materials"));}current() {return this.active.getStore();@@ -44351,17 +44564,17 @@ var scope = 0;function workspaceSourceReader(root) {return async (file) => {const segments = file.split(/[\\/]/u);- if (!file || isAbsolute(file) || /^[A-Za-z]:/u.test(file) || segments.includes("..") || segments.includes(""))+ if (!file || isAbsolute2(file) || /^[A-Za-z]:/u.test(file) || segments.includes("..") || segments.includes(""))throw new Error('file must name a program inside the workspace, relative to its root: no absolute path and no "..". Use a path such as assets/asset.kiln.js, or pass code or programRef.');- const path = resolve7(root, file);- const info = await stat4(path).catch(() => {+ const path = resolve9(root, file);+ const info = await stat6(path).catch(() => {return;});if (!info?.isFile())throw new Error(`file ${file} was not found inside the workspace. Check the relative path, or pass code or programRef.`);if (info.size > MAX_PROGRAM_BYTES)throw new Error(`file ${file} exceeds the ${MAX_PROGRAM_BYTES / (1024 * 1024)} MiB source limit.`);- return readFile7(path, "utf8");+ return readFile8(path, "utf8");};}function integer4(env, name, fallback, min, max) {@@ -44371,7 +44584,7 @@ function integer4(env, name, fallback, min, max) {return value;}function createLocalToolContext(base = {}, env = process.env) {- const workspaceRoot = env.KILN_WORKSPACE ? resolve7(env.KILN_WORKSPACE) : base.programStore instanceof FileProgramStore ? dirname6(dirname6(base.programStore.directory)) : localWorkspaceRoot(env);+ const workspaceRoot = env.KILN_WORKSPACE ? resolve9(env.KILN_WORKSPACE) : base.programStore instanceof FileProgramStore ? dirname7(dirname7(base.programStore.directory)) : localWorkspaceRoot(env);const workspace = base.workspace ?? new FileWorkspace(workspaceRoot, env.KILN_PROJECT);const projectStore = base.projectStore ?? (workspace instanceof FileWorkspace ? workspace.projects : undefined);const liveReview = base.liveReview ?? (env.KILN_LIVE_REVIEW === "off" ? undefined : new FileLiveReview(workspaceRoot, {@@ -44536,7 +44749,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer4(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve7(env.KILN_BUILD_CACHE_DIR ?? join14(store instanceof FileProgramStore ? dirname6(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve9(env.KILN_BUILD_CACHE_DIR ?? join16(store instanceof FileProgramStore ? dirname7(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -44575,7 +44788,7 @@ import {StdioServerTransport,serveStdio} from "@modelcontextprotocol/server/stdio";-import { readFile as readFile8 } from "node:fs/promises";+import { readFile as readFile9 } from "node:fs/promises";// src/asset-widget-uri.tsvar KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v6.html";@@ -44640,7 +44853,7 @@ function errorMessage(error) {return error instanceof Error ? error.message : String(error);}async function readPackagedWidgetHtml() {- return readFile8(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");+ return readFile9(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");}function createKilnServer(options) {const { manifest } = options;@@ -52828,6 +53041,11 @@ function createKilnAssetDefs(context, presentation = "grouped") {const profileExportInput = exportInput.extend({profile: z25.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")});+ const exportToInput = exportInput.extend({+ path: z25.string().max(240).describe("Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."),+ profile: z25.enum(["runtime", "editable"]).default("runtime").describe("runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only."),+ target: z25.enum(["three"]).optional().describe("Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).")+ });const importInput = z25.object({...selector,sourceCollection: selector.collection@@ -53004,6 +53222,7 @@ function createKilnAssetDefs(context, presentation = "grouped") {};}},+ ...context.exportRoot && context.assetLibrary ? [createKilnExportToDef(context.exportRoot, exportToInput, library, listCall)] : [],{name: "kiln_import",description: "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",@@ -53018,6 +53237,61 @@ function createKilnAssetDefs(context, presentation = "grouped") {}];}+function createKilnExportToDef(writer, inputSchema, library, listCall) {+ return {+ name: "kiln_export_to",+ description: "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ inputSchema,+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false+ },+ run: async (raw) => {+ const input = inputSchema.parse(raw);+ if (input.target !== undefined && input.profile !== "runtime")+ throw new Error("target requires profile runtime");+ await Promise.resolve().then(() => init_export_root());+ const destination = validateExportPath(input.path);+ await Promise.resolve().then(() => init_asset_export());+ if (input.profile === "runtime")+ validateMetadataFileName(destination.metadataFileName);+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId, listCall(input.collection));+ const files = [];+ if (input.profile === "runtime") {+ const output = await exportAssetGlb(record, {+ profile: "runtime",+ metadataFileName: destination.metadataFileName,+ ...input.target ? { target: input.target } : {}+ });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ files.push({ kind: "glb", path: destination.path, data: output.glb }, { kind: "metadata", path: destination.metadataPath, data: output.metadata.bytes });+ } else+ files.push({ kind: "glb", path: destination.path, data: record.files["asset.glb"] });+ await writer.writeNew([...files].reverse());+ await Promise.resolve().then(() => init_draw_diagnostics());+ const digest = async (data) => `sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(data))), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ return {+ ok: true,+ collection: input.collection,+ assetId: input.assetId,+ revisionId: input.revisionId,+ profile: input.profile,+ ...input.target ? { target: input.target } : {},+ format: "glb",+ drawDiagnostics: await inspectDrawDiagnostics(files[0].data),+ files: await Promise.all(files.map(async ({ kind, path, data }) => ({+ kind,+ path,+ bytes: data.byteLength,+ sha256: await digest(data)+ })))+ };+ }+ };+}// src/mcp-manifest.tsvar JSON_SCHEMA_TARGET = "draft-2020-12";@@ -53226,10 +53500,16 @@ async function createPackagedKilnHost(options = {}) {throw new Error(`Kiln workspace is out of date${report.runtimeChanged ? " (runtime changed)" : ""}: ${report.files.filter((entry) => entry.status !== "customized").map((entry) => entry.path).join(", ")}. In the workspace folder run kiln-init . --check, then kiln-init . --upgrade (or kiln-init . --repair if the installation moved), and restart the MCP session.`);}const mode = resolveRenderMode();+ const assetLibrary = localAssetLibrary();+ const exportRoot = await exportRootWriterFromEnv(env, {+ collectionRoots: assetLibrary.collections().map(({ id }) => assetLibrary.directory(id)),+ workspaceRoot: localWorkspaceRoot()+ });const context = await createPackagedLocalToolContext({...await buildRenderPort(mode, env["KILN_RENDER_PORT_URL"], { autoSpawn: true }),requirements,- assetLibrary: localAssetLibrary(),+ assetLibrary,+ ...exportRoot ? { exportRoot } : {},...env.KILN_LIVE_REVIEW !== "off" ? {liveReview: new FileLiveReview(localWorkspaceRoot(), {transport: "mcp",diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjsindex cc63b740..378a822a 100644--- a/dist/mcp-server.mjs+++ b/dist/mcp-server.mjs@@ -2007,6 +2007,61 @@ var mcp_manifest_default = {openWorldHint: false}},+ {+ name: "kiln_export_to",+ description: "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ inputSchema: {+ type: "object",+ properties: {+ collection: {+ default: "project",+ type: "string",+ pattern: "^[a-z][a-z0-9_-]{0,79}$",+ description: "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ assetId: {+ type: "string",+ pattern: "^[a-z][a-z0-9_-]{0,79}$"+ },+ revisionId: {+ type: "string",+ pattern: "^[a-z][a-z0-9_-]{0,79}$"+ },+ path: {+ type: "string",+ maxLength: 240,+ description: "Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."+ },+ profile: {+ default: "runtime",+ description: "runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only.",+ type: "string",+ enum: [+ "runtime",+ "editable"+ ]+ },+ target: {+ description: "Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).",+ type: "string",+ enum: [+ "three"+ ]+ }+ },+ required: [+ "assetId",+ "revisionId",+ "path"+ ]+ },+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false+ }+ },{name: "kiln_import",description: "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",@@ -2351,11 +2406,13 @@ function packagedEngineHost(options) {});}function manifestFor(env) {- if (env["KILN_LIVE_REVIEW"] !== "off")- return KILN_MCP_MANIFEST;+ const dropped = new Set([+ ...env["KILN_LIVE_REVIEW"] === "off" ? ["kiln_review"] : [],+ ...env["KILN_EXPORT_ROOT"] ? [] : ["kiln_export_to"]+ ]);return {...KILN_MCP_MANIFEST,- tools: KILN_MCP_MANIFEST.tools.filter((tool) => tool.name !== "kiln_review")+ tools: KILN_MCP_MANIFEST.tools.filter((tool) => !dropped.has(tool.name))};}if (isDirectEntry(import.meta.url)) {@@ -2399,5 +2456,6 @@ export {MCP_SERVER_INSTRUCTIONS,MCP_SERVER_NAME,MCP_SERVER_VERSION,+ manifestFor,packagedEngineHost};diff --git a/docs/architecture.md b/docs/architecture.mdindex 21058ccf..c2090511 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -35,7 +35,8 @@ See [package.json](../package.json) for all exports.[src/tools/registry.ts](../src/tools/registry.ts) owns the current tool definitions.`createKilnProgramToolRegistry` supplies fifteen MCP tools; the packaged local host-adds `kiln_project`, `kiln_material` and `kiln_review`, for eighteen over stdio.+adds `kiln_project`, `kiln_material` and `kiln_review`, for eighteen over stdio, and+`kiln_export_to` when `KILN_EXPORT_ROOT` is set.`createKilnNativeToolRegistry` reuses those definitions, removes unavailable deliveryservices and adds exact-reference completion. The retired mutable-buffer factoriesand separate `kiln_screenshot` are not the supported native workflow.diff --git a/docs/backlog.md b/docs/backlog.mdindex 993b8f44..cb7fecde 100644--- a/docs/backlog.md+++ b/docs/backlog.md@@ -131,7 +131,7 @@ solely because a historical report used pending-release language.| Static scene export (GG-006) | Separate delivery-contract decision || Vegetation cycle (D33) | Later per-tree culling exploration with visual and measured GPU-work checks || R8 shadows, reflection cadence, output depth, extra merging | Optional measured follow-ups |-| MCP render file destination | Unadopted; existing CLI output and MCP media/receipts remain valid |+| MCP export file destination | Adopted (opt-in `KILN_EXPORT_ROOT`, `kiln_export_to`); render file output remains unadopted: delivery starts from a saved revision || SEP-2640 resources and large present metadata | Recorded deferrals; see the roadmap and engine ledger |## Maintaining this queuediff --git a/docs/export-profiles.md b/docs/export-profiles.mdindex 7864aceb..1ad341da 100644--- a/docs/export-profiles.md+++ b/docs/export-profiles.md@@ -119,8 +119,41 @@ separate. Neither GLB contains the complete editable bundle. Gallery examples arhistorical showcases and may still contain modeling defects.Runtime results do not reuse configured canonical download URLs: those would deliver-the wrong GLB. Client support for saving MCP resources varies. Use the local CLI pair-when the client cannot save them. No binary data is put into tool text.+the wrong GLB. Client support for saving MCP resources varies. No binary data is put+into tool text. To write files, configure an export root (below) or use the local CLI.++### Writing files: `kiln_export_to`++When the host sets `KILN_EXPORT_ROOT` on the MCP server, it also advertises+`kiln_export_to`. Without the variable the tool list and `kiln_export` are unchanged.++```js+kiln_export_to({ collection: "project", assetId, revisionId, path: "game/door.glb" })+// game/door.glb+// game/door.kiln-metadata.json+kiln_export_to({ assetId, revisionId, path: "web/door.glb", target: "three" })+kiln_export_to({ assetId, revisionId, path: "archive/door.glb", profile: "editable" })+```++- `profile` is `runtime` (default) or `editable`, which writes the exact saved GLB only;+ ZIP and source stay resources. `target: "three"` requires `runtime`, as in the CLI,+ and produces the same bytes as `export --profile runtime --target three` with the+ same file name.+- `path` is relative to the root: forward slashes, at most 240 characters and 8+ segments, each segment portable (the filename-stem rule above), ending in `.glb`.+ `..`, absolute, drive-letter and UNC paths, backslashes and Windows device names+ are refused. The sidecar name is derived, `<stem>.kiln-metadata.json`, beside it.+- Existing files are never replaced, through the same writer as the CLI. Directories+ that are symlinks or junctions are refused; missing directories are created.+- The receipt is the CLI `--json` receipt with paths relative to the root:+ `ok`, `collection`, `assetId`, `revisionId`, `profile`, `target?`, `format: "glb"`,+ `drawDiagnostics` and `files[{ kind, path, bytes, sha256 }]`. No absolute path or+ file bytes appear in tool text.++The root is host configuration, never a tool input: an existing absolute directory+(on Windows a drive or UNC path) that neither contains nor sits inside a collection+directory or the workspace `.kiln/`. It is a destination, not project membership.+Render output has no file destination: delivery starts from a saved revision.## TypeScript library@@ -447,7 +480,8 @@ of exporter backend qualification and optional geometry/texture compression.does not acquire editable source through either profile.3. Keep the editable ZIP when source is available. For runtime delivery, save theGLB and the named sidecar without renaming or reserializing the sidecar. The CLI- writes the pair; MCP resource delivery depends on the host's download support.+ and, when the host sets an export root, `kiln_export_to` write the pair; other MCP+ resource delivery depends on the host's download support.4. Verify that the runtime GLB loads and its native animations play independently.Verify the sidecar filename and byte hash when checking provenance. Use thecanonical asset for Kiln's full review workflow; standard loaders do not fetchdiff --git a/docs/install.md b/docs/install.mdindex 1320c163..d8c353cf 100644--- a/docs/install.md+++ b/docs/install.md@@ -157,7 +157,8 @@ For agent-assisted installation, give your agent the repository URL and ask:The packaged local MCP server lists the fifteen base tools in the[generated tool reference](tools.md), plus `kiln_project`, `kiln_material` and-`kiln_review` from the packaged local host: eighteen in all. When installing an+`kiln_review` from the packaged local host: eighteen in all, and nineteen with+`kiln_export_to` when `KILN_EXPORT_ROOT` is set. When installing anolder release, use the documentation and receipt attached to that release; newertools and migration changes are not retroactively available there.@@ -477,6 +478,15 @@ The table above names each client's native configuration location; their JSON/TOshapes differ. Prefer generated configuration. Without an explicit store, the serveruses `.kiln/programs` beneath its process working directory.+To let the agent write exported files without a shell call, add `"KILN_EXPORT_ROOT"`+to `env`: an existing absolute directory (on Windows a drive or UNC path, not Git Bash+`/c/...`) outside every collection and the workspace `.kiln/`. The server then also+advertises `kiln_export_to`, which writes a saved revision's GLB, and for the runtime+profile its metadata sidecar, at a path relative to that directory and never replaces+a file. Without the variable the tool list is unchanged. The server checks the+directory when the engine starts; a wrong value fails each call with the fix. See+[export profiles](export-profiles.md#mcp).+For an explicitly bound asset brief, append `"--requirements"` and the absolutepath to a host-binding JSON file to `args`. This optional policy is fixed for theserver session; changing the file requires a new session. The default remainsdiff --git a/docs/runtime.md b/docs/runtime.mdindex 2db53749..1b7c3a7a 100644--- a/docs/runtime.md+++ b/docs/runtime.md@@ -128,6 +128,7 @@ Use `kiln_discover({ capabilities: true })` or `node kiln.mjs discover --capabil| `KILN_BUILD_CACHE_MB` | Disk artifact budget, 0–1,024; default 128 || `KILN_BUILD_CACHE_DIR` | Optional disk-cache directory || `KILN_GEOMETRY_POLICY` | `warn` (default) or `strict`; strict rejects unsupported export attributes and cannot be weakened by a tool request |+| `KILN_EXPORT_ROOT` | Unset (default) or an existing absolute directory outside every collection and `.kiln/`. When set, the MCP server advertises `kiln_export_to`, which writes saved revisions beneath it and never replaces a file; see [export profiles](export-profiles.md#mcp) || `KILN_RESULT_DETAIL` | `compact` (default) or `lean`: the result detail of the review tools when a call names none; `full` stays per call. A generated Antigravity workspace sets `lean` in its server entry (`.agents/mcp_config.json`), the one harness where lean won both measures of the readiness cycle; the other harnesses' entries set nothing |Advanced geometry callbacks also have operation-specific input limits. Those checks do not replace the process deadline: a callback that never returns cannot check its own evaluation counter. Capture pixels and PNG payloads have independent host limits described in [cameras](cameras.md).diff --git a/docs/tools.md b/docs/tools.mdindex ccc5d9f6..a2ebf758 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -8,6 +8,8 @@ Call `kiln_discover({capabilities:true})` for the current host limits, the confikiln_project, kiln_material and kiln_review are injected by the packaged local host; an embedding advertises them only when it supplies the corresponding store, and the connected tools/list is authoritative. Projects are optional: authoring tools accept projectId, projectRevision and independent materialDependencies, and projectId:null selects standalone work. See [projects and live review](projects-and-live-review.md) for CLI equivalents, project packages and exact reviewed saves.+kiln_export_to is advertised only when the host sets KILN_EXPORT_ROOT, an existing absolute directory outside every collection and .kiln/. It writes a saved revision under that root and never replaces a file; kiln_export stays read-only. See [export profiles](export-profiles.md#mcp).+Renderer capabilities distinguish configured routing, dependency readiness, endpoint health and unverified authentication. Use kiln_renderer with action=reprobe after renderer setup or repair to refresh the current session. Material capabilities list approved texture IDs by allowed slot for the selected evaluator. Capability inspection never starts a renderer, requests an image or fetches texture bytes; ordinary catalog search is offline. See [renderer readiness and resources](rendering.md).## kiln_discover@@ -1849,6 +1851,64 @@ Export one saved revision. Default editable returns exact GLB, source, preview,</details>+## kiln_export_to++Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.++<details>+<summary>Input JSON Schema</summary>+++```json+{+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "path": {+ "type": "string",+ "maxLength": 240,+ "description": "Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."+ },+ "profile": {+ "default": "runtime",+ "description": "runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only.",+ "type": "string",+ "enum": [+ "runtime",+ "editable"+ ]+ },+ "target": {+ "description": "Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).",+ "type": "string",+ "enum": [+ "three"+ ]+ }+ },+ "required": [+ "assetId",+ "revisionId",+ "path"+ ]+}+```++</details>+## kiln_importCopy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.diff --git a/scripts/generate-tool-reference.ts b/scripts/generate-tool-reference.tsindex 58c5e438..2c9dd46c 100644--- a/scripts/generate-tool-reference.ts+++ b/scripts/generate-tool-reference.ts@@ -52,6 +52,7 @@ export function toolReferenceMarkdown(): string {'Use these tools through your connected agent. Supply `code` once (or `file`, a path inside the workspace), then pass the returned `programRef` to later calls. References identify exact source revisions and are kept in the workspace program store across sessions and processes. [Source workflow](programs.md) · [Camera recipes](cameras.md) · [Geometry guide](geometry.md).','Call `kiln_discover({capabilities:true})` for the current host limits, the configured project and export/camera support. Nested records that the schemas keep opaque (`draft`, `patch`, `payload`, `capture`, `shot`) are described in full by `kiln_discover({ ids: ["shape:project-draft"] })` and the other `shape:` entries. The schema below describes inputs; actual image replies include fidelity and capture metadata. Source reads return exact text, edits return a new revision, and failed builds return their errors.','kiln_project, kiln_material and kiln_review are injected by the packaged local host; an embedding advertises them only when it supplies the corresponding store, and the connected tools/list is authoritative. Projects are optional: authoring tools accept projectId, projectRevision and independent materialDependencies, and projectId:null selects standalone work. See [projects and live review](projects-and-live-review.md) for CLI equivalents, project packages and exact reviewed saves.',+ 'kiln_export_to is advertised only when the host sets KILN_EXPORT_ROOT, an existing absolute directory outside every collection and .kiln/. It writes a saved revision under that root and never replaces a file; kiln_export stays read-only. See [export profiles](export-profiles.md#mcp).','Renderer capabilities distinguish configured routing, dependency readiness, endpoint health and unverified authentication. Use kiln_renderer with action=reprobe after renderer setup or repair to refresh the current session. Material capabilities list approved texture IDs by allowed slot for the selected evaluator. Capability inspection never starts a renderer, requests an image or fetches texture bytes; ordinary catalog search is offline. See [renderer readiness and resources](rendering.md).',...manifest.tools.flatMap((tool) => [`## ${tool.name}`,diff --git a/skills/kiln-author-asset/SKILL.md b/skills/kiln-author-asset/SKILL.mdindex 6bab46ab..27e89185 100644--- a/skills/kiln-author-asset/SKILL.md+++ b/skills/kiln-author-asset/SKILL.md@@ -80,7 +80,7 @@ original record and history stay.Report QA `acceptance` separately from delivery, including incomplete checks and unverified material appearance. Never use an unrendered edit or a previous image as evidence for the selected revision.-Read the [export profile guide](references/export-profiles.md) when choosing delivery files: the default editable ZIP for continued authoring, or the opt-in runtime GLB and metadata sidecar when its measured size benefit is useful. MCP `kiln_export` returns resource descriptors to read through the host; `node kiln.mjs export ASSET_ID REVISION_ID --format glb --out asset.glb` writes the files (`--profile runtime` for the runtime pair). Report the actual choices and preserve the canonical source; neither option establishes scene performance.+Read the [export profile guide](references/export-profiles.md) when choosing delivery files: the default editable ZIP for continued authoring, or the opt-in runtime GLB and metadata sidecar when its measured size benefit is useful. MCP `kiln_export` returns descriptors; `kiln_export_to` (if advertised) or `node kiln.mjs export ASSET_ID REVISION_ID --format glb --out asset.glb` writes files (`--profile runtime` for the runtime pair). Report the actual choices and preserve the canonical source; neither option establishes scene performance.Read a bounded source region with `kiln_source({ programRef, query: "dimensionOrPart" })`. Copy an exact anchor into `kiln_edit`, batch related replacements, and continue with its new `programRef`. Rendering is on by default, and `capture` can keep the relevant framing. An applied edit can still fail to build, so inspect `render.ok` separately. The result opens with the new `programRef` and its `parentRef`, then `ok`, `applied`, what `changed` and `next`; its `render` is compact like `kiln_render`'s and is enough to decide the next edit; ask `detail: "full"` only as a second look when every instance of a grouped finding matters.diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.mdindex 32025f08..57b65928 100644--- a/skills/kiln-author-asset/references/export-profiles.md+++ b/skills/kiln-author-asset/references/export-profiles.md@@ -145,8 +145,25 @@ a new revision. The local viewer host also serves those resource filenames throuits existing `/files/` endpoint. Existing viewer download buttons retain editable behavior.Runtime results do not reuse configured canonical download URLs: those would deliver-the wrong GLB. Client support for saving MCP resources varies. Use the local CLI pair-when the client cannot save them. No binary data is put into tool text.+the wrong GLB. Client support for saving MCP resources varies. No binary data is put+into tool text. To write files, use `kiln_export_to` when the host advertises it,+otherwise the local CLI pair.++### `kiln_export_to` (host opt-in)++Present only when the host sets `KILN_EXPORT_ROOT`. It writes one saved revision under+that root and returns the CLI `--json` receipt with root-relative paths:++```js+kiln_export_to({ assetId, revisionId, path: "game/door.glb" }) // runtime pair+kiln_export_to({ assetId, revisionId, path: "web/door.glb", target: "three" }) // three.js runtime+kiln_export_to({ assetId, revisionId, path: "keep/door.glb", profile: "editable" }) // exact saved GLB+```++`path` is relative with forward slashes, portable segments and a `.glb` name; the+sidecar `<stem>.kiln-metadata.json` is written beside it. It never replaces a file:+choose a new path rather than retrying the same one. It has no project input; the+root is a destination, not project membership.## TypeScript librarydiff --git a/skills/kiln-qa-asset/references/integration-checks.md b/skills/kiln-qa-asset/references/integration-checks.mdindex c05d54f3..8d3271b2 100644--- a/skills/kiln-qa-asset/references/integration-checks.md+++ b/skills/kiln-qa-asset/references/integration-checks.md@@ -114,7 +114,7 @@ file as a derivative with its own hash and keep the editable source and baseline## Performance evidenceIn builds that provide it, `drawDiagnostics` appears in `kiln_inspect` compact/full-results, `kiln_export`, and CLI export JSON for GLBs/bundles. It is advisory output,+results, `kiln_export`, `kiln_export_to` receipts, and CLI export JSON for GLBs/bundles. It is advisory output,not a QA rule or acceptance result. Read `status` and `reason` first: `input-limit`,`unreadable-glb` or `analysis-failed` means no assessment. An absent field in an olderinstallation or a lean response is not a clean result.diff --git a/src/__tests__/mcp-export-to-stdio.test.ts b/src/__tests__/mcp-export-to-stdio.test.tsnew file mode 100644index 00000000..f72c84cf--- /dev/null+++ b/src/__tests__/mcp-export-to-stdio.test.ts@@ -0,0 +1,105 @@+/**+ * `kiln_export_to` through the packaged stdio executable (#207): advertised and+ * writing when the host sets `KILN_EXPORT_ROOT`, and a wrong root reported as a+ * tool result naming the fix, never a write elsewhere.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdir, mkdtemp, readdir, rm } from 'node:fs/promises';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++import { REPO_ROOT, SERVER_BUNDLE } from './stdio-mcp';++const CODE =+ "const meta = { name: 'Box' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";++let root: string;+beforeAll(async () => {+ await mkdir(join(REPO_ROOT, 'tmp'), { recursive: true });+ root = await mkdtemp(join(REPO_ROOT, 'tmp', 'mcp-export-to-'));+});+afterAll(async () => {+ await rm(root, { recursive: true, force: true });+});++async function connect(exportRoot: string) {+ const client = new Client({ name: 'export-to-stdio', version: '0' });+ const transport = new StdioClientTransport({+ command: 'node',+ args: [SERVER_BUNDLE],+ cwd: root,+ env: {+ ...process.env,+ KILN_WORKSPACE: '',+ KILN_PROJECT: '',+ KILN_PROGRAM_STORE: join(root, '.kiln', 'programs'),+ KILN_COLLECTIONS: JSON.stringify({ project: join(root, 'collection') }),+ KILN_RENDER: 'cpu',+ KILN_BUILD_CACHE: 'memory',+ KILN_EVALUATOR_MODE: 'in-process',+ KILN_LIVE_REVIEW: 'off',+ KILN_EXPORT_ROOT: exportRoot,+ } as Record<string, string>,+ stderr: 'pipe',+ });+ await client.connect(transport);+ return client;+}++const text = (result: Awaited<ReturnType<Client['callTool']>>) =>+ (result.content as { type: string; text?: string }[]).find((block) => block.type === 'text')!+ .text!;++test('a configured export root advertises kiln_export_to and receives the files', async () => {+ const exportRoot = join(root, 'exports');+ await mkdir(exportRoot);+ const client = await connect(exportRoot);+ try {+ const { tools } = await client.listTools();+ expect(tools.find((tool) => tool.name === 'kiln_export_to')?.annotations).toMatchObject({+ readOnlyHint: false,+ destructiveHint: false,+ });+ const { programRef } = JSON.parse(+ text(await client.callTool({ name: 'kiln_validate', arguments: { code: CODE } })),+ );+ const saved = await client.callTool({+ name: 'kiln_save',+ arguments: { programRef, name: 'Box' },+ });+ expect(saved.isError, text(saved)).not.toBe(true);+ const { asset } = JSON.parse(text(saved));+ const result = await client.callTool({+ name: 'kiln_export_to',+ arguments: { assetId: asset.assetId, revisionId: asset.revisionId, path: 'out/box.glb' },+ });+ expect(result.isError, text(result)).not.toBe(true);+ expect(text(result)).not.toContain(root);+ expect(JSON.parse(text(result)).files.map((file: { path: string }) => file.path)).toEqual([+ 'out/box.glb',+ 'out/box.kiln-metadata.json',+ ]);+ expect((await readdir(join(exportRoot, 'out'))).sort()).toEqual([+ 'box.glb',+ 'box.kiln-metadata.json',+ ]);+ } finally {+ await client.close();+ }+});++test('a wrong export root is a tool result naming the fix', async () => {+ const client = await connect('exports');+ try {+ expect((await client.listTools()).tools.map((tool) => tool.name)).toContain('kiln_export_to');+ const result = await client.callTool({+ name: 'kiln_export_to',+ arguments: { assetId: 'a', revisionId: 'r', path: 'box.glb' },+ });+ expect(result.isError).toBe(true);+ expect(text(result)).toContain('KILN_EXPORT_ROOT must be an absolute directory');+ } finally {+ await client.close();+ }+});diff --git a/src/__tests__/mcp-manifest.test.ts b/src/__tests__/mcp-manifest.test.tsindex 4f265e78..3f59ab30 100644--- a/src/__tests__/mcp-manifest.test.ts+++ b/src/__tests__/mcp-manifest.test.ts@@ -10,6 +10,7 @@ import { resolve } from 'node:path';import { KILN_RESOURCE_TEMPLATES, KILN_WIDGET_RESOURCE, type KilnMcpManifest } from '../mcp-core';import { packagedMcpManifest } from '../mcp-manifest';+import { manifestFor } from '../mcp-server';const FILE = resolve(import.meta.dir, '../generated/mcp-manifest.json');const committed = async () => JSON.parse(await readFile(FILE, 'utf8')) as KilnMcpManifest;@@ -27,6 +28,7 @@ describe('generated MCP manifest', () => {'kiln_discover','kiln_edit','kiln_export',+ 'kiln_export_to','kiln_import','kiln_inspect','kiln_material',@@ -61,3 +63,34 @@ describe('generated MCP manifest', () => {]);});});++describe('the manifest the stdio entry advertises for its environment', () => {+ const tool = (manifest: KilnMcpManifest, name: string) =>+ manifest.tools.find((entry) => entry.name === name);++ it('advertises kiln_export_to only when the host sets KILN_EXPORT_ROOT (#207)', () => {+ for (const env of [{}, { KILN_EXPORT_ROOT: '' }])+ expect(tool(manifestFor(env), 'kiln_export_to')).toBeUndefined();+ const rooted = manifestFor({ KILN_EXPORT_ROOT: 'C:/exports' });+ expect(tool(rooted, 'kiln_export_to')?.annotations).toEqual({+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false,+ });+ // kiln_export stays read-only and byte-for-byte the same either way.+ expect(JSON.stringify(tool(manifestFor({}), 'kiln_export'))).toBe(+ JSON.stringify(tool(rooted, 'kiln_export')),+ );+ expect(tool(rooted, 'kiln_export')?.annotations?.readOnlyHint).toBe(true);+ expect(manifestFor({}).tools).toHaveLength(rooted.tools.length - 1);+ });++ it('drops kiln_review with KILN_LIVE_REVIEW=off, independently of the export root', () => {+ const names = (env: Record<string, string>) => manifestFor(env).tools.map((t) => t.name);+ expect(names({ KILN_LIVE_REVIEW: 'off' })).not.toContain('kiln_review');+ expect(names({ KILN_LIVE_REVIEW: 'off', KILN_EXPORT_ROOT: 'C:/exports' })).toContain(+ 'kiln_export_to',+ );+ });+});diff --git a/src/__tests__/stdio-mcp.ts b/src/__tests__/stdio-mcp.tsindex 561e3c47..ca131053 100644--- a/src/__tests__/stdio-mcp.ts+++ b/src/__tests__/stdio-mcp.ts@@ -86,6 +86,8 @@ export function startStdioServer(options: StartOptions): Promise<StdioServer> {KILN_PROGRAM_STORE: join(options.cwd, '.kiln', 'programs'),KILN_BUILD_CACHE: 'memory',KILN_EVALUATOR_MODE: 'in-process',+ // An export root in the caller's shell must not change the advertised surface.+ KILN_EXPORT_ROOT: '',...options.env,};const child: ChildProcess = spawn(diff --git a/src/export-root-node.ts b/src/export-root-node.tsnew file mode 100644index 00000000..9f1c9c3e--- /dev/null+++ b/src/export-root-node.ts@@ -0,0 +1,170 @@+/**+ * The Node writer behind `kiln_export_to` (#207). The host configures one export+ * root (`KILN_EXPORT_ROOT`), checked once at start; the model names files+ * relative to it. Writes go through the CLI's never-replace writer, and every+ * message names root-relative paths only, because it is returned to the agent.+ */+import type { Stats } from 'node:fs';+import { lstat, realpath, stat } from 'node:fs/promises';+import { isAbsolute, join, relative, resolve, sep } from 'node:path';+import { platform } from 'node:os';++import { writeNewDestinationsAtomic } from './cli-output';+import { rootRelativeSegments, type ExportRootWriter } from './export-root';++const windowsDrivePath = /^[A-Za-z]:[\\/]/;+const windowsSharePath = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;+const RESTART = 'Correct KILN_EXPORT_ROOT and restart the MCP session.';++function inside(parent: string, child: string): boolean {+ const rel = relative(parent, child);+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));+}++async function canonical(path: string): Promise<string> {+ try {+ return await realpath(path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return resolve(path);+ throw error;+ }+}++export interface ExportRootOptions {+ /** Every configured collection directory; saved revisions never change. */+ collectionRoots: readonly string[];+ /** The workspace whose `.kiln/` holds program, review and material state. */+ workspaceRoot?: string;+ operatingSystem?: NodeJS.Platform;+}++/**+ * Check a configured export root and return its real path. It must be an+ * absolute existing directory (on Windows a drive or UNC path; Git Bash `/c/...`+ * would resolve against the current drive), and must neither contain nor sit+ * inside a collection root or the workspace's `.kiln/`.+ */+export async function resolveExportRoot(+ value: string,+ options: ExportRootOptions,+): Promise<string> {+ const operatingSystem = options.operatingSystem ?? platform();+ if (+ operatingSystem === 'win32' &&+ !windowsDrivePath.test(value) &&+ !windowsSharePath.test(value)+ ) {+ const gitBash = /^\/([A-Za-z])(?:\/|$)/.exec(value);+ if (gitBash)+ throw new Error(+ `KILN_EXPORT_ROOT is a Git Bash path (/${gitBash[1]}/...); Windows would resolve it against the current drive. Write it as ${gitBash[1]!.toUpperCase()}:/... or a UNC share. ${RESTART}`,+ );+ throw new Error(+ `KILN_EXPORT_ROOT must be an absolute directory: a Windows drive (C:/...) or UNC share. ${RESTART}`,+ );+ }+ if (!isAbsolute(value))+ throw new Error(`KILN_EXPORT_ROOT must be an absolute directory. ${RESTART}`);+ let entry: Stats;+ try {+ entry = await stat(value);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')+ throw new Error(+ `KILN_EXPORT_ROOT does not exist; create the directory or ${RESTART[0]!.toLowerCase()}${RESTART.slice(1)}`,+ );+ throw new Error(+ `KILN_EXPORT_ROOT could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'}). ${RESTART}`,+ );+ }+ if (!entry.isDirectory()) throw new Error(`KILN_EXPORT_ROOT is not a directory. ${RESTART}`);+ const root = await realpath(value);+ for (const collection of options.collectionRoots) {+ const directory = await canonical(collection);+ if (inside(directory, root) || inside(root, directory))+ throw new Error(+ `KILN_EXPORT_ROOT overlaps a collection directory; saved revisions never change. Choose a directory outside every collection and .kiln/. ${RESTART}`,+ );+ }+ if (options.workspaceRoot !== undefined) {+ const state = await canonical(join(options.workspaceRoot, '.kiln'));+ if (inside(state, root) || inside(root, state))+ throw new Error(+ `KILN_EXPORT_ROOT overlaps the workspace .kiln/ directory. Choose a directory outside every collection and .kiln/. ${RESTART}`,+ );+ }+ return root;+}++/**+ * A writer confined to `root`, which must already be a real path (from+ * {@link resolveExportRoot}). Each path is checked again here; existing+ * ancestors may not be links (symlinks or junctions), and the deepest existing+ * one must resolve inside the root. Missing directories are created by the+ * writer; a link planted at the final name is refused because publishing never+ * replaces.+ */+export function createExportRootWriter(root: string): ExportRootWriter {+ return {+ async writeNew(files) {+ const targets = files.map(({ path, data }) => ({+ path,+ segments: rootRelativeSegments(path),+ absolute: join(root, ...rootRelativeSegments(path)),+ data,+ }));+ for (const target of targets) {+ let deepest = root;+ for (const [index, segment] of target.segments.slice(0, -1).entries()) {+ const next = join(deepest, segment);+ let entry: Stats;+ try {+ entry = await lstat(next);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') break;+ throw error;+ }+ const shown = target.segments.slice(0, index + 1).join('/');+ if (entry.isSymbolicLink())+ throw new Error(+ `${shown} in the export root is a symlink or junction; links are not followed. Choose a path through ordinary directories.`,+ );+ if (!entry.isDirectory())+ throw new Error(`${shown} in the export root is a file, not a directory.`);+ deepest = next;+ }+ if (!inside(root, await realpath(deepest)))+ throw new Error(`${target.path} resolves outside the export root.`);+ }+ try {+ await writeNewDestinationsAtomic(+ targets.map(({ absolute, data }) => ({ path: absolute, data })),+ );+ } catch (error) {+ const failure = error as NodeJS.ErrnoException;+ if (failure.code === 'EEXIST') {+ const existing = targets.find(({ absolute }) => failure.message.startsWith(absolute));+ throw new Error(+ `${existing?.path ?? 'An export file'} already exists in the export root and is never replaced; choose a new path or remove the file.`,+ );+ }+ throw new Error(+ `Could not write ${targets.map(({ path }) => path).join(' and ')} in the export root (${failure.code ?? failure.message.split(root).join('<export root>')}).`,+ );+ }+ },+ };+}++/**+ * The packaged host's export root: absent without `KILN_EXPORT_ROOT` (the entry+ * then does not advertise `kiln_export_to`), otherwise checked here, once, at host start.+ */+export async function exportRootWriterFromEnv(+ env: Record<string, string | undefined>,+ options: ExportRootOptions,+): Promise<ExportRootWriter | undefined> {+ const value = env['KILN_EXPORT_ROOT'];+ if (!value) return undefined;+ return createExportRootWriter(await resolveExportRoot(value, options));+}diff --git a/src/export-root.test.ts b/src/export-root.test.tsnew file mode 100644index 00000000..7f756203--- /dev/null+++ b/src/export-root.test.ts@@ -0,0 +1,214 @@+/**+ * The host-rooted export destination behind `kiln_export_to` (#207): the model+ * names a path relative to a root the host configured, and nothing it names can+ * leave that root, replace a file or reveal where the root is.+ */+import { describe, expect, test } from 'bun:test';+import {+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ realpath,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { validateExportPath } from './export-root';+import {+ createExportRootWriter,+ exportRootWriterFromEnv,+ resolveExportRoot,+} from './export-root-node';++const bytes = (text: string) => new TextEncoder().encode(text);++describe('export path rules', () => {+ test('accepts a relative forward-slash .glb path and derives the sidecar beside it', () => {+ expect(validateExportPath('models/doors/door-01.glb')).toEqual({+ path: 'models/doors/door-01.glb',+ metadataPath: 'models/doors/door-01.kiln-metadata.json',+ metadataFileName: 'door-01.kiln-metadata.json',+ });+ expect(validateExportPath('Crate.GLB').metadataPath).toBe('Crate.kiln-metadata.json');+ });++ test.each([+ ['../escape.glb', /\.\./],+ ['models/../../escape.glb', /\.\./],+ ['./door.glb', /segment/],+ ['/abs/door.glb', /relative/],+ ['C:/Users/door.glb', /relative/],+ ['c:door.glb', /relative/],+ ['//host/share/door.glb', /relative/],+ ['models\\door.glb', /forward slashes/],+ ['models//door.glb', /segment/],+ ['models/', /\.glb/],+ ['models/door.gltf', /\.glb/],+ ['models/door', /\.glb/],+ ['.glb', /segment/],+ ['con/door.glb', /device/],+ ['models/NUL.glb', /device/],+ ['models/lpt1.txt/door.glb', /device/],+ ['models/door .glb', /segment/],+ ['models/dir./door.glb', /segment/],+ ['a/b/c/d/e/f/g/h/door.glb', /8 segments/],+ [`${'a'.repeat(237)}.glb`, /240/],+ ])('refuses %s', (path, message) => {+ expect(() => validateExportPath(path)).toThrow(message);+ });+});++describe('export root configuration', () => {+ test('resolves an existing absolute directory to its real path', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-root-'));+ try {+ const root = join(base, 'exports');+ await mkdir(root);+ expect(+ await resolveExportRoot(root, { collectionRoots: [join(base, 'assets', 'kiln')] }),+ ).toBe(await realpath(root));+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });++ test('refuses a relative, Git Bash, missing, file or collection-overlapping root', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-root-'));+ try {+ const collection = join(base, 'assets', 'kiln');+ await mkdir(collection, { recursive: true });+ await mkdir(join(base, '.kiln'));+ await writeFile(join(base, 'file.txt'), 'x');+ const options = { collectionRoots: [collection], workspaceRoot: base };+ await expect(resolveExportRoot('exports', options)).rejects.toThrow(/absolute/);+ await expect(+ resolveExportRoot('/c/Users/me/exports', { ...options, operatingSystem: 'win32' }),+ ).rejects.toThrow(/Git Bash path \(\/c\/\.\.\.\).*Write it as C:\/\.\.\./);+ await expect(resolveExportRoot(join(base, 'missing'), options)).rejects.toThrow(+ /does not exist/,+ );+ await expect(resolveExportRoot(join(base, 'file.txt'), options)).rejects.toThrow(+ /not a directory/,+ );+ await expect(resolveExportRoot(collection, options)).rejects.toThrow(/collection/);+ await mkdir(join(collection, 'exports'));+ await expect(resolveExportRoot(join(collection, 'exports'), options)).rejects.toThrow(+ /collection/,+ );+ await expect(resolveExportRoot(join(base, 'assets'), options)).rejects.toThrow(/collection/);+ await mkdir(join(base, '.kiln', 'exports'));+ await expect(resolveExportRoot(join(base, '.kiln', 'exports'), options)).rejects.toThrow(+ /\.kiln/,+ );+ await expect(resolveExportRoot(base, options)).rejects.toThrow(/collection|\.kiln/);+ // Rule 9: the message is returned to the agent, so it names no local path.+ const failure = await resolveExportRoot(join(base, 'missing'), options).catch(+ (error: Error) => error.message,+ );+ expect(failure).not.toContain(base);+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });+});++describe('export root from the host environment', () => {+ test('is absent without KILN_EXPORT_ROOT and checked at host start with it', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-env-'));+ try {+ const options = { collectionRoots: [join(base, 'assets', 'kiln')], workspaceRoot: base };+ expect(await exportRootWriterFromEnv({}, options)).toBeUndefined();+ expect(await exportRootWriterFromEnv({ KILN_EXPORT_ROOT: '' }, options)).toBeUndefined();+ await expect(+ exportRootWriterFromEnv({ KILN_EXPORT_ROOT: join(base, 'missing') }, options),+ ).rejects.toThrow(/does not exist/);+ await mkdir(join(base, 'exports'));+ const writer = await exportRootWriterFromEnv(+ { KILN_EXPORT_ROOT: join(base, 'exports') },+ options,+ );+ await writer!.writeNew([{ path: 'a.glb', data: bytes('glb') }]);+ expect(await readdir(join(base, 'exports'))).toEqual(['a.glb']);+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });+});++describe('export root writer', () => {+ test('writes new files under the root and creates missing directories', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-writer-'));+ try {+ const writer = createExportRootWriter(await realpath(base));+ await writer.writeNew([+ { path: 'game/props/crate.kiln-metadata.json', data: bytes('{}') },+ { path: 'game/props/crate.glb', data: bytes('glb') },+ ]);+ expect(await readFile(join(base, 'game', 'props', 'crate.glb'), 'utf8')).toBe('glb');+ expect(await readdir(join(base, 'game', 'props'))).toEqual([+ 'crate.glb',+ 'crate.kiln-metadata.json',+ ]);+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });++ test('never replaces an existing GLB or sidecar, and names only the root-relative path', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-writer-'));+ try {+ const writer = createExportRootWriter(await realpath(base));+ await writeFile(join(base, 'door.glb'), 'original');+ const replaced = await writer+ .writeNew([{ path: 'door.glb', data: bytes('new') }])+ .catch((error: Error) => error.message);+ expect(replaced).toBe(+ 'door.glb already exists in the export root and is never replaced; choose a new path or remove the file.',+ );+ expect(await readFile(join(base, 'door.glb'), 'utf8')).toBe('original');+ // A pre-existing sidecar stops the pair before the GLB is published.+ await writeFile(join(base, 'gate.kiln-metadata.json'), 'old');+ await expect(+ writer.writeNew([+ { path: 'gate.kiln-metadata.json', data: bytes('{}') },+ { path: 'gate.glb', data: bytes('glb') },+ ]),+ ).rejects.toThrow('gate.kiln-metadata.json already exists');+ expect((await readdir(base)).sort()).toEqual(['door.glb', 'gate.kiln-metadata.json']);+ expect(await readFile(join(base, 'gate.kiln-metadata.json'), 'utf8')).toBe('old');+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });++ test('refuses a symlink or junction ancestor and writes nothing', async () => {+ const base = await mkdtemp(join(tmpdir(), 'kiln-export-writer-'));+ try {+ const root = join(base, 'root');+ const outside = join(base, 'outside');+ await mkdir(root);+ await mkdir(outside);+ // A junction needs no privilege on Windows; elsewhere it is an ordinary symlink.+ await symlink(outside, join(root, 'linked'), 'junction');+ const writer = createExportRootWriter(await realpath(root));+ const failure = await writer+ .writeNew([{ path: 'linked/door.glb', data: bytes('glb') }])+ .catch((error: Error) => error.message);+ expect(failure).toContain('linked');+ expect(failure).toMatch(/link/);+ expect(failure).not.toContain(base);+ expect(await readdir(outside)).toEqual([]);+ // The writer applies the path rules itself, not only the tool.+ await expect(+ writer.writeNew([{ path: '../outside/door.glb', data: bytes('x') }]),+ ).rejects.toThrow(/\.\./);+ expect(await readdir(outside)).toEqual([]);+ } finally {+ await rm(base, { recursive: true, force: true });+ }+ });+});diff --git a/src/export-root.ts b/src/export-root.tsnew file mode 100644index 00000000..b23084f1--- /dev/null+++ b/src/export-root.ts@@ -0,0 +1,76 @@+/**+ * The model-facing half of the host-rooted export destination (#207). No+ * filesystem access: the host injects an {@link ExportRootWriter} through+ * `KilnToolContext.exportRoot`, and `src/export-root-node.ts` is the Node one.+ */++/** Writes new files under a root the host configured. Never replaces a file. */+export interface ExportRootWriter {+ /**+ * Publish complete files at root-relative, forward-slash paths, in order. An+ * existing file at any path refuses the call and nothing new is left behind.+ * Errors name root-relative paths only.+ */+ writeNew(files: readonly { path: string; data: Uint8Array }[]): Promise<void>;+}++export interface ExportPath {+ /** The validated root-relative GLB path. */+ path: string;+ /** The runtime sidecar beside it: `<stem>.kiln-metadata.json`. */+ metadataPath: string;+ /** The sidecar's file name alone, as the GLB's provenance pointer records it. */+ metadataFileName: string;+}++const MAX_PATH_CHARS = 240;+const MAX_SEGMENTS = 8;+/** The portable stem rule documented for exports, applied to every segment. */+const PORTABLE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+const DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;++/**+ * Check a root-relative path and return its segments: relative, forward slashes,+ * at most 240 characters and 8 segments, each segment portable (ASCII letters,+ * digits, `.`, `_`, `-`; starting with a letter or digit; not ending in `.`; not+ * a Windows device name).+ */+export function rootRelativeSegments(path: string): string[] {+ if (path.length > MAX_PATH_CHARS)+ throw new Error(`Export path must be at most ${MAX_PATH_CHARS} characters.`);+ if (path.includes('\\'))+ throw new Error('Export path must use forward slashes, for example models/door.glb.');+ if (path.startsWith('/') || /^[A-Za-z]:/.test(path))+ throw new Error(+ 'Export path must be relative to the export root, for example models/door.glb.',+ );+ const segments = path.split('/');+ if (segments.length > MAX_SEGMENTS)+ throw new Error(`Export path must have at most ${MAX_SEGMENTS} segments.`);+ for (const segment of segments) {+ if (segment === '..')+ throw new Error('Export path must stay inside the export root; ".." is not allowed.');+ if (!PORTABLE_SEGMENT.test(segment) || segment.endsWith('.'))+ throw new Error(+ `Export path segment ${JSON.stringify(segment)} is not portable: use ASCII letters, digits, ".", "_" or "-", starting with a letter or digit.`,+ );+ if (DEVICE_NAME.test(segment))+ throw new Error(+ `Export path segment ${JSON.stringify(segment)} is a Windows device name; choose another name.`,+ );+ }+ return segments;+}++/** Check a model-supplied GLB path and derive its runtime sidecar beside it. */+export function validateExportPath(path: string): ExportPath {+ if (!path.toLowerCase().endsWith('.glb'))+ throw new Error('Export path must name a .glb file, for example models/door.glb.');+ const segments = rootRelativeSegments(path);+ const metadataFileName = `${segments.at(-1)!.slice(0, -4)}.kiln-metadata.json`;+ return {+ path,+ metadataPath: [...segments.slice(0, -1), metadataFileName].join('/'),+ metadataFileName,+ };+}diff --git a/src/generated/mcp-manifest.json b/src/generated/mcp-manifest.jsonindex a9211fdb..ead2ed4d 100644--- a/src/generated/mcp-manifest.json+++ b/src/generated/mcp-manifest.json@@ -1991,6 +1991,61 @@"openWorldHint": false}},+ {+ "name": "kiln_export_to",+ "description": "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "path": {+ "type": "string",+ "maxLength": 240,+ "description": "Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it."+ },+ "profile": {+ "default": "runtime",+ "description": "runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only.",+ "type": "string",+ "enum": [+ "runtime",+ "editable"+ ]+ },+ "target": {+ "description": "Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).",+ "type": "string",+ "enum": [+ "three"+ ]+ }+ },+ "required": [+ "assetId",+ "revisionId",+ "path"+ ]+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false+ }+ },{"name": "kiln_import","description": "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",diff --git a/src/mcp-engine.ts b/src/mcp-engine.tsindex 197b88de..a0fa51bb 100644--- a/src/mcp-engine.ts+++ b/src/mcp-engine.ts@@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url';import { localAssetLibrary } from './assets-node';import { type AssetLink, readAssetResource } from './assets-resources';import { buildRenderPort, resolveRenderMode } from './cli-render-mode';+import { exportRootWriterFromEnv } from './export-root-node';import { FileLiveReview } from './live-review-node';import { createPackagedLocalToolContext } from './local-runtime';import { LOOPBACK_HOSTNAMES } from './loopback';@@ -338,10 +339,17 @@ export async function createPackagedKilnHost(// back a port that starts the packaged renderer on the first view that needs// one, which is the only ordering a user can actually achieve: the harness owns// this process's lifecycle, so "start the renderer first" was never theirs to do.+ const assetLibrary = localAssetLibrary();+ // Checked at start: a bad root fails every call with the fix, never a write elsewhere.+ const exportRoot = await exportRootWriterFromEnv(env, {+ collectionRoots: assetLibrary.collections().map(({ id }) => assetLibrary.directory(id)),+ workspaceRoot: localWorkspaceRoot(),+ });const context = await createPackagedLocalToolContext({...(await buildRenderPort(mode, env['KILN_RENDER_PORT_URL'], { autoSpawn: true })),requirements,- assetLibrary: localAssetLibrary(),+ assetLibrary,+ ...(exportRoot ? { exportRoot } : {}),...(env.KILN_LIVE_REVIEW !== 'off'? {liveReview: new FileLiveReview(localWorkspaceRoot(), {diff --git a/src/mcp-manifest.ts b/src/mcp-manifest.tsindex a7ad86e1..042e97cb 100644--- a/src/mcp-manifest.ts+++ b/src/mcp-manifest.ts@@ -7,11 +7,12 @@* applies when it is handed a zod schema, so the manifest is what the library* would have advertised -- minus the `$schema` keyword, because 2020-12 is the* dialect MCP assumes when none is named, and the keyword costs 56 bytes in- * every one of the eighteen definitions a harness sends with every request.+ * every definition a harness sends with every request.*/import type { z } from 'zod';import { localAssetLibrary } from './assets-node';+import type { ExportRootWriter } from './export-root';import { createLocalToolContext } from './local-runtime';import {KILN_RESOURCE_TEMPLATES,@@ -93,12 +94,22 @@ export function buildMcpManifest(defs: KilnToolDef[], context: KilnToolContext):};}+const MANIFEST_EXPORT_ROOT: ExportRootWriter = {+ writeNew: async () => {+ throw new Error('The manifest export root writes nothing.');+ },+};+/*** The manifest the packaged server advertises: the full surface with both* templates, built from a context shaped like the packaged host's but with no* environment of its own, so the file is the same on every machine.*/export function packagedMcpManifest(): KilnMcpManifest {- const context = createLocalToolContext({ assetLibrary: localAssetLibrary() }, {});+ const context = createLocalToolContext(+ // The entry drops kiln_export_to unless KILN_EXPORT_ROOT is set; this writer is never called.+ { assetLibrary: localAssetLibrary(), exportRoot: MANIFEST_EXPORT_ROOT },+ {},+ );return buildMcpManifest(createKilnProgramToolRegistry(context), context);}diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex 26ea3dd3..d4170394 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -67,12 +67,19 @@ export function packagedEngineHost(options: {}));}-/** `KILN_LIVE_REVIEW=off` removes the review store, and with it the one tool that needs it. */-function manifestFor(env: Record<string, string | undefined>): KilnMcpManifest {- if (env['KILN_LIVE_REVIEW'] !== 'off') return KILN_MCP_MANIFEST;+/**+ * The definitions advertised for this environment. `KILN_LIVE_REVIEW=off`+ * removes the review store, and with it the one tool that needs it;+ * `kiln_export_to` is advertised only when the host sets `KILN_EXPORT_ROOT`.+ */+export function manifestFor(env: Record<string, string | undefined>): KilnMcpManifest {+ const dropped = new Set([+ ...(env['KILN_LIVE_REVIEW'] === 'off' ? ['kiln_review'] : []),+ ...(env['KILN_EXPORT_ROOT'] ? [] : ['kiln_export_to']),+ ]);return {...KILN_MCP_MANIFEST,- tools: KILN_MCP_MANIFEST.tools.filter((tool) => tool.name !== 'kiln_review'),+ tools: KILN_MCP_MANIFEST.tools.filter((tool) => !dropped.has(tool.name)),};}diff --git a/src/tools/__tests__/export-to.test.ts b/src/tools/__tests__/export-to.test.tsnew file mode 100644index 00000000..cd8616c9--- /dev/null+++ b/src/tools/__tests__/export-to.test.ts@@ -0,0 +1,275 @@+/**+ * `kiln_export_to` (#207): a host-enabled tool that writes one saved revision's+ * GLB (and, for runtime, its metadata sidecar) under the host's export root,+ * through the CLI's never-replace writer, and returns the CLI `--json` receipt+ * with root-relative paths. `kiln_export` stays read-only and unchanged.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { Client, InMemoryTransport } from '@modelcontextprotocol/client';++import type { AssetManifest } from '../../assets';+import { FileAssetLibrary } from '../../assets-node';+import { createExportRootWriter } from '../../export-root-node';+import type { ExportRootWriter } from '../../export-root';+import { createKilnMcpServer } from '../../mcp-engine';+import { toolManifestEntry } from '../../mcp-manifest';+import { renderGLBInProcess } from '../../render';+import {+ createKilnNativeToolRegistry,+ createKilnProgramToolRegistry,+ type KilnToolDef,+} from '../registry';++const CODE =+ "const meta = { name: 'Box' }; function build() { const root = createRoot('Box'); createPart('Body', boxGeo(1,1,1), gameMaterial(0x88aa66), {parent: root, position: [0,0.5,0]}); return root; }";+const sha256 = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const names = (defs: KilnToolDef[]) => defs.map((def) => def.name);+const unusedWriter: ExportRootWriter = {+ writeNew: async () => {+ throw new Error('not used');+ },+};++let base: string;+let library: FileAssetLibrary;+let asset: AssetManifest;+let roots = 0;++beforeAll(async () => {+ base = await realpath(await mkdtemp(join(tmpdir(), 'kiln-export-to-')));+ library = new FileAssetLibrary({ project: join(base, 'collection') });+ const rendered = await renderGLBInProcess(CODE);+ asset = await library.save('project', { name: 'Box', code: CODE, glb: rendered.glb });+});++afterAll(async () => {+ await rm(base, { recursive: true, force: true });+});++/** A fresh export root, and the tool bound to it. */+async function exportTo() {+ const root = join(base, `exports-${++roots}`);+ await mkdir(root);+ const def = createKilnProgramToolRegistry({+ assetLibrary: library,+ exportRoot: createExportRootWriter(root),+ }).find((candidate) => candidate.name === 'kiln_export_to')!;+ const selector = { collection: 'project', assetId: asset.assetId, revisionId: asset.revisionId };+ return { root, run: (input: Record<string, unknown>) => def.run({ ...selector, ...input }) };+}++describe('kiln_export_to advertisement', () => {+ test('is defined only with an export root and an asset library; kiln_export is unchanged', async () => {+ expect(names(createKilnProgramToolRegistry({ assetLibrary: library }))).not.toContain(+ 'kiln_export_to',+ );+ expect(names(createKilnProgramToolRegistry({ exportRoot: unusedWriter }))).not.toContain(+ 'kiln_export_to',+ );+ const plain = createKilnProgramToolRegistry({ assetLibrary: library });+ const enabled = createKilnProgramToolRegistry({+ assetLibrary: library,+ exportRoot: unusedWriter,+ });+ expect(names(enabled)).toContain('kiln_export_to');+ expect(names(enabled).filter((name) => name !== 'kiln_export_to')).toEqual(names(plain));+ const entry = (defs: KilnToolDef[], name: string) =>+ JSON.stringify(toolManifestEntry(defs.find((def) => def.name === name)!));+ expect(entry(enabled, 'kiln_export')).toBe(entry(plain, 'kiln_export'));+ const exportTo = toolManifestEntry(enabled.find((def) => def.name === 'kiln_export_to')!);+ expect(exportTo.annotations).toEqual({+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false,+ });+ // A destination, not project membership.+ expect(Object.keys(exportTo.inputSchema['properties'] as object).sort()).toEqual([+ 'assetId',+ 'collection',+ 'path',+ 'profile',+ 'revisionId',+ 'target',+ ]);+ // Native: a delivery tool, present only with both host services.+ expect(names(createKilnNativeToolRegistry({ exportRoot: unusedWriter }, {}))).not.toContain(+ 'kiln_export_to',+ );+ expect(names(createKilnNativeToolRegistry({ assetLibrary: library }, {}))).not.toContain(+ 'kiln_export_to',+ );+ expect(+ names(createKilnNativeToolRegistry({ assetLibrary: library, exportRoot: unusedWriter }, {})),+ ).toContain('kiln_export_to');+ // Over the wire: honest annotations on both tools.+ const server = createKilnMcpServer({ assetLibrary: library, exportRoot: unusedWriter });+ const client = new Client({ name: 'export-to', version: '0' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);+ try {+ const { tools } = await client.listTools();+ expect(tools.find((tool) => tool.name === 'kiln_export')?.annotations?.readOnlyHint).toBe(+ true,+ );+ expect(tools.find((tool) => tool.name === 'kiln_export_to')?.annotations).toMatchObject({+ readOnlyHint: false,+ destructiveHint: false,+ });+ } finally {+ await client.close();+ await server.close();+ }+ });+});++describe('kiln_export_to writes', () => {+ test('writes a runtime GLB and sidecar with the CLI receipt shape and root-relative paths', async () => {+ const before = await library.read('project', asset.assetId, asset.revisionId);+ const { root, run } = await exportTo();+ const receipt = (await run({ path: 'game/props/box.glb' })) as Record<string, unknown>;+ const glb = new Uint8Array(await readFile(join(root, 'game', 'props', 'box.glb')));+ const metadata = new Uint8Array(+ await readFile(join(root, 'game', 'props', 'box.kiln-metadata.json')),+ );+ expect(receipt).toEqual({+ ok: true,+ collection: 'project',+ assetId: asset.assetId,+ revisionId: asset.revisionId,+ profile: 'runtime',+ format: 'glb',+ drawDiagnostics: expect.any(Object),+ files: [+ { kind: 'glb', path: 'game/props/box.glb', bytes: glb.byteLength, sha256: sha256(glb) },+ {+ kind: 'metadata',+ path: 'game/props/box.kiln-metadata.json',+ bytes: metadata.byteLength,+ sha256: sha256(metadata),+ },+ ],+ });+ expect(JSON.stringify(receipt)).not.toContain(base);+ expect(JSON.parse(new TextDecoder().decode(metadata)).source.revisionId).toBe(asset.revisionId);+ // The canonical revision never changes.+ expect(await library.read('project', asset.assetId, asset.revisionId)).toEqual(before);+ });++ test('editable writes the exact saved GLB and nothing else', async () => {+ const { root, run } = await exportTo();+ const receipt = (await run({ path: 'box.glb', profile: 'editable' })) as {+ profile: string;+ files: { kind: string; path: string }[];+ };+ const saved = (await library.read('project', asset.assetId, asset.revisionId)).files[+ 'asset.glb'+ ]!;+ expect(sha256(await readFile(join(root, 'box.glb')))).toBe(sha256(saved));+ expect(receipt.profile).toBe('editable');+ expect(receipt.files.map(({ kind, path }) => [kind, path])).toEqual([['glb', 'box.glb']]);+ expect(await readdir(root)).toEqual(['box.glb']);+ });++ test('target three writes the same bytes as CLI export --profile runtime --target three', async () => {+ const { root, run } = await exportTo();+ const receipt = (await run({ path: 'door.glb', target: 'three' })) as {+ target: string;+ files: { kind: string; sha256: string }[];+ };+ expect(receipt.target).toBe('three');+ const cliOut = join(base, `cli-${roots}`, 'door.glb');+ const cli = spawnSync(+ process.execPath,+ [+ resolve('src/cli.ts'),+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ cliOut,+ '--profile',+ 'runtime',+ '--target',+ 'three',+ '--json',+ ],+ {+ cwd: base,+ env: {+ ...process.env,+ KILN_RENDER: 'cpu',+ KILN_EVALUATOR_MODE: 'in-process',+ KILN_LIVE_REVIEW: 'off',+ KILN_PROGRAM_STORE: join(base, '.kiln', 'programs'),+ KILN_COLLECTIONS: JSON.stringify({ project: join(base, 'collection') }),+ },+ encoding: 'utf8',+ windowsHide: true,+ },+ );+ expect(cli.stderr).toBe('');+ expect(cli.status).toBe(0);+ const cliReceipt = JSON.parse(cli.stdout) as { files: { kind: string; sha256: string }[] };+ expect(receipt.files.map(({ kind, sha256 }) => [kind, sha256])).toEqual(+ cliReceipt.files.map(({ kind, sha256 }) => [kind, sha256]),+ );+ expect((await readdir(root)).sort()).toEqual(['door.glb', 'door.kiln-metadata.json']);+ });+});++describe('kiln_export_to refusals', () => {+ test('refuses unsafe paths and target without runtime, writing nothing', async () => {+ const { root, run } = await exportTo();+ for (const path of [+ '../escape.glb',+ '/abs/box.glb',+ 'C:/box.glb',+ '//host/share/box.glb',+ 'models\\box.glb',+ 'box.gltf',+ 'con/box.glb',+ 'aux.glb',+ 'models/',+ ]) {+ const message = await run({ path }).then(+ () => 'written',+ (error: Error) => error.message,+ );+ expect(message, path).toMatch(/^Export path/);+ }+ await expect(run({ path: 'box.glb', profile: 'editable', target: 'three' })).rejects.toThrow(+ /target requires profile runtime/,+ );+ expect(await readdir(root)).toEqual([]);+ });++ test('never replaces an existing GLB or sidecar', async () => {+ const { root, run } = await exportTo();+ await run({ path: 'box.glb' });+ const glb = await readFile(join(root, 'box.glb'));+ const failure = await run({ path: 'box.glb' }).catch((error: Error) => error.message);+ expect(failure).toContain('already exists in the export root and is never replaced');+ expect(failure).not.toContain(base);+ expect(await readFile(join(root, 'box.glb'))).toEqual(glb);+ await expect(run({ path: 'box.glb', profile: 'editable' })).rejects.toThrow(+ 'box.glb already exists',+ );+ // An orphan sidecar stops the pair before any GLB is published.+ await writeFile(join(root, 'gate.kiln-metadata.json'), 'orphan');+ await expect(run({ path: 'gate.glb' })).rejects.toThrow(+ 'gate.kiln-metadata.json already exists',+ );+ expect((await readdir(root)).sort()).toEqual([+ 'box.glb',+ 'box.kiln-metadata.json',+ 'gate.kiln-metadata.json',+ ]);+ expect(await readFile(join(root, 'gate.kiln-metadata.json'), 'utf8')).toBe('orphan');+ });+});diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 0aeb0ad3..1ccf1668 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -186,6 +186,8 @@ export interface KilnToolContext {skillResourceReader?: import('./skill-resource').SkillResourceReader;/** Durable user collections, supplied by the host; never a disposable build cache. */assetLibrary?: import('../assets').AssetLibrary;+ /** Host-configured export root; advertises kiln_export_to with an assetLibrary. No model-chosen root. */+ exportRoot?: import('../export-root').ExportRootWriter;/** Host-owned delivery URLs, for example expiring HTTPS links or a running local viewer. */assetDownloadUrls?: (collection: string,@@ -2667,6 +2669,7 @@ export function createKilnNativeToolRegistry('kiln_save','kiln_assets','kiln_export',+ 'kiln_export_to','kiln_import','kiln_present',]);@@ -2959,6 +2962,22 @@ export function createKilnAssetDefs('editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.',),});+ const exportToInput = exportInput.extend({+ path: z+ .string()+ .max(240)+ .describe(+ 'Root-relative .glb path with forward slashes, e.g. game/door.glb; runtime adds door.kiln-metadata.json beside it.',+ ),+ profile: z+ .enum(['runtime', 'editable'])+ .default('runtime')+ .describe('runtime: standalone GLB plus metadata sidecar. editable: exact saved GLB only.'),+ target: z+ .enum(['three'])+ .optional()+ .describe('Runtime only: a three.js delivery GLB (instancing, quantization, meshopt).'),+ });const importInput = z.object({...selector,sourceCollection: selector.collection,@@ -3195,6 +3214,9 @@ export function createKilnAssetDefs(};},},+ ...(context.exportRoot && context.assetLibrary+ ? [createKilnExportToDef(context.exportRoot, exportToInput, library, listCall)]+ : []),{name: 'kiln_import',description:@@ -3216,3 +3238,86 @@ export function createKilnAssetDefs(},];}++/** `kiln_export_to` (#207): only with a host export root; the CLI export receipt, root-relative. */+function createKilnExportToDef(+ writer: import('../export-root').ExportRootWriter,+ inputSchema: z.ZodType<{+ collection: string;+ assetId: string;+ revisionId: string;+ path: string;+ profile: 'runtime' | 'editable';+ target?: 'three';+ }>,+ library: () => import('../assets').AssetLibrary,+ listCall: (collection: string) => string,+): KilnToolDef {+ return {+ name: 'kiln_export_to',+ description:+ "Write one saved revision's GLB to a path under the host's export root. Default runtime writes the GLB plus a matching .kiln-metadata.json sidecar; editable writes the exact saved GLB; target three derives a three.js delivery GLB. Never replaces an existing file. Returns the CLI export receipt with root-relative paths, bytes and sha256.",+ inputSchema,+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false,+ },+ run: async (raw) => {+ const input = inputSchema.parse(raw);+ if (input.target !== undefined && input.profile !== 'runtime')+ throw new Error('target requires profile runtime');+ const { validateExportPath } = await import('../export-root');+ const destination = validateExportPath(input.path);+ const { exportAssetGlb, validateMetadataFileName } = await import('../asset-export');+ if (input.profile === 'runtime') validateMetadataFileName(destination.metadataFileName);+ const record = await readSavedRevision(+ library(),+ input.collection,+ input.assetId,+ input.revisionId,+ listCall(input.collection),+ );+ const files: { kind: 'glb' | 'metadata'; path: string; data: Uint8Array }[] = [];+ if (input.profile === 'runtime') {+ const output = await exportAssetGlb(record, {+ profile: 'runtime',+ metadataFileName: destination.metadataFileName,+ ...(input.target ? { target: input.target } : {}),+ });+ if (output.profile !== 'runtime') throw new Error('Expected runtime export');+ files.push(+ { kind: 'glb', path: destination.path, data: output.glb },+ { kind: 'metadata', path: destination.metadataPath, data: output.metadata.bytes },+ );+ } else files.push({ kind: 'glb', path: destination.path, data: record.files['asset.glb']! });+ // Sidecar first, as the CLI publishes: an interrupted pair never leaves a GLB alone.+ await writer.writeNew([...files].reverse());+ const { inspectDrawDiagnostics } = await import('../draw-diagnostics');+ const digest = async (data: Uint8Array) =>+ `sha256:${Array.from(+ new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(data))),+ (byte) => byte.toString(16).padStart(2, '0'),+ ).join('')}`;+ return {+ ok: true,+ collection: input.collection,+ assetId: input.assetId,+ revisionId: input.revisionId,+ profile: input.profile,+ ...(input.target ? { target: input.target } : {}),+ format: 'glb',+ drawDiagnostics: await inspectDrawDiagnostics(files[0]!.data),+ files: await Promise.all(+ files.map(async ({ kind, path, data }) => ({+ kind,+ path,+ bytes: data.byteLength,+ sha256: await digest(data),+ })),+ ),+ };+ },+ };+}diff --git a/src/workspace-mcp.test.ts b/src/workspace-mcp.test.tsindex 01e72db1..72bdfdab 100644--- a/src/workspace-mcp.test.ts+++ b/src/workspace-mcp.test.ts@@ -33,6 +33,7 @@ test('real MCP creates project materials, renders their exact closure, and exposKILN_RENDER: 'cpu',KILN_BUILD_CACHE: 'memory',KILN_EVALUATOR_MODE: 'in-process',+ KILN_EXPORT_ROOT: '',} as Record<string, string>,stderr: 'pipe',});