Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Name an oversize source before the request leaves the host (#299) (#303)

Matthew Kissinger004c23f3d1d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5519fe55..82cf5517 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,28 @@ does not publish a package.
## Unreleased
+- Source between the program store's 1 MiB limit and the evaluator transport's 512 KiB is
+ named as the size problem it is. Such a program saved, edited and validated, then failed
+ evaluation through the generic invalid-request path, which reported the size as something
+ else in each of three ways: a host-injected transport threw a bare `invalid evaluator
+ request` with no outcome code; the local subprocess and isolated evaluators degraded to
+ `PROTOCOL_ERROR`, "Evaluator returned invalid data", because a request the worker cannot
+ decode returns without the request id the host matches on; and a host handing raw request
+ JSON to the evaluator handler got `INPUT_INVALID`, whose message advises updating host and
+ worker together and reading `docs/migration.md`. Both request builders now refuse an
+ oversize source before it leaves the host, naming both byte counts and the repair. The
+ worker keeps reporting a request it cannot decode as the malformed request it is: each host
+ rebuilds the message from the outcome code and discards the wire message, so a cause named
+ inside the worker could not reach a reader, and the engine gains no new outcome code an
+ older host would decode as a protocol error. `kiln_validate` and a `render: false`
+ `kiln_edit` report the same finding as a warning at save time -- in MCP and in `kiln
+ validate` / `kiln edit`, which declare that one host fact rather than building a host --
+ and the source stays valid, because it is. Trusted `KILN_EVALUATOR_MODE=in-process`
+ evaluation builds no request, has no such limit and is not warned about. The two limits are
+ unchanged and still differ on purpose: a stored revision is read, imported and exported
+ without ever being evaluated, so the range is a documented gap rather than a mistake to
+ close, and `docs/programs.md` now states both
+ ([#299](https://github.com/instruktlabs/kiln/issues/299)).
- QA measures open surfaces against the closed solids they meet.
`GEO_OPEN_SURFACE_PENETRATION` samples each open surface's vertices against every closed
solid whose bounds it overlaps and reports how far inside one it reaches, naming both
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 1e68b663..9104d630 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -40050,6 +40050,14 @@ var init_render = __esm(() => {
function evaluatorOutcomeMessage(code) {
return EVALUATOR_OUTCOME_MESSAGES[code];
}
+function evaluatorSourceBudgetFailure(code) {
+ if (typeof code !== "string")
+ return;
+ const bytes = Buffer.byteLength(code, "utf8");
+ if (bytes <= MAX_EVALUATOR_CODE_BYTES)
+ return;
+ return `Source is ${bytes} bytes; one evaluator request carries at most ${MAX_EVALUATOR_CODE_BYTES} bytes of source. ` + "The program store accepts more on purpose, so this revision saves, reads, imports and exports; only evaluation refuses it. " + "Build the geometry inside build() from the primitive, profile and procedural helpers instead of embedding a literal vertex buffer, " + "round the literals you must keep to the precision the asset needs, or bind texture bytes as approved material resources instead of inlining them. " + "kiln_discover reports both limits as source.maxBytes and source.transportEvaluatorMaxBytes.";
+}
function resolveEvaluatorPortV2(port, profile) {
if (port)
return port;
@@ -49330,6 +49338,19 @@ var viewInteriorInput = z24.object({
nodeName: z24.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
});
var viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureRecordInput });
+function transportsEvaluatorSource(context) {
+ if (context.evaluatorTransportsSource !== undefined)
+ return context.evaluatorTransportsSource;
+ if (context.localExecution)
+ return context.localExecution.mode !== "in-process";
+ return Boolean(context.evaluatorPort) || context.evaluatorProfile === "evaluator-required";
+}
+function sourceBudgetAdvisory(code, context) {
+ if (!transportsEvaluatorSource(context))
+ return [];
+ const failure = evaluatorSourceBudgetFailure(code);
+ return failure ? [failure] : [];
+}
function runValidate(input, context) {
const requirements = toolRequirements(context);
const result = validate(input.code);
@@ -49339,7 +49360,10 @@ function runValidate(input, context) {
valid: result.valid,
errors: result.errors,
issues: result.issues,
- warnings: result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ warnings: [
+ ...sourceBudgetAdvisory(input.code, context),
+ ...result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ ]
};
}
var partListInput = z24.object({
@@ -50046,17 +50070,20 @@ async function runEdit(input, context) {
fromLabel: "before",
toLabel: "after"
});
- if (input.render === false)
+ if (input.render === false) {
+ const warnings = sourceBudgetAdvisory(code, context);
return {
ok: true,
code,
applied,
diff,
+ ...warnings.length ? { warnings } : {},
preservation: {
status: "not_assessed",
reason: "Source-only edit. Unchanged source text does not prove unchanged geometry; compare the rendered revisions with kiln_inspect compare."
}
};
+ }
let editedArtifact;
const rendered = await runRenderViews({ code, ...input.capture ? { capture: input.capture } : {} }, context, (artifact) => {
editedArtifact = artifact;
@@ -50286,7 +50313,11 @@ function createKilnProgramToolRegistry(suppliedContext = {}) {
function createProgramDefs(suppliedContext, presentation) {
toolRequirements(suppliedContext);
const store = suppliedContext.programStore ?? new MemoryProgramStore;
- const context = withCaptureCache(withBuildCache({ ...suppliedContext, programStore: store }));
+ const context = withCaptureCache(withBuildCache({
+ ...suppliedContext,
+ programStore: store,
+ evaluatorTransportsSource: transportsEvaluatorSource(suppliedContext)
+ }));
return [
createKilnDiscoveryDef({ ...suppliedContext, programStore: store }, presentation),
{
diff --git a/dist/build.json b/dist/build.json
index b833a5fb..b07ab47d 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -40,10 +40,10 @@
"bundleHash": "sha256:395bac1322db31159ac553f054496245315a1473099fd4c6bd0e1e7b339aed66"
},
"agent-run": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -75,13 +75,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:36dec36a18ce6d33f049180709c53e4b464475f78842fd3a4e0798e841bc6295"
+ "bundleHash": "sha256:9a9fa4577619b5a060f2cd113b32b757715678a26e9645a581dccc72ba05dd27"
},
"agent-providers": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -116,10 +116,10 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -154,10 +154,10 @@
"bundleHash": "sha256:deeb947091b693e92337a2081678ed06cd0a2d23f813a375001c31dbf529a815"
},
"cli": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -189,13 +189,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:769aacd03ca587946da398590ae2417a0a01484fbd185a9eea8c30d146105617"
+ "bundleHash": "sha256:fa19d5e178e7293d707e220628c6b1a361a0e90ddf8dab4ad7c31b1b9630b257"
},
"engine": {
- "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be",
+ "identity": "sha256:63990784c232b14cffe8a4e4f4d88d5a2417eb9de11d820632fb0c3fb90c9006",
"engineVersion": "1.5.0",
"toolchain": "[email protected]",
- "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2",
+ "sourceHash": "26c96371d19403636794fb2d7b06d6262980bfedb28f4fd92b41b1c1727a6621",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -227,7 +227,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:e5a7160d3ba3d72d478ae3e7d1c0e230028fbe9f9c01b07aa46c94d8ff0c36c4"
+ "bundleHash": "sha256:e090b7f1806ce131c7440847c3056b283eca5d80ab59e9b70958912a8672efde"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index e0c169e0..4dd79a83 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -37741,6 +37741,14 @@ import { createHash as createHash8 } from "node:crypto";
function evaluatorOutcomeMessage(code) {
return EVALUATOR_OUTCOME_MESSAGES[code];
}
+function evaluatorSourceBudgetFailure(code) {
+ if (typeof code !== "string")
+ return;
+ const bytes = Buffer.byteLength(code, "utf8");
+ if (bytes <= MAX_EVALUATOR_CODE_BYTES)
+ return;
+ return `Source is ${bytes} bytes; one evaluator request carries at most ${MAX_EVALUATOR_CODE_BYTES} bytes of source. ` + "The program store accepts more on purpose, so this revision saves, reads, imports and exports; only evaluation refuses it. " + "Build the geometry inside build() from the primitive, profile and procedural helpers instead of embedding a literal vertex buffer, " + "round the literals you must keep to the precision the asset needs, or bind texture bytes as approved material resources instead of inlining them. " + "kiln_discover reports both limits as source.maxBytes and source.transportEvaluatorMaxBytes.";
+}
function resolveEvaluatorPortV2(port, profile) {
if (port)
return port;
@@ -42078,6 +42086,9 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, laun
if (options.textureResolver) {
throw new EvaluatorSubprocessError("INPUT_INVALID", "Subprocess evaluation does not accept host resolver capabilities.");
}
+ const oversizeSource = evaluatorSourceBudgetFailure(code);
+ if (oversizeSource)
+ throw new EvaluatorSubprocessError("INPUT_INVALID", oversizeSource);
const deadlineMs = boundedInteger2(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);
const maxGlbBytes = boundedInteger2(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
const maxResponseBytes = boundedInteger2(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
@@ -45936,6 +45947,9 @@ function integer4(env, name, fallback, min, max) {
throw new Error(`${name} requires an integer from ${min} to ${max}.`);
return value;
}
+function localEvaluatorMode(env = process.env) {
+ return resolveEvaluatorMode({ KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess" });
+}
function createLocalToolContext(base = {}, env = process.env) {
const workspaceRoot = env.KILN_WORKSPACE ? resolve12(env.KILN_WORKSPACE) : base.programStore instanceof FileProgramStore ? dirname7(dirname7(base.programStore.directory)) : localWorkspaceRoot(env);
const workspace = base.workspace ?? new FileWorkspace(workspaceRoot, env.KILN_PROJECT);
@@ -45950,9 +45964,7 @@ function createLocalToolContext(base = {}, env = process.env) {
throw new Error("KILN_INDEX_POLICY must be indexed or asBuilt.");
if (!["warn", "strict"].includes(geometryPolicy))
throw new Error("KILN_GEOMETRY_POLICY must be warn or strict.");
- const mode = resolveEvaluatorMode({
- KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess"
- });
+ const mode = localEvaluatorMode(env);
const deadlineMs = integer4(env, "KILN_EVALUATOR_TIMEOUT_MS", 60000, 1, 120000);
const heapMb = integer4(env, "KILN_EVALUATOR_HEAP_MB", 512, 64, 4096);
if (mode === "subprocess" && process.versions.bun && env.KILN_EVALUATOR_HEAP_MB !== undefined) {
@@ -54468,6 +54480,19 @@ function derivativeReviewFidelity(receipts) {
...reasonCodes.length ? { reasonCodes } : {}
};
}
+function transportsEvaluatorSource(context) {
+ if (context.evaluatorTransportsSource !== undefined)
+ return context.evaluatorTransportsSource;
+ if (context.localExecution)
+ return context.localExecution.mode !== "in-process";
+ return Boolean(context.evaluatorPort) || context.evaluatorProfile === "evaluator-required";
+}
+function sourceBudgetAdvisory(code, context) {
+ if (!transportsEvaluatorSource(context))
+ return [];
+ const failure = evaluatorSourceBudgetFailure(code);
+ return failure ? [failure] : [];
+}
function runValidate(input, context) {
const requirements = toolRequirements(context);
const result = validate(input.code);
@@ -54477,7 +54502,10 @@ function runValidate(input, context) {
valid: result.valid,
errors: result.errors,
issues: result.issues,
- warnings: result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ warnings: [
+ ...sourceBudgetAdvisory(input.code, context),
+ ...result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ ]
};
}
async function listPartNames2(root, options = {}) {
@@ -55123,17 +55151,20 @@ async function runEdit(input, context) {
fromLabel: "before",
toLabel: "after"
});
- if (input.render === false)
+ if (input.render === false) {
+ const warnings = sourceBudgetAdvisory(code, context);
return {
ok: true,
code,
applied,
diff,
+ ...warnings.length ? { warnings } : {},
preservation: {
status: "not_assessed",
reason: "Source-only edit. Unchanged source text does not prove unchanged geometry; compare the rendered revisions with kiln_inspect compare."
}
};
+ }
let editedArtifact;
const rendered = await runRenderViews({ code, ...input.capture ? { capture: input.capture } : {} }, context, (artifact) => {
editedArtifact = artifact;
@@ -55352,7 +55383,11 @@ function createKilnProgramToolRegistry(suppliedContext = {}) {
function createProgramDefs(suppliedContext, presentation) {
toolRequirements(suppliedContext);
const store = suppliedContext.programStore ?? new MemoryProgramStore;
- const context = withCaptureCache(withBuildCache({ ...suppliedContext, programStore: store }));
+ const context = withCaptureCache(withBuildCache({
+ ...suppliedContext,
+ programStore: store,
+ evaluatorTransportsSource: transportsEvaluatorSource(suppliedContext)
+ }));
return [
createKilnDiscoveryDef({ ...suppliedContext, programStore: store }, presentation),
{
@@ -58630,7 +58665,8 @@ async function editMain(argv) {
const tool = createKilnProgramToolRegistry({
programStore: localProgramStore(),
workspace,
- liveReview
+ liveReview,
+ evaluatorTransportsSource: localEvaluatorMode() !== "in-process"
}).find((definition) => definition.name === "kiln_edit");
const input = tool.inputSchema.parse({
programRef,
@@ -58674,6 +58710,7 @@ var init_edit_cli = __esm(() => {
init_program_store();
init_program_store_node();
init_registry2();
+ init_local_runtime();
init_workspace_node();
init_live_review_node();
init_workspace_cli();
@@ -60089,7 +60126,10 @@ ${USAGE3}`);
}
const store = localProgramStore();
const isRef = input.startsWith("sha256:") || programRefPattern.test(input);
- const def = createKilnProgramToolRegistry({ programStore: store }).find((d) => d.name === "kiln_validate");
+ const def = createKilnProgramToolRegistry({
+ programStore: store,
+ evaluatorTransportsSource: localEvaluatorMode() !== "in-process"
+ }).find((d) => d.name === "kiln_validate");
if (!def)
throw new Error("kiln_validate is missing from the MCP tool surface");
const result = await def.run(isRef ? { programRef: input } : { code: await readFile15(resolvePath(input), "utf8") });
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 06950841..9c311666 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -40642,6 +40642,14 @@ import { createHash as createHash14 } from "node:crypto";
function evaluatorOutcomeMessage(code) {
return EVALUATOR_OUTCOME_MESSAGES[code];
}
+function evaluatorSourceBudgetFailure(code) {
+ if (typeof code !== "string")
+ return;
+ const bytes = Buffer.byteLength(code, "utf8");
+ if (bytes <= MAX_EVALUATOR_CODE_BYTES)
+ return;
+ return `Source is ${bytes} bytes; one evaluator request carries at most ${MAX_EVALUATOR_CODE_BYTES} bytes of source. ` + "The program store accepts more on purpose, so this revision saves, reads, imports and exports; only evaluation refuses it. " + "Build the geometry inside build() from the primitive, profile and procedural helpers instead of embedding a literal vertex buffer, " + "round the literals you must keep to the precision the asset needs, or bind texture bytes as approved material resources instead of inlining them. " + "kiln_discover reports both limits as source.maxBytes and source.transportEvaluatorMaxBytes.";
+}
function resolveEvaluatorPortV2(port, profile) {
if (port)
return port;
@@ -40928,6 +40936,9 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, laun
if (options.textureResolver) {
throw new EvaluatorSubprocessError("INPUT_INVALID", "Subprocess evaluation does not accept host resolver capabilities.");
}
+ const oversizeSource = evaluatorSourceBudgetFailure(code);
+ if (oversizeSource)
+ throw new EvaluatorSubprocessError("INPUT_INVALID", oversizeSource);
const deadlineMs = boundedInteger2(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);
const maxGlbBytes = boundedInteger2(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
const maxResponseBytes = boundedInteger2(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
@@ -46145,6 +46156,9 @@ function integer4(env, name, fallback, min, max) {
throw new Error(`${name} requires an integer from ${min} to ${max}.`);
return value;
}
+function localEvaluatorMode(env = process.env) {
+ return resolveEvaluatorMode({ KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess" });
+}
function createLocalToolContext(base = {}, env = process.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);
@@ -46159,9 +46173,7 @@ function createLocalToolContext(base = {}, env = process.env) {
throw new Error("KILN_INDEX_POLICY must be indexed or asBuilt.");
if (!["warn", "strict"].includes(geometryPolicy))
throw new Error("KILN_GEOMETRY_POLICY must be warn or strict.");
- const mode = resolveEvaluatorMode({
- KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess"
- });
+ const mode = localEvaluatorMode(env);
const deadlineMs = integer4(env, "KILN_EVALUATOR_TIMEOUT_MS", 60000, 1, 120000);
const heapMb = integer4(env, "KILN_EVALUATOR_HEAP_MB", 512, 64, 4096);
if (mode === "subprocess" && process.versions.bun && env.KILN_EVALUATOR_HEAP_MB !== undefined) {
@@ -53550,6 +53562,19 @@ var viewInteriorInput = z25.object({
nodeName: z25.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
});
var viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureRecordInput });
+function transportsEvaluatorSource(context) {
+ if (context.evaluatorTransportsSource !== undefined)
+ return context.evaluatorTransportsSource;
+ if (context.localExecution)
+ return context.localExecution.mode !== "in-process";
+ return Boolean(context.evaluatorPort) || context.evaluatorProfile === "evaluator-required";
+}
+function sourceBudgetAdvisory(code, context) {
+ if (!transportsEvaluatorSource(context))
+ return [];
+ const failure = evaluatorSourceBudgetFailure(code);
+ return failure ? [failure] : [];
+}
function runValidate(input, context) {
const requirements = toolRequirements(context);
const result = validate(input.code);
@@ -53559,7 +53584,10 @@ function runValidate(input, context) {
valid: result.valid,
errors: result.errors,
issues: result.issues,
- warnings: result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ warnings: [
+ ...sourceBudgetAdvisory(input.code, context),
+ ...result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
+ ]
};
}
var partListInput = z25.object({
@@ -54266,17 +54294,20 @@ async function runEdit(input, context) {
fromLabel: "before",
toLabel: "after"
});
- if (input.render === false)
+ if (input.render === false) {
+ const warnings = sourceBudgetAdvisory(code, context);
return {
ok: true,
code,
applied,
diff,
+ ...warnings.length ? { warnings } : {},
preservation: {
status: "not_assessed",
reason: "Source-only edit. Unchanged source text does not prove unchanged geometry; compare the rendered revisions with kiln_inspect compare."
}
};
+ }
let editedArtifact;
const rendered = await runRenderViews({ code, ...input.capture ? { capture: input.capture } : {} }, context, (artifact) => {
editedArtifact = artifact;
@@ -54506,7 +54537,11 @@ function createKilnProgramToolRegistry(suppliedContext = {}) {
function createProgramDefs(suppliedContext, presentation) {
toolRequirements(suppliedContext);
const store = suppliedContext.programStore ?? new MemoryProgramStore;
- const context = withCaptureCache(withBuildCache({ ...suppliedContext, programStore: store }));
+ const context = withCaptureCache(withBuildCache({
+ ...suppliedContext,
+ programStore: store,
+ evaluatorTransportsSource: transportsEvaluatorSource(suppliedContext)
+ }));
return [
createKilnDiscoveryDef({ ...suppliedContext, programStore: store }, presentation),
{
diff --git a/docs/programs.md b/docs/programs.md
index 297f03dd..4e2295e5 100644
--- a/docs/programs.md
+++ b/docs/programs.md
@@ -104,6 +104,16 @@ eviction or total disk quota. Export accepted work before deleting an old worksp
store; its references then stop resolving. Source is integrity-checked on read. A hash
identifies content and does not authorize access in a hosted service.
+One evaluator request carries at most 512 KiB of source, which is lower than the store's
+1 MiB on purpose: a stored revision is read, imported and exported without ever being
+evaluated, and trusted in-process evaluation builds no request at all. So the two limits
+leave a range a program can be saved in but not built in. `kiln_discover` reports both as
+`source.maxBytes` and `source.transportEvaluatorMaxBytes`. A host that transports source
+reports a program over the transport limit as a warning from `kiln_validate` and from a
+`render: false` edit, and refuses the build naming both byte counts — build geometry inside
+`build()` from the helpers instead of embedding a literal vertex buffer, round the literals
+you must keep, or bind texture bytes as approved material resources.
+
## Failure handling
A failed replacement leaves the base unchanged. An edit may apply successfully while
diff --git a/src/cli.ts b/src/cli.ts
index 9dae4cbb..6b6ada62 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -9,7 +9,7 @@ import { resolve as resolvePath, extname } from 'node:path';
import { writeDestinationAtomic, writeNewDestinationsAtomic } from './cli-output';
import { isDirectEntry } from './direct-entry';
-import { createPackagedLocalToolContext } from './local-runtime';
+import { createPackagedLocalToolContext, localEvaluatorMode } from './local-runtime';
import { createKilnProgramToolRegistry, type KilnToolContext } from './tools/registry';
import { createKilnSourceDef } from './tools/programs';
import { BACKDROP_IDS, isBackdropId, type BackdropId } from './views/background';
@@ -554,9 +554,12 @@ async function cmdValidate(args: Args): Promise<number> {
}
const store = localProgramStore();
const isRef = input.startsWith('sha256:') || programRefPattern.test(input);
- const def = createKilnProgramToolRegistry({ programStore: store }).find(
- (d) => d.name === 'kiln_validate',
- );
+ // A syntax check builds no host context, but a source finding needs one host fact:
+ // whether a render will carry this source to a worker (#299).
+ const def = createKilnProgramToolRegistry({
+ programStore: store,
+ evaluatorTransportsSource: localEvaluatorMode() !== 'in-process',
+ }).find((d) => d.name === 'kiln_validate');
if (!def) throw new Error('kiln_validate is missing from the MCP tool surface');
const result = (await def.run(
isRef ? { programRef: input } : { code: await readFile(resolvePath(input), 'utf8') },
diff --git a/src/edit-cli.ts b/src/edit-cli.ts
index 18b320fa..3df9b5b6 100644
--- a/src/edit-cli.ts
+++ b/src/edit-cli.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { programRefPattern } from './program-store';
import { localProgramStore } from './program-store-node';
import { createKilnProgramToolRegistry } from './tools/registry';
+import { localEvaluatorMode } from './local-runtime';
import { FileWorkspace, localWorkspaceRoot } from './workspace-node';
import { FileLiveReview } from './live-review-node';
import { cliWorkspaceSelection, readMaterialDependencies } from './workspace-cli';
@@ -100,6 +101,9 @@ export async function editMain(argv: readonly string[]): Promise<number> {
programStore: localProgramStore(),
workspace,
liveReview,
+ // Still no evaluator here; this only declares what a later render would do with the
+ // patched source, so an oversize program is reported now rather than then (#299).
+ evaluatorTransportsSource: localEvaluatorMode() !== 'in-process',
}).find((definition) => definition.name === 'kiln_edit')!;
const input = tool.inputSchema.parse({
programRef,
diff --git a/src/evaluator/index.ts b/src/evaluator/index.ts
index 457e6aa6..8eba5f33 100644
--- a/src/evaluator/index.ts
+++ b/src/evaluator/index.ts
@@ -7,6 +7,7 @@ export {
decodeEvaluatorResultV2,
encodeRenderResultV2,
evaluatorOutcomeMessage,
+ evaluatorSourceBudgetFailure,
EvaluatorPortError,
resolveEvaluatorPortV2,
trustedInProcessEvaluatorPortV2,
diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.ts
index 798281e2..d7d72c39 100644
--- a/src/evaluator/protocol.ts
+++ b/src/evaluator/protocol.ts
@@ -65,6 +65,30 @@ export function evaluatorOutcomeMessage(code: EvaluatorOutcomeCode): string {
return EVALUATOR_OUTCOME_MESSAGES[code];
}
+/**
+ * The one request budget an author reaches by authoring, rather than by sending a malformed
+ * request: source larger than a single evaluator request carries. The program store's limit
+ * is deliberately higher, because a stored revision is read, imported and exported without
+ * ever being evaluated, so this is a gap and not a mistake to close. Named here as a closed
+ * cause (#299): the generic `fail('request')` path reports it as a version mismatch, and a
+ * request carrying source over this budget never has to leave the host to find out.
+ *
+ * Returns the message, or undefined when the source fits. A non-string `code` belongs to the
+ * strict decoder, which rejects it as the malformed request it is.
+ */
+export function evaluatorSourceBudgetFailure(code: unknown): string | undefined {
+ if (typeof code !== 'string') return undefined;
+ const bytes = Buffer.byteLength(code, 'utf8');
+ if (bytes <= MAX_EVALUATOR_CODE_BYTES) return undefined;
+ return (
+ `Source is ${bytes} bytes; one evaluator request carries at most ${MAX_EVALUATOR_CODE_BYTES} bytes of source. ` +
+ 'The program store accepts more on purpose, so this revision saves, reads, imports and exports; only evaluation refuses it. ' +
+ 'Build the geometry inside build() from the primitive, profile and procedural helpers instead of embedding a literal vertex buffer, ' +
+ 'round the literals you must keep to the precision the asset needs, or bind texture bytes as approved material resources instead of inlining them. ' +
+ 'kiln_discover reports both limits as source.maxBytes and source.transportEvaluatorMaxBytes.'
+ );
+}
+
export interface EvaluatorRequestV2 {
version: typeof EVALUATOR_REQUEST_VERSION;
requestId: string;
@@ -252,6 +276,8 @@ export function createEvaluatorRequestV2(input: CreateEvaluatorRequestV2Input):
'Evaluator requests do not accept a host console capability.',
);
}
+ const oversizeSource = evaluatorSourceBudgetFailure(input.code);
+ if (oversizeSource) throw new EvaluatorPortError('INPUT_INVALID', oversizeSource);
const maxGlbBytes = boundedControl(
input.maxGlbBytes,
DEFAULT_EVALUATOR_MAX_GLB_BYTES,
diff --git a/src/evaluator/source-budget.test.ts b/src/evaluator/source-budget.test.ts
new file mode 100644
index 00000000..2005bfcc
--- /dev/null
+++ b/src/evaluator/source-budget.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ createEvaluatorRequestV2,
+ evaluatorOutcomeMessage,
+ MAX_EVALUATOR_CODE_BYTES,
+} from './protocol';
+import { createEvaluatorPortV2 } from './protocol';
+import { renderGLBViaSubprocess } from './subprocess';
+import { MAX_PROGRAM_BYTES, programReference } from '../program-store';
+import { createKilnProgramToolRegistry, type KilnToolContext } from '../tools/registry';
+
+/**
+ * A valid program padded with a literal buffer, sized into the gap between the program
+ * store's limit and the evaluator transport's. This is the authoring shape #299 was filed
+ * from: a large literal mesh buffer that saves and validates, then fails evaluation.
+ */
+function paddedProgram(bytes: number): string {
+ const program = (pad: string) =>
+ `const meta={name:'Padded'};\nconst DATA=[${pad}0];\nfunction build(){const r=createRoot('Padded');return r;}\n`;
+ const cell = '0.12345,';
+ const base = Buffer.byteLength(program(''), 'utf8');
+ return program(cell.repeat(Math.ceil((bytes - base) / cell.length)));
+}
+
+const OVERSIZE = paddedProgram(600 * 1024);
+const OVERSIZE_BYTES = Buffer.byteLength(OVERSIZE, 'utf8');
+/** The generic request message, which advises a host/worker version migration. */
+const VERSION_ADVICE = evaluatorOutcomeMessage('INPUT_INVALID');
+
+const port = { render: async () => ({}) as never };
+
+function registry(context: KilnToolContext) {
+ const tools = createKilnProgramToolRegistry(context);
+ return (name: string) => {
+ const def = tools.find((tool) => tool.name === name);
+ if (!def) throw new Error(`${name} is not registered`);
+ return def;
+ };
+}
+
+describe('source between the store and transport limits (#299)', () => {
+ test('the gap exists: the store accepts a program the transport refuses', async () => {
+ expect(OVERSIZE_BYTES).toBeGreaterThan(MAX_EVALUATOR_CODE_BYTES);
+ expect(OVERSIZE_BYTES).toBeLessThanOrEqual(MAX_PROGRAM_BYTES);
+ // Deliberate: a stored revision is read, imported and exported without evaluation.
+ await expect(programReference(OVERSIZE)).resolves.toMatch(/^sha256:[a-f0-9]{64}$/);
+ });
+
+ test('request construction names source size, not a version mismatch', () => {
+ let message = '';
+ try {
+ createEvaluatorRequestV2({ requestId: 'pad-1', code: OVERSIZE });
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+ expect(message).toContain(String(OVERSIZE_BYTES));
+ expect(message).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ expect(message).not.toContain('docs/migration.md');
+ expect(message).not.toBe(VERSION_ADVICE);
+ });
+
+ test('the subprocess evaluator names source size before launching a worker', async () => {
+ const failure = await renderGLBViaSubprocess(OVERSIZE).catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(Error);
+ const error = failure as Error & { code?: string };
+ expect(error.code).toBe('INPUT_INVALID');
+ expect(error.message).toContain(String(OVERSIZE_BYTES));
+ expect(error.message).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ expect(error.message).not.toContain('docs/migration.md');
+ });
+
+ test('kiln_validate reports the finding at save time and keeps the source valid', async () => {
+ const result = (await registry({ evaluatorPort: port })('kiln_validate').run({
+ code: OVERSIZE,
+ })) as { valid: boolean; errors: string[]; warnings: string[] };
+ // Advisory: the program is syntactically valid, and a trusted in-process host runs it.
+ expect(result.valid).toBe(true);
+ expect(result.errors).toEqual([]);
+ const found = result.warnings.filter((warning) => warning.includes(String(OVERSIZE_BYTES)));
+ expect(found).toHaveLength(1);
+ expect(found[0]).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ });
+
+ test('kiln_validate stays quiet where no request carries the source', async () => {
+ for (const context of [
+ {},
+ { evaluatorPort: port, localExecution: { mode: 'in-process' } as never },
+ ]) {
+ const result = (await registry(context)('kiln_validate').run({ code: OVERSIZE })) as {
+ valid: boolean;
+ warnings: string[];
+ };
+ expect(result.valid).toBe(true);
+ expect(result.warnings.join('\n')).not.toContain(String(OVERSIZE_BYTES));
+ }
+ });
+
+ test('a local host reports it from a context built for a cheap syntax check', async () => {
+ // `kiln validate` and `kiln edit` build no host context, so they declare the one host
+ // fact a source finding needs rather than inheriting a forged evaluator port.
+ const { localEvaluatorMode } = await import('../local-runtime');
+ expect(localEvaluatorMode({})).toBe('subprocess');
+ expect(localEvaluatorMode({ KILN_EVALUATOR_MODE: 'in-process' })).toBe('in-process');
+ const result = (await registry({
+ evaluatorTransportsSource: localEvaluatorMode({}) !== 'in-process',
+ })('kiln_validate').run({ code: OVERSIZE })) as { valid: boolean; warnings: string[] };
+ expect(result.valid).toBe(true);
+ expect(result.warnings[0]).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ });
+
+ test('the worker still reports a request it cannot decode as a malformed one', async () => {
+ // Deliberate: both hosts rebuild the message from the outcome code and discard the
+ // wire message, so a cause named inside the worker could not reach a reader. The
+ // request builders above are the seam where naming it carries information.
+ const { evaluateEvaluatorRequestV2 } = await import('./handler');
+ const handRolled = JSON.stringify({
+ version: 'kiln.evaluator.request.v2',
+ requestId: 'pad-2',
+ operation: 'execute-export-glb',
+ code: OVERSIZE,
+ options: {},
+ limits: { maxGlbBytes: 1024 },
+ });
+ const result = JSON.parse(await evaluateEvaluatorRequestV2(handRolled)) as {
+ ok: boolean;
+ error: { code: string; message: string };
+ };
+ expect(result.ok).toBe(false);
+ expect(result.error.code).toBe('INPUT_INVALID');
+ expect(result.error.message).toBe(VERSION_ADVICE);
+ });
+
+ test('kiln_render puts the named cause in the error a reader actually sees', async () => {
+ const evaluatorPort = createEvaluatorPortV2(async () => {
+ throw new Error('the transport must not be reached');
+ });
+ const result = (await registry({ evaluatorPort })('kiln_render').run({ code: OVERSIZE })) as {
+ ok: boolean;
+ error: string;
+ };
+ expect(result.ok).toBe(false);
+ expect(result.error).toContain(String(OVERSIZE_BYTES));
+ expect(result.error).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ expect(result.error).not.toContain('docs/migration.md');
+ });
+
+ test('kiln_edit reports the finding when it patches without rendering', async () => {
+ const result = (await registry({ evaluatorPort: port })('kiln_edit').run({
+ code: OVERSIZE,
+ edits: [{ oldString: "name:'Padded'", newString: "name:'Padded2'" }],
+ render: false,
+ })) as { ok: boolean; warnings?: string[] };
+ expect(result.ok).toBe(true);
+ expect(result.warnings?.join('\n')).toContain(String(MAX_EVALUATOR_CODE_BYTES));
+ });
+});
diff --git a/src/evaluator/subprocess-pipe-close.test.ts b/src/evaluator/subprocess-pipe-close.test.ts
index 682ed9bd..97e5be82 100644
--- a/src/evaluator/subprocess-pipe-close.test.ts
+++ b/src/evaluator/subprocess-pipe-close.test.ts
@@ -6,6 +6,13 @@ const result = JSON.stringify({
ok: false,
error: { code: 'EXECUTION_REJECTED', message: 'Generated asset execution was rejected.' },
});
+/**
+ * A source far larger than any OS pipe buffer, so the worker's `process.stdin.destroy()`
+ * lands mid-write and the close race is real. The size is the instrument here, never the
+ * subject: it stays under the transport's own source budget, which refuses an oversize
+ * request before any worker launches (#299).
+ */
+const UNFLUSHABLE_SOURCE = `//${'x'.repeat(400_000)}`;
const launch = (output: string, exit = 0) => ({
command: process.execPath,
args: [
@@ -16,20 +23,15 @@ const launch = (output: string, exit = 0) => ({
});
test('a worker closing its input before a valid rejection still settles its complete fd3 envelope', async () => {
await expect(
- renderGLBViaProcessLaunch(`//${'x'.repeat(900000)}`, {}, { deadlineMs: 5000 }, launch(result)),
+ renderGLBViaProcessLaunch(UNFLUSHABLE_SOURCE, {}, { deadlineMs: 5000 }, launch(result)),
).rejects.toMatchObject({ code: 'EXECUTION_REJECTED' });
}, 10000);
test('input-close races never accept incomplete output or a failed worker exit', async () => {
await expect(
- renderGLBViaProcessLaunch(`//${'x'.repeat(900000)}`, {}, { deadlineMs: 5000 }, launch('{')),
+ renderGLBViaProcessLaunch(UNFLUSHABLE_SOURCE, {}, { deadlineMs: 5000 }, launch('{')),
).rejects.toMatchObject({ code: 'PROTOCOL_ERROR' });
await expect(
- renderGLBViaProcessLaunch(
- `//${'x'.repeat(900000)}`,
- {},
- { deadlineMs: 5000 },
- launch(result, 1),
- ),
+ renderGLBViaProcessLaunch(UNFLUSHABLE_SOURCE, {}, { deadlineMs: 5000 }, launch(result, 1)),
).rejects.toMatchObject({ code: 'WORKER_FAILED' });
}, 15000);
@@ -40,14 +42,14 @@ test('input-close errors retain deadline and cancellation authority', async () =
env: sanitizedEvaluatorEnv(),
};
await expect(
- renderGLBViaProcessLaunch(`//${'x'.repeat(900000)}`, {}, { deadlineMs: 500 }, hanging),
+ renderGLBViaProcessLaunch(UNFLUSHABLE_SOURCE, {}, { deadlineMs: 500 }, hanging),
).rejects.toMatchObject({ code: 'DEADLINE_EXCEEDED' });
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 300);
try {
await expect(
renderGLBViaProcessLaunch(
- `//${'x'.repeat(900000)}`,
+ UNFLUSHABLE_SOURCE,
{},
{ deadlineMs: 5000, signal: controller.signal },
hanging,
diff --git a/src/evaluator/subprocess.ts b/src/evaluator/subprocess.ts
index ee20c1ab..f300c466 100644
--- a/src/evaluator/subprocess.ts
+++ b/src/evaluator/subprocess.ts
@@ -15,6 +15,7 @@ import {
assertEvaluatorResultRequirements,
assertEvaluatorResultMaterialResources,
evaluatorOutcomeMessage,
+ evaluatorSourceBudgetFailure,
EVALUATOR_REQUEST_VERSION,
type EvaluatorOutcomeCode,
type EvaluatorRequestV2,
@@ -111,6 +112,10 @@ export async function renderGLBViaProcessLaunch(
'Subprocess evaluation does not accept host resolver capabilities.',
);
}
+ // Named before any worker launch: the host still has the source, and the worker's own
+ // decode reports an oversize request as a malformed one (#299).
+ const oversizeSource = evaluatorSourceBudgetFailure(code);
+ if (oversizeSource) throw new EvaluatorSubprocessError('INPUT_INVALID', oversizeSource);
const deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120_000);
const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
const maxResponseBytes = boundedInteger(
diff --git a/src/local-runtime.ts b/src/local-runtime.ts
index 5ee8af28..ad63f1d8 100644
--- a/src/local-runtime.ts
+++ b/src/local-runtime.ts
@@ -84,6 +84,17 @@ function integer(
return value;
}
+/**
+ * The evaluator mode a local CLI/MCP host runs in, without building a host context. A cheap
+ * offline command such as `kiln validate` needs this one fact and none of the rest, so the
+ * default lives here rather than being spelled a second time at the call site.
+ */
+export function localEvaluatorMode(
+ env: Record<string, string | undefined> = process.env,
+): LocalExecution['mode'] {
+ return resolveEvaluatorMode({ KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? 'subprocess' });
+}
+
/** Local CLI/MCP host defaults; library callers retain explicit evaluator choice. */
export function createLocalToolContext(
base: KilnToolContext = {},
@@ -111,9 +122,7 @@ export function createLocalToolContext(
throw new Error('KILN_INDEX_POLICY must be indexed or asBuilt.');
if (!['warn', 'strict'].includes(geometryPolicy))
throw new Error('KILN_GEOMETRY_POLICY must be warn or strict.');
- const mode = resolveEvaluatorMode({
- KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? 'subprocess',
- });
+ const mode = localEvaluatorMode(env);
const deadlineMs = integer(env, 'KILN_EVALUATOR_TIMEOUT_MS', 60000, 1, 120000);
const heapMb = integer(env, 'KILN_EVALUATOR_HEAP_MB', 512, 64, 4096);
if (mode === 'subprocess' && process.versions.bun && env.KILN_EVALUATOR_HEAP_MB !== undefined) {
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 5fc4d510..e76ffbc6 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -74,7 +74,7 @@ import type {
} from '../composer/render-port';
import type { ViewGridResult } from '../views';
import type { EvaluatorExecutionProfileV2, EvaluatorPortV2 } from '../evaluator';
-import { resolveEvaluatorPortV2 } from '../evaluator';
+import { evaluatorSourceBudgetFailure, resolveEvaluatorPortV2 } from '../evaluator';
import { sceneNeedsPbrShading } from '../material-resources';
import { nextRenderRoute } from '../render-route';
import { KilnDraftBuffer } from '../edit-buffer';
@@ -200,6 +200,13 @@ export interface KilnToolContext {
geometryPolicy?: import('../geometry-export').GeometryExportPolicy;
indexPolicy?: import('../index-policy').IndexPolicy;
localExecution?: import('../local-runtime').LocalExecution;
+ /**
+ * Whether the host carries source through an evaluator request, where the transport's own
+ * source budget applies. Resolved from the supplied host before a build-cache wrapper
+ * forges an `evaluatorPort`, so a save-time finding reads the host and not the wrapper
+ * (#299). Left unset, the host is read directly.
+ */
+ evaluatorTransportsSource?: boolean;
/** Host-only, lazy provenance scan for saved builds; independent of evaluator reuse. */
prepareBuildProvenance?: () => Promise<void>;
evaluationControls?: () => import('../evaluator/protocol').EvaluatorPortCallControlsV2;
@@ -788,6 +795,24 @@ const viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureR
// kiln_validate
// =============================================================================
+/**
+ * Whether this host sends source through an evaluator request, where the transport's own
+ * source budget applies. Trusted in-process evaluation builds no request, so a program
+ * between the store limit and the transport limit renders there and is not a finding (#299).
+ */
+function transportsEvaluatorSource(context: KilnToolContext): boolean {
+ if (context.evaluatorTransportsSource !== undefined) return context.evaluatorTransportsSource;
+ if (context.localExecution) return context.localExecution.mode !== 'in-process';
+ return Boolean(context.evaluatorPort) || context.evaluatorProfile === 'evaluator-required';
+}
+
+/** The transport source budget as a save-time advisory, before a render spends the cause. */
+function sourceBudgetAdvisory(code: string, context: KilnToolContext): string[] {
+ if (!transportsEvaluatorSource(context)) return [];
+ const failure = evaluatorSourceBudgetFailure(code);
+ return failure ? [failure] : [];
+}
+
function runValidate(
input: z.infer<typeof validateInput>,
context: KilnToolContext,
@@ -807,7 +832,10 @@ function runValidate(
valid: result.valid,
errors: result.errors,
issues: result.issues,
- warnings: result.warnings.map((w) => (w.fixHint ? `${w.message} (${w.fixHint})` : w.message)),
+ warnings: [
+ ...sourceBudgetAdvisory(input.code, context),
+ ...result.warnings.map((w) => (w.fixHint ? `${w.message} (${w.fixHint})` : w.message)),
+ ],
};
}
@@ -2198,6 +2226,8 @@ export interface KilnEditResult {
diff?: string;
/** The render of the patched program, when render was not disabled. */
render?: KilnRenderViewsResult;
+ /** Advisories about the patched source itself; a render reports its own. */
+ warnings?: string[];
/** Six-view PNG, lifted from the render so transports can attach it as an image. */
pngBase64?: string;
}
@@ -2230,18 +2260,23 @@ async function runEdit(
toLabel: 'after',
});
- if (input.render === false)
+ if (input.render === false) {
+ // Nothing evaluates this patch, so the source budget has to be reported here or not
+ // at all; a rendering edit hears the same cause from the evaluator.
+ const warnings = sourceBudgetAdvisory(code, context);
return {
ok: true,
code,
applied,
diff,
+ ...(warnings.length ? { warnings } : {}),
preservation: {
status: 'not_assessed',
reason:
'Source-only edit. Unchanged source text does not prove unchanged geometry; compare the rendered revisions with kiln_inspect compare.',
},
};
+ }
let editedArtifact: RenderResult | undefined;
const rendered = await runRenderViews(
@@ -2581,7 +2616,15 @@ function createProgramDefs(
): KilnToolDef[] {
toolRequirements(suppliedContext);
const store = suppliedContext.programStore ?? new MemoryProgramStore();
- const context = withCaptureCache(withBuildCache({ ...suppliedContext, programStore: store }));
+ // Read the host before wrapping: the build cache forges an `evaluatorPort` where the
+ // caller had none, and Discovery sidesteps the same wrapper just below.
+ const context = withCaptureCache(
+ withBuildCache({
+ ...suppliedContext,
+ programStore: store,
+ evaluatorTransportsSource: transportsEvaluatorSource(suppliedContext),
+ }),
+ );
return [
createKilnDiscoveryDef({ ...suppliedContext, programStore: store }, presentation),
{